iroh_quinn_proto/
lib.rs

1//! Low-level protocol logic for the QUIC protoocol
2//!
3//! quinn-proto contains a fully deterministic implementation of QUIC protocol logic. It contains
4//! no networking code and does not get any relevant timestamps from the operating system. Most
5//! users may want to use the futures-based quinn API instead.
6//!
7//! The quinn-proto API might be of interest if you want to use it from a C or C++ project
8//! through C bindings or if you want to use a different event loop than the one tokio provides.
9//!
10//! The most important types are `Endpoint`, which conceptually represents the protocol state for
11//! a single socket and mostly manages configuration and dispatches incoming datagrams to the
12//! related `Connection`. `Connection` types contain the bulk of the protocol logic related to
13//! managing a single connection and all the related state (such as streams).
14
15#![cfg_attr(not(fuzzing), warn(missing_docs))]
16#![cfg_attr(test, allow(dead_code))]
17// Fixes welcome:
18#![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// Deal with time
117#[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    //! Exports for benchmarks
125    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
175/// The QUIC protocol version implemented.
176pub 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/// Whether an endpoint was the initiator of a connection
187#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
188#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
189pub enum Side {
190    /// The initiator of a connection
191    Client = 0,
192    /// The acceptor of a connection
193    Server = 1,
194}
195
196impl Side {
197    #[inline]
198    /// Shorthand for `self == Side::Client`
199    pub fn is_client(self) -> bool {
200        self == Self::Client
201    }
202
203    #[inline]
204    /// Shorthand for `self == Side::Server`
205    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/// Whether a stream communicates data in both directions or only from the initiator
221#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
222#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
223pub enum Dir {
224    /// Data flows in both directions
225    Bi = 0,
226    /// Data flows only from the stream's initiator
227    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/// Identifier for a stream within a particular connection
247#[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    /// Create a new StreamId
273    pub fn new(initiator: Side, dir: Dir, index: u64) -> Self {
274        Self((index << 2) | ((dir as u64) << 1) | initiator as u64)
275    }
276    /// Which side of a connection initiated the stream
277    pub fn initiator(self) -> Side {
278        if self.0 & 0x1 == 0 {
279            Side::Client
280        } else {
281            Side::Server
282        }
283    }
284    /// Which directions data flows in
285    pub fn dir(self) -> Dir {
286        if self.0 & 0x2 == 0 { Dir::Bi } else { Dir::Uni }
287    }
288    /// Distinguishes streams of the same initiator and directionality
289    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/// An outgoing packet
324#[derive(Debug)]
325#[must_use]
326pub struct Transmit {
327    /// The socket this datagram should be sent to
328    pub destination: SocketAddr,
329    /// Explicit congestion notification bits to set on the packet
330    pub ecn: Option<EcnCodepoint>,
331    /// Amount of data written to the caller-supplied buffer
332    pub size: usize,
333    /// The segment size if this transmission contains multiple datagrams.
334    /// This is `None` if the transmit only contains a single datagram
335    pub segment_size: Option<usize>,
336    /// Optional source IP address for the datagram
337    pub src_ip: Option<IpAddr>,
338}
339
340//
341// Useful internal constants
342//
343
344/// The maximum number of CIDs we bother to issue per path
345const LOC_CID_COUNT: u64 = 12;
346const RESET_TOKEN_SIZE: usize = 16;
347const MAX_CID_SIZE: usize = 20;
348const MIN_INITIAL_SIZE: u16 = 1200;
349/// <https://www.rfc-editor.org/rfc/rfc9000.html#name-datagram-size>
350const INITIAL_MTU: u16 = 1200;
351const MAX_UDP_PAYLOAD: u16 = 65527;
352const TIMER_GRANULARITY: Duration = Duration::from_millis(1);
353/// Maximum number of streams that can be uniquely identified by a stream ID
354const MAX_STREAM_COUNT: u64 = 1 << 60;
355
356/// Identifies a network path by the combination of remote and local addresses
357///
358/// Including the local ensures good behavior when the host has multiple IP addresses on the same
359/// subnet and zero-length connection IDs are in use or when multipath is enabled and multiple
360/// paths exist with the same remote, but different local IP interfaces.
361#[derive(Hash, Eq, PartialEq, Copy, Clone)]
362pub struct FourTuple {
363    /// The remote side of this tuple
364    pub remote: SocketAddr,
365    /// The local side of this tuple.
366    ///
367    /// The socket is irrelevant for our intents and purposes:
368    /// When we send, we can only specify the `src_ip`, not the source port.
369    /// So even if we track the port, we won't be able to make use of it.
370    pub local_ip: Option<IpAddr>,
371}
372
373impl FourTuple {
374    /// Returns whether we think the other address probably represents the same path
375    /// as ours.
376    ///
377    /// If we have a local IP set, then we're exact and only match if the 4-tuples are
378    /// exactly equal.
379    /// If we don't have a local IP set, then we only check the remote addresses for equality.
380    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    /// Updates this tuple's local address iff
385    /// - it was unset before,
386    /// - the other tuple has the same remote, and
387    /// - the other tuple has a local address set.
388    ///
389    /// Returns whether this and the other remote are now fully equal.
390    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}