1#![allow(elided_lifetimes_in_paths)]
10#![allow(missing_debug_implementations)]
11#![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#![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
108mod cid_queue;
110pub mod coding;
111mod constant_time;
112mod range_set;
113pub mod transport_parameters;
114mod varint;
115
116pub use varint::{VarInt, VarIntBoundsExceeded};
117
118pub mod bounded_pending_buffer;
122
123pub mod path_selection;
125
126pub mod shutdown;
128
129pub mod watchable;
131
132pub mod fair_polling;
134
135pub mod transport_resilience;
137
138pub mod discovery_trait;
140
141pub mod structured_events;
143
144pub mod node;
155
156pub mod node_config;
158
159pub mod node_status;
161
162pub mod node_event;
164
165pub mod config;
168pub mod connection;
170pub mod endpoint;
172pub mod frame;
174pub mod packet;
176pub mod shared;
178pub mod transport_error;
180pub mod candidate_discovery;
183pub mod cid_generator;
185mod congestion;
186mod protocol_violations;
187#[cfg(test)]
188mod protocol_violations_tests;
189
190pub mod nat_traversal_api;
193mod token;
194mod token_memory_cache;
195pub mod tracing;
197
198pub mod crypto;
201pub mod discovery;
203pub mod nat_traversal;
205pub mod transport;
207
208pub mod chat;
212pub mod p2p_endpoint;
224
225pub mod unified_config;
230
231pub mod stats_dashboard;
233pub mod terminal_ui;
235
236pub mod compliance_validator;
239
240pub mod logging;
243
244pub mod metrics;
246
247pub mod relay;
249
250pub mod masque;
252
253pub mod trust;
255
256#[cfg(feature = "aws-lc-rs")]
258pub mod token_v2;
259
260pub mod high_level;
262
263pub use high_level::{
265 Accept, Connecting, Connection as HighLevelConnection, Endpoint,
266 RecvStream as HighLevelRecvStream, SendStream as HighLevelSendStream,
267};
268
269pub mod link_transport;
271mod link_transport_impl;
272
273pub use link_transport::{
275 BoxFuture, BoxStream, Capabilities, ConnectionStats as LinkConnectionStats,
276 DisconnectReason as LinkDisconnectReason, Incoming as LinkIncoming, LinkConn, LinkError,
277 LinkEvent, LinkRecvStream, LinkResult, LinkSendStream, LinkTransport, NatHint, ProtocolId,
278};
279pub use link_transport_impl::{P2pLinkConn, P2pLinkTransport, P2pRecvStream, P2pSendStream};
280
281pub use crypto::raw_public_keys::key_utils::{
283 ML_DSA_65_PUBLIC_KEY_SIZE, ML_DSA_65_SECRET_KEY_SIZE, MlDsaPublicKey, MlDsaSecretKey,
284 derive_peer_id_from_key_bytes, derive_peer_id_from_public_key, generate_ml_dsa_keypair,
285 verify_peer_id,
286};
287
288pub use candidate_discovery::{
290 CandidateDiscoveryManager, DiscoveryConfig, DiscoveryError, DiscoveryEvent, NetworkInterface,
291 ValidatedCandidate,
292};
293pub use connection::nat_traversal::{CandidateSource, CandidateState};
295pub use connection::{
296 Chunk, Chunks, ClosedStream, Connection, ConnectionError, ConnectionStats, Datagrams, Event,
297 FinishError, ReadError, ReadableError, RecvStream, SendDatagramError, SendStream, StreamEvent,
298 Streams, WriteError, Written,
299};
300pub use endpoint::{
301 AcceptError, ConnectError, ConnectionHandle, DatagramEvent, Endpoint as LowLevelEndpoint,
302 Incoming,
303};
304pub use nat_traversal_api::{
305 BootstrapNode, CandidateAddress, NatTraversalConfig, NatTraversalEndpoint, NatTraversalError,
306 NatTraversalEvent, NatTraversalStatistics, PeerId,
307};
308
309pub use node::{Node, NodeError};
315
316pub use node_config::{NodeConfig, NodeConfigBuilder};
318
319pub use node_status::{NatType, NodeStatus};
321
322pub use node_event::{DisconnectReason as NodeDisconnectReason, NodeEvent, TraversalMethod};
324
325pub use p2p_endpoint::{
331 ConnectionMetrics, DisconnectReason, EndpointError, EndpointStats, P2pEndpoint, P2pEvent,
332 PeerConnection, TraversalPhase,
333};
334
335pub use unified_config::{ConfigError, MtuConfig, NatConfig, P2pConfig, P2pConfigBuilder};
337
338pub use relay::{
339 AuthToken, RelayAction, RelayAuthenticator, RelayConnection, RelayConnectionConfig, RelayError,
340 RelayEvent, RelayResult, SessionId, SessionManager, SessionState,
341};
342pub use shared::{ConnectionId, EcnCodepoint, EndpointEvent};
343pub use transport_error::{Code as TransportErrorCode, Error as TransportError};
344
345pub const DEFAULT_SUPPORTED_VERSIONS: &[u32] = &[
354 0x00000001, 0xff00_001d, ];
357
358#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
360#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
361pub enum Side {
362 Client = 0,
364 Server = 1,
366}
367
368impl Side {
369 #[inline]
370 pub fn is_client(self) -> bool {
372 self == Self::Client
373 }
374
375 #[inline]
376 pub fn is_server(self) -> bool {
378 self == Self::Server
379 }
380}
381
382impl ops::Not for Side {
383 type Output = Self;
384 fn not(self) -> Self {
385 match self {
386 Self::Client => Self::Server,
387 Self::Server => Self::Client,
388 }
389 }
390}
391
392#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
394#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
395pub enum Dir {
396 Bi = 0,
398 Uni = 1,
400}
401
402impl Dir {
403 fn iter() -> impl Iterator<Item = Self> {
404 [Self::Bi, Self::Uni].iter().cloned()
405 }
406}
407
408impl fmt::Display for Dir {
409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410 use Dir::*;
411 f.pad(match *self {
412 Bi => "bidirectional",
413 Uni => "unidirectional",
414 })
415 }
416}
417
418#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
420#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
421pub struct StreamId(u64);
422
423impl fmt::Display for StreamId {
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425 let initiator = match self.initiator() {
426 Side::Client => "client",
427 Side::Server => "server",
428 };
429 let dir = match self.dir() {
430 Dir::Uni => "uni",
431 Dir::Bi => "bi",
432 };
433 write!(
434 f,
435 "{} {}directional stream {}",
436 initiator,
437 dir,
438 self.index()
439 )
440 }
441}
442
443impl StreamId {
444 pub fn new(initiator: Side, dir: Dir, index: u64) -> Self {
446 Self((index << 2) | ((dir as u64) << 1) | initiator as u64)
447 }
448 pub fn initiator(self) -> Side {
450 if self.0 & 0x1 == 0 {
451 Side::Client
452 } else {
453 Side::Server
454 }
455 }
456 pub fn dir(self) -> Dir {
458 if self.0 & 0x2 == 0 { Dir::Bi } else { Dir::Uni }
459 }
460 pub fn index(self) -> u64 {
462 self.0 >> 2
463 }
464}
465
466impl From<StreamId> for VarInt {
467 fn from(x: StreamId) -> Self {
468 unsafe { Self::from_u64_unchecked(x.0) }
469 }
470}
471
472impl From<VarInt> for StreamId {
473 fn from(v: VarInt) -> Self {
474 Self(v.0)
475 }
476}
477
478impl From<StreamId> for u64 {
479 fn from(x: StreamId) -> Self {
480 x.0
481 }
482}
483
484impl coding::Codec for StreamId {
485 fn decode<B: bytes::Buf>(buf: &mut B) -> coding::Result<Self> {
486 VarInt::decode(buf).map(|x| Self(x.into_inner()))
487 }
488 fn encode<B: bytes::BufMut>(&self, buf: &mut B) {
489 match VarInt::from_u64(self.0) {
491 Ok(varint) => varint.encode(buf),
492 Err(_) => {
493 VarInt::MAX.encode(buf);
495 }
496 }
497 }
498}
499
500#[derive(Debug)]
502#[must_use]
503pub struct Transmit {
504 pub destination: SocketAddr,
506 pub ecn: Option<EcnCodepoint>,
508 pub size: usize,
510 pub segment_size: Option<usize>,
513 pub src_ip: Option<IpAddr>,
515}
516
517#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
519pub(crate) use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
520#[cfg(all(target_family = "wasm", target_os = "unknown"))]
521pub(crate) use web_time::{Duration, Instant, SystemTime, UNIX_EPOCH};
522
523pub(crate) const LOC_CID_COUNT: u64 = 8;
529pub(crate) const RESET_TOKEN_SIZE: usize = 16;
530pub(crate) const MAX_CID_SIZE: usize = 20;
531pub(crate) const MIN_INITIAL_SIZE: u16 = 1200;
532pub(crate) const INITIAL_MTU: u16 = 1200;
534pub(crate) const MAX_UDP_PAYLOAD: u16 = 65527;
535pub(crate) const TIMER_GRANULARITY: Duration = Duration::from_millis(1);
536pub(crate) const MAX_STREAM_COUNT: u64 = 1 << 60;
538
539pub use cid_generator::RandomConnectionIdGenerator;
541pub use config::{
542 AckFrequencyConfig, ClientConfig, EndpointConfig, MtuDiscoveryConfig, ServerConfig,
543 TransportConfig,
544};
545
546pub use crypto::pqc::{MlDsa65, MlKem768, PqcConfig, PqcConfigBuilder, PqcError, PqcResult};
549pub(crate) use frame::Frame;
550pub use token::TokenStore;
551pub(crate) use token::{NoneTokenLog, ResetToken, TokenLog};
552pub(crate) use token_memory_cache::TokenMemoryCache;