quinn/lib.rs
1//! QUIC transport protocol implementation
2//!
3//! [QUIC](https://en.wikipedia.org/wiki/QUIC) is a modern transport protocol addressing
4//! shortcomings of TCP, such as head-of-line blocking, poor security, slow handshakes, and
5//! inefficient congestion control. This crate provides a portable userspace implementation. It
6//! builds on top of quinn-proto, which implements protocol logic independent of any particular
7//! runtime.
8//!
9//! The entry point of this crate is the [`Endpoint`].
10//!
11//! # About QUIC
12//!
13//! A QUIC connection is an association between two endpoints. The endpoint which initiates the
14//! connection is termed the client, and the endpoint which accepts it is termed the server. A
15//! single endpoint may function as both client and server for different connections, for example
16//! in a peer-to-peer application. To communicate application data, each endpoint may open streams
17//! up to a limit dictated by its peer. Typically, that limit is increased as old streams are
18//! finished.
19//!
20//! Streams may be unidirectional or bidirectional, and are cheap to create and disposable. For
21//! example, a traditionally datagram-oriented application could use a new stream for every
22//! message it wants to send, no longer needing to worry about MTUs. Bidirectional streams behave
23//! much like a traditional TCP connection, and are useful for sending messages that have an
24//! immediate response, such as an HTTP request. Stream data is delivered reliably, and there is no
25//! ordering enforced between data on different streams.
26//!
27//! By avoiding head-of-line blocking and providing unified congestion control across all streams
28//! of a connection, QUIC is able to provide higher throughput and lower latency than one or
29//! multiple TCP connections between the same two hosts, while providing more useful behavior than
30//! raw UDP sockets.
31//!
32//! Quinn also exposes unreliable datagrams, which are a low-level primitive preferred when
33//! automatic fragmentation and retransmission of certain data is not desired.
34//!
35//! QUIC uses encryption and identity verification built directly on TLS 1.3. Just as with a TLS
36//! server, it is useful for a QUIC server to be identified by a certificate signed by a trusted
37//! authority. If this is infeasible--for example, if servers are short-lived or not associated
38//! with a domain name--then as with TLS, self-signed certificates can be used to provide
39//! encryption alone.
40#![warn(missing_docs)]
41#![warn(unreachable_pub)]
42#![warn(clippy::use_self)]
43
44use std::sync::Arc;
45
46mod connection;
47mod endpoint;
48mod incoming;
49mod mutex;
50mod recv_stream;
51mod runtime;
52mod send_stream;
53mod work_limiter;
54
55#[cfg(not(wasm_browser))]
56pub(crate) use std::time::{Duration, Instant};
57#[cfg(wasm_browser)]
58pub(crate) use web_time::{Duration, Instant};
59
60#[cfg(feature = "bloom")]
61pub use proto::BloomTokenLog;
62pub use proto::{
63 AckFrequencyConfig, ApplicationClose, Chunk, ClientConfig, ClosedStream, ConfigError,
64 ConnectError, ConnectionClose, ConnectionError, ConnectionId, ConnectionIdGenerator,
65 ConnectionStats, Dir, EcnCodepoint, EndpointConfig, FrameStats, FrameType, IdleTimeout,
66 MtuDiscoveryConfig, NoneTokenLog, NoneTokenStore, PathStats, ServerConfig, Side, StdSystemTime,
67 StreamId, TimeSource, TokenLog, TokenMemoryCache, TokenReuseError, TokenStore, Transmit,
68 TransportConfig, TransportErrorCode, UdpStats, ValidationTokenConfig, VarInt,
69 VarIntBoundsExceeded, Written, congestion, crypto,
70};
71#[cfg(feature = "qlog")]
72pub use proto::{QlogConfig, QlogStream};
73#[cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
74pub use rustls;
75pub use udp;
76
77pub use crate::connection::{
78 AcceptBi, AcceptUni, Connecting, Connection, OpenBi, OpenUni, ReadDatagram, SendDatagram,
79 SendDatagramError, ZeroRttAccepted,
80};
81pub use crate::endpoint::{Accept, Endpoint, EndpointStats};
82pub use crate::incoming::{Incoming, IncomingFuture, RetryError};
83pub use crate::recv_stream::{ReadError, ReadExactError, ReadToEndError, RecvStream, ResetError};
84#[cfg(feature = "runtime-async-std")]
85pub use crate::runtime::AsyncStdRuntime;
86#[cfg(feature = "runtime-smol")]
87pub use crate::runtime::SmolRuntime;
88#[cfg(feature = "runtime-tokio")]
89pub use crate::runtime::TokioRuntime;
90pub use crate::runtime::{AsyncTimer, AsyncUdpSocket, Runtime, UdpPoller, default_runtime};
91pub use crate::send_stream::{SendStream, StoppedError, WriteError};
92
93#[cfg(test)]
94mod tests;
95
96#[derive(Debug)]
97enum ConnectionEvent {
98 Close {
99 error_code: VarInt,
100 reason: bytes::Bytes,
101 },
102 Proto(proto::ConnectionEvent),
103 Rebind(Arc<dyn AsyncUdpSocket>),
104}
105
106fn udp_transmit<'a>(t: &proto::Transmit, buffer: &'a [u8]) -> udp::Transmit<'a> {
107 udp::Transmit {
108 destination: t.destination,
109 ecn: t.ecn.map(udp_ecn),
110 contents: buffer,
111 segment_size: t.segment_size,
112 src_ip: t.src_ip,
113 }
114}
115
116fn udp_ecn(ecn: proto::EcnCodepoint) -> udp::EcnCodepoint {
117 match ecn {
118 proto::EcnCodepoint::Ect0 => udp::EcnCodepoint::Ect0,
119 proto::EcnCodepoint::Ect1 => udp::EcnCodepoint::Ect1,
120 proto::EcnCodepoint::Ce => udp::EcnCodepoint::Ce,
121 }
122}
123
124/// Maximum number of datagrams processed in send/recv calls to make before moving on to other processing
125///
126/// This helps ensure we don't starve anything when the CPU is slower than the link.
127/// Value is selected by picking a low number which didn't degrade throughput in benchmarks.
128const IO_LOOP_BOUND: usize = 160;
129
130/// The maximum amount of time that should be spent in `recvmsg()` calls per endpoint iteration
131///
132/// 50us are chosen so that an endpoint iteration with a 50us sendmsg limit blocks
133/// the runtime for a maximum of about 100us.
134/// Going much lower does not yield any noticeable difference, since a single `recvmmsg`
135/// batch of size 32 was observed to take 30us on some systems.
136const RECV_TIME_BOUND: Duration = Duration::from_micros(50);