1#![cfg_attr(not(fuzzing), warn(missing_docs))]
16#![cfg_attr(test, allow(dead_code))]
17#![allow(clippy::too_many_arguments)]
19#![warn(unreachable_pub)]
20#![warn(clippy::use_self)]
21
22use std::{
23 fmt,
24 net::{IpAddr, SocketAddr},
25 ops,
26};
27
28mod cid_queue;
29pub mod coding;
30mod constant_time;
31mod range_set;
32#[cfg(all(test, any(feature = "rustls-aws-lc-rs", feature = "rustls-ring")))]
33mod tests;
34pub mod transport_parameters;
35mod varint;
36
37pub use varint::{VarInt, VarIntBoundsExceeded};
38
39#[cfg(feature = "bloom")]
40mod bloom_token_log;
41#[cfg(feature = "bloom")]
42pub use bloom_token_log::BloomTokenLog;
43
44pub(crate) mod connection;
45pub use crate::connection::{
46 Chunk, Chunks, ClosePathError, ClosedPath, ClosedStream, Connection, ConnectionError,
47 ConnectionStats, Datagrams, Event, FinishError, FrameStats, MultipathNotNegotiated, PathError,
48 PathEvent, PathId, PathStats, PathStatus, ReadError, ReadableError, RecvStream, RttEstimator,
49 SendDatagramError, SendStream, SetPathStatusError, ShouldTransmit, StreamEvent, Streams,
50 UdpStats, WriteError, Written,
51};
52
53#[cfg(feature = "rustls")]
54pub use rustls;
55
56mod config;
57#[cfg(doc)]
58pub use config::DEFAULT_CONCURRENT_MULTIPATH_PATHS_WHEN_ENABLED;
59pub use config::{
60 AckFrequencyConfig, ClientConfig, ConfigError, EndpointConfig, IdleTimeout, MtuDiscoveryConfig,
61 ServerConfig, StdSystemTime, TimeSource, TransportConfig, ValidationTokenConfig,
62};
63#[cfg(feature = "qlog")]
64pub use config::{QlogConfig, QlogFactory, QlogFileFactory};
65
66pub mod crypto;
67
68mod frame;
69pub use crate::frame::{
70 ApplicationClose, ConnectionClose, Datagram, DatagramInfo, FrameType, InvalidFrameId,
71 MaybeFrame, StreamInfo,
72};
73use crate::{
74 coding::{Decodable, Encodable},
75 frame::Frame,
76};
77
78mod endpoint;
79pub use crate::endpoint::{
80 AcceptError, ConnectError, ConnectionHandle, DatagramEvent, Endpoint, Incoming, RetryError,
81};
82
83mod packet;
84pub use packet::{
85 ConnectionIdParser, FixedLengthConnectionIdParser, LongType, PacketDecodeError, PartialDecode,
86 ProtectedHeader, ProtectedInitialHeader,
87};
88
89mod shared;
90pub use crate::shared::{ConnectionEvent, ConnectionId, EcnCodepoint, EndpointEvent};
91
92mod transport_error;
93pub use crate::transport_error::{Code as TransportErrorCode, Error as TransportError};
94
95pub mod congestion;
96
97mod cid_generator;
98pub use crate::cid_generator::{
99 ConnectionIdGenerator, HashedConnectionIdGenerator, InvalidCid, RandomConnectionIdGenerator,
100};
101
102mod token;
103use token::ResetToken;
104pub use token::{NoneTokenLog, NoneTokenStore, TokenLog, TokenReuseError, TokenStore};
105
106mod address_discovery;
107
108mod token_memory_cache;
109pub use token_memory_cache::TokenMemoryCache;
110
111pub mod iroh_hp;
112
113#[cfg(feature = "arbitrary")]
114use arbitrary::Arbitrary;
115
116#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
118pub(crate) use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
119#[cfg(all(target_family = "wasm", target_os = "unknown"))]
120pub(crate) use web_time::{Duration, Instant, SystemTime, UNIX_EPOCH};
121
122#[cfg(feature = "bench")]
123pub mod bench_exports {
124 pub use crate::connection::send_buffer::send_buffer_benches;
126}
127
128#[cfg(fuzzing)]
129pub mod fuzzing {
130 pub use crate::connection::{Retransmits, State as ConnectionState, StreamsState};
131 pub use crate::frame::ResetStream;
132 pub use crate::packet::PartialDecode;
133 pub use crate::transport_parameters::TransportParameters;
134 pub use bytes::{BufMut, BytesMut};
135
136 #[cfg(feature = "arbitrary")]
137 use arbitrary::{Arbitrary, Result, Unstructured};
138
139 #[cfg(feature = "arbitrary")]
140 impl<'arbitrary> Arbitrary<'arbitrary> for TransportParameters {
141 fn arbitrary(u: &mut Unstructured<'arbitrary>) -> Result<Self> {
142 Ok(Self {
143 initial_max_streams_bidi: u.arbitrary()?,
144 initial_max_streams_uni: u.arbitrary()?,
145 ack_delay_exponent: u.arbitrary()?,
146 max_udp_payload_size: u.arbitrary()?,
147 ..Self::default()
148 })
149 }
150 }
151
152 #[derive(Debug)]
153 pub struct PacketParams {
154 pub local_cid_len: usize,
155 pub buf: BytesMut,
156 pub grease_quic_bit: bool,
157 }
158
159 #[cfg(feature = "arbitrary")]
160 impl<'arbitrary> Arbitrary<'arbitrary> for PacketParams {
161 fn arbitrary(u: &mut Unstructured<'arbitrary>) -> Result<Self> {
162 let local_cid_len: usize = u.int_in_range(0..=crate::MAX_CID_SIZE)?;
163 let bytes: Vec<u8> = Vec::arbitrary(u)?;
164 let mut buf = BytesMut::new();
165 buf.put_slice(&bytes[..]);
166 Ok(Self {
167 local_cid_len,
168 buf,
169 grease_quic_bit: bool::arbitrary(u)?,
170 })
171 }
172 }
173}
174
175pub const DEFAULT_SUPPORTED_VERSIONS: &[u32] = &[
177 0x00000001,
178 0xff00_001d,
179 0xff00_001e,
180 0xff00_001f,
181 0xff00_0020,
182 0xff00_0021,
183 0xff00_0022,
184];
185
186#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
188#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
189pub enum Side {
190 Client = 0,
192 Server = 1,
194}
195
196impl Side {
197 #[inline]
198 pub fn is_client(self) -> bool {
200 self == Self::Client
201 }
202
203 #[inline]
204 pub fn is_server(self) -> bool {
206 self == Self::Server
207 }
208}
209
210impl ops::Not for Side {
211 type Output = Self;
212 fn not(self) -> Self {
213 match self {
214 Self::Client => Self::Server,
215 Self::Server => Self::Client,
216 }
217 }
218}
219
220#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
222#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
223pub enum Dir {
224 Bi = 0,
226 Uni = 1,
228}
229
230impl Dir {
231 fn iter() -> impl Iterator<Item = Self> {
232 [Self::Bi, Self::Uni].iter().cloned()
233 }
234}
235
236impl fmt::Display for Dir {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 use Dir::*;
239 f.pad(match *self {
240 Bi => "bidirectional",
241 Uni => "unidirectional",
242 })
243 }
244}
245
246#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
248#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
249pub struct StreamId(u64);
250
251impl fmt::Display for StreamId {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 let initiator = match self.initiator() {
254 Side::Client => "client",
255 Side::Server => "server",
256 };
257 let dir = match self.dir() {
258 Dir::Uni => "uni",
259 Dir::Bi => "bi",
260 };
261 write!(
262 f,
263 "{} {}directional stream {}",
264 initiator,
265 dir,
266 self.index()
267 )
268 }
269}
270
271impl StreamId {
272 pub fn new(initiator: Side, dir: Dir, index: u64) -> Self {
274 Self((index << 2) | ((dir as u64) << 1) | initiator as u64)
275 }
276 pub fn initiator(self) -> Side {
278 if self.0 & 0x1 == 0 {
279 Side::Client
280 } else {
281 Side::Server
282 }
283 }
284 pub fn dir(self) -> Dir {
286 if self.0 & 0x2 == 0 { Dir::Bi } else { Dir::Uni }
287 }
288 pub fn index(self) -> u64 {
290 self.0 >> 2
291 }
292}
293
294impl From<StreamId> for VarInt {
295 fn from(x: StreamId) -> Self {
296 unsafe { Self::from_u64_unchecked(x.0) }
297 }
298}
299
300impl From<VarInt> for StreamId {
301 fn from(v: VarInt) -> Self {
302 Self(v.0)
303 }
304}
305
306impl From<StreamId> for u64 {
307 fn from(x: StreamId) -> Self {
308 x.0
309 }
310}
311
312impl Decodable for StreamId {
313 fn decode<B: bytes::Buf>(buf: &mut B) -> coding::Result<Self> {
314 VarInt::decode(buf).map(|x| Self(x.into_inner()))
315 }
316}
317impl Encodable for StreamId {
318 fn encode<B: bytes::BufMut>(&self, buf: &mut B) {
319 VarInt::from_u64(self.0).unwrap().encode(buf);
320 }
321}
322
323#[derive(Debug)]
325#[must_use]
326pub struct Transmit {
327 pub destination: SocketAddr,
329 pub ecn: Option<EcnCodepoint>,
331 pub size: usize,
333 pub segment_size: Option<usize>,
336 pub src_ip: Option<IpAddr>,
338}
339
340const LOC_CID_COUNT: u64 = 12;
346const RESET_TOKEN_SIZE: usize = 16;
347const MAX_CID_SIZE: usize = 20;
348const MIN_INITIAL_SIZE: u16 = 1200;
349const INITIAL_MTU: u16 = 1200;
351const MAX_UDP_PAYLOAD: u16 = 65527;
352const TIMER_GRANULARITY: Duration = Duration::from_millis(1);
353const MAX_STREAM_COUNT: u64 = 1 << 60;
355
356#[derive(Hash, Eq, PartialEq, Copy, Clone)]
362pub struct FourTuple {
363 pub remote: SocketAddr,
365 pub local_ip: Option<IpAddr>,
371}
372
373impl FourTuple {
374 pub fn is_probably_same_path(&self, other: &Self) -> bool {
381 self.remote == other.remote && (self.local_ip.is_none() || self.local_ip == other.local_ip)
382 }
383
384 pub fn update_local_if_same_remote(&mut self, other: &Self) -> bool {
391 if self.remote != other.remote {
392 return false;
393 }
394 if self.local_ip.is_some() && self.local_ip != other.local_ip {
395 return false;
396 }
397 self.local_ip = other.local_ip;
398 true
399 }
400}
401
402impl fmt::Display for FourTuple {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.write_str("(")?;
405 if let Some(local_ip) = &self.local_ip {
406 local_ip.fmt(f)?;
407 f.write_str(", ")?;
408 } else {
409 f.write_str("<unknown>, ")?;
410 }
411 self.remote.fmt(f)?;
412 f.write_str(")")
413 }
414}
415
416impl fmt::Debug for FourTuple {
417 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418 fmt::Display::fmt(&self, f)
419 }
420}