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
171// ============================================================================
172// P2P API
173// ============================================================================
174
175/// P2P endpoint - the primary API for ant-quic
176///
177/// This module provides the main API for P2P networking with NAT traversal,
178/// connection management, and secure communication.
179pub mod p2p_endpoint;
180
181/// P2P configuration system
182///
183/// This module provides `P2pConfig` with builder pattern support for
184/// configuring endpoints, NAT traversal, MTU, PQC, and other settings.
185pub mod unified_config;
186
187/// Real-time statistics dashboard
188pub mod stats_dashboard;
189/// Terminal user interface components
190pub mod terminal_ui;
191
192// Compliance validation framework
193/// IETF compliance validation tools
194pub mod compliance_validator;
195
196// Comprehensive logging system
197/// Structured logging and diagnostics
198pub mod logging;
199
200/// Metrics collection and export system (basic metrics always available)
201pub mod metrics;
202
203/// TURN-style relay protocol for NAT traversal fallback
204pub mod relay;
205
206/// Transport trust module (TOFU, rotations, channel binding surfaces)
207pub mod trust;
208
209/// Address-validation tokens bound to (PeerId||CID||nonce)
210#[cfg(feature = "aws-lc-rs")]
211pub mod token_v2;
212
213// High-level async API modules (ported from quinn crate)
214pub mod high_level;
215
216// Re-export high-level API types for easier usage
217pub use high_level::{
218    Accept, Connecting, Connection as HighLevelConnection, Endpoint,
219    RecvStream as HighLevelRecvStream, SendStream as HighLevelSendStream,
220};
221
222// Re-export crypto utilities for peer ID management
223pub use crypto::raw_public_keys::key_utils::{
224    derive_peer_id_from_key_bytes, derive_peer_id_from_public_key, generate_ed25519_keypair,
225    public_key_from_bytes, public_key_to_bytes, verify_peer_id,
226};
227
228// Re-export key types for backward compatibility
229pub use candidate_discovery::{
230    CandidateDiscoveryManager, DiscoveryConfig, DiscoveryError, DiscoveryEvent, NetworkInterface,
231    ValidatedCandidate,
232};
233// v0.13.0: NatTraversalRole removed - all nodes are symmetric P2P nodes
234pub use connection::nat_traversal::{CandidateSource, CandidateState};
235pub use connection::{
236    Chunk, Chunks, ClosedStream, Connection, ConnectionError, ConnectionStats, Datagrams, Event,
237    FinishError, ReadError, ReadableError, RecvStream, SendDatagramError, SendStream, StreamEvent,
238    Streams, WriteError, Written,
239};
240pub use endpoint::{
241    AcceptError, ConnectError, ConnectionHandle, DatagramEvent, Endpoint as LowLevelEndpoint,
242    Incoming,
243};
244pub use nat_traversal_api::{
245    BootstrapNode, CandidateAddress, NatTraversalConfig, NatTraversalEndpoint, NatTraversalError,
246    NatTraversalEvent, NatTraversalStatistics, PeerId,
247};
248
249// ============================================================================
250// P2P API EXPORTS
251// ============================================================================
252
253/// P2P endpoint - the primary entry point for applications
254pub use p2p_endpoint::{
255    ConnectionMetrics, DisconnectReason, EndpointError, EndpointStats, P2pEndpoint, P2pEvent,
256    PeerConnection, TraversalPhase,
257};
258
259/// P2P configuration with builder pattern
260pub use unified_config::{ConfigError, MtuConfig, NatConfig, P2pConfig, P2pConfigBuilder};
261
262pub use relay::{
263    AuthToken, RelayAction, RelayAuthenticator, RelayConnection, RelayConnectionConfig, RelayError,
264    RelayEvent, RelayResult, SessionId, SessionManager, SessionState,
265};
266pub use shared::{ConnectionId, EcnCodepoint, EndpointEvent};
267pub use transport_error::{Code as TransportErrorCode, Error as TransportError};
268
269// #[cfg(fuzzing)]
270// pub mod fuzzing; // Module not implemented yet
271
272/// The QUIC protocol version implemented.
273///
274/// Simplified to include only the essential versions:
275/// - 0x00000001: QUIC v1 (RFC 9000)
276/// - 0xff00_001d: Draft 29
277pub const DEFAULT_SUPPORTED_VERSIONS: &[u32] = &[
278    0x00000001,  // QUIC v1 (RFC 9000)
279    0xff00_001d, // Draft 29
280];
281
282/// Whether an endpoint was the initiator of a connection
283#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
284#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
285pub enum Side {
286    /// The initiator of a connection
287    Client = 0,
288    /// The acceptor of a connection
289    Server = 1,
290}
291
292impl Side {
293    #[inline]
294    /// Shorthand for `self == Side::Client`
295    pub fn is_client(self) -> bool {
296        self == Self::Client
297    }
298
299    #[inline]
300    /// Shorthand for `self == Side::Server`
301    pub fn is_server(self) -> bool {
302        self == Self::Server
303    }
304}
305
306impl ops::Not for Side {
307    type Output = Self;
308    fn not(self) -> Self {
309        match self {
310            Self::Client => Self::Server,
311            Self::Server => Self::Client,
312        }
313    }
314}
315
316/// Whether a stream communicates data in both directions or only from the initiator
317#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
318#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
319pub enum Dir {
320    /// Data flows in both directions
321    Bi = 0,
322    /// Data flows only from the stream's initiator
323    Uni = 1,
324}
325
326impl Dir {
327    fn iter() -> impl Iterator<Item = Self> {
328        [Self::Bi, Self::Uni].iter().cloned()
329    }
330}
331
332impl fmt::Display for Dir {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        use Dir::*;
335        f.pad(match *self {
336            Bi => "bidirectional",
337            Uni => "unidirectional",
338        })
339    }
340}
341
342/// Identifier for a stream within a particular connection
343#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
344#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
345pub struct StreamId(u64);
346
347impl fmt::Display for StreamId {
348    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349        let initiator = match self.initiator() {
350            Side::Client => "client",
351            Side::Server => "server",
352        };
353        let dir = match self.dir() {
354            Dir::Uni => "uni",
355            Dir::Bi => "bi",
356        };
357        write!(
358            f,
359            "{} {}directional stream {}",
360            initiator,
361            dir,
362            self.index()
363        )
364    }
365}
366
367impl StreamId {
368    /// Create a new StreamId
369    pub fn new(initiator: Side, dir: Dir, index: u64) -> Self {
370        Self((index << 2) | ((dir as u64) << 1) | initiator as u64)
371    }
372    /// Which side of a connection initiated the stream
373    pub fn initiator(self) -> Side {
374        if self.0 & 0x1 == 0 {
375            Side::Client
376        } else {
377            Side::Server
378        }
379    }
380    /// Which directions data flows in
381    pub fn dir(self) -> Dir {
382        if self.0 & 0x2 == 0 { Dir::Bi } else { Dir::Uni }
383    }
384    /// Distinguishes streams of the same initiator and directionality
385    pub fn index(self) -> u64 {
386        self.0 >> 2
387    }
388}
389
390impl From<StreamId> for VarInt {
391    fn from(x: StreamId) -> Self {
392        unsafe { Self::from_u64_unchecked(x.0) }
393    }
394}
395
396impl From<VarInt> for StreamId {
397    fn from(v: VarInt) -> Self {
398        Self(v.0)
399    }
400}
401
402impl From<StreamId> for u64 {
403    fn from(x: StreamId) -> Self {
404        x.0
405    }
406}
407
408impl coding::Codec for StreamId {
409    fn decode<B: bytes::Buf>(buf: &mut B) -> coding::Result<Self> {
410        VarInt::decode(buf).map(|x| Self(x.into_inner()))
411    }
412    fn encode<B: bytes::BufMut>(&self, buf: &mut B) {
413        // StreamId values should always be valid VarInt values, but handle the error case
414        match VarInt::from_u64(self.0) {
415            Ok(varint) => varint.encode(buf),
416            Err(_) => {
417                // This should never happen for valid StreamIds, but use a safe fallback
418                VarInt::MAX.encode(buf);
419            }
420        }
421    }
422}
423
424/// An outgoing packet
425#[derive(Debug)]
426#[must_use]
427pub struct Transmit {
428    /// The socket this datagram should be sent to
429    pub destination: SocketAddr,
430    /// Explicit congestion notification bits to set on the packet
431    pub ecn: Option<EcnCodepoint>,
432    /// Amount of data written to the caller-supplied buffer
433    pub size: usize,
434    /// The segment size if this transmission contains multiple datagrams.
435    /// This is `None` if the transmit only contains a single datagram
436    pub segment_size: Option<usize>,
437    /// Optional source IP address for the datagram
438    pub src_ip: Option<IpAddr>,
439}
440
441// Deal with time
442#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
443pub(crate) use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
444#[cfg(all(target_family = "wasm", target_os = "unknown"))]
445pub(crate) use web_time::{Duration, Instant, SystemTime, UNIX_EPOCH};
446
447//
448// Useful internal constants
449//
450
451/// The maximum number of CIDs we bother to issue per connection
452pub(crate) const LOC_CID_COUNT: u64 = 8;
453pub(crate) const RESET_TOKEN_SIZE: usize = 16;
454pub(crate) const MAX_CID_SIZE: usize = 20;
455pub(crate) const MIN_INITIAL_SIZE: u16 = 1200;
456/// <https://www.rfc-editor.org/rfc/rfc9000.html#name-datagram-size>
457pub(crate) const INITIAL_MTU: u16 = 1200;
458pub(crate) const MAX_UDP_PAYLOAD: u16 = 65527;
459pub(crate) const TIMER_GRANULARITY: Duration = Duration::from_millis(1);
460/// Maximum number of streams that can be tracked per connection
461pub(crate) const MAX_STREAM_COUNT: u64 = 1 << 60;
462
463// Internal type re-exports for crate modules
464pub use cid_generator::RandomConnectionIdGenerator;
465pub use config::{
466    AckFrequencyConfig, ClientConfig, EndpointConfig, MtuDiscoveryConfig, ServerConfig,
467    TransportConfig,
468};
469
470// Post-Quantum Cryptography (PQC) re-exports - always available
471pub use crypto::pqc::{
472    HybridKem, HybridSignature, MlDsa65, MlKem768, PqcConfig, PqcConfigBuilder, PqcError, PqcResult,
473};
474pub(crate) use frame::Frame;
475pub use token::TokenStore;
476pub(crate) use token::{NoneTokenLog, ResetToken, TokenLog};
477pub(crate) use token_memory_cache::TokenMemoryCache;