Skip to main content

quiche/
lib.rs

1// Copyright (C) 2018-2019, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//
11//     * Redistributions in binary form must reproduce the above copyright
12//       notice, this list of conditions and the following disclaimer in the
13//       documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27//! 🥧 Savoury implementation of the QUIC transport protocol and HTTP/3.
28//!
29//! [quiche] is an implementation of the QUIC transport protocol and HTTP/3 as
30//! specified by the [IETF]. It provides a low level API for processing QUIC
31//! packets and handling connection state. The application is responsible for
32//! providing I/O (e.g. sockets handling) as well as an event loop with support
33//! for timers.
34//!
35//! [quiche]: https://github.com/cloudflare/quiche/
36//! [ietf]: https://quicwg.org/
37//!
38//! ## Configuring connections
39//!
40//! The first step in establishing a QUIC connection using quiche is creating a
41//! [`Config`] object:
42//!
43//! ```
44//! let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
45//! config.set_application_protos(&[b"example-proto"]);
46//!
47//! // Additional configuration specific to application and use case...
48//! # Ok::<(), quiche::Error>(())
49//! ```
50//!
51//! The [`Config`] object controls important aspects of the QUIC connection such
52//! as QUIC version, ALPN IDs, flow control, congestion control, idle timeout
53//! and other properties or features.
54//!
55//! QUIC is a general-purpose transport protocol and there are several
56//! configuration properties where there is no reasonable default value. For
57//! example, the permitted number of concurrent streams of any particular type
58//! is dependent on the application running over QUIC, and other use-case
59//! specific concerns.
60//!
61//! quiche defaults several properties to zero, applications most likely need
62//! to set these to something else to satisfy their needs using the following:
63//!
64//! - [`set_initial_max_streams_bidi()`]
65//! - [`set_initial_max_streams_uni()`]
66//! - [`set_initial_max_data()`]
67//! - [`set_initial_max_stream_data_bidi_local()`]
68//! - [`set_initial_max_stream_data_bidi_remote()`]
69//! - [`set_initial_max_stream_data_uni()`]
70//!
71//! [`Config`] also holds TLS configuration. This can be changed by mutators on
72//! the an existing object, or by constructing a TLS context manually and
73//! creating a configuration using [`with_boring_ssl_ctx_builder()`].
74//!
75//! A configuration object can be shared among multiple connections.
76//!
77//! ### Connection setup
78//!
79//! On the client-side the [`connect()`] utility function can be used to create
80//! a new connection, while [`accept()`] is for servers:
81//!
82//! ```
83//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
84//! # let server_name = "quic.tech";
85//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
86//! # let peer = "127.0.0.1:1234".parse().unwrap();
87//! # let local = "127.0.0.1:4321".parse().unwrap();
88//! // Client connection.
89//! let conn =
90//!     quiche::connect(Some(&server_name), &scid, local, peer, &mut config)?;
91//!
92//! // Server connection.
93//! # let peer = "127.0.0.1:1234".parse().unwrap();
94//! # let local = "127.0.0.1:4321".parse().unwrap();
95//! let conn = quiche::accept(&scid, None, local, peer, &mut config)?;
96//! # Ok::<(), quiche::Error>(())
97//! ```
98//!
99//! In both cases, the application is responsible for generating a new source
100//! connection ID that will be used to identify the new connection.
101//!
102//! The application also need to pass the address of the remote peer of the
103//! connection: in the case of a client that would be the address of the server
104//! it is trying to connect to, and for a server that is the address of the
105//! client that initiated the connection.
106//!
107//! ## Handling incoming packets
108//!
109//! Using the connection's [`recv()`] method the application can process
110//! incoming packets that belong to that connection from the network:
111//!
112//! ```no_run
113//! # let mut buf = [0; 512];
114//! # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
115//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
116//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
117//! # let peer = "127.0.0.1:1234".parse().unwrap();
118//! # let local = "127.0.0.1:4321".parse().unwrap();
119//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
120//! let to = socket.local_addr().unwrap();
121//!
122//! loop {
123//!     let (read, from) = socket.recv_from(&mut buf).unwrap();
124//!
125//!     let recv_info = quiche::RecvInfo { from, to };
126//!
127//!     let read = match conn.recv(&mut buf[..read], recv_info) {
128//!         Ok(v) => v,
129//!
130//!         Err(quiche::Error::Done) => {
131//!             // Done reading.
132//!             break;
133//!         },
134//!
135//!         Err(e) => {
136//!             // An error occurred, handle it.
137//!             break;
138//!         },
139//!     };
140//! }
141//! # Ok::<(), quiche::Error>(())
142//! ```
143//!
144//! The application has to pass a [`RecvInfo`] structure in order to provide
145//! additional information about the received packet (such as the address it
146//! was received from).
147//!
148//! ## Generating outgoing packets
149//!
150//! Outgoing packet are generated using the connection's [`send()`] method
151//! instead:
152//!
153//! ```no_run
154//! # let mut out = [0; 512];
155//! # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
156//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
157//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
158//! # let peer = "127.0.0.1:1234".parse().unwrap();
159//! # let local = "127.0.0.1:4321".parse().unwrap();
160//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
161//! loop {
162//!     let (write, send_info) = match conn.send(&mut out) {
163//!         Ok(v) => v,
164//!
165//!         Err(quiche::Error::Done) => {
166//!             // Done writing.
167//!             break;
168//!         },
169//!
170//!         Err(e) => {
171//!             // An error occurred, handle it.
172//!             break;
173//!         },
174//!     };
175//!
176//!     socket.send_to(&out[..write], &send_info.to).unwrap();
177//! }
178//! # Ok::<(), quiche::Error>(())
179//! ```
180//!
181//! The application will be provided with a [`SendInfo`] structure providing
182//! additional information about the newly created packet (such as the address
183//! the packet should be sent to).
184//!
185//! When packets are sent, the application is responsible for maintaining a
186//! timer to react to time-based connection events. The timer expiration can be
187//! obtained using the connection's [`timeout()`] method.
188//!
189//! ```
190//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
191//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
192//! # let peer = "127.0.0.1:1234".parse().unwrap();
193//! # let local = "127.0.0.1:4321".parse().unwrap();
194//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
195//! let timeout = conn.timeout();
196//! # Ok::<(), quiche::Error>(())
197//! ```
198//!
199//! The application is responsible for providing a timer implementation, which
200//! can be specific to the operating system or networking framework used. When
201//! a timer expires, the connection's [`on_timeout()`] method should be called,
202//! after which additional packets might need to be sent on the network:
203//!
204//! ```no_run
205//! # let mut out = [0; 512];
206//! # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
207//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
208//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
209//! # let peer = "127.0.0.1:1234".parse().unwrap();
210//! # let local = "127.0.0.1:4321".parse().unwrap();
211//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
212//! // Timeout expired, handle it.
213//! conn.on_timeout();
214//!
215//! // Send more packets as needed after timeout.
216//! loop {
217//!     let (write, send_info) = match conn.send(&mut out) {
218//!         Ok(v) => v,
219//!
220//!         Err(quiche::Error::Done) => {
221//!             // Done writing.
222//!             break;
223//!         },
224//!
225//!         Err(e) => {
226//!             // An error occurred, handle it.
227//!             break;
228//!         },
229//!     };
230//!
231//!     socket.send_to(&out[..write], &send_info.to).unwrap();
232//! }
233//! # Ok::<(), quiche::Error>(())
234//! ```
235//!
236//! ### Pacing
237//!
238//! It is recommended that applications [pace] sending of outgoing packets to
239//! avoid creating packet bursts that could cause short-term congestion and
240//! losses in the network.
241//!
242//! quiche exposes pacing hints for outgoing packets through the [`at`] field
243//! of the [`SendInfo`] structure that is returned by the [`send()`] method.
244//! This field represents the time when a specific packet should be sent into
245//! the network.
246//!
247//! Applications can use these hints by artificially delaying the sending of
248//! packets through platform-specific mechanisms (such as the [`SO_TXTIME`]
249//! socket option on Linux), or custom methods (for example by using user-space
250//! timers).
251//!
252//! [pace]: https://datatracker.ietf.org/doc/html/rfc9002#section-7.7
253//! [`SO_TXTIME`]: https://man7.org/linux/man-pages/man8/tc-etf.8.html
254//!
255//! ## Sending and receiving stream data
256//!
257//! After some back and forth, the connection will complete its handshake and
258//! will be ready for sending or receiving application data.
259//!
260//! Data can be sent on a stream by using the [`stream_send()`] method:
261//!
262//! ```no_run
263//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
264//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
265//! # let peer = "127.0.0.1:1234".parse().unwrap();
266//! # let local = "127.0.0.1:4321".parse().unwrap();
267//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
268//! if conn.is_established() {
269//!     // Handshake completed, send some data on stream 0.
270//!     conn.stream_send(0, b"hello", true)?;
271//! }
272//! # Ok::<(), quiche::Error>(())
273//! ```
274//!
275//! The application can check whether there are any readable streams by using
276//! the connection's [`readable()`] method, which returns an iterator over all
277//! the streams that have outstanding data to read.
278//!
279//! The [`stream_recv()`] method can then be used to retrieve the application
280//! data from the readable stream:
281//!
282//! ```no_run
283//! # let mut buf = [0; 512];
284//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
285//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
286//! # let peer = "127.0.0.1:1234".parse().unwrap();
287//! # let local = "127.0.0.1:4321".parse().unwrap();
288//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
289//! if conn.is_established() {
290//!     // Iterate over readable streams.
291//!     for stream_id in conn.readable() {
292//!         // Stream is readable, read until there's no more data.
293//!         while let Ok((read, fin)) = conn.stream_recv(stream_id, &mut buf) {
294//!             println!("Got {} bytes on stream {}", read, stream_id);
295//!         }
296//!     }
297//! }
298//! # Ok::<(), quiche::Error>(())
299//! ```
300//!
301//! ## HTTP/3
302//!
303//! The quiche [HTTP/3 module] provides a high level API for sending and
304//! receiving HTTP requests and responses on top of the QUIC transport protocol.
305//!
306//! [`Config`]: https://docs.quic.tech/quiche/struct.Config.html
307//! [`set_initial_max_streams_bidi()`]: https://docs.rs/quiche/latest/quiche/struct.Config.html#method.set_initial_max_streams_bidi
308//! [`set_initial_max_streams_uni()`]: https://docs.rs/quiche/latest/quiche/struct.Config.html#method.set_initial_max_streams_uni
309//! [`set_initial_max_data()`]: https://docs.rs/quiche/latest/quiche/struct.Config.html#method.set_initial_max_data
310//! [`set_initial_max_stream_data_bidi_local()`]: https://docs.rs/quiche/latest/quiche/struct.Config.html#method.set_initial_max_stream_data_bidi_local
311//! [`set_initial_max_stream_data_bidi_remote()`]: https://docs.rs/quiche/latest/quiche/struct.Config.html#method.set_initial_max_stream_data_bidi_remote
312//! [`set_initial_max_stream_data_uni()`]: https://docs.rs/quiche/latest/quiche/struct.Config.html#method.set_initial_max_stream_data_uni
313//! [`with_boring_ssl_ctx_builder()`]: https://docs.quic.tech/quiche/struct.Config.html#method.with_boring_ssl_ctx_builder
314//! [`connect()`]: fn.connect.html
315//! [`accept()`]: fn.accept.html
316//! [`recv()`]: struct.Connection.html#method.recv
317//! [`RecvInfo`]: struct.RecvInfo.html
318//! [`send()`]: struct.Connection.html#method.send
319//! [`SendInfo`]: struct.SendInfo.html
320//! [`at`]: struct.SendInfo.html#structfield.at
321//! [`timeout()`]: struct.Connection.html#method.timeout
322//! [`on_timeout()`]: struct.Connection.html#method.on_timeout
323//! [`stream_send()`]: struct.Connection.html#method.stream_send
324//! [`readable()`]: struct.Connection.html#method.readable
325//! [`stream_recv()`]: struct.Connection.html#method.stream_recv
326//! [HTTP/3 module]: h3/index.html
327//!
328//! ## Congestion Control
329//!
330//! The quiche library provides a high-level API for configuring which
331//! congestion control algorithm to use throughout the QUIC connection.
332//!
333//! When a QUIC connection is created, the application can optionally choose
334//! which CC algorithm to use. See [`CongestionControlAlgorithm`] for currently
335//! available congestion control algorithms.
336//!
337//! For example:
338//!
339//! ```
340//! let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
341//! config.set_cc_algorithm(quiche::CongestionControlAlgorithm::Reno);
342//! ```
343//!
344//! Alternatively, you can configure the congestion control algorithm to use
345//! by its name.
346//!
347//! ```
348//! let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
349//! config.set_cc_algorithm_name("reno").unwrap();
350//! ```
351//!
352//! Note that the CC algorithm should be configured before calling [`connect()`]
353//! or [`accept()`]. Otherwise the connection will use a default CC algorithm.
354//!
355//! [`CongestionControlAlgorithm`]: enum.CongestionControlAlgorithm.html
356//!
357//! ## Feature flags
358//!
359//! quiche defines a number of [feature flags] to reduce the amount of compiled
360//! code and dependencies:
361//!
362//! * `boringssl-vendored` (default): Build the vendored BoringSSL library.
363//!
364//! * `boringssl-boring-crate`: Use the BoringSSL library provided by the
365//!   [boring] crate. It takes precedence over `boringssl-vendored` if both
366//!   features are enabled.
367//!
368//! * `pkg-config-meta`: Generate pkg-config metadata file for libquiche.
369//!
370//! * `ffi`: Build and expose the FFI API.
371//!
372//! * `qlog`: Enable support for the [qlog] logging format.
373//!
374//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section
375//! [boring]: https://crates.io/crates/boring
376//! [qlog]: https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-main-schema
377
378#![allow(clippy::upper_case_acronyms)]
379#![warn(missing_docs)]
380#![warn(unused_qualifications)]
381#![cfg_attr(docsrs, feature(doc_cfg))]
382
383#[macro_use]
384extern crate log;
385
386use std::cmp;
387
388use std::collections::VecDeque;
389
390use std::net::SocketAddr;
391
392use std::str::FromStr;
393
394use std::sync::Arc;
395
396use std::time::Duration;
397use std::time::Instant;
398
399#[cfg(feature = "qlog")]
400use qlog::events::connectivity::ConnectivityEventType;
401#[cfg(feature = "qlog")]
402use qlog::events::connectivity::TransportOwner;
403#[cfg(feature = "qlog")]
404use qlog::events::quic::RecoveryEventType;
405#[cfg(feature = "qlog")]
406use qlog::events::quic::TransportEventType;
407#[cfg(feature = "qlog")]
408use qlog::events::DataRecipient;
409#[cfg(feature = "qlog")]
410use qlog::events::Event;
411#[cfg(feature = "qlog")]
412use qlog::events::EventData;
413#[cfg(feature = "qlog")]
414use qlog::events::EventImportance;
415#[cfg(feature = "qlog")]
416use qlog::events::EventType;
417#[cfg(feature = "qlog")]
418use qlog::events::RawInfo;
419
420use smallvec::SmallVec;
421
422use crate::range_buf::DefaultBufFactory;
423
424use crate::recovery::OnAckReceivedOutcome;
425use crate::recovery::OnLossDetectionTimeoutOutcome;
426use crate::recovery::RecoveryOps;
427use crate::recovery::ReleaseDecision;
428
429use crate::stream::RecvAction;
430use crate::stream::StreamPriorityKey;
431
432/// The current QUIC wire version.
433pub const PROTOCOL_VERSION: u32 = PROTOCOL_VERSION_V1;
434
435/// Supported QUIC versions.
436const PROTOCOL_VERSION_V1: u32 = 0x0000_0001;
437
438/// The maximum length of a connection ID.
439pub const MAX_CONN_ID_LEN: usize = packet::MAX_CID_LEN as usize;
440
441/// The minimum length of Initial packets sent by a client.
442pub const MIN_CLIENT_INITIAL_LEN: usize = 1200;
443
444/// The default initial RTT.
445const DEFAULT_INITIAL_RTT: Duration = Duration::from_millis(333);
446
447const PAYLOAD_MIN_LEN: usize = 4;
448
449// PATH_CHALLENGE (9 bytes) + AEAD tag (16 bytes).
450const MIN_PROBING_SIZE: usize = 25;
451
452const MAX_AMPLIFICATION_FACTOR: usize = 3;
453
454// The maximum number of tracked packet number ranges that need to be acked.
455//
456// This represents more or less how many ack blocks can fit in a typical packet.
457const MAX_ACK_RANGES: usize = 68;
458
459// The highest possible stream ID allowed.
460const MAX_STREAM_ID: u64 = 1 << 60;
461
462// The default max_datagram_size used in congestion control.
463const MAX_SEND_UDP_PAYLOAD_SIZE: usize = 1200;
464
465// The default length of DATAGRAM queues.
466const DEFAULT_MAX_DGRAM_QUEUE_LEN: usize = 0;
467
468// The default length of PATH_CHALLENGE receive queue.
469const DEFAULT_MAX_PATH_CHALLENGE_RX_QUEUE_LEN: usize = 3;
470
471// The DATAGRAM standard recommends either none or 65536 as maximum DATAGRAM
472// frames size. We enforce the recommendation for forward compatibility.
473const MAX_DGRAM_FRAME_SIZE: u64 = 65536;
474
475// The length of the payload length field.
476const PAYLOAD_LENGTH_LEN: usize = 2;
477
478// The number of undecryptable that can be buffered.
479const MAX_UNDECRYPTABLE_PACKETS: usize = 10;
480
481const RESERVED_VERSION_MASK: u32 = 0xfafafafa;
482
483// The default size of the receiver connection flow control window.
484const DEFAULT_CONNECTION_WINDOW: u64 = 48 * 1024;
485
486// The maximum size of the receiver connection flow control window.
487const MAX_CONNECTION_WINDOW: u64 = 24 * 1024 * 1024;
488
489// How much larger the connection flow control window need to be larger than
490// the stream flow control window.
491const CONNECTION_WINDOW_FACTOR: f64 = 1.5;
492
493// How many probing packet timeouts do we tolerate before considering the path
494// validation as failed.
495const MAX_PROBING_TIMEOUTS: usize = 3;
496
497// The default initial congestion window size in terms of packet count.
498const DEFAULT_INITIAL_CONGESTION_WINDOW_PACKETS: usize = 10;
499
500// The maximum data offset that can be stored in a crypto stream.
501const MAX_CRYPTO_STREAM_OFFSET: u64 = 1 << 16;
502
503// The send capacity factor.
504const TX_CAP_FACTOR: f64 = 1.0;
505
506/// Ancillary information about incoming packets.
507#[derive(Clone, Copy, Debug, PartialEq, Eq)]
508pub struct RecvInfo {
509    /// The remote address the packet was received from.
510    pub from: SocketAddr,
511
512    /// The local address the packet was received on.
513    pub to: SocketAddr,
514}
515
516/// Ancillary information about outgoing packets.
517#[derive(Clone, Copy, Debug, PartialEq, Eq)]
518pub struct SendInfo {
519    /// The local address the packet should be sent from.
520    pub from: SocketAddr,
521
522    /// The remote address the packet should be sent to.
523    pub to: SocketAddr,
524
525    /// The time to send the packet out.
526    ///
527    /// See [Pacing] for more details.
528    ///
529    /// [Pacing]: index.html#pacing
530    pub at: Instant,
531}
532
533/// The side of the stream to be shut down.
534///
535/// This should be used when calling [`stream_shutdown()`].
536///
537/// [`stream_shutdown()`]: struct.Connection.html#method.stream_shutdown
538#[repr(C)]
539#[derive(PartialEq, Eq)]
540pub enum Shutdown {
541    /// Stop receiving stream data.
542    Read  = 0,
543
544    /// Stop sending stream data.
545    Write = 1,
546}
547
548/// Qlog logging level.
549#[repr(C)]
550#[cfg(feature = "qlog")]
551#[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
552pub enum QlogLevel {
553    /// Logs any events of Core importance.
554    Core  = 0,
555
556    /// Logs any events of Core and Base importance.
557    Base  = 1,
558
559    /// Logs any events of Core, Base and Extra importance
560    Extra = 2,
561}
562
563/// Stores configuration shared between multiple connections.
564pub struct Config {
565    local_transport_params: TransportParams,
566
567    version: u32,
568
569    tls_ctx: tls::Context,
570
571    application_protos: Vec<Vec<u8>>,
572
573    grease: bool,
574
575    cc_algorithm: CongestionControlAlgorithm,
576    custom_bbr_params: Option<BbrParams>,
577    initial_congestion_window_packets: usize,
578    enable_relaxed_loss_threshold: bool,
579
580    pmtud: bool,
581    pmtud_max_probes: u8,
582
583    hystart: bool,
584
585    pacing: bool,
586    /// Send rate limit in Mbps
587    max_pacing_rate: Option<u64>,
588
589    tx_cap_factor: f64,
590
591    dgram_recv_max_queue_len: usize,
592    dgram_send_max_queue_len: usize,
593
594    path_challenge_recv_max_queue_len: usize,
595
596    max_send_udp_payload_size: usize,
597
598    max_connection_window: u64,
599    max_stream_window: u64,
600
601    max_amplification_factor: usize,
602
603    disable_dcid_reuse: bool,
604
605    track_unknown_transport_params: Option<usize>,
606
607    initial_rtt: Duration,
608}
609
610// See https://quicwg.org/base-drafts/rfc9000.html#section-15
611fn is_reserved_version(version: u32) -> bool {
612    version & RESERVED_VERSION_MASK == version
613}
614
615impl Config {
616    /// Creates a config object with the given version.
617    ///
618    /// ## Examples:
619    ///
620    /// ```
621    /// let config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
622    /// # Ok::<(), quiche::Error>(())
623    /// ```
624    pub fn new(version: u32) -> Result<Config> {
625        Self::with_tls_ctx(version, tls::Context::new()?)
626    }
627
628    /// Creates a config object with the given version and
629    /// [`SslContextBuilder`].
630    ///
631    /// This is useful for applications that wish to manually configure
632    /// [`SslContextBuilder`].
633    ///
634    /// [`SslContextBuilder`]: https://docs.rs/boring/latest/boring/ssl/struct.SslContextBuilder.html
635    #[cfg(feature = "boringssl-boring-crate")]
636    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
637    pub fn with_boring_ssl_ctx_builder(
638        version: u32, tls_ctx_builder: boring::ssl::SslContextBuilder,
639    ) -> Result<Config> {
640        Self::with_tls_ctx(version, tls::Context::from_boring(tls_ctx_builder))
641    }
642
643    fn with_tls_ctx(version: u32, tls_ctx: tls::Context) -> Result<Config> {
644        if !is_reserved_version(version) && !version_is_supported(version) {
645            return Err(Error::UnknownVersion);
646        }
647
648        Ok(Config {
649            local_transport_params: TransportParams::default(),
650            version,
651            tls_ctx,
652            application_protos: Vec::new(),
653            grease: true,
654            cc_algorithm: CongestionControlAlgorithm::CUBIC,
655            custom_bbr_params: None,
656            initial_congestion_window_packets:
657                DEFAULT_INITIAL_CONGESTION_WINDOW_PACKETS,
658            enable_relaxed_loss_threshold: false,
659            pmtud: false,
660            pmtud_max_probes: pmtud::MAX_PROBES_DEFAULT,
661            hystart: true,
662            pacing: true,
663            max_pacing_rate: None,
664
665            tx_cap_factor: TX_CAP_FACTOR,
666
667            dgram_recv_max_queue_len: DEFAULT_MAX_DGRAM_QUEUE_LEN,
668            dgram_send_max_queue_len: DEFAULT_MAX_DGRAM_QUEUE_LEN,
669
670            path_challenge_recv_max_queue_len:
671                DEFAULT_MAX_PATH_CHALLENGE_RX_QUEUE_LEN,
672
673            max_send_udp_payload_size: MAX_SEND_UDP_PAYLOAD_SIZE,
674
675            max_connection_window: MAX_CONNECTION_WINDOW,
676            max_stream_window: stream::MAX_STREAM_WINDOW,
677
678            max_amplification_factor: MAX_AMPLIFICATION_FACTOR,
679
680            disable_dcid_reuse: false,
681
682            track_unknown_transport_params: None,
683            initial_rtt: DEFAULT_INITIAL_RTT,
684        })
685    }
686
687    /// Configures the given certificate chain.
688    ///
689    /// The content of `file` is parsed as a PEM-encoded leaf certificate,
690    /// followed by optional intermediate certificates.
691    ///
692    /// ## Examples:
693    ///
694    /// ```no_run
695    /// # let mut config = quiche::Config::new(0xbabababa)?;
696    /// config.load_cert_chain_from_pem_file("/path/to/cert.pem")?;
697    /// # Ok::<(), quiche::Error>(())
698    /// ```
699    pub fn load_cert_chain_from_pem_file(&mut self, file: &str) -> Result<()> {
700        self.tls_ctx.use_certificate_chain_file(file)
701    }
702
703    /// Configures the given private key.
704    ///
705    /// The content of `file` is parsed as a PEM-encoded private key.
706    ///
707    /// ## Examples:
708    ///
709    /// ```no_run
710    /// # let mut config = quiche::Config::new(0xbabababa)?;
711    /// config.load_priv_key_from_pem_file("/path/to/key.pem")?;
712    /// # Ok::<(), quiche::Error>(())
713    /// ```
714    pub fn load_priv_key_from_pem_file(&mut self, file: &str) -> Result<()> {
715        self.tls_ctx.use_privkey_file(file)
716    }
717
718    /// Specifies a file where trusted CA certificates are stored for the
719    /// purposes of certificate verification.
720    ///
721    /// The content of `file` is parsed as a PEM-encoded certificate chain.
722    ///
723    /// ## Examples:
724    ///
725    /// ```no_run
726    /// # let mut config = quiche::Config::new(0xbabababa)?;
727    /// config.load_verify_locations_from_file("/path/to/cert.pem")?;
728    /// # Ok::<(), quiche::Error>(())
729    /// ```
730    pub fn load_verify_locations_from_file(&mut self, file: &str) -> Result<()> {
731        self.tls_ctx.load_verify_locations_from_file(file)
732    }
733
734    /// Specifies a directory where trusted CA certificates are stored for the
735    /// purposes of certificate verification.
736    ///
737    /// The content of `dir` a set of PEM-encoded certificate chains.
738    ///
739    /// ## Examples:
740    ///
741    /// ```no_run
742    /// # let mut config = quiche::Config::new(0xbabababa)?;
743    /// config.load_verify_locations_from_directory("/path/to/certs")?;
744    /// # Ok::<(), quiche::Error>(())
745    /// ```
746    pub fn load_verify_locations_from_directory(
747        &mut self, dir: &str,
748    ) -> Result<()> {
749        self.tls_ctx.load_verify_locations_from_directory(dir)
750    }
751
752    /// Configures whether to verify the peer's certificate.
753    ///
754    /// This should usually be `true` for client-side connections and `false`
755    /// for server-side ones.
756    ///
757    /// Note that by default, no verification is performed.
758    ///
759    /// Also note that on the server-side, enabling verification of the peer
760    /// will trigger a certificate request and make authentication errors
761    /// fatal, but will still allow anonymous clients (i.e. clients that
762    /// don't present a certificate at all). Servers can check whether a
763    /// client presented a certificate by calling [`peer_cert()`] if they
764    /// need to.
765    ///
766    /// [`peer_cert()`]: struct.Connection.html#method.peer_cert
767    pub fn verify_peer(&mut self, verify: bool) {
768        self.tls_ctx.set_verify(verify);
769    }
770
771    /// Configures whether to do path MTU discovery.
772    ///
773    /// The default value is `false`.
774    pub fn discover_pmtu(&mut self, discover: bool) {
775        self.pmtud = discover;
776    }
777
778    /// Configures the maximum number of PMTUD probe attempts before treating
779    /// a probe size as failed.
780    ///
781    /// Defaults to 3 per [RFC 8899 Section 5.1.2](https://datatracker.ietf.org/doc/html/rfc8899#section-5.1.2).
782    /// If 0 is passed, the default value is used.
783    pub fn set_pmtud_max_probes(&mut self, max_probes: u8) {
784        self.pmtud_max_probes = max_probes;
785    }
786
787    /// Configures whether to send GREASE values.
788    ///
789    /// The default value is `true`.
790    pub fn grease(&mut self, grease: bool) {
791        self.grease = grease;
792    }
793
794    /// Enables logging of secrets.
795    ///
796    /// When logging is enabled, the [`set_keylog()`] method must be called on
797    /// the connection for its cryptographic secrets to be logged in the
798    /// [keylog] format to the specified writer.
799    ///
800    /// [`set_keylog()`]: struct.Connection.html#method.set_keylog
801    /// [keylog]: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
802    pub fn log_keys(&mut self) {
803        self.tls_ctx.enable_keylog();
804    }
805
806    /// Configures the session ticket key material.
807    ///
808    /// On the server this key will be used to encrypt and decrypt session
809    /// tickets, used to perform session resumption without server-side state.
810    ///
811    /// By default a key is generated internally, and rotated regularly, so
812    /// applications don't need to call this unless they need to use a
813    /// specific key (e.g. in order to support resumption across multiple
814    /// servers), in which case the application is also responsible for
815    /// rotating the key to provide forward secrecy.
816    pub fn set_ticket_key(&mut self, key: &[u8]) -> Result<()> {
817        self.tls_ctx.set_ticket_key(key)
818    }
819
820    /// Enables sending or receiving early data.
821    pub fn enable_early_data(&mut self) {
822        self.tls_ctx.set_early_data_enabled(true);
823    }
824
825    /// Configures the list of supported application protocols.
826    ///
827    /// On the client this configures the list of protocols to send to the
828    /// server as part of the ALPN extension.
829    ///
830    /// On the server this configures the list of supported protocols to match
831    /// against the client-supplied list.
832    ///
833    /// Applications must set a value, but no default is provided.
834    ///
835    /// ## Examples:
836    ///
837    /// ```
838    /// # let mut config = quiche::Config::new(0xbabababa)?;
839    /// config.set_application_protos(&[b"http/1.1", b"http/0.9"]);
840    /// # Ok::<(), quiche::Error>(())
841    /// ```
842    pub fn set_application_protos(
843        &mut self, protos_list: &[&[u8]],
844    ) -> Result<()> {
845        self.application_protos =
846            protos_list.iter().map(|s| s.to_vec()).collect();
847
848        self.tls_ctx.set_alpn(protos_list)
849    }
850
851    /// Configures the list of supported application protocols using wire
852    /// format.
853    ///
854    /// The list of protocols `protos` must be a series of non-empty, 8-bit
855    /// length-prefixed strings.
856    ///
857    /// See [`set_application_protos`](Self::set_application_protos) for more
858    /// background about application protocols.
859    ///
860    /// ## Examples:
861    ///
862    /// ```
863    /// # let mut config = quiche::Config::new(0xbabababa)?;
864    /// config.set_application_protos_wire_format(b"\x08http/1.1\x08http/0.9")?;
865    /// # Ok::<(), quiche::Error>(())
866    /// ```
867    pub fn set_application_protos_wire_format(
868        &mut self, protos: &[u8],
869    ) -> Result<()> {
870        let mut b = octets::Octets::with_slice(protos);
871
872        let mut protos_list = Vec::new();
873
874        while let Ok(proto) = b.get_bytes_with_u8_length() {
875            protos_list.push(proto.buf());
876        }
877
878        self.set_application_protos(&protos_list)
879    }
880
881    /// Sets the anti-amplification limit factor.
882    ///
883    /// The default value is `3`.
884    pub fn set_max_amplification_factor(&mut self, v: usize) {
885        self.max_amplification_factor = v;
886    }
887
888    /// Sets the send capacity factor.
889    ///
890    /// The default value is `1`.
891    pub fn set_send_capacity_factor(&mut self, v: f64) {
892        self.tx_cap_factor = v;
893    }
894
895    /// Sets the connection's initial RTT.
896    ///
897    /// The default value is `333`.
898    pub fn set_initial_rtt(&mut self, v: Duration) {
899        self.initial_rtt = v;
900    }
901
902    /// Sets the `max_idle_timeout` transport parameter, in milliseconds.
903    ///
904    /// The default value is infinite, that is, no timeout is used.
905    pub fn set_max_idle_timeout(&mut self, v: u64) {
906        self.local_transport_params.max_idle_timeout =
907            cmp::min(v, octets::MAX_VAR_INT);
908    }
909
910    /// Sets the `max_udp_payload_size transport` parameter.
911    ///
912    /// The default value is `65527`.
913    pub fn set_max_recv_udp_payload_size(&mut self, v: usize) {
914        self.local_transport_params.max_udp_payload_size =
915            cmp::min(v as u64, octets::MAX_VAR_INT);
916    }
917
918    /// Sets the maximum outgoing UDP payload size.
919    ///
920    /// The default and minimum value is `1200`.
921    pub fn set_max_send_udp_payload_size(&mut self, v: usize) {
922        self.max_send_udp_payload_size = cmp::max(v, MAX_SEND_UDP_PAYLOAD_SIZE);
923    }
924
925    /// Sets the `initial_max_data` transport parameter.
926    ///
927    /// When set to a non-zero value quiche will only allow at most `v` bytes of
928    /// incoming stream data to be buffered for the whole connection (that is,
929    /// data that is not yet read by the application) and will allow more data
930    /// to be received as the buffer is consumed by the application.
931    ///
932    /// When set to zero, either explicitly or via the default, quiche will not
933    /// give any flow control to the peer, preventing it from sending any stream
934    /// data.
935    ///
936    /// The default value is `0`.
937    pub fn set_initial_max_data(&mut self, v: u64) {
938        self.local_transport_params.initial_max_data =
939            cmp::min(v, octets::MAX_VAR_INT);
940    }
941
942    /// Sets the `initial_max_stream_data_bidi_local` transport parameter.
943    ///
944    /// When set to a non-zero value quiche will only allow at most `v` bytes
945    /// of incoming stream data to be buffered for each locally-initiated
946    /// bidirectional stream (that is, data that is not yet read by the
947    /// application) and will allow more data to be received as the buffer is
948    /// consumed by the application.
949    ///
950    /// When set to zero, either explicitly or via the default, quiche will not
951    /// give any flow control to the peer, preventing it from sending any stream
952    /// data.
953    ///
954    /// The default value is `0`.
955    pub fn set_initial_max_stream_data_bidi_local(&mut self, v: u64) {
956        self.local_transport_params
957            .initial_max_stream_data_bidi_local =
958            cmp::min(v, octets::MAX_VAR_INT);
959    }
960
961    /// Sets the `initial_max_stream_data_bidi_remote` transport parameter.
962    ///
963    /// When set to a non-zero value quiche will only allow at most `v` bytes
964    /// of incoming stream data to be buffered for each remotely-initiated
965    /// bidirectional stream (that is, data that is not yet read by the
966    /// application) and will allow more data to be received as the buffer is
967    /// consumed by the application.
968    ///
969    /// When set to zero, either explicitly or via the default, quiche will not
970    /// give any flow control to the peer, preventing it from sending any stream
971    /// data.
972    ///
973    /// The default value is `0`.
974    pub fn set_initial_max_stream_data_bidi_remote(&mut self, v: u64) {
975        self.local_transport_params
976            .initial_max_stream_data_bidi_remote =
977            cmp::min(v, octets::MAX_VAR_INT);
978    }
979
980    /// Sets the `initial_max_stream_data_uni` transport parameter.
981    ///
982    /// When set to a non-zero value quiche will only allow at most `v` bytes
983    /// of incoming stream data to be buffered for each unidirectional stream
984    /// (that is, data that is not yet read by the application) and will allow
985    /// more data to be received as the buffer is consumed by the application.
986    ///
987    /// When set to zero, either explicitly or via the default, quiche will not
988    /// give any flow control to the peer, preventing it from sending any stream
989    /// data.
990    ///
991    /// The default value is `0`.
992    pub fn set_initial_max_stream_data_uni(&mut self, v: u64) {
993        self.local_transport_params.initial_max_stream_data_uni =
994            cmp::min(v, octets::MAX_VAR_INT);
995    }
996
997    /// Sets the `initial_max_streams_bidi` transport parameter.
998    ///
999    /// When set to a non-zero value quiche will only allow `v` number of
1000    /// concurrent remotely-initiated bidirectional streams to be open at any
1001    /// given time and will increase the limit automatically as streams are
1002    /// completed.
1003    ///
1004    /// When set to zero, either explicitly or via the default, quiche will not
1005    /// not allow the peer to open any bidirectional streams.
1006    ///
1007    /// A bidirectional stream is considered completed when all incoming data
1008    /// has been read by the application (up to the `fin` offset) or the
1009    /// stream's read direction has been shutdown, and all outgoing data has
1010    /// been acked by the peer (up to the `fin` offset) or the stream's write
1011    /// direction has been shutdown.
1012    ///
1013    /// The default value is `0`.
1014    pub fn set_initial_max_streams_bidi(&mut self, v: u64) {
1015        self.local_transport_params.initial_max_streams_bidi =
1016            cmp::min(v, octets::MAX_VAR_INT);
1017    }
1018
1019    /// Sets the `initial_max_streams_uni` transport parameter.
1020    ///
1021    /// When set to a non-zero value quiche will only allow `v` number of
1022    /// concurrent remotely-initiated unidirectional streams to be open at any
1023    /// given time and will increase the limit automatically as streams are
1024    /// completed.
1025    ///
1026    /// When set to zero, either explicitly or via the default, quiche will not
1027    /// not allow the peer to open any unidirectional streams.
1028    ///
1029    /// A unidirectional stream is considered completed when all incoming data
1030    /// has been read by the application (up to the `fin` offset) or the
1031    /// stream's read direction has been shutdown.
1032    ///
1033    /// The default value is `0`.
1034    pub fn set_initial_max_streams_uni(&mut self, v: u64) {
1035        self.local_transport_params.initial_max_streams_uni =
1036            cmp::min(v, octets::MAX_VAR_INT);
1037    }
1038
1039    /// Sets the `ack_delay_exponent` transport parameter.
1040    ///
1041    /// The default value is `3`.
1042    pub fn set_ack_delay_exponent(&mut self, v: u64) {
1043        self.local_transport_params.ack_delay_exponent =
1044            cmp::min(v, octets::MAX_VAR_INT);
1045    }
1046
1047    /// Sets the `max_ack_delay` transport parameter.
1048    ///
1049    /// The default value is `25`.
1050    pub fn set_max_ack_delay(&mut self, v: u64) {
1051        self.local_transport_params.max_ack_delay =
1052            cmp::min(v, octets::MAX_VAR_INT);
1053    }
1054
1055    /// Sets the `active_connection_id_limit` transport parameter.
1056    ///
1057    /// The default value is `2`. Lower values will be ignored.
1058    pub fn set_active_connection_id_limit(&mut self, v: u64) {
1059        if v >= 2 {
1060            self.local_transport_params.active_conn_id_limit =
1061                cmp::min(v, octets::MAX_VAR_INT);
1062        }
1063    }
1064
1065    /// Sets the `disable_active_migration` transport parameter.
1066    ///
1067    /// The default value is `false`.
1068    pub fn set_disable_active_migration(&mut self, v: bool) {
1069        self.local_transport_params.disable_active_migration = v;
1070    }
1071
1072    /// Sets the congestion control algorithm used.
1073    ///
1074    /// The default value is `CongestionControlAlgorithm::CUBIC`.
1075    pub fn set_cc_algorithm(&mut self, algo: CongestionControlAlgorithm) {
1076        self.cc_algorithm = algo;
1077    }
1078
1079    /// Sets custom BBR settings.
1080    ///
1081    /// This API is experimental and will be removed in the future.
1082    ///
1083    /// Currently this only applies if cc_algorithm is
1084    /// `CongestionControlAlgorithm::Bbr2Gcongestion` is set.
1085    ///
1086    /// The default value is `None`.
1087    #[cfg(feature = "internal")]
1088    #[doc(hidden)]
1089    pub fn set_custom_bbr_params(&mut self, custom_bbr_settings: BbrParams) {
1090        self.custom_bbr_params = Some(custom_bbr_settings);
1091    }
1092
1093    /// Sets the congestion control algorithm used by string.
1094    ///
1095    /// The default value is `cubic`. On error `Error::CongestionControl`
1096    /// will be returned.
1097    ///
1098    /// ## Examples:
1099    ///
1100    /// ```
1101    /// # let mut config = quiche::Config::new(0xbabababa)?;
1102    /// config.set_cc_algorithm_name("reno");
1103    /// # Ok::<(), quiche::Error>(())
1104    /// ```
1105    pub fn set_cc_algorithm_name(&mut self, name: &str) -> Result<()> {
1106        self.cc_algorithm = CongestionControlAlgorithm::from_str(name)?;
1107
1108        Ok(())
1109    }
1110
1111    /// Sets initial congestion window size in terms of packet count.
1112    ///
1113    /// The default value is 10.
1114    pub fn set_initial_congestion_window_packets(&mut self, packets: usize) {
1115        self.initial_congestion_window_packets = packets;
1116    }
1117
1118    /// Configure whether to enable relaxed loss detection on spurious loss.
1119    ///
1120    /// The default value is false.
1121    pub fn set_enable_relaxed_loss_threshold(&mut self, enable: bool) {
1122        self.enable_relaxed_loss_threshold = enable;
1123    }
1124
1125    /// Configures whether to enable HyStart++.
1126    ///
1127    /// The default value is `true`.
1128    pub fn enable_hystart(&mut self, v: bool) {
1129        self.hystart = v;
1130    }
1131
1132    /// Configures whether to enable pacing.
1133    ///
1134    /// The default value is `true`.
1135    pub fn enable_pacing(&mut self, v: bool) {
1136        self.pacing = v;
1137    }
1138
1139    /// Sets the max value for pacing rate.
1140    ///
1141    /// By default pacing rate is not limited.
1142    pub fn set_max_pacing_rate(&mut self, v: u64) {
1143        self.max_pacing_rate = Some(v);
1144    }
1145
1146    /// Configures whether to enable receiving DATAGRAM frames.
1147    ///
1148    /// When enabled, the `max_datagram_frame_size` transport parameter is set
1149    /// to 65536 as recommended by draft-ietf-quic-datagram-01.
1150    ///
1151    /// The default is `false`.
1152    pub fn enable_dgram(
1153        &mut self, enabled: bool, recv_queue_len: usize, send_queue_len: usize,
1154    ) {
1155        self.local_transport_params.max_datagram_frame_size = if enabled {
1156            Some(MAX_DGRAM_FRAME_SIZE)
1157        } else {
1158            None
1159        };
1160        self.dgram_recv_max_queue_len = recv_queue_len;
1161        self.dgram_send_max_queue_len = send_queue_len;
1162    }
1163
1164    /// Configures the max number of queued received PATH_CHALLENGE frames.
1165    ///
1166    /// When an endpoint receives a PATH_CHALLENGE frame and the queue is full,
1167    /// the frame is discarded.
1168    ///
1169    /// The default is 3.
1170    pub fn set_path_challenge_recv_max_queue_len(&mut self, queue_len: usize) {
1171        self.path_challenge_recv_max_queue_len = queue_len;
1172    }
1173
1174    /// Sets the maximum size of the connection window.
1175    ///
1176    /// The default value is MAX_CONNECTION_WINDOW (24MBytes).
1177    pub fn set_max_connection_window(&mut self, v: u64) {
1178        self.max_connection_window = v;
1179    }
1180
1181    /// Sets the maximum size of the stream window.
1182    ///
1183    /// The default value is MAX_STREAM_WINDOW (16MBytes).
1184    pub fn set_max_stream_window(&mut self, v: u64) {
1185        self.max_stream_window = v;
1186    }
1187
1188    /// Sets the initial stateless reset token.
1189    ///
1190    /// This value is only advertised by servers. Setting a stateless retry
1191    /// token as a client has no effect on the connection.
1192    ///
1193    /// The default value is `None`.
1194    pub fn set_stateless_reset_token(&mut self, v: Option<u128>) {
1195        self.local_transport_params.stateless_reset_token = v;
1196    }
1197
1198    /// Sets whether the QUIC connection should avoid reusing DCIDs over
1199    /// different paths.
1200    ///
1201    /// When set to `true`, it ensures that a destination Connection ID is never
1202    /// reused on different paths. Such behaviour may lead to connection stall
1203    /// if the peer performs a non-voluntary migration (e.g., NAT rebinding) and
1204    /// does not provide additional destination Connection IDs to handle such
1205    /// event.
1206    ///
1207    /// The default value is `false`.
1208    pub fn set_disable_dcid_reuse(&mut self, v: bool) {
1209        self.disable_dcid_reuse = v;
1210    }
1211
1212    /// Enables tracking unknown transport parameters.
1213    ///
1214    /// Specify the maximum number of bytes used to track unknown transport
1215    /// parameters. The size includes the identifier and its value. If storing a
1216    /// transport parameter would cause the limit to be exceeded, it is quietly
1217    /// dropped.
1218    ///
1219    /// The default is that the feature is disabled.
1220    pub fn enable_track_unknown_transport_parameters(&mut self, size: usize) {
1221        self.track_unknown_transport_params = Some(size);
1222    }
1223}
1224
1225/// Tracks the health of the tx_buffered value.
1226#[derive(Clone, Copy, Debug, Default, PartialEq)]
1227pub enum TxBufferTrackingState {
1228    /// The send buffer is in a good state
1229    #[default]
1230    Ok,
1231    /// The send buffer is in an inconsistent state, which could lead to
1232    /// connection stalls or excess buffering due to bugs we haven't
1233    /// tracked down yet.
1234    Inconsistent,
1235}
1236
1237/// A QUIC connection.
1238pub struct Connection<F = DefaultBufFactory>
1239where
1240    F: BufFactory,
1241{
1242    /// QUIC wire version used for the connection.
1243    version: u32,
1244
1245    /// Connection Identifiers.
1246    ids: cid::ConnectionIdentifiers,
1247
1248    /// Unique opaque ID for the connection that can be used for logging.
1249    trace_id: String,
1250
1251    /// Packet number spaces.
1252    pkt_num_spaces: [packet::PktNumSpace; packet::Epoch::count()],
1253
1254    /// The crypto context.
1255    crypto_ctx: [packet::CryptoContext; packet::Epoch::count()],
1256
1257    /// Next packet number.
1258    next_pkt_num: u64,
1259
1260    // TODO
1261    // combine with `next_pkt_num`
1262    /// Track the packet skip context
1263    pkt_num_manager: packet::PktNumManager,
1264
1265    /// Peer's transport parameters.
1266    peer_transport_params: TransportParams,
1267
1268    /// If tracking unknown transport parameters from a peer, how much space to
1269    /// use in bytes.
1270    peer_transport_params_track_unknown: Option<usize>,
1271
1272    /// Local transport parameters.
1273    local_transport_params: TransportParams,
1274
1275    /// TLS handshake state.
1276    handshake: tls::Handshake,
1277
1278    /// Serialized TLS session buffer.
1279    ///
1280    /// This field is populated when a new session ticket is processed on the
1281    /// client. On the server this is empty.
1282    session: Option<Vec<u8>>,
1283
1284    /// The configuration for recovery.
1285    recovery_config: recovery::RecoveryConfig,
1286
1287    /// The path manager.
1288    paths: path::PathMap,
1289
1290    /// PATH_CHALLENGE receive queue max length.
1291    path_challenge_recv_max_queue_len: usize,
1292
1293    /// Total number of received PATH_CHALLENGE frames.
1294    path_challenge_rx_count: u64,
1295
1296    /// List of supported application protocols.
1297    application_protos: Vec<Vec<u8>>,
1298
1299    /// Total number of received packets.
1300    recv_count: usize,
1301
1302    /// Total number of sent packets.
1303    sent_count: usize,
1304
1305    /// Total number of lost packets.
1306    lost_count: usize,
1307
1308    /// Total number of lost packets that were later acked.
1309    spurious_lost_count: usize,
1310
1311    /// Total number of packets sent with data retransmitted.
1312    retrans_count: usize,
1313
1314    /// Total number of sent DATAGRAM frames.
1315    dgram_sent_count: usize,
1316
1317    /// Total number of received DATAGRAM frames.
1318    dgram_recv_count: usize,
1319
1320    /// Total number of bytes received from the peer.
1321    rx_data: u64,
1322
1323    /// Receiver flow controller.
1324    flow_control: flowcontrol::FlowControl,
1325
1326    /// Whether we send MAX_DATA frame.
1327    almost_full: bool,
1328
1329    /// Number of stream data bytes that can be buffered.
1330    tx_cap: usize,
1331
1332    /// The send capacity factor.
1333    tx_cap_factor: f64,
1334
1335    /// Number of bytes buffered in the send buffer.
1336    tx_buffered: usize,
1337
1338    /// Tracks the health of tx_buffered.
1339    tx_buffered_state: TxBufferTrackingState,
1340
1341    /// Total number of bytes sent to the peer.
1342    tx_data: u64,
1343
1344    /// Peer's flow control limit for the connection.
1345    max_tx_data: u64,
1346
1347    /// Last tx_data before running a full send() loop.
1348    last_tx_data: u64,
1349
1350    /// Total number of bytes retransmitted over the connection.
1351    /// This counts only STREAM and CRYPTO data.
1352    stream_retrans_bytes: u64,
1353
1354    /// Total number of bytes sent over the connection.
1355    sent_bytes: u64,
1356
1357    /// Total number of bytes received over the connection.
1358    recv_bytes: u64,
1359
1360    /// Total number of bytes sent acked over the connection.
1361    acked_bytes: u64,
1362
1363    /// Total number of bytes sent lost over the connection.
1364    lost_bytes: u64,
1365
1366    /// Streams map, indexed by stream ID.
1367    streams: stream::StreamMap<F>,
1368
1369    /// Peer's original destination connection ID. Used by the client to
1370    /// validate the server's transport parameter.
1371    odcid: Option<ConnectionId<'static>>,
1372
1373    /// Peer's retry source connection ID. Used by the client during stateless
1374    /// retry to validate the server's transport parameter.
1375    rscid: Option<ConnectionId<'static>>,
1376
1377    /// Received address verification token.
1378    token: Option<Vec<u8>>,
1379
1380    /// Error code and reason to be sent to the peer in a CONNECTION_CLOSE
1381    /// frame.
1382    local_error: Option<ConnectionError>,
1383
1384    /// Error code and reason received from the peer in a CONNECTION_CLOSE
1385    /// frame.
1386    peer_error: Option<ConnectionError>,
1387
1388    /// The connection-level limit at which send blocking occurred.
1389    blocked_limit: Option<u64>,
1390
1391    /// Idle timeout expiration time.
1392    idle_timer: Option<Instant>,
1393
1394    /// Draining timeout expiration time.
1395    draining_timer: Option<Instant>,
1396
1397    /// List of raw packets that were received before they could be decrypted.
1398    undecryptable_pkts: VecDeque<(Vec<u8>, RecvInfo)>,
1399
1400    /// The negotiated ALPN protocol.
1401    alpn: Vec<u8>,
1402
1403    /// Whether this is a server-side connection.
1404    is_server: bool,
1405
1406    /// Whether the initial secrets have been derived.
1407    derived_initial_secrets: bool,
1408
1409    /// Whether a version negotiation packet has already been received. Only
1410    /// relevant for client connections.
1411    did_version_negotiation: bool,
1412
1413    /// Whether stateless retry has been performed.
1414    did_retry: bool,
1415
1416    /// Whether the peer already updated its connection ID.
1417    got_peer_conn_id: bool,
1418
1419    /// Whether the peer verified our initial address.
1420    peer_verified_initial_address: bool,
1421
1422    /// Whether the peer's transport parameters were parsed.
1423    parsed_peer_transport_params: bool,
1424
1425    /// Whether the connection handshake has been completed.
1426    handshake_completed: bool,
1427
1428    /// Whether the HANDSHAKE_DONE frame has been sent.
1429    handshake_done_sent: bool,
1430
1431    /// Whether the HANDSHAKE_DONE frame has been acked.
1432    handshake_done_acked: bool,
1433
1434    /// Whether the connection handshake has been confirmed.
1435    handshake_confirmed: bool,
1436
1437    /// Key phase bit used for outgoing protected packets.
1438    key_phase: bool,
1439
1440    /// Whether an ack-eliciting packet has been sent since last receiving a
1441    /// packet.
1442    ack_eliciting_sent: bool,
1443
1444    /// Whether the connection is closed.
1445    closed: bool,
1446
1447    /// Whether the connection was timed out.
1448    timed_out: bool,
1449
1450    /// Whether to send GREASE.
1451    grease: bool,
1452
1453    /// TLS keylog writer.
1454    keylog: Option<Box<dyn std::io::Write + Send + Sync>>,
1455
1456    #[cfg(feature = "qlog")]
1457    qlog: QlogInfo,
1458
1459    /// DATAGRAM queues.
1460    dgram_recv_queue: dgram::DatagramQueue,
1461    dgram_send_queue: dgram::DatagramQueue,
1462
1463    /// Whether to emit DATAGRAM frames in the next packet.
1464    emit_dgram: bool,
1465
1466    /// Whether the connection should prevent from reusing destination
1467    /// Connection IDs when the peer migrates.
1468    disable_dcid_reuse: bool,
1469
1470    /// The number of streams reset by local.
1471    reset_stream_local_count: u64,
1472
1473    /// The number of streams stopped by local.
1474    stopped_stream_local_count: u64,
1475
1476    /// The number of streams reset by remote.
1477    reset_stream_remote_count: u64,
1478
1479    /// The number of streams stopped by remote.
1480    stopped_stream_remote_count: u64,
1481
1482    /// The number of DATA_BLOCKED frames sent due to hitting the connection
1483    /// flow control limit.
1484    data_blocked_sent_count: u64,
1485
1486    /// The number of STREAM_DATA_BLOCKED frames sent due to a stream hitting
1487    /// the stream flow control limit.
1488    stream_data_blocked_sent_count: u64,
1489
1490    /// The number of DATA_BLOCKED frames received from the remote endpoint.
1491    data_blocked_recv_count: u64,
1492
1493    /// The number of STREAM_DATA_BLOCKED frames received from the remote
1494    /// endpoint.
1495    stream_data_blocked_recv_count: u64,
1496
1497    /// The anti-amplification limit factor.
1498    max_amplification_factor: usize,
1499}
1500
1501/// Creates a new server-side connection.
1502///
1503/// The `scid` parameter represents the server's source connection ID, while
1504/// the optional `odcid` parameter represents the original destination ID the
1505/// client sent before a Retry packet (this is only required when using the
1506/// [`retry()`] function). See also the [`accept_with_retry()`] function for
1507/// more advanced retry cases.
1508///
1509/// [`retry()`]: fn.retry.html
1510///
1511/// ## Examples:
1512///
1513/// ```no_run
1514/// # let mut config = quiche::Config::new(0xbabababa)?;
1515/// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
1516/// # let local = "127.0.0.1:0".parse().unwrap();
1517/// # let peer = "127.0.0.1:1234".parse().unwrap();
1518/// let conn = quiche::accept(&scid, None, local, peer, &mut config)?;
1519/// # Ok::<(), quiche::Error>(())
1520/// ```
1521#[inline(always)]
1522pub fn accept(
1523    scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1524    peer: SocketAddr, config: &mut Config,
1525) -> Result<Connection> {
1526    accept_with_buf_factory(scid, odcid, local, peer, config)
1527}
1528
1529/// Creates a new server-side connection, with a custom buffer generation
1530/// method.
1531///
1532/// The buffers generated can be anything that can be drereferenced as a byte
1533/// slice. See [`accept`] and [`BufFactory`] for more info.
1534#[inline]
1535pub fn accept_with_buf_factory<F: BufFactory>(
1536    scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1537    peer: SocketAddr, config: &mut Config,
1538) -> Result<Connection<F>> {
1539    // For connections with `odcid` set, we historically used `retry_source_cid =
1540    // scid`. Keep this behavior to preserve backwards compatibility.
1541    // `accept_with_retry` allows the SCIDs to be specified separately.
1542    let retry_cids = odcid.map(|odcid| RetryConnectionIds {
1543        original_destination_cid: odcid,
1544        retry_source_cid: scid,
1545    });
1546
1547    Connection::new(scid, retry_cids, local, peer, config, true)
1548}
1549
1550/// A wrapper for connection IDs used in [`accept_with_retry`].
1551pub struct RetryConnectionIds<'a> {
1552    /// The DCID of the first Initial packet received by the server, which
1553    /// triggered the Retry packet.
1554    pub original_destination_cid: &'a ConnectionId<'a>,
1555    /// The SCID of the Retry packet sent by the server. This can be different
1556    /// from the new connection's SCID.
1557    pub retry_source_cid: &'a ConnectionId<'a>,
1558}
1559
1560/// Creates a new server-side connection after the client responded to a Retry
1561/// packet.
1562///
1563/// To generate a Retry packet in the first place, use the [`retry()`] function.
1564///
1565/// The `scid` parameter represents the server's source connection ID, which can
1566/// be freshly generated after the application has successfully verified the
1567/// Retry. `retry_cids` is used to tie the new connection to the Initial + Retry
1568/// exchange that preceded the connection's creation.
1569///
1570/// The DCID of the client's Initial packet is inherently untrusted data. It is
1571/// safe to use the DCID in the `retry_source_cid` field of the
1572/// `RetryConnectionIds` provided to this function. However, using the Initial's
1573/// DCID for the `scid` parameter carries risks. Applications are advised to
1574/// implement their own DCID validation steps before using the DCID in that
1575/// manner.
1576#[inline]
1577pub fn accept_with_retry<F: BufFactory>(
1578    scid: &ConnectionId, retry_cids: RetryConnectionIds, local: SocketAddr,
1579    peer: SocketAddr, config: &mut Config,
1580) -> Result<Connection<F>> {
1581    Connection::new(scid, Some(retry_cids), local, peer, config, true)
1582}
1583
1584/// Creates a new client-side connection.
1585///
1586/// The `scid` parameter is used as the connection's source connection ID,
1587/// while the optional `server_name` parameter is used to verify the peer's
1588/// certificate.
1589///
1590/// ## Examples:
1591///
1592/// ```no_run
1593/// # let mut config = quiche::Config::new(0xbabababa)?;
1594/// # let server_name = "quic.tech";
1595/// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
1596/// # let local = "127.0.0.1:4321".parse().unwrap();
1597/// # let peer = "127.0.0.1:1234".parse().unwrap();
1598/// let conn =
1599///     quiche::connect(Some(&server_name), &scid, local, peer, &mut config)?;
1600/// # Ok::<(), quiche::Error>(())
1601/// ```
1602#[inline]
1603pub fn connect(
1604    server_name: Option<&str>, scid: &ConnectionId, local: SocketAddr,
1605    peer: SocketAddr, config: &mut Config,
1606) -> Result<Connection> {
1607    let mut conn = Connection::new(scid, None, local, peer, config, false)?;
1608
1609    if let Some(server_name) = server_name {
1610        conn.handshake.set_host_name(server_name)?;
1611    }
1612
1613    Ok(conn)
1614}
1615
1616/// Creates a new client-side connection, with a custom buffer generation
1617/// method.
1618///
1619/// The buffers generated can be anything that can be drereferenced as a byte
1620/// slice. See [`connect`] and [`BufFactory`] for more info.
1621#[inline]
1622pub fn connect_with_buffer_factory<F: BufFactory>(
1623    server_name: Option<&str>, scid: &ConnectionId, local: SocketAddr,
1624    peer: SocketAddr, config: &mut Config,
1625) -> Result<Connection<F>> {
1626    let mut conn = Connection::new(scid, None, local, peer, config, false)?;
1627
1628    if let Some(server_name) = server_name {
1629        conn.handshake.set_host_name(server_name)?;
1630    }
1631
1632    Ok(conn)
1633}
1634
1635/// Writes a version negotiation packet.
1636///
1637/// The `scid` and `dcid` parameters are the source connection ID and the
1638/// destination connection ID extracted from the received client's Initial
1639/// packet that advertises an unsupported version.
1640///
1641/// ## Examples:
1642///
1643/// ```no_run
1644/// # let mut buf = [0; 512];
1645/// # let mut out = [0; 512];
1646/// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1647/// let (len, src) = socket.recv_from(&mut buf).unwrap();
1648///
1649/// let hdr =
1650///     quiche::Header::from_slice(&mut buf[..len], quiche::MAX_CONN_ID_LEN)?;
1651///
1652/// if hdr.version != quiche::PROTOCOL_VERSION {
1653///     let len = quiche::negotiate_version(&hdr.scid, &hdr.dcid, &mut out)?;
1654///     socket.send_to(&out[..len], &src).unwrap();
1655/// }
1656/// # Ok::<(), quiche::Error>(())
1657/// ```
1658#[inline]
1659pub fn negotiate_version(
1660    scid: &ConnectionId, dcid: &ConnectionId, out: &mut [u8],
1661) -> Result<usize> {
1662    packet::negotiate_version(scid, dcid, out)
1663}
1664
1665/// Writes a stateless retry packet.
1666///
1667/// The `scid` and `dcid` parameters are the source connection ID and the
1668/// destination connection ID extracted from the received client's Initial
1669/// packet, while `new_scid` is the server's new source connection ID and
1670/// `token` is the address validation token the client needs to echo back.
1671///
1672/// The application is responsible for generating the address validation
1673/// token to be sent to the client, and verifying tokens sent back by the
1674/// client. The generated token should include the `dcid` parameter, such
1675/// that it can be later extracted from the token and passed to the
1676/// [`accept()`] function as its `odcid` parameter.
1677///
1678/// [`accept()`]: fn.accept.html
1679///
1680/// ## Examples:
1681///
1682/// ```no_run
1683/// # let mut config = quiche::Config::new(0xbabababa)?;
1684/// # let mut buf = [0; 512];
1685/// # let mut out = [0; 512];
1686/// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
1687/// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1688/// # let local = socket.local_addr().unwrap();
1689/// # fn mint_token(hdr: &quiche::Header, src: &std::net::SocketAddr) -> Vec<u8> {
1690/// #     vec![]
1691/// # }
1692/// # fn validate_token<'a>(src: &std::net::SocketAddr, token: &'a [u8]) -> Option<quiche::ConnectionId<'a>> {
1693/// #     None
1694/// # }
1695/// let (len, peer) = socket.recv_from(&mut buf).unwrap();
1696///
1697/// let hdr = quiche::Header::from_slice(&mut buf[..len], quiche::MAX_CONN_ID_LEN)?;
1698///
1699/// let token = hdr.token.as_ref().unwrap();
1700///
1701/// // No token sent by client, create a new one.
1702/// if token.is_empty() {
1703///     let new_token = mint_token(&hdr, &peer);
1704///
1705///     let len = quiche::retry(
1706///         &hdr.scid, &hdr.dcid, &scid, &new_token, hdr.version, &mut out,
1707///     )?;
1708///
1709///     socket.send_to(&out[..len], &peer).unwrap();
1710///     return Ok(());
1711/// }
1712///
1713/// // Client sent token, validate it.
1714/// let odcid = validate_token(&peer, token);
1715///
1716/// if odcid.is_none() {
1717///     // Invalid address validation token.
1718///     return Ok(());
1719/// }
1720///
1721/// let conn = quiche::accept(&scid, odcid.as_ref(), local, peer, &mut config)?;
1722/// # Ok::<(), quiche::Error>(())
1723/// ```
1724#[inline]
1725pub fn retry(
1726    scid: &ConnectionId, dcid: &ConnectionId, new_scid: &ConnectionId,
1727    token: &[u8], version: u32, out: &mut [u8],
1728) -> Result<usize> {
1729    packet::retry(scid, dcid, new_scid, token, version, out)
1730}
1731
1732/// Returns true if the given protocol version is supported.
1733#[inline]
1734pub fn version_is_supported(version: u32) -> bool {
1735    matches!(version, PROTOCOL_VERSION_V1)
1736}
1737
1738/// Pushes a frame to the output packet if there is enough space.
1739///
1740/// Returns `true` on success, `false` otherwise. In case of failure it means
1741/// there is no room to add the frame in the packet. You may retry to add the
1742/// frame later.
1743macro_rules! push_frame_to_pkt {
1744    ($out:expr, $frames:expr, $frame:expr, $left:expr) => {{
1745        if $frame.wire_len() <= $left {
1746            $left -= $frame.wire_len();
1747
1748            $frame.to_bytes(&mut $out)?;
1749
1750            $frames.push($frame);
1751
1752            true
1753        } else {
1754            false
1755        }
1756    }};
1757}
1758
1759/// Executes the provided body if the qlog feature is enabled, quiche has been
1760/// configured with a log writer, the event's importance is within the
1761/// configured level.
1762macro_rules! qlog_with_type {
1763    ($ty:expr, $qlog:expr, $qlog_streamer_ref:ident, $body:block) => {{
1764        #[cfg(feature = "qlog")]
1765        {
1766            if EventImportance::from($ty).is_contained_in(&$qlog.level) {
1767                if let Some($qlog_streamer_ref) = &mut $qlog.streamer {
1768                    $body
1769                }
1770            }
1771        }
1772    }};
1773}
1774
1775#[cfg(feature = "qlog")]
1776const QLOG_PARAMS_SET: EventType =
1777    EventType::TransportEventType(TransportEventType::ParametersSet);
1778
1779#[cfg(feature = "qlog")]
1780const QLOG_PACKET_RX: EventType =
1781    EventType::TransportEventType(TransportEventType::PacketReceived);
1782
1783#[cfg(feature = "qlog")]
1784const QLOG_PACKET_TX: EventType =
1785    EventType::TransportEventType(TransportEventType::PacketSent);
1786
1787#[cfg(feature = "qlog")]
1788const QLOG_DATA_MV: EventType =
1789    EventType::TransportEventType(TransportEventType::DataMoved);
1790
1791#[cfg(feature = "qlog")]
1792const QLOG_METRICS: EventType =
1793    EventType::RecoveryEventType(RecoveryEventType::MetricsUpdated);
1794
1795#[cfg(feature = "qlog")]
1796const QLOG_CONNECTION_CLOSED: EventType =
1797    EventType::ConnectivityEventType(ConnectivityEventType::ConnectionClosed);
1798
1799#[cfg(feature = "qlog")]
1800struct QlogInfo {
1801    streamer: Option<qlog::streamer::QlogStreamer>,
1802    logged_peer_params: bool,
1803    level: EventImportance,
1804}
1805
1806#[cfg(feature = "qlog")]
1807impl Default for QlogInfo {
1808    fn default() -> Self {
1809        QlogInfo {
1810            streamer: None,
1811            logged_peer_params: false,
1812            level: EventImportance::Base,
1813        }
1814    }
1815}
1816
1817impl<F: BufFactory> Connection<F> {
1818    fn new(
1819        scid: &ConnectionId, retry_cids: Option<RetryConnectionIds>,
1820        local: SocketAddr, peer: SocketAddr, config: &mut Config,
1821        is_server: bool,
1822    ) -> Result<Connection<F>> {
1823        let tls = config.tls_ctx.new_handshake()?;
1824        Connection::with_tls(
1825            scid, retry_cids, local, peer, config, tls, is_server,
1826        )
1827    }
1828
1829    fn with_tls(
1830        scid: &ConnectionId, retry_cids: Option<RetryConnectionIds>,
1831        local: SocketAddr, peer: SocketAddr, config: &Config,
1832        tls: tls::Handshake, is_server: bool,
1833    ) -> Result<Connection<F>> {
1834        let max_rx_data = config.local_transport_params.initial_max_data;
1835
1836        let scid_as_hex: Vec<String> =
1837            scid.iter().map(|b| format!("{b:02x}")).collect();
1838
1839        let reset_token = if is_server {
1840            config.local_transport_params.stateless_reset_token
1841        } else {
1842            None
1843        };
1844
1845        let recovery_config = recovery::RecoveryConfig::from_config(config);
1846
1847        let mut path = path::Path::new(
1848            local,
1849            peer,
1850            &recovery_config,
1851            config.path_challenge_recv_max_queue_len,
1852            true,
1853            Some(config),
1854        );
1855
1856        // If we sent a Retry assume the peer's address is verified.
1857        path.verified_peer_address = retry_cids.is_some();
1858        // Assume clients validate the server's address implicitly.
1859        path.peer_verified_local_address = is_server;
1860
1861        // Do not allocate more than the number of active CIDs.
1862        let paths = path::PathMap::new(
1863            path,
1864            config.local_transport_params.active_conn_id_limit as usize,
1865            is_server,
1866        );
1867
1868        let active_path_id = paths.get_active_path_id()?;
1869
1870        let ids = cid::ConnectionIdentifiers::new(
1871            config.local_transport_params.active_conn_id_limit as usize,
1872            scid,
1873            active_path_id,
1874            reset_token,
1875        );
1876
1877        let mut conn = Connection {
1878            version: config.version,
1879
1880            ids,
1881
1882            trace_id: scid_as_hex.join(""),
1883
1884            pkt_num_spaces: [
1885                packet::PktNumSpace::new(),
1886                packet::PktNumSpace::new(),
1887                packet::PktNumSpace::new(),
1888            ],
1889
1890            crypto_ctx: [
1891                packet::CryptoContext::new(),
1892                packet::CryptoContext::new(),
1893                packet::CryptoContext::new(),
1894            ],
1895
1896            next_pkt_num: 0,
1897
1898            pkt_num_manager: packet::PktNumManager::new(),
1899
1900            peer_transport_params: TransportParams::default(),
1901
1902            peer_transport_params_track_unknown: config
1903                .track_unknown_transport_params,
1904
1905            local_transport_params: config.local_transport_params.clone(),
1906
1907            handshake: tls,
1908
1909            session: None,
1910
1911            recovery_config,
1912
1913            paths,
1914            path_challenge_recv_max_queue_len: config
1915                .path_challenge_recv_max_queue_len,
1916            path_challenge_rx_count: 0,
1917
1918            application_protos: config.application_protos.clone(),
1919
1920            recv_count: 0,
1921            sent_count: 0,
1922            lost_count: 0,
1923            spurious_lost_count: 0,
1924            retrans_count: 0,
1925            dgram_sent_count: 0,
1926            dgram_recv_count: 0,
1927            sent_bytes: 0,
1928            recv_bytes: 0,
1929            acked_bytes: 0,
1930            lost_bytes: 0,
1931
1932            rx_data: 0,
1933            flow_control: flowcontrol::FlowControl::new(
1934                max_rx_data,
1935                cmp::min(max_rx_data / 2 * 3, DEFAULT_CONNECTION_WINDOW),
1936                config.max_connection_window,
1937            ),
1938            almost_full: false,
1939
1940            tx_cap: 0,
1941            tx_cap_factor: config.tx_cap_factor,
1942
1943            tx_buffered: 0,
1944            tx_buffered_state: TxBufferTrackingState::Ok,
1945
1946            tx_data: 0,
1947            max_tx_data: 0,
1948            last_tx_data: 0,
1949
1950            stream_retrans_bytes: 0,
1951
1952            streams: stream::StreamMap::new(
1953                config.local_transport_params.initial_max_streams_bidi,
1954                config.local_transport_params.initial_max_streams_uni,
1955                config.max_stream_window,
1956            ),
1957
1958            odcid: None,
1959
1960            rscid: None,
1961
1962            token: None,
1963
1964            local_error: None,
1965
1966            peer_error: None,
1967
1968            blocked_limit: None,
1969
1970            idle_timer: None,
1971
1972            draining_timer: None,
1973
1974            undecryptable_pkts: VecDeque::new(),
1975
1976            alpn: Vec::new(),
1977
1978            is_server,
1979
1980            derived_initial_secrets: false,
1981
1982            did_version_negotiation: false,
1983
1984            did_retry: false,
1985
1986            got_peer_conn_id: false,
1987
1988            // Assume clients validate the server's address implicitly.
1989            peer_verified_initial_address: is_server,
1990
1991            parsed_peer_transport_params: false,
1992
1993            handshake_completed: false,
1994
1995            handshake_done_sent: false,
1996            handshake_done_acked: false,
1997
1998            handshake_confirmed: false,
1999
2000            key_phase: false,
2001
2002            ack_eliciting_sent: false,
2003
2004            closed: false,
2005
2006            timed_out: false,
2007
2008            grease: config.grease,
2009
2010            keylog: None,
2011
2012            #[cfg(feature = "qlog")]
2013            qlog: Default::default(),
2014
2015            dgram_recv_queue: dgram::DatagramQueue::new(
2016                config.dgram_recv_max_queue_len,
2017            ),
2018
2019            dgram_send_queue: dgram::DatagramQueue::new(
2020                config.dgram_send_max_queue_len,
2021            ),
2022
2023            emit_dgram: true,
2024
2025            disable_dcid_reuse: config.disable_dcid_reuse,
2026
2027            reset_stream_local_count: 0,
2028            stopped_stream_local_count: 0,
2029            reset_stream_remote_count: 0,
2030            stopped_stream_remote_count: 0,
2031
2032            data_blocked_sent_count: 0,
2033            stream_data_blocked_sent_count: 0,
2034            data_blocked_recv_count: 0,
2035            stream_data_blocked_recv_count: 0,
2036
2037            max_amplification_factor: config.max_amplification_factor,
2038        };
2039
2040        if let Some(retry_cids) = retry_cids {
2041            conn.local_transport_params
2042                .original_destination_connection_id =
2043                Some(retry_cids.original_destination_cid.to_vec().into());
2044
2045            conn.local_transport_params.retry_source_connection_id =
2046                Some(retry_cids.retry_source_cid.to_vec().into());
2047
2048            conn.did_retry = true;
2049        }
2050
2051        conn.local_transport_params.initial_source_connection_id =
2052            Some(conn.ids.get_scid(0)?.cid.to_vec().into());
2053
2054        conn.handshake.init(is_server)?;
2055
2056        conn.handshake
2057            .use_legacy_codepoint(config.version != PROTOCOL_VERSION_V1);
2058
2059        conn.encode_transport_params()?;
2060
2061        // Derive initial secrets for the client. We can do this here because
2062        // we already generated the random destination connection ID.
2063        if !is_server {
2064            let mut dcid = [0; 16];
2065            rand::rand_bytes(&mut dcid[..]);
2066
2067            let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2068                &dcid,
2069                conn.version,
2070                conn.is_server,
2071                false,
2072            )?;
2073
2074            let reset_token = conn.peer_transport_params.stateless_reset_token;
2075            conn.set_initial_dcid(
2076                dcid.to_vec().into(),
2077                reset_token,
2078                active_path_id,
2079            )?;
2080
2081            conn.crypto_ctx[packet::Epoch::Initial].crypto_open = Some(aead_open);
2082            conn.crypto_ctx[packet::Epoch::Initial].crypto_seal = Some(aead_seal);
2083
2084            conn.derived_initial_secrets = true;
2085        }
2086
2087        Ok(conn)
2088    }
2089
2090    /// Sets keylog output to the designated [`Writer`].
2091    ///
2092    /// This needs to be called as soon as the connection is created, to avoid
2093    /// missing some early logs.
2094    ///
2095    /// [`Writer`]: https://doc.rust-lang.org/std/io/trait.Write.html
2096    #[inline]
2097    pub fn set_keylog(&mut self, writer: Box<dyn std::io::Write + Send + Sync>) {
2098        self.keylog = Some(writer);
2099    }
2100
2101    /// Sets qlog output to the designated [`Writer`].
2102    ///
2103    /// Only events included in `QlogLevel::Base` are written. The serialization
2104    /// format is JSON-SEQ.
2105    ///
2106    /// This needs to be called as soon as the connection is created, to avoid
2107    /// missing some early logs.
2108    ///
2109    /// [`Writer`]: https://doc.rust-lang.org/std/io/trait.Write.html
2110    #[cfg(feature = "qlog")]
2111    #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
2112    pub fn set_qlog(
2113        &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String,
2114        description: String,
2115    ) {
2116        self.set_qlog_with_level(writer, title, description, QlogLevel::Base)
2117    }
2118
2119    /// Sets qlog output to the designated [`Writer`].
2120    ///
2121    /// Only qlog events included in the specified `QlogLevel` are written. The
2122    /// serialization format is JSON-SEQ.
2123    ///
2124    /// This needs to be called as soon as the connection is created, to avoid
2125    /// missing some early logs.
2126    ///
2127    /// [`Writer`]: https://doc.rust-lang.org/std/io/trait.Write.html
2128    #[cfg(feature = "qlog")]
2129    #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
2130    pub fn set_qlog_with_level(
2131        &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String,
2132        description: String, qlog_level: QlogLevel,
2133    ) {
2134        let vp = if self.is_server {
2135            qlog::VantagePointType::Server
2136        } else {
2137            qlog::VantagePointType::Client
2138        };
2139
2140        let level = match qlog_level {
2141            QlogLevel::Core => EventImportance::Core,
2142
2143            QlogLevel::Base => EventImportance::Base,
2144
2145            QlogLevel::Extra => EventImportance::Extra,
2146        };
2147
2148        self.qlog.level = level;
2149
2150        let trace = qlog::TraceSeq::new(
2151            qlog::VantagePoint {
2152                name: None,
2153                ty: vp,
2154                flow: None,
2155            },
2156            Some(title.to_string()),
2157            Some(description.to_string()),
2158            Some(qlog::Configuration {
2159                time_offset: Some(0.0),
2160                original_uris: None,
2161            }),
2162            None,
2163        );
2164
2165        let mut streamer = qlog::streamer::QlogStreamer::new(
2166            qlog::QLOG_VERSION.to_string(),
2167            Some(title),
2168            Some(description),
2169            None,
2170            Instant::now(),
2171            trace,
2172            self.qlog.level,
2173            writer,
2174        );
2175
2176        streamer.start_log().ok();
2177
2178        let ev_data = self
2179            .local_transport_params
2180            .to_qlog(TransportOwner::Local, self.handshake.cipher());
2181
2182        // This event occurs very early, so just mark the relative time as 0.0.
2183        streamer.add_event(Event::with_time(0.0, ev_data)).ok();
2184
2185        self.qlog.streamer = Some(streamer);
2186    }
2187
2188    /// Returns a mutable reference to the QlogStreamer, if it exists.
2189    #[cfg(feature = "qlog")]
2190    #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
2191    pub fn qlog_streamer(&mut self) -> Option<&mut qlog::streamer::QlogStreamer> {
2192        self.qlog.streamer.as_mut()
2193    }
2194
2195    /// Configures the given session for resumption.
2196    ///
2197    /// On the client, this can be used to offer the given serialized session,
2198    /// as returned by [`session()`], for resumption.
2199    ///
2200    /// This must only be called immediately after creating a connection, that
2201    /// is, before any packet is sent or received.
2202    ///
2203    /// [`session()`]: struct.Connection.html#method.session
2204    #[inline]
2205    pub fn set_session(&mut self, session: &[u8]) -> Result<()> {
2206        let mut b = octets::Octets::with_slice(session);
2207
2208        let session_len = b.get_u64()? as usize;
2209        let session_bytes = b.get_bytes(session_len)?;
2210
2211        self.handshake.set_session(session_bytes.as_ref())?;
2212
2213        let raw_params_len = b.get_u64()? as usize;
2214        let raw_params_bytes = b.get_bytes(raw_params_len)?;
2215
2216        let peer_params = TransportParams::decode(
2217            raw_params_bytes.as_ref(),
2218            self.is_server,
2219            self.peer_transport_params_track_unknown,
2220        )?;
2221
2222        self.process_peer_transport_params(peer_params)?;
2223
2224        Ok(())
2225    }
2226
2227    /// Sets the `max_idle_timeout` transport parameter, in milliseconds.
2228    ///
2229    /// This must only be called immediately after creating a connection, that
2230    /// is, before any packet is sent or received.
2231    ///
2232    /// The default value is infinite, that is, no timeout is used unless
2233    /// already configured when creating the connection.
2234    pub fn set_max_idle_timeout(&mut self, v: u64) -> Result<()> {
2235        self.local_transport_params.max_idle_timeout =
2236            cmp::min(v, octets::MAX_VAR_INT);
2237
2238        self.encode_transport_params()
2239    }
2240
2241    /// Sets the congestion control algorithm used.
2242    ///
2243    /// This function can only be called inside one of BoringSSL's handshake
2244    /// callbacks, before any packet has been sent. Calling this function any
2245    /// other time will have no effect.
2246    ///
2247    /// See [`Config::set_cc_algorithm()`].
2248    ///
2249    /// [`Config::set_cc_algorithm()`]: struct.Config.html#method.set_cc_algorithm
2250    #[cfg(feature = "boringssl-boring-crate")]
2251    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2252    pub fn set_cc_algorithm_in_handshake(
2253        ssl: &mut boring::ssl::SslRef, algo: CongestionControlAlgorithm,
2254    ) -> Result<()> {
2255        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2256
2257        ex_data.recovery_config.cc_algorithm = algo;
2258
2259        Ok(())
2260    }
2261
2262    /// Sets custom BBR settings.
2263    ///
2264    /// This API is experimental and will be removed in the future.
2265    ///
2266    /// Currently this only applies if cc_algorithm is
2267    /// `CongestionControlAlgorithm::Bbr2Gcongestion` is set.
2268    ///
2269    /// This function can only be called inside one of BoringSSL's handshake
2270    /// callbacks, before any packet has been sent. Calling this function any
2271    /// other time will have no effect.
2272    ///
2273    /// See [`Config::set_custom_bbr_settings()`].
2274    ///
2275    /// [`Config::set_custom_bbr_settings()`]: struct.Config.html#method.set_custom_bbr_settings
2276    #[cfg(all(feature = "boringssl-boring-crate", feature = "internal"))]
2277    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2278    #[doc(hidden)]
2279    pub fn set_custom_bbr_settings_in_handshake(
2280        ssl: &mut boring::ssl::SslRef, custom_bbr_params: BbrParams,
2281    ) -> Result<()> {
2282        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2283
2284        ex_data.recovery_config.custom_bbr_params = Some(custom_bbr_params);
2285
2286        Ok(())
2287    }
2288
2289    /// Sets the congestion control algorithm used by string.
2290    ///
2291    /// This function can only be called inside one of BoringSSL's handshake
2292    /// callbacks, before any packet has been sent. Calling this function any
2293    /// other time will have no effect.
2294    ///
2295    /// See [`Config::set_cc_algorithm_name()`].
2296    ///
2297    /// [`Config::set_cc_algorithm_name()`]: struct.Config.html#method.set_cc_algorithm_name
2298    #[cfg(feature = "boringssl-boring-crate")]
2299    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2300    pub fn set_cc_algorithm_name_in_handshake(
2301        ssl: &mut boring::ssl::SslRef, name: &str,
2302    ) -> Result<()> {
2303        let cc_algo = CongestionControlAlgorithm::from_str(name)?;
2304        Self::set_cc_algorithm_in_handshake(ssl, cc_algo)
2305    }
2306
2307    /// Sets initial congestion window size in terms of packet count.
2308    ///
2309    /// This function can only be called inside one of BoringSSL's handshake
2310    /// callbacks, before any packet has been sent. Calling this function any
2311    /// other time will have no effect.
2312    ///
2313    /// See [`Config::set_initial_congestion_window_packets()`].
2314    ///
2315    /// [`Config::set_initial_congestion_window_packets()`]: struct.Config.html#method.set_initial_congestion_window_packets
2316    #[cfg(feature = "boringssl-boring-crate")]
2317    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2318    pub fn set_initial_congestion_window_packets_in_handshake(
2319        ssl: &mut boring::ssl::SslRef, packets: usize,
2320    ) -> Result<()> {
2321        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2322
2323        ex_data.recovery_config.initial_congestion_window_packets = packets;
2324
2325        Ok(())
2326    }
2327
2328    /// Configure whether to enable relaxed loss detection on spurious loss.
2329    ///
2330    /// This function can only be called inside one of BoringSSL's handshake
2331    /// callbacks, before any packet has been sent. Calling this function any
2332    /// other time will have no effect.
2333    ///
2334    /// See [`Config::set_enable_relaxed_loss_threshold()`].
2335    ///
2336    /// [`Config::set_enable_relaxed_loss_threshold()`]: struct.Config.html#method.set_enable_relaxed_loss_threshold
2337    #[cfg(feature = "boringssl-boring-crate")]
2338    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2339    pub fn set_enable_relaxed_loss_threshold_in_handshake(
2340        ssl: &mut boring::ssl::SslRef, enable: bool,
2341    ) -> Result<()> {
2342        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2343
2344        ex_data.recovery_config.enable_relaxed_loss_threshold = enable;
2345
2346        Ok(())
2347    }
2348
2349    /// Configures whether to enable HyStart++.
2350    ///
2351    /// This function can only be called inside one of BoringSSL's handshake
2352    /// callbacks, before any packet has been sent. Calling this function any
2353    /// other time will have no effect.
2354    ///
2355    /// See [`Config::enable_hystart()`].
2356    ///
2357    /// [`Config::enable_hystart()`]: struct.Config.html#method.enable_hystart
2358    #[cfg(feature = "boringssl-boring-crate")]
2359    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2360    pub fn set_hystart_in_handshake(
2361        ssl: &mut boring::ssl::SslRef, v: bool,
2362    ) -> Result<()> {
2363        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2364
2365        ex_data.recovery_config.hystart = v;
2366
2367        Ok(())
2368    }
2369
2370    /// Configures whether to enable pacing.
2371    ///
2372    /// This function can only be called inside one of BoringSSL's handshake
2373    /// callbacks, before any packet has been sent. Calling this function any
2374    /// other time will have no effect.
2375    ///
2376    /// See [`Config::enable_pacing()`].
2377    ///
2378    /// [`Config::enable_pacing()`]: struct.Config.html#method.enable_pacing
2379    #[cfg(feature = "boringssl-boring-crate")]
2380    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2381    pub fn set_pacing_in_handshake(
2382        ssl: &mut boring::ssl::SslRef, v: bool,
2383    ) -> Result<()> {
2384        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2385
2386        ex_data.recovery_config.pacing = v;
2387
2388        Ok(())
2389    }
2390
2391    /// Sets the max value for pacing rate.
2392    ///
2393    /// This function can only be called inside one of BoringSSL's handshake
2394    /// callbacks, before any packet has been sent. Calling this function any
2395    /// other time will have no effect.
2396    ///
2397    /// See [`Config::set_max_pacing_rate()`].
2398    ///
2399    /// [`Config::set_max_pacing_rate()`]: struct.Config.html#method.set_max_pacing_rate
2400    #[cfg(feature = "boringssl-boring-crate")]
2401    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2402    pub fn set_max_pacing_rate_in_handshake(
2403        ssl: &mut boring::ssl::SslRef, v: Option<u64>,
2404    ) -> Result<()> {
2405        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2406
2407        ex_data.recovery_config.max_pacing_rate = v;
2408
2409        Ok(())
2410    }
2411
2412    /// Sets the maximum outgoing UDP payload size.
2413    ///
2414    /// This function can only be called inside one of BoringSSL's handshake
2415    /// callbacks, before any packet has been sent. Calling this function any
2416    /// other time will have no effect.
2417    ///
2418    /// See [`Config::set_max_send_udp_payload_size()`].
2419    ///
2420    /// [`Config::set_max_send_udp_payload_size()`]: struct.Config.html#method.set_max_send_udp_payload_size
2421    #[cfg(feature = "boringssl-boring-crate")]
2422    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2423    pub fn set_max_send_udp_payload_size_in_handshake(
2424        ssl: &mut boring::ssl::SslRef, v: usize,
2425    ) -> Result<()> {
2426        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2427
2428        ex_data.recovery_config.max_send_udp_payload_size = v;
2429
2430        Ok(())
2431    }
2432
2433    /// Sets the send capacity factor.
2434    ///
2435    /// This function can only be called inside one of BoringSSL's handshake
2436    /// callbacks, before any packet has been sent. Calling this function any
2437    /// other time will have no effect.
2438    ///
2439    /// See [`Config::set_send_capacity_factor()`].
2440    ///
2441    /// [`Config::set_max_send_udp_payload_size()`]: struct.Config.html#method.set_send_capacity_factor
2442    #[cfg(feature = "boringssl-boring-crate")]
2443    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2444    pub fn set_send_capacity_factor_in_handshake(
2445        ssl: &mut boring::ssl::SslRef, v: f64,
2446    ) -> Result<()> {
2447        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2448
2449        ex_data.tx_cap_factor = v;
2450
2451        Ok(())
2452    }
2453
2454    /// Configures whether to do path MTU discovery.
2455    ///
2456    /// This function can only be called inside one of BoringSSL's handshake
2457    /// callbacks, before any packet has been sent. Calling this function any
2458    /// other time will have no effect.
2459    ///
2460    /// See [`Config::discover_pmtu()`].
2461    ///
2462    /// [`Config::discover_pmtu()`]: struct.Config.html#method.discover_pmtu
2463    #[cfg(feature = "boringssl-boring-crate")]
2464    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2465    pub fn set_discover_pmtu_in_handshake(
2466        ssl: &mut boring::ssl::SslRef, discover: bool, max_probes: u8,
2467    ) -> Result<()> {
2468        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2469
2470        ex_data.pmtud = Some((discover, max_probes));
2471
2472        Ok(())
2473    }
2474
2475    /// Sets the `max_idle_timeout` transport parameter, in milliseconds.
2476    ///
2477    /// This function can only be called inside one of BoringSSL's handshake
2478    /// callbacks, before any packet has been sent. Calling this function any
2479    /// other time will have no effect.
2480    ///
2481    /// See [`Config::set_max_idle_timeout()`].
2482    ///
2483    /// [`Config::set_max_idle_timeout()`]: struct.Config.html#method.set_max_idle_timeout
2484    #[cfg(feature = "boringssl-boring-crate")]
2485    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2486    pub fn set_max_idle_timeout_in_handshake(
2487        ssl: &mut boring::ssl::SslRef, v: u64,
2488    ) -> Result<()> {
2489        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2490
2491        ex_data.local_transport_params.max_idle_timeout = v;
2492
2493        Self::set_transport_parameters_in_hanshake(
2494            ex_data.local_transport_params.clone(),
2495            ex_data.is_server,
2496            ssl,
2497        )
2498    }
2499
2500    /// Sets the `initial_max_streams_bidi` transport parameter.
2501    ///
2502    /// This function can only be called inside one of BoringSSL's handshake
2503    /// callbacks, before any packet has been sent. Calling this function any
2504    /// other time will have no effect.
2505    ///
2506    /// See [`Config::set_initial_max_streams_bidi()`].
2507    ///
2508    /// [`Config::set_initial_max_streams_bidi()`]: struct.Config.html#method.set_initial_max_streams_bidi
2509    #[cfg(feature = "boringssl-boring-crate")]
2510    #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2511    pub fn set_initial_max_streams_bidi_in_handshake(
2512        ssl: &mut boring::ssl::SslRef, v: u64,
2513    ) -> Result<()> {
2514        let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2515
2516        ex_data.local_transport_params.initial_max_streams_bidi = v;
2517
2518        Self::set_transport_parameters_in_hanshake(
2519            ex_data.local_transport_params.clone(),
2520            ex_data.is_server,
2521            ssl,
2522        )
2523    }
2524
2525    #[cfg(feature = "boringssl-boring-crate")]
2526    fn set_transport_parameters_in_hanshake(
2527        params: TransportParams, is_server: bool, ssl: &mut boring::ssl::SslRef,
2528    ) -> Result<()> {
2529        use foreign_types_shared::ForeignTypeRef;
2530
2531        // In order to apply the new parameter to the TLS state before TPs are
2532        // written into a TLS message, we need to re-encode all TPs immediately.
2533        //
2534        // Since we don't have direct access to the main `Connection` object, we
2535        // need to re-create the `Handshake` state from the `SslRef`.
2536        //
2537        // SAFETY: the `Handshake` object must not be drop()ed, otherwise it
2538        // would free the underlying BoringSSL structure.
2539        let mut handshake =
2540            unsafe { tls::Handshake::from_ptr(ssl.as_ptr() as _) };
2541        handshake.set_quic_transport_params(&params, is_server)?;
2542
2543        // Avoid running `drop(handshake)` as that would free the underlying
2544        // handshake state.
2545        std::mem::forget(handshake);
2546
2547        Ok(())
2548    }
2549
2550    /// Processes QUIC packets received from the peer.
2551    ///
2552    /// On success the number of bytes processed from the input buffer is
2553    /// returned. On error the connection will be closed by calling [`close()`]
2554    /// with the appropriate error code.
2555    ///
2556    /// Coalesced packets will be processed as necessary.
2557    ///
2558    /// Note that the contents of the input buffer `buf` might be modified by
2559    /// this function due to, for example, in-place decryption.
2560    ///
2561    /// [`close()`]: struct.Connection.html#method.close
2562    ///
2563    /// ## Examples:
2564    ///
2565    /// ```no_run
2566    /// # let mut buf = [0; 512];
2567    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
2568    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
2569    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
2570    /// # let peer = "127.0.0.1:1234".parse().unwrap();
2571    /// # let local = socket.local_addr().unwrap();
2572    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
2573    /// loop {
2574    ///     let (read, from) = socket.recv_from(&mut buf).unwrap();
2575    ///
2576    ///     let recv_info = quiche::RecvInfo {
2577    ///         from,
2578    ///         to: local,
2579    ///     };
2580    ///
2581    ///     let read = match conn.recv(&mut buf[..read], recv_info) {
2582    ///         Ok(v) => v,
2583    ///
2584    ///         Err(e) => {
2585    ///             // An error occurred, handle it.
2586    ///             break;
2587    ///         },
2588    ///     };
2589    /// }
2590    /// # Ok::<(), quiche::Error>(())
2591    /// ```
2592    pub fn recv(&mut self, buf: &mut [u8], info: RecvInfo) -> Result<usize> {
2593        let len = buf.len();
2594
2595        if len == 0 {
2596            return Err(Error::BufferTooShort);
2597        }
2598
2599        let recv_pid = self.paths.path_id_from_addrs(&(info.to, info.from));
2600
2601        if let Some(recv_pid) = recv_pid {
2602            let recv_path = self.paths.get_mut(recv_pid)?;
2603
2604            // Keep track of how many bytes we received from the client, so we
2605            // can limit bytes sent back before address validation, to a
2606            // multiple of this. The limit needs to be increased early on, so
2607            // that if there is an error there is enough credit to send a
2608            // CONNECTION_CLOSE.
2609            //
2610            // It doesn't matter if the packets received were valid or not, we
2611            // only need to track the total amount of bytes received.
2612            //
2613            // Note that we also need to limit the number of bytes we sent on a
2614            // path if we are not the host that initiated its usage.
2615            if self.is_server && !recv_path.verified_peer_address {
2616                recv_path.max_send_bytes += len * self.max_amplification_factor;
2617            }
2618        } else if !self.is_server {
2619            // If a client receives packets from an unknown server address,
2620            // the client MUST discard these packets.
2621            trace!(
2622                "{} client received packet from unknown address {:?}, dropping",
2623                self.trace_id,
2624                info,
2625            );
2626
2627            return Ok(len);
2628        }
2629
2630        let mut done = 0;
2631        let mut left = len;
2632
2633        // Process coalesced packets.
2634        while left > 0 {
2635            let read = match self.recv_single(
2636                &mut buf[len - left..len],
2637                &info,
2638                recv_pid,
2639            ) {
2640                Ok(v) => v,
2641
2642                Err(Error::Done) => {
2643                    // If the packet can't be processed or decrypted, check if
2644                    // it's a stateless reset.
2645                    if self.is_stateless_reset(&buf[len - left..len]) {
2646                        trace!("{} packet is a stateless reset", self.trace_id);
2647
2648                        self.mark_closed();
2649                    }
2650
2651                    left
2652                },
2653
2654                Err(e) => {
2655                    // In case of error processing the incoming packet, close
2656                    // the connection.
2657                    self.close(false, e.to_wire(), b"").ok();
2658                    return Err(e);
2659                },
2660            };
2661
2662            done += read;
2663            left -= read;
2664        }
2665
2666        // Even though the packet was previously "accepted", it
2667        // should be safe to forward the error, as it also comes
2668        // from the `recv()` method.
2669        self.process_undecrypted_0rtt_packets()?;
2670
2671        Ok(done)
2672    }
2673
2674    fn process_undecrypted_0rtt_packets(&mut self) -> Result<()> {
2675        // Process previously undecryptable 0-RTT packets if the decryption key
2676        // is now available.
2677        if self.crypto_ctx[packet::Epoch::Application]
2678            .crypto_0rtt_open
2679            .is_some()
2680        {
2681            while let Some((mut pkt, info)) = self.undecryptable_pkts.pop_front()
2682            {
2683                if let Err(e) = self.recv(&mut pkt, info) {
2684                    self.undecryptable_pkts.clear();
2685
2686                    return Err(e);
2687                }
2688            }
2689        }
2690        Ok(())
2691    }
2692
2693    /// Returns true if a QUIC packet is a stateless reset.
2694    fn is_stateless_reset(&self, buf: &[u8]) -> bool {
2695        // If the packet is too small, then we just throw it away.
2696        let buf_len = buf.len();
2697        if buf_len < 21 {
2698            return false;
2699        }
2700
2701        // TODO: we should iterate over all active destination connection IDs
2702        // and check against their reset token.
2703        match self.peer_transport_params.stateless_reset_token {
2704            Some(token) => {
2705                let token_len = 16;
2706
2707                crypto::verify_slices_are_equal(
2708                    &token.to_be_bytes(),
2709                    &buf[buf_len - token_len..buf_len],
2710                )
2711                .is_ok()
2712            },
2713
2714            None => false,
2715        }
2716    }
2717
2718    /// Processes a single QUIC packet received from the peer.
2719    ///
2720    /// On success the number of bytes processed from the input buffer is
2721    /// returned. When the [`Done`] error is returned, processing of the
2722    /// remainder of the incoming UDP datagram should be interrupted.
2723    ///
2724    /// Note that a server might observe a new 4-tuple, preventing to
2725    /// know in advance to which path the incoming packet belongs to (`recv_pid`
2726    /// is `None`). As a client, packets from unknown 4-tuple are dropped
2727    /// beforehand (see `recv()`).
2728    ///
2729    /// On error, an error other than [`Done`] is returned.
2730    ///
2731    /// [`Done`]: enum.Error.html#variant.Done
2732    fn recv_single(
2733        &mut self, buf: &mut [u8], info: &RecvInfo, recv_pid: Option<usize>,
2734    ) -> Result<usize> {
2735        let now = Instant::now();
2736
2737        if buf.is_empty() {
2738            return Err(Error::Done);
2739        }
2740
2741        if self.is_closed() || self.is_draining() {
2742            return Err(Error::Done);
2743        }
2744
2745        let is_closing = self.local_error.is_some();
2746
2747        if is_closing {
2748            return Err(Error::Done);
2749        }
2750
2751        let buf_len = buf.len();
2752
2753        let mut b = octets::OctetsMut::with_slice(buf);
2754
2755        let mut hdr = Header::from_bytes(&mut b, self.source_id().len())
2756            .map_err(|e| {
2757                drop_pkt_on_err(
2758                    e,
2759                    self.recv_count,
2760                    self.is_server,
2761                    &self.trace_id,
2762                )
2763            })?;
2764
2765        if hdr.ty == Type::VersionNegotiation {
2766            // Version negotiation packets can only be sent by the server.
2767            if self.is_server {
2768                return Err(Error::Done);
2769            }
2770
2771            // Ignore duplicate version negotiation.
2772            if self.did_version_negotiation {
2773                return Err(Error::Done);
2774            }
2775
2776            // Ignore version negotiation if any other packet has already been
2777            // successfully processed.
2778            if self.recv_count > 0 {
2779                return Err(Error::Done);
2780            }
2781
2782            if hdr.dcid != self.source_id() {
2783                return Err(Error::Done);
2784            }
2785
2786            if hdr.scid != self.destination_id() {
2787                return Err(Error::Done);
2788            }
2789
2790            trace!("{} rx pkt {:?}", self.trace_id, hdr);
2791
2792            let versions = hdr.versions.ok_or(Error::Done)?;
2793
2794            // Ignore version negotiation if the version already selected is
2795            // listed.
2796            if versions.contains(&self.version) {
2797                return Err(Error::Done);
2798            }
2799
2800            let supported_versions =
2801                versions.iter().filter(|&&v| version_is_supported(v));
2802
2803            let mut found_version = false;
2804
2805            for &v in supported_versions {
2806                found_version = true;
2807
2808                // The final version takes precedence over draft ones.
2809                if v == PROTOCOL_VERSION_V1 {
2810                    self.version = v;
2811                    break;
2812                }
2813
2814                self.version = cmp::max(self.version, v);
2815            }
2816
2817            if !found_version {
2818                // We don't support any of the versions offered.
2819                //
2820                // While a man-in-the-middle attacker might be able to
2821                // inject a version negotiation packet that triggers this
2822                // failure, the window of opportunity is very small and
2823                // this error is quite useful for debugging, so don't just
2824                // ignore the packet.
2825                return Err(Error::UnknownVersion);
2826            }
2827
2828            self.did_version_negotiation = true;
2829
2830            // Derive Initial secrets based on the new version.
2831            let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2832                &self.destination_id(),
2833                self.version,
2834                self.is_server,
2835                true,
2836            )?;
2837
2838            // Reset connection state to force sending another Initial packet.
2839            self.drop_epoch_state(packet::Epoch::Initial, now);
2840            self.got_peer_conn_id = false;
2841            self.handshake.clear()?;
2842
2843            self.crypto_ctx[packet::Epoch::Initial].crypto_open = Some(aead_open);
2844            self.crypto_ctx[packet::Epoch::Initial].crypto_seal = Some(aead_seal);
2845
2846            self.handshake
2847                .use_legacy_codepoint(self.version != PROTOCOL_VERSION_V1);
2848
2849            // Encode transport parameters again, as the new version might be
2850            // using a different format.
2851            self.encode_transport_params()?;
2852
2853            return Err(Error::Done);
2854        }
2855
2856        if hdr.ty == Type::Retry {
2857            // Retry packets can only be sent by the server.
2858            if self.is_server {
2859                return Err(Error::Done);
2860            }
2861
2862            // Ignore duplicate retry.
2863            if self.did_retry {
2864                return Err(Error::Done);
2865            }
2866
2867            // Check if Retry packet is valid.
2868            if packet::verify_retry_integrity(
2869                &b,
2870                &self.destination_id(),
2871                self.version,
2872            )
2873            .is_err()
2874            {
2875                return Err(Error::Done);
2876            }
2877
2878            trace!("{} rx pkt {:?}", self.trace_id, hdr);
2879
2880            self.token = hdr.token;
2881            self.did_retry = true;
2882
2883            // Remember peer's new connection ID.
2884            self.odcid = Some(self.destination_id().into_owned());
2885
2886            self.set_initial_dcid(
2887                hdr.scid.clone(),
2888                None,
2889                self.paths.get_active_path_id()?,
2890            )?;
2891
2892            self.rscid = Some(self.destination_id().into_owned());
2893
2894            // Derive Initial secrets using the new connection ID.
2895            let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2896                &hdr.scid,
2897                self.version,
2898                self.is_server,
2899                true,
2900            )?;
2901
2902            // Reset connection state to force sending another Initial packet.
2903            self.drop_epoch_state(packet::Epoch::Initial, now);
2904            self.got_peer_conn_id = false;
2905            self.handshake.clear()?;
2906
2907            self.crypto_ctx[packet::Epoch::Initial].crypto_open = Some(aead_open);
2908            self.crypto_ctx[packet::Epoch::Initial].crypto_seal = Some(aead_seal);
2909
2910            return Err(Error::Done);
2911        }
2912
2913        if self.is_server && !self.did_version_negotiation {
2914            if !version_is_supported(hdr.version) {
2915                return Err(Error::UnknownVersion);
2916            }
2917
2918            self.version = hdr.version;
2919            self.did_version_negotiation = true;
2920
2921            self.handshake
2922                .use_legacy_codepoint(self.version != PROTOCOL_VERSION_V1);
2923
2924            // Encode transport parameters again, as the new version might be
2925            // using a different format.
2926            self.encode_transport_params()?;
2927        }
2928
2929        if hdr.ty != Type::Short && hdr.version != self.version {
2930            // At this point version negotiation was already performed, so
2931            // ignore packets that don't match the connection's version.
2932            return Err(Error::Done);
2933        }
2934
2935        // Long header packets have an explicit payload length, but short
2936        // packets don't so just use the remaining capacity in the buffer.
2937        let payload_len = if hdr.ty == Type::Short {
2938            b.cap()
2939        } else {
2940            b.get_varint().map_err(|e| {
2941                drop_pkt_on_err(
2942                    e.into(),
2943                    self.recv_count,
2944                    self.is_server,
2945                    &self.trace_id,
2946                )
2947            })? as usize
2948        };
2949
2950        // Make sure the buffer is same or larger than an explicit
2951        // payload length.
2952        if payload_len > b.cap() {
2953            return Err(drop_pkt_on_err(
2954                Error::InvalidPacket,
2955                self.recv_count,
2956                self.is_server,
2957                &self.trace_id,
2958            ));
2959        }
2960
2961        // Derive initial secrets on the server.
2962        if !self.derived_initial_secrets {
2963            let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2964                &hdr.dcid,
2965                self.version,
2966                self.is_server,
2967                false,
2968            )?;
2969
2970            self.crypto_ctx[packet::Epoch::Initial].crypto_open = Some(aead_open);
2971            self.crypto_ctx[packet::Epoch::Initial].crypto_seal = Some(aead_seal);
2972
2973            self.derived_initial_secrets = true;
2974        }
2975
2976        // Select packet number space epoch based on the received packet's type.
2977        let epoch = hdr.ty.to_epoch()?;
2978
2979        // Select AEAD context used to open incoming packet.
2980        let aead = if hdr.ty == Type::ZeroRTT {
2981            // Only use 0-RTT key if incoming packet is 0-RTT.
2982            self.crypto_ctx[epoch].crypto_0rtt_open.as_ref()
2983        } else {
2984            // Otherwise use the packet number space's main key.
2985            self.crypto_ctx[epoch].crypto_open.as_ref()
2986        };
2987
2988        // Finally, discard packet if no usable key is available.
2989        let mut aead = match aead {
2990            Some(v) => v,
2991
2992            None => {
2993                if hdr.ty == Type::ZeroRTT &&
2994                    self.undecryptable_pkts.len() < MAX_UNDECRYPTABLE_PACKETS &&
2995                    !self.is_established()
2996                {
2997                    // Buffer 0-RTT packets when the required read key is not
2998                    // available yet, and process them later.
2999                    //
3000                    // TODO: in the future we might want to buffer other types
3001                    // of undecryptable packets as well.
3002                    let pkt_len = b.off() + payload_len;
3003                    let pkt = (b.buf()[..pkt_len]).to_vec();
3004
3005                    self.undecryptable_pkts.push_back((pkt, *info));
3006                    return Ok(pkt_len);
3007                }
3008
3009                let e = drop_pkt_on_err(
3010                    Error::CryptoFail,
3011                    self.recv_count,
3012                    self.is_server,
3013                    &self.trace_id,
3014                );
3015
3016                return Err(e);
3017            },
3018        };
3019
3020        let aead_tag_len = aead.alg().tag_len();
3021
3022        packet::decrypt_hdr(&mut b, &mut hdr, aead).map_err(|e| {
3023            drop_pkt_on_err(e, self.recv_count, self.is_server, &self.trace_id)
3024        })?;
3025
3026        let pn = packet::decode_pkt_num(
3027            self.pkt_num_spaces[epoch].largest_rx_pkt_num,
3028            hdr.pkt_num,
3029            hdr.pkt_num_len,
3030        );
3031
3032        let pn_len = hdr.pkt_num_len;
3033
3034        trace!(
3035            "{} rx pkt {:?} len={} pn={} {}",
3036            self.trace_id,
3037            hdr,
3038            payload_len,
3039            pn,
3040            AddrTupleFmt(info.from, info.to)
3041        );
3042
3043        #[cfg(feature = "qlog")]
3044        let mut qlog_frames = vec![];
3045
3046        // Check for key update.
3047        let mut aead_next = None;
3048
3049        if self.handshake_confirmed &&
3050            hdr.ty != Type::ZeroRTT &&
3051            hdr.key_phase != self.key_phase
3052        {
3053            // Check if this packet arrived before key update.
3054            if let Some(key_update) = self.crypto_ctx[epoch]
3055                .key_update
3056                .as_ref()
3057                .and_then(|key_update| {
3058                    (pn < key_update.pn_on_update).then_some(key_update)
3059                })
3060            {
3061                aead = &key_update.crypto_open;
3062            } else {
3063                trace!("{} peer-initiated key update", self.trace_id);
3064
3065                aead_next = Some((
3066                    self.crypto_ctx[epoch]
3067                        .crypto_open
3068                        .as_ref()
3069                        .unwrap()
3070                        .derive_next_packet_key()?,
3071                    self.crypto_ctx[epoch]
3072                        .crypto_seal
3073                        .as_ref()
3074                        .unwrap()
3075                        .derive_next_packet_key()?,
3076                ));
3077
3078                // `aead_next` is always `Some()` at this point, so the `unwrap()`
3079                // will never fail.
3080                aead = &aead_next.as_ref().unwrap().0;
3081            }
3082        }
3083
3084        let mut payload = packet::decrypt_pkt(
3085            &mut b,
3086            pn,
3087            pn_len,
3088            payload_len,
3089            aead,
3090        )
3091        .map_err(|e| {
3092            drop_pkt_on_err(e, self.recv_count, self.is_server, &self.trace_id)
3093        })?;
3094
3095        if self.pkt_num_spaces[epoch].recv_pkt_num.contains(pn) {
3096            trace!("{} ignored duplicate packet {}", self.trace_id, pn);
3097            return Err(Error::Done);
3098        }
3099
3100        // Packets with no frames are invalid.
3101        if payload.cap() == 0 {
3102            return Err(Error::InvalidPacket);
3103        }
3104
3105        // Now that we decrypted the packet, let's see if we can map it to an
3106        // existing path.
3107        let recv_pid = if hdr.ty == Type::Short && self.got_peer_conn_id {
3108            let pkt_dcid = ConnectionId::from_ref(&hdr.dcid);
3109            self.get_or_create_recv_path_id(recv_pid, &pkt_dcid, buf_len, info)?
3110        } else {
3111            // During handshake, we are on the initial path.
3112            self.paths.get_active_path_id()?
3113        };
3114
3115        // The key update is verified once a packet is successfully decrypted
3116        // using the new keys.
3117        if let Some((open_next, seal_next)) = aead_next {
3118            if !self.crypto_ctx[epoch]
3119                .key_update
3120                .as_ref()
3121                .is_none_or(|prev| prev.update_acked)
3122            {
3123                // Peer has updated keys twice without awaiting confirmation.
3124                return Err(Error::KeyUpdate);
3125            }
3126
3127            trace!("{} key update verified", self.trace_id);
3128
3129            let _ = self.crypto_ctx[epoch].crypto_seal.replace(seal_next);
3130
3131            let open_prev = self.crypto_ctx[epoch]
3132                .crypto_open
3133                .replace(open_next)
3134                .unwrap();
3135
3136            let recv_path = self.paths.get_mut(recv_pid)?;
3137
3138            self.crypto_ctx[epoch].key_update = Some(packet::KeyUpdate {
3139                crypto_open: open_prev,
3140                pn_on_update: pn,
3141                update_acked: false,
3142                timer: now + (recv_path.recovery.pto() * 3),
3143            });
3144
3145            self.key_phase = !self.key_phase;
3146
3147            qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
3148                let trigger = Some(
3149                    qlog::events::security::KeyUpdateOrRetiredTrigger::RemoteUpdate,
3150                );
3151
3152                let ev_data_client =
3153                    EventData::KeyUpdated(qlog::events::security::KeyUpdated {
3154                        key_type:
3155                            qlog::events::security::KeyType::Client1RttSecret,
3156                        trigger: trigger.clone(),
3157                        ..Default::default()
3158                    });
3159
3160                q.add_event_data_with_instant(ev_data_client, now).ok();
3161
3162                let ev_data_server =
3163                    EventData::KeyUpdated(qlog::events::security::KeyUpdated {
3164                        key_type:
3165                            qlog::events::security::KeyType::Server1RttSecret,
3166                        trigger,
3167                        ..Default::default()
3168                    });
3169
3170                q.add_event_data_with_instant(ev_data_server, now).ok();
3171            });
3172        }
3173
3174        if !self.is_server && !self.got_peer_conn_id {
3175            if self.odcid.is_none() {
3176                self.odcid = Some(self.destination_id().into_owned());
3177            }
3178
3179            // Replace the randomly generated destination connection ID with
3180            // the one supplied by the server.
3181            self.set_initial_dcid(
3182                hdr.scid.clone(),
3183                self.peer_transport_params.stateless_reset_token,
3184                recv_pid,
3185            )?;
3186
3187            self.got_peer_conn_id = true;
3188        }
3189
3190        if self.is_server && !self.got_peer_conn_id {
3191            self.set_initial_dcid(hdr.scid.clone(), None, recv_pid)?;
3192
3193            if !self.did_retry {
3194                self.local_transport_params
3195                    .original_destination_connection_id =
3196                    Some(hdr.dcid.to_vec().into());
3197
3198                self.encode_transport_params()?;
3199            }
3200
3201            self.got_peer_conn_id = true;
3202        }
3203
3204        // To avoid sending an ACK in response to an ACK-only packet, we need
3205        // to keep track of whether this packet contains any frame other than
3206        // ACK and PADDING.
3207        let mut ack_elicited = false;
3208
3209        // Process packet payload. If a frame cannot be processed, store the
3210        // error and stop further packet processing.
3211        let mut frame_processing_err = None;
3212
3213        // To know if the peer migrated the connection, we need to keep track
3214        // whether this is a non-probing packet.
3215        let mut probing = true;
3216
3217        // Process packet payload.
3218        while payload.cap() > 0 {
3219            let frame = frame::Frame::from_bytes(&mut payload, hdr.ty)?;
3220
3221            qlog_with_type!(QLOG_PACKET_RX, self.qlog, _q, {
3222                qlog_frames.push(frame.to_qlog());
3223            });
3224
3225            if frame.ack_eliciting() {
3226                ack_elicited = true;
3227            }
3228
3229            if !frame.probing() {
3230                probing = false;
3231            }
3232
3233            if let Err(e) = self.process_frame(frame, &hdr, recv_pid, epoch, now)
3234            {
3235                frame_processing_err = Some(e);
3236                break;
3237            }
3238        }
3239
3240        qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
3241            let packet_size = b.len();
3242
3243            let qlog_pkt_hdr = qlog::events::quic::PacketHeader::with_type(
3244                hdr.ty.to_qlog(),
3245                Some(pn),
3246                Some(hdr.version),
3247                Some(&hdr.scid),
3248                Some(&hdr.dcid),
3249            );
3250
3251            let qlog_raw_info = RawInfo {
3252                length: Some(packet_size as u64),
3253                payload_length: Some(payload_len as u64),
3254                data: None,
3255            };
3256
3257            let ev_data =
3258                EventData::PacketReceived(qlog::events::quic::PacketReceived {
3259                    header: qlog_pkt_hdr,
3260                    frames: Some(qlog_frames),
3261                    raw: Some(qlog_raw_info),
3262                    ..Default::default()
3263                });
3264
3265            q.add_event_data_with_instant(ev_data, now).ok();
3266        });
3267
3268        qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
3269            let recv_path = self.paths.get_mut(recv_pid)?;
3270            recv_path.recovery.maybe_qlog(q, now);
3271        });
3272
3273        if let Some(e) = frame_processing_err {
3274            // Any frame error is terminal, so now just return.
3275            return Err(e);
3276        }
3277
3278        // Only log the remote transport parameters once the connection is
3279        // established (i.e. after frames have been fully parsed) and only
3280        // once per connection.
3281        if self.is_established() {
3282            qlog_with_type!(QLOG_PARAMS_SET, self.qlog, q, {
3283                if !self.qlog.logged_peer_params {
3284                    let ev_data = self
3285                        .peer_transport_params
3286                        .to_qlog(TransportOwner::Remote, self.handshake.cipher());
3287
3288                    q.add_event_data_with_instant(ev_data, now).ok();
3289
3290                    self.qlog.logged_peer_params = true;
3291                }
3292            });
3293        }
3294
3295        // Process acked frames. Note that several packets from several paths
3296        // might have been acked by the received packet.
3297        for (_, p) in self.paths.iter_mut() {
3298            while let Some(acked) = p.recovery.next_acked_frame(epoch) {
3299                match acked {
3300                    frame::Frame::Ping {
3301                        mtu_probe: Some(mtu_probe),
3302                    } =>
3303                        if let Some(pmtud) = p.pmtud.as_mut() {
3304                            trace!(
3305                                "{} pmtud probe acked; probe size {:?}",
3306                                self.trace_id,
3307                                mtu_probe
3308                            );
3309
3310                            // Ensure the probe is within the supported MTU range
3311                            // before updating the max datagram size
3312                            if let Some(current_mtu) =
3313                                pmtud.successful_probe(mtu_probe)
3314                            {
3315                                qlog_with_type!(
3316                                    EventType::ConnectivityEventType(
3317                                        ConnectivityEventType::MtuUpdated
3318                                    ),
3319                                    self.qlog,
3320                                    q,
3321                                    {
3322                                        let pmtu_data = EventData::MtuUpdated(
3323                                            qlog::events::connectivity::MtuUpdated {
3324                                                old: Some(
3325                                                    p.recovery.max_datagram_size()
3326                                                        as u16,
3327                                                ),
3328                                                new: current_mtu as u16,
3329                                                done: Some(true),
3330                                            },
3331                                        );
3332
3333                                        q.add_event_data_with_instant(
3334                                            pmtu_data, now,
3335                                        )
3336                                        .ok();
3337                                    }
3338                                );
3339
3340                                p.recovery
3341                                    .pmtud_update_max_datagram_size(current_mtu);
3342                            }
3343                        },
3344
3345                    frame::Frame::ACK { ranges, .. } => {
3346                        // Stop acknowledging packets less than or equal to the
3347                        // largest acknowledged in the sent ACK frame that, in
3348                        // turn, got acked.
3349                        if let Some(largest_acked) = ranges.last() {
3350                            self.pkt_num_spaces[epoch]
3351                                .recv_pkt_need_ack
3352                                .remove_until(largest_acked);
3353                        }
3354                    },
3355
3356                    frame::Frame::CryptoHeader { offset, length } => {
3357                        self.crypto_ctx[epoch]
3358                            .crypto_stream
3359                            .send
3360                            .ack_and_drop(offset, length);
3361                    },
3362
3363                    frame::Frame::StreamHeader {
3364                        stream_id,
3365                        offset,
3366                        length,
3367                        ..
3368                    } => {
3369                        // Update tx_buffered and emit qlog before checking if the
3370                        // stream still exists.  The client does need to ACK
3371                        // frames that were received after the client sends a
3372                        // ResetStream.
3373                        self.tx_buffered =
3374                            self.tx_buffered.saturating_sub(length);
3375
3376                        qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
3377                            let ev_data = EventData::DataMoved(
3378                                qlog::events::quic::DataMoved {
3379                                    stream_id: Some(stream_id),
3380                                    offset: Some(offset),
3381                                    length: Some(length as u64),
3382                                    from: Some(DataRecipient::Transport),
3383                                    to: Some(DataRecipient::Dropped),
3384                                    ..Default::default()
3385                                },
3386                            );
3387
3388                            q.add_event_data_with_instant(ev_data, now).ok();
3389                        });
3390
3391                        let stream = match self.streams.get_mut(stream_id) {
3392                            Some(v) => v,
3393
3394                            None => continue,
3395                        };
3396
3397                        stream.send.ack_and_drop(offset, length);
3398
3399                        let priority_key = Arc::clone(&stream.priority_key);
3400
3401                        // Only collect the stream if it is complete and not
3402                        // readable or writable.
3403                        //
3404                        // If it is readable, it will get collected when
3405                        // stream_recv() is next used.
3406                        //
3407                        // If it is writable, it might mean that the stream
3408                        // has been stopped by the peer (i.e. a STOP_SENDING
3409                        // frame is received), in which case before collecting
3410                        // the stream we will need to propagate the
3411                        // `StreamStopped` error to the application. It will
3412                        // instead get collected when one of stream_capacity(),
3413                        // stream_writable(), stream_send(), ... is next called.
3414                        //
3415                        // Note that we can't use `is_writable()` here because
3416                        // it returns false if the stream is stopped. Instead,
3417                        // since the stream is marked as writable when a
3418                        // STOP_SENDING frame is received, we check the writable
3419                        // queue directly instead.
3420                        let is_writable = priority_key.writable.is_linked() &&
3421                            // Ensure that the stream is actually stopped.
3422                            stream.send.is_stopped();
3423
3424                        let is_complete = stream.is_complete();
3425                        let is_readable = stream.is_readable();
3426
3427                        if is_complete && !is_readable && !is_writable {
3428                            let local = stream.local;
3429                            self.streams.collect(stream_id, local);
3430                        }
3431                    },
3432
3433                    frame::Frame::HandshakeDone => {
3434                        // Explicitly set this to true, so that if the frame was
3435                        // already scheduled for retransmission, it is aborted.
3436                        self.handshake_done_sent = true;
3437
3438                        self.handshake_done_acked = true;
3439                    },
3440
3441                    frame::Frame::ResetStream { stream_id, .. } => {
3442                        let stream = match self.streams.get_mut(stream_id) {
3443                            Some(v) => v,
3444
3445                            None => continue,
3446                        };
3447
3448                        let priority_key = Arc::clone(&stream.priority_key);
3449
3450                        // Only collect the stream if it is complete and not
3451                        // readable or writable.
3452                        //
3453                        // If it is readable, it will get collected when
3454                        // stream_recv() is next used.
3455                        //
3456                        // If it is writable, it might mean that the stream
3457                        // has been stopped by the peer (i.e. a STOP_SENDING
3458                        // frame is received), in which case before collecting
3459                        // the stream we will need to propagate the
3460                        // `StreamStopped` error to the application. It will
3461                        // instead get collected when one of stream_capacity(),
3462                        // stream_writable(), stream_send(), ... is next called.
3463                        //
3464                        // Note that we can't use `is_writable()` here because
3465                        // it returns false if the stream is stopped. Instead,
3466                        // since the stream is marked as writable when a
3467                        // STOP_SENDING frame is received, we check the writable
3468                        // queue directly instead.
3469                        let is_writable = priority_key.writable.is_linked() &&
3470                            // Ensure that the stream is actually stopped.
3471                            stream.send.is_stopped();
3472
3473                        let is_complete = stream.is_complete();
3474                        let is_readable = stream.is_readable();
3475
3476                        if is_complete && !is_readable && !is_writable {
3477                            let local = stream.local;
3478                            self.streams.collect(stream_id, local);
3479                        }
3480                    },
3481
3482                    _ => (),
3483                }
3484            }
3485        }
3486
3487        // Now that we processed all the frames, if there is a path that has no
3488        // Destination CID, try to allocate one.
3489        let no_dcid = self
3490            .paths
3491            .iter_mut()
3492            .filter(|(_, p)| p.active_dcid_seq.is_none());
3493
3494        for (pid, p) in no_dcid {
3495            if self.ids.zero_length_dcid() {
3496                p.active_dcid_seq = Some(0);
3497                continue;
3498            }
3499
3500            let dcid_seq = match self.ids.lowest_available_dcid_seq() {
3501                Some(seq) => seq,
3502                None => break,
3503            };
3504
3505            self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
3506
3507            p.active_dcid_seq = Some(dcid_seq);
3508        }
3509
3510        // We only record the time of arrival of the largest packet number
3511        // that still needs to be acked, to be used for ACK delay calculation.
3512        if self.pkt_num_spaces[epoch].recv_pkt_need_ack.last() < Some(pn) {
3513            self.pkt_num_spaces[epoch].largest_rx_pkt_time = now;
3514        }
3515
3516        self.pkt_num_spaces[epoch].recv_pkt_num.insert(pn);
3517
3518        self.pkt_num_spaces[epoch].recv_pkt_need_ack.push_item(pn);
3519
3520        self.pkt_num_spaces[epoch].ack_elicited =
3521            cmp::max(self.pkt_num_spaces[epoch].ack_elicited, ack_elicited);
3522
3523        self.pkt_num_spaces[epoch].largest_rx_pkt_num =
3524            cmp::max(self.pkt_num_spaces[epoch].largest_rx_pkt_num, pn);
3525
3526        if !probing {
3527            self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num = cmp::max(
3528                self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num,
3529                pn,
3530            );
3531
3532            // Did the peer migrated to another path?
3533            let active_path_id = self.paths.get_active_path_id()?;
3534
3535            if self.is_server &&
3536                recv_pid != active_path_id &&
3537                self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num == pn
3538            {
3539                self.on_peer_migrated(recv_pid, self.disable_dcid_reuse, now)?;
3540            }
3541        }
3542
3543        if let Some(idle_timeout) = self.idle_timeout() {
3544            self.idle_timer = Some(now + idle_timeout);
3545        }
3546
3547        // Update send capacity.
3548        self.update_tx_cap();
3549
3550        self.recv_count += 1;
3551        self.paths.get_mut(recv_pid)?.recv_count += 1;
3552
3553        let read = b.off() + aead_tag_len;
3554
3555        self.recv_bytes += read as u64;
3556        self.paths.get_mut(recv_pid)?.recv_bytes += read as u64;
3557
3558        // An Handshake packet has been received from the client and has been
3559        // successfully processed, so we can drop the initial state and consider
3560        // the client's address to be verified.
3561        if self.is_server && hdr.ty == Type::Handshake {
3562            self.drop_epoch_state(packet::Epoch::Initial, now);
3563
3564            self.paths.get_mut(recv_pid)?.verified_peer_address = true;
3565        }
3566
3567        self.ack_eliciting_sent = false;
3568
3569        Ok(read)
3570    }
3571
3572    /// Writes a single QUIC packet to be sent to the peer.
3573    ///
3574    /// On success the number of bytes written to the output buffer is
3575    /// returned, or [`Done`] if there was nothing to write.
3576    ///
3577    /// The application should call `send()` multiple times until [`Done`] is
3578    /// returned, indicating that there are no more packets to send. It is
3579    /// recommended that `send()` be called in the following cases:
3580    ///
3581    ///  * When the application receives QUIC packets from the peer (that is,
3582    ///    any time [`recv()`] is also called).
3583    ///
3584    ///  * When the connection timer expires (that is, any time [`on_timeout()`]
3585    ///    is also called).
3586    ///
3587    ///  * When the application sends data to the peer (for example, any time
3588    ///    [`stream_send()`] or [`stream_shutdown()`] are called).
3589    ///
3590    ///  * When the application receives data from the peer (for example any
3591    ///    time [`stream_recv()`] is called).
3592    ///
3593    /// Once [`is_draining()`] returns `true`, it is no longer necessary to call
3594    /// `send()` and all calls will return [`Done`].
3595    ///
3596    /// [`Done`]: enum.Error.html#variant.Done
3597    /// [`recv()`]: struct.Connection.html#method.recv
3598    /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
3599    /// [`stream_send()`]: struct.Connection.html#method.stream_send
3600    /// [`stream_shutdown()`]: struct.Connection.html#method.stream_shutdown
3601    /// [`stream_recv()`]: struct.Connection.html#method.stream_recv
3602    /// [`is_draining()`]: struct.Connection.html#method.is_draining
3603    ///
3604    /// ## Examples:
3605    ///
3606    /// ```no_run
3607    /// # let mut out = [0; 512];
3608    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
3609    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
3610    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
3611    /// # let peer = "127.0.0.1:1234".parse().unwrap();
3612    /// # let local = socket.local_addr().unwrap();
3613    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
3614    /// loop {
3615    ///     let (write, send_info) = match conn.send(&mut out) {
3616    ///         Ok(v) => v,
3617    ///
3618    ///         Err(quiche::Error::Done) => {
3619    ///             // Done writing.
3620    ///             break;
3621    ///         },
3622    ///
3623    ///         Err(e) => {
3624    ///             // An error occurred, handle it.
3625    ///             break;
3626    ///         },
3627    ///     };
3628    ///
3629    ///     socket.send_to(&out[..write], &send_info.to).unwrap();
3630    /// }
3631    /// # Ok::<(), quiche::Error>(())
3632    /// ```
3633    pub fn send(&mut self, out: &mut [u8]) -> Result<(usize, SendInfo)> {
3634        self.send_on_path(out, None, None)
3635    }
3636
3637    /// Writes a single QUIC packet to be sent to the peer from the specified
3638    /// local address `from` to the destination address `to`.
3639    ///
3640    /// The behavior of this method differs depending on the value of the `from`
3641    /// and `to` parameters:
3642    ///
3643    ///  * If both are `Some`, then the method only consider the 4-tuple
3644    ///    (`from`, `to`). Application can monitor the 4-tuple availability,
3645    ///    either by monitoring [`path_event_next()`] events or by relying on
3646    ///    the [`paths_iter()`] method. If the provided 4-tuple does not exist
3647    ///    on the connection (anymore), it returns an [`InvalidState`].
3648    ///
3649    ///  * If `from` is `Some` and `to` is `None`, then the method only
3650    ///    considers sending packets on paths having `from` as local address.
3651    ///
3652    ///  * If `to` is `Some` and `from` is `None`, then the method only
3653    ///    considers sending packets on paths having `to` as peer address.
3654    ///
3655    ///  * If both are `None`, all available paths are considered.
3656    ///
3657    /// On success the number of bytes written to the output buffer is
3658    /// returned, or [`Done`] if there was nothing to write.
3659    ///
3660    /// The application should call `send_on_path()` multiple times until
3661    /// [`Done`] is returned, indicating that there are no more packets to
3662    /// send. It is recommended that `send_on_path()` be called in the
3663    /// following cases:
3664    ///
3665    ///  * When the application receives QUIC packets from the peer (that is,
3666    ///    any time [`recv()`] is also called).
3667    ///
3668    ///  * When the connection timer expires (that is, any time [`on_timeout()`]
3669    ///    is also called).
3670    ///
3671    ///  * When the application sends data to the peer (for examples, any time
3672    ///    [`stream_send()`] or [`stream_shutdown()`] are called).
3673    ///
3674    ///  * When the application receives data from the peer (for example any
3675    ///    time [`stream_recv()`] is called).
3676    ///
3677    /// Once [`is_draining()`] returns `true`, it is no longer necessary to call
3678    /// `send_on_path()` and all calls will return [`Done`].
3679    ///
3680    /// [`Done`]: enum.Error.html#variant.Done
3681    /// [`InvalidState`]: enum.Error.html#InvalidState
3682    /// [`recv()`]: struct.Connection.html#method.recv
3683    /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
3684    /// [`stream_send()`]: struct.Connection.html#method.stream_send
3685    /// [`stream_shutdown()`]: struct.Connection.html#method.stream_shutdown
3686    /// [`stream_recv()`]: struct.Connection.html#method.stream_recv
3687    /// [`path_event_next()`]: struct.Connection.html#method.path_event_next
3688    /// [`paths_iter()`]: struct.Connection.html#method.paths_iter
3689    /// [`is_draining()`]: struct.Connection.html#method.is_draining
3690    ///
3691    /// ## Examples:
3692    ///
3693    /// ```no_run
3694    /// # let mut out = [0; 512];
3695    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
3696    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
3697    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
3698    /// # let peer = "127.0.0.1:1234".parse().unwrap();
3699    /// # let local = socket.local_addr().unwrap();
3700    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
3701    /// loop {
3702    ///     let (write, send_info) = match conn.send_on_path(&mut out, Some(local), Some(peer)) {
3703    ///         Ok(v) => v,
3704    ///
3705    ///         Err(quiche::Error::Done) => {
3706    ///             // Done writing.
3707    ///             break;
3708    ///         },
3709    ///
3710    ///         Err(e) => {
3711    ///             // An error occurred, handle it.
3712    ///             break;
3713    ///         },
3714    ///     };
3715    ///
3716    ///     socket.send_to(&out[..write], &send_info.to).unwrap();
3717    /// }
3718    /// # Ok::<(), quiche::Error>(())
3719    /// ```
3720    pub fn send_on_path(
3721        &mut self, out: &mut [u8], from: Option<SocketAddr>,
3722        to: Option<SocketAddr>,
3723    ) -> Result<(usize, SendInfo)> {
3724        if out.is_empty() {
3725            return Err(Error::BufferTooShort);
3726        }
3727
3728        if self.is_closed() || self.is_draining() {
3729            return Err(Error::Done);
3730        }
3731
3732        let now = Instant::now();
3733
3734        if self.local_error.is_none() {
3735            self.do_handshake(now)?;
3736        }
3737
3738        // Forwarding the error value here could confuse
3739        // applications, as they may not expect getting a `recv()`
3740        // error when calling `send()`.
3741        //
3742        // We simply fall-through to sending packets, which should
3743        // take care of terminating the connection as needed.
3744        let _ = self.process_undecrypted_0rtt_packets();
3745
3746        // There's no point in trying to send a packet if the Initial secrets
3747        // have not been derived yet, so return early.
3748        if !self.derived_initial_secrets {
3749            return Err(Error::Done);
3750        }
3751
3752        let mut has_initial = false;
3753
3754        let mut done = 0;
3755
3756        // Limit output packet size to respect the sender and receiver's
3757        // maximum UDP payload size limit.
3758        let mut left = cmp::min(out.len(), self.max_send_udp_payload_size());
3759
3760        let send_pid = match (from, to) {
3761            (Some(f), Some(t)) => self
3762                .paths
3763                .path_id_from_addrs(&(f, t))
3764                .ok_or(Error::InvalidState)?,
3765
3766            _ => self.get_send_path_id(from, to)?,
3767        };
3768
3769        let send_path = self.paths.get_mut(send_pid)?;
3770
3771        // Update max datagram size to allow path MTU discovery probe to be sent.
3772        if let Some(pmtud) = send_path.pmtud.as_mut() {
3773            if pmtud.should_probe() {
3774                let size = if self.handshake_confirmed || self.handshake_completed
3775                {
3776                    pmtud.get_probe_size()
3777                } else {
3778                    pmtud.get_current_mtu()
3779                };
3780
3781                send_path.recovery.pmtud_update_max_datagram_size(size);
3782
3783                left =
3784                    cmp::min(out.len(), send_path.recovery.max_datagram_size());
3785            }
3786        }
3787
3788        // Limit data sent by the server based on the amount of data received
3789        // from the client before its address is validated.
3790        if !send_path.verified_peer_address && self.is_server {
3791            left = cmp::min(left, send_path.max_send_bytes);
3792        }
3793
3794        // Generate coalesced packets.
3795        while left > 0 {
3796            let (ty, written) = match self.send_single(
3797                &mut out[done..done + left],
3798                send_pid,
3799                has_initial,
3800                now,
3801            ) {
3802                Ok(v) => v,
3803
3804                Err(Error::BufferTooShort) | Err(Error::Done) => break,
3805
3806                Err(e) => return Err(e),
3807            };
3808
3809            done += written;
3810            left -= written;
3811
3812            match ty {
3813                Type::Initial => has_initial = true,
3814
3815                // No more packets can be coalesced after a 1-RTT.
3816                Type::Short => break,
3817
3818                _ => (),
3819            };
3820
3821            // When sending multiple PTO probes, don't coalesce them together,
3822            // so they are sent on separate UDP datagrams.
3823            if let Ok(epoch) = ty.to_epoch() {
3824                if self.paths.get_mut(send_pid)?.recovery.loss_probes(epoch) > 0 {
3825                    break;
3826                }
3827            }
3828
3829            // Don't coalesce packets that must go on different paths.
3830            if !(from.is_some() && to.is_some()) &&
3831                self.get_send_path_id(from, to)? != send_pid
3832            {
3833                break;
3834            }
3835        }
3836
3837        if done == 0 {
3838            self.last_tx_data = self.tx_data;
3839
3840            return Err(Error::Done);
3841        }
3842
3843        if has_initial && left > 0 && done < MIN_CLIENT_INITIAL_LEN {
3844            let pad_len = cmp::min(left, MIN_CLIENT_INITIAL_LEN - done);
3845
3846            // Fill padding area with null bytes, to avoid leaking information
3847            // in case the application reuses the packet buffer.
3848            out[done..done + pad_len].fill(0);
3849
3850            done += pad_len;
3851        }
3852
3853        let send_path = self.paths.get(send_pid)?;
3854
3855        let info = SendInfo {
3856            from: send_path.local_addr(),
3857            to: send_path.peer_addr(),
3858
3859            at: send_path.recovery.get_packet_send_time(now),
3860        };
3861
3862        Ok((done, info))
3863    }
3864
3865    fn send_single(
3866        &mut self, out: &mut [u8], send_pid: usize, has_initial: bool,
3867        now: Instant,
3868    ) -> Result<(Type, usize)> {
3869        if out.is_empty() {
3870            return Err(Error::BufferTooShort);
3871        }
3872
3873        if self.is_draining() {
3874            return Err(Error::Done);
3875        }
3876
3877        let is_closing = self.local_error.is_some();
3878
3879        let out_len = out.len();
3880
3881        let mut b = octets::OctetsMut::with_slice(out);
3882
3883        let pkt_type = self.write_pkt_type(send_pid)?;
3884
3885        let max_dgram_len = if !self.dgram_send_queue.is_empty() {
3886            self.dgram_max_writable_len()
3887        } else {
3888            None
3889        };
3890
3891        let epoch = pkt_type.to_epoch()?;
3892        let pkt_space = &mut self.pkt_num_spaces[epoch];
3893        let crypto_ctx = &mut self.crypto_ctx[epoch];
3894
3895        // Process lost frames. There might be several paths having lost frames.
3896        for (_, p) in self.paths.iter_mut() {
3897            while let Some(lost) = p.recovery.next_lost_frame(epoch) {
3898                match lost {
3899                    frame::Frame::CryptoHeader { offset, length } => {
3900                        crypto_ctx.crypto_stream.send.retransmit(offset, length);
3901
3902                        self.stream_retrans_bytes += length as u64;
3903                        p.stream_retrans_bytes += length as u64;
3904
3905                        self.retrans_count += 1;
3906                        p.retrans_count += 1;
3907                    },
3908
3909                    frame::Frame::StreamHeader {
3910                        stream_id,
3911                        offset,
3912                        length,
3913                        fin,
3914                    } => {
3915                        let stream = match self.streams.get_mut(stream_id) {
3916                            // Only retransmit data if the stream is not closed
3917                            // or stopped.
3918                            Some(v) if !v.send.is_stopped() => v,
3919
3920                            // Data on a closed stream will not be retransmitted
3921                            // or acked after it is declared lost, so update
3922                            // tx_buffered and qlog.
3923                            _ => {
3924                                self.tx_buffered =
3925                                    self.tx_buffered.saturating_sub(length);
3926
3927                                qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
3928                                    let ev_data = EventData::DataMoved(
3929                                        qlog::events::quic::DataMoved {
3930                                            stream_id: Some(stream_id),
3931                                            offset: Some(offset),
3932                                            length: Some(length as u64),
3933                                            from: Some(DataRecipient::Transport),
3934                                            to: Some(DataRecipient::Dropped),
3935                                            ..Default::default()
3936                                        },
3937                                    );
3938
3939                                    q.add_event_data_with_instant(ev_data, now)
3940                                        .ok();
3941                                });
3942
3943                                continue;
3944                            },
3945                        };
3946
3947                        let was_flushable = stream.is_flushable();
3948
3949                        let empty_fin = length == 0 && fin;
3950
3951                        stream.send.retransmit(offset, length);
3952
3953                        // If the stream is now flushable push it to the
3954                        // flushable queue, but only if it wasn't already
3955                        // queued.
3956                        //
3957                        // Consider the stream flushable also when we are
3958                        // sending a zero-length frame that has the fin flag
3959                        // set.
3960                        if (stream.is_flushable() || empty_fin) && !was_flushable
3961                        {
3962                            let priority_key = Arc::clone(&stream.priority_key);
3963                            self.streams.insert_flushable(&priority_key);
3964                        }
3965
3966                        self.stream_retrans_bytes += length as u64;
3967                        p.stream_retrans_bytes += length as u64;
3968
3969                        self.retrans_count += 1;
3970                        p.retrans_count += 1;
3971                    },
3972
3973                    frame::Frame::ACK { .. } => {
3974                        pkt_space.ack_elicited = true;
3975                    },
3976
3977                    frame::Frame::ResetStream {
3978                        stream_id,
3979                        error_code,
3980                        final_size,
3981                    } =>
3982                        if self.streams.get(stream_id).is_some() {
3983                            self.streams
3984                                .insert_reset(stream_id, error_code, final_size);
3985                        },
3986
3987                    // Retransmit HANDSHAKE_DONE only if it hasn't been acked at
3988                    // least once already.
3989                    frame::Frame::HandshakeDone if !self.handshake_done_acked => {
3990                        self.handshake_done_sent = false;
3991                    },
3992
3993                    frame::Frame::MaxStreamData { stream_id, .. } => {
3994                        if self.streams.get(stream_id).is_some() {
3995                            self.streams.insert_almost_full(stream_id);
3996                        }
3997                    },
3998
3999                    frame::Frame::MaxData { .. } => {
4000                        self.almost_full = true;
4001                    },
4002
4003                    frame::Frame::NewConnectionId { seq_num, .. } => {
4004                        self.ids.mark_advertise_new_scid_seq(seq_num, true);
4005                    },
4006
4007                    frame::Frame::RetireConnectionId { seq_num } => {
4008                        self.ids.mark_retire_dcid_seq(seq_num, true)?;
4009                    },
4010
4011                    frame::Frame::Ping {
4012                        mtu_probe: Some(failed_probe),
4013                    } =>
4014                        if let Some(pmtud) = p.pmtud.as_mut() {
4015                            trace!("pmtud probe dropped: {failed_probe}");
4016                            pmtud.failed_probe(failed_probe);
4017                        },
4018
4019                    _ => (),
4020                }
4021            }
4022        }
4023        self.check_tx_buffered_invariant();
4024
4025        let is_app_limited = self.delivery_rate_check_if_app_limited();
4026        let n_paths = self.paths.len();
4027        let path = self.paths.get_mut(send_pid)?;
4028        let flow_control = &mut self.flow_control;
4029        let pkt_space = &mut self.pkt_num_spaces[epoch];
4030        let crypto_ctx = &mut self.crypto_ctx[epoch];
4031        let pkt_num_manager = &mut self.pkt_num_manager;
4032
4033        let mut left = if let Some(pmtud) = path.pmtud.as_mut() {
4034            // Limit output buffer size by estimated path MTU.
4035            cmp::min(pmtud.get_current_mtu(), b.cap())
4036        } else {
4037            b.cap()
4038        };
4039
4040        if pkt_num_manager.should_skip_pn(self.handshake_completed) {
4041            pkt_num_manager.set_skip_pn(Some(self.next_pkt_num));
4042            self.next_pkt_num += 1;
4043        };
4044        let pn = self.next_pkt_num;
4045
4046        let largest_acked_pkt =
4047            path.recovery.get_largest_acked_on_epoch(epoch).unwrap_or(0);
4048        let pn_len = packet::pkt_num_len(pn, largest_acked_pkt);
4049
4050        // The AEAD overhead at the current encryption level.
4051        let crypto_overhead = crypto_ctx.crypto_overhead().ok_or(Error::Done)?;
4052
4053        let dcid_seq = path.active_dcid_seq.ok_or(Error::OutOfIdentifiers)?;
4054
4055        let dcid =
4056            ConnectionId::from_ref(self.ids.get_dcid(dcid_seq)?.cid.as_ref());
4057
4058        let scid = if let Some(scid_seq) = path.active_scid_seq {
4059            ConnectionId::from_ref(self.ids.get_scid(scid_seq)?.cid.as_ref())
4060        } else if pkt_type == Type::Short {
4061            ConnectionId::default()
4062        } else {
4063            return Err(Error::InvalidState);
4064        };
4065
4066        let hdr = Header {
4067            ty: pkt_type,
4068
4069            version: self.version,
4070
4071            dcid,
4072            scid,
4073
4074            pkt_num: 0,
4075            pkt_num_len: pn_len,
4076
4077            // Only clone token for Initial packets, as other packets don't have
4078            // this field (Retry doesn't count, as it's not encoded as part of
4079            // this code path).
4080            token: if pkt_type == Type::Initial {
4081                self.token.clone()
4082            } else {
4083                None
4084            },
4085
4086            versions: None,
4087            key_phase: self.key_phase,
4088        };
4089
4090        hdr.to_bytes(&mut b)?;
4091
4092        let hdr_trace = if log::max_level() == log::LevelFilter::Trace {
4093            Some(format!("{hdr:?}"))
4094        } else {
4095            None
4096        };
4097
4098        let hdr_ty = hdr.ty;
4099
4100        #[cfg(feature = "qlog")]
4101        let qlog_pkt_hdr = self.qlog.streamer.as_ref().map(|_q| {
4102            qlog::events::quic::PacketHeader::with_type(
4103                hdr.ty.to_qlog(),
4104                Some(pn),
4105                Some(hdr.version),
4106                Some(&hdr.scid),
4107                Some(&hdr.dcid),
4108            )
4109        });
4110
4111        // Calculate the space required for the packet, including the header
4112        // the payload length, the packet number and the AEAD overhead.
4113        let mut overhead = b.off() + pn_len + crypto_overhead;
4114
4115        // We assume that the payload length, which is only present in long
4116        // header packets, can always be encoded with a 2-byte varint.
4117        if pkt_type != Type::Short {
4118            overhead += PAYLOAD_LENGTH_LEN;
4119        }
4120
4121        // Make sure we have enough space left for the packet overhead.
4122        match left.checked_sub(overhead) {
4123            Some(v) => left = v,
4124
4125            None => {
4126                // We can't send more because there isn't enough space available
4127                // in the output buffer.
4128                //
4129                // This usually happens when we try to send a new packet but
4130                // failed because cwnd is almost full. In such case app_limited
4131                // is set to false here to make cwnd grow when ACK is received.
4132                path.recovery.update_app_limited(false);
4133                return Err(Error::Done);
4134            },
4135        }
4136
4137        // Make sure there is enough space for the minimum payload length.
4138        if left < PAYLOAD_MIN_LEN {
4139            path.recovery.update_app_limited(false);
4140            return Err(Error::Done);
4141        }
4142
4143        let mut frames: SmallVec<[frame::Frame; 1]> = SmallVec::new();
4144
4145        let mut ack_eliciting = false;
4146        let mut in_flight = false;
4147        let mut is_pmtud_probe = false;
4148        let mut has_data = false;
4149
4150        // Whether or not we should explicitly elicit an ACK via PING frame if we
4151        // implicitly elicit one otherwise.
4152        let ack_elicit_required = path.recovery.should_elicit_ack(epoch);
4153
4154        let header_offset = b.off();
4155
4156        // Reserve space for payload length in advance. Since we don't yet know
4157        // what the final length will be, we reserve 2 bytes in all cases.
4158        //
4159        // Only long header packets have an explicit length field.
4160        if pkt_type != Type::Short {
4161            b.skip(PAYLOAD_LENGTH_LEN)?;
4162        }
4163
4164        packet::encode_pkt_num(pn, pn_len, &mut b)?;
4165
4166        let payload_offset = b.off();
4167
4168        let cwnd_available =
4169            path.recovery.cwnd_available().saturating_sub(overhead);
4170
4171        let left_before_packing_ack_frame = left;
4172
4173        // Create ACK frame.
4174        //
4175        // When we need to explicitly elicit an ACK via PING later, go ahead and
4176        // generate an ACK (if there's anything to ACK) since we're going to
4177        // send a packet with PING anyways, even if we haven't received anything
4178        // ACK eliciting.
4179        if pkt_space.recv_pkt_need_ack.len() > 0 &&
4180            (pkt_space.ack_elicited || ack_elicit_required) &&
4181            (!is_closing ||
4182                (pkt_type == Type::Handshake &&
4183                    self.local_error
4184                        .as_ref()
4185                        .is_some_and(|le| le.is_app))) &&
4186            path.active()
4187        {
4188            #[cfg(not(feature = "fuzzing"))]
4189            let ack_delay = pkt_space.largest_rx_pkt_time.elapsed();
4190
4191            #[cfg(not(feature = "fuzzing"))]
4192            let ack_delay = ack_delay.as_micros() as u64 /
4193                2_u64
4194                    .pow(self.local_transport_params.ack_delay_exponent as u32);
4195
4196            // pseudo-random reproducible ack delays when fuzzing
4197            #[cfg(feature = "fuzzing")]
4198            let ack_delay = rand::rand_u8() as u64 + 1;
4199
4200            let frame = frame::Frame::ACK {
4201                ack_delay,
4202                ranges: pkt_space.recv_pkt_need_ack.clone(),
4203                ecn_counts: None, // sending ECN is not supported at this time
4204            };
4205
4206            // When a PING frame needs to be sent, avoid sending the ACK if
4207            // there is not enough cwnd available for both (note that PING
4208            // frames are always 1 byte, so we just need to check that the
4209            // ACK's length is lower than cwnd).
4210            if pkt_space.ack_elicited || frame.wire_len() < cwnd_available {
4211                // ACK-only packets are not congestion controlled so ACKs must
4212                // be bundled considering the buffer capacity only, and not the
4213                // available cwnd.
4214                if push_frame_to_pkt!(b, frames, frame, left) {
4215                    pkt_space.ack_elicited = false;
4216                }
4217            }
4218        }
4219
4220        // Limit output packet size by congestion window size.
4221        left = cmp::min(
4222            left,
4223            // Bytes consumed by ACK frames.
4224            cwnd_available.saturating_sub(left_before_packing_ack_frame - left),
4225        );
4226
4227        let mut challenge_data = None;
4228
4229        let active_path = self.paths.get_active_mut()?;
4230
4231        if pkt_type == Type::Short {
4232            // Create PMTUD probe.
4233            //
4234            // In order to send a PMTUD probe the current `left` value, which was
4235            // already limited by the current PMTU measure, needs to be ignored,
4236            // but the outgoing packet still needs to be limited by
4237            // the output buffer size, as well as the congestion
4238            // window.
4239            //
4240            // In addition, the PMTUD probe is only generated when the handshake
4241            // is confirmed, to avoid interfering with the handshake
4242            // (e.g. due to the anti-amplification limits).
4243            let should_probe_pmtu = active_path.should_send_pmtu_probe(
4244                self.handshake_confirmed,
4245                self.handshake_completed,
4246                out_len,
4247                is_closing,
4248                frames.is_empty(),
4249            );
4250
4251            if should_probe_pmtu {
4252                if let Some(pmtud) = active_path.pmtud.as_mut() {
4253                    let probe_size = pmtud.get_probe_size();
4254                    trace!(
4255                        "{} sending pmtud probe pmtu_probe={} estimated_pmtu={}",
4256                        self.trace_id,
4257                        probe_size,
4258                        pmtud.get_current_mtu(),
4259                    );
4260
4261                    left = probe_size;
4262
4263                    match left.checked_sub(overhead) {
4264                        Some(v) => left = v,
4265
4266                        None => {
4267                            // We can't send more because there isn't enough space
4268                            // available in the output buffer.
4269                            //
4270                            // This usually happens when we try to send a new
4271                            // packet but failed
4272                            // because cwnd is almost full.
4273                            //
4274                            // In such case app_limited is set to false here to
4275                            // make cwnd grow when ACK
4276                            // is received.
4277                            active_path.recovery.update_app_limited(false);
4278                            return Err(Error::Done);
4279                        },
4280                    }
4281
4282                    let frame = frame::Frame::Padding {
4283                        len: probe_size - overhead - 1,
4284                    };
4285
4286                    if push_frame_to_pkt!(b, frames, frame, left) {
4287                        let frame = frame::Frame::Ping {
4288                            mtu_probe: Some(probe_size),
4289                        };
4290
4291                        if push_frame_to_pkt!(b, frames, frame, left) {
4292                            ack_eliciting = true;
4293                            in_flight = true;
4294                        }
4295                    }
4296
4297                    // Reset probe flag after sending to prevent duplicate probes
4298                    // in a single flight.
4299                    pmtud.set_in_flight(true);
4300                    is_pmtud_probe = true;
4301                }
4302            }
4303
4304            let path = self.paths.get_mut(send_pid)?;
4305            // Create PATH_RESPONSE frame if needed.
4306            // We do not try to ensure that these are really sent.
4307            while let Some(challenge) = path.pop_received_challenge() {
4308                let frame = frame::Frame::PathResponse { data: challenge };
4309
4310                if push_frame_to_pkt!(b, frames, frame, left) {
4311                    ack_eliciting = true;
4312                    in_flight = true;
4313                } else {
4314                    // If there are other pending PATH_RESPONSE, don't lose them
4315                    // now.
4316                    break;
4317                }
4318            }
4319
4320            // Create PATH_CHALLENGE frame if needed.
4321            if path.validation_requested() {
4322                // TODO: ensure that data is unique over paths.
4323                let data = rand::rand_u64().to_be_bytes();
4324
4325                let frame = frame::Frame::PathChallenge { data };
4326
4327                if push_frame_to_pkt!(b, frames, frame, left) {
4328                    // Let's notify the path once we know the packet size.
4329                    challenge_data = Some(data);
4330
4331                    ack_eliciting = true;
4332                    in_flight = true;
4333                }
4334            }
4335
4336            if let Some(key_update) = crypto_ctx.key_update.as_mut() {
4337                key_update.update_acked = true;
4338            }
4339        }
4340
4341        let path = self.paths.get_mut(send_pid)?;
4342
4343        if pkt_type == Type::Short && !is_closing {
4344            // Create NEW_CONNECTION_ID frames as needed.
4345            while let Some(seq_num) = self.ids.next_advertise_new_scid_seq() {
4346                let frame = self.ids.get_new_connection_id_frame_for(seq_num)?;
4347
4348                if push_frame_to_pkt!(b, frames, frame, left) {
4349                    self.ids.mark_advertise_new_scid_seq(seq_num, false);
4350
4351                    ack_eliciting = true;
4352                    in_flight = true;
4353                } else {
4354                    break;
4355                }
4356            }
4357        }
4358
4359        if pkt_type == Type::Short && !is_closing && path.active() {
4360            // Create HANDSHAKE_DONE frame.
4361            // self.should_send_handshake_done() but without the need to borrow
4362            if self.handshake_completed &&
4363                !self.handshake_done_sent &&
4364                self.is_server
4365            {
4366                let frame = frame::Frame::HandshakeDone;
4367
4368                if push_frame_to_pkt!(b, frames, frame, left) {
4369                    self.handshake_done_sent = true;
4370
4371                    ack_eliciting = true;
4372                    in_flight = true;
4373                }
4374            }
4375
4376            // Create MAX_STREAMS_BIDI frame.
4377            if self.streams.should_update_max_streams_bidi() {
4378                let frame = frame::Frame::MaxStreamsBidi {
4379                    max: self.streams.max_streams_bidi_next(),
4380                };
4381
4382                if push_frame_to_pkt!(b, frames, frame, left) {
4383                    self.streams.update_max_streams_bidi();
4384
4385                    ack_eliciting = true;
4386                    in_flight = true;
4387                }
4388            }
4389
4390            // Create MAX_STREAMS_UNI frame.
4391            if self.streams.should_update_max_streams_uni() {
4392                let frame = frame::Frame::MaxStreamsUni {
4393                    max: self.streams.max_streams_uni_next(),
4394                };
4395
4396                if push_frame_to_pkt!(b, frames, frame, left) {
4397                    self.streams.update_max_streams_uni();
4398
4399                    ack_eliciting = true;
4400                    in_flight = true;
4401                }
4402            }
4403
4404            // Create DATA_BLOCKED frame.
4405            if let Some(limit) = self.blocked_limit {
4406                let frame = frame::Frame::DataBlocked { limit };
4407
4408                if push_frame_to_pkt!(b, frames, frame, left) {
4409                    self.blocked_limit = None;
4410                    self.data_blocked_sent_count =
4411                        self.data_blocked_sent_count.saturating_add(1);
4412
4413                    ack_eliciting = true;
4414                    in_flight = true;
4415                }
4416            }
4417
4418            // Create MAX_STREAM_DATA frames as needed.
4419            for stream_id in self.streams.almost_full() {
4420                let stream = match self.streams.get_mut(stream_id) {
4421                    Some(v) => v,
4422
4423                    None => {
4424                        // The stream doesn't exist anymore, so remove it from
4425                        // the almost full set.
4426                        self.streams.remove_almost_full(stream_id);
4427                        continue;
4428                    },
4429                };
4430
4431                // Autotune the stream window size.
4432                stream.recv.autotune_window(now, path.recovery.rtt());
4433
4434                let frame = frame::Frame::MaxStreamData {
4435                    stream_id,
4436                    max: stream.recv.max_data_next(),
4437                };
4438
4439                if push_frame_to_pkt!(b, frames, frame, left) {
4440                    let recv_win = stream.recv.window();
4441
4442                    stream.recv.update_max_data(now);
4443
4444                    self.streams.remove_almost_full(stream_id);
4445
4446                    ack_eliciting = true;
4447                    in_flight = true;
4448
4449                    // Make sure the connection window always has some
4450                    // room compared to the stream window.
4451                    flow_control.ensure_window_lower_bound(
4452                        (recv_win as f64 * CONNECTION_WINDOW_FACTOR) as u64,
4453                    );
4454
4455                    // Also send MAX_DATA when MAX_STREAM_DATA is sent, to avoid a
4456                    // potential race condition.
4457                    self.almost_full = true;
4458                }
4459            }
4460
4461            // Create MAX_DATA frame as needed.
4462            if self.almost_full &&
4463                flow_control.max_data() < flow_control.max_data_next()
4464            {
4465                // Autotune the connection window size.
4466                flow_control.autotune_window(now, path.recovery.rtt());
4467
4468                let frame = frame::Frame::MaxData {
4469                    max: flow_control.max_data_next(),
4470                };
4471
4472                if push_frame_to_pkt!(b, frames, frame, left) {
4473                    self.almost_full = false;
4474
4475                    // Commits the new max_rx_data limit.
4476                    flow_control.update_max_data(now);
4477
4478                    ack_eliciting = true;
4479                    in_flight = true;
4480                }
4481            }
4482
4483            // Create STOP_SENDING frames as needed.
4484            for (stream_id, error_code) in self
4485                .streams
4486                .stopped()
4487                .map(|(&k, &v)| (k, v))
4488                .collect::<Vec<(u64, u64)>>()
4489            {
4490                let frame = frame::Frame::StopSending {
4491                    stream_id,
4492                    error_code,
4493                };
4494
4495                if push_frame_to_pkt!(b, frames, frame, left) {
4496                    self.streams.remove_stopped(stream_id);
4497
4498                    ack_eliciting = true;
4499                    in_flight = true;
4500                }
4501            }
4502
4503            // Create RESET_STREAM frames as needed.
4504            for (stream_id, (error_code, final_size)) in self
4505                .streams
4506                .reset()
4507                .map(|(&k, &v)| (k, v))
4508                .collect::<Vec<(u64, (u64, u64))>>()
4509            {
4510                let frame = frame::Frame::ResetStream {
4511                    stream_id,
4512                    error_code,
4513                    final_size,
4514                };
4515
4516                if push_frame_to_pkt!(b, frames, frame, left) {
4517                    self.streams.remove_reset(stream_id);
4518
4519                    ack_eliciting = true;
4520                    in_flight = true;
4521                }
4522            }
4523
4524            // Create STREAM_DATA_BLOCKED frames as needed.
4525            for (stream_id, limit) in self
4526                .streams
4527                .blocked()
4528                .map(|(&k, &v)| (k, v))
4529                .collect::<Vec<(u64, u64)>>()
4530            {
4531                let frame = frame::Frame::StreamDataBlocked { stream_id, limit };
4532
4533                if push_frame_to_pkt!(b, frames, frame, left) {
4534                    self.streams.remove_blocked(stream_id);
4535                    self.stream_data_blocked_sent_count =
4536                        self.stream_data_blocked_sent_count.saturating_add(1);
4537
4538                    ack_eliciting = true;
4539                    in_flight = true;
4540                }
4541            }
4542
4543            // Create RETIRE_CONNECTION_ID frames as needed.
4544            let retire_dcid_seqs = self.ids.retire_dcid_seqs();
4545
4546            for seq_num in retire_dcid_seqs {
4547                // The sequence number specified in a RETIRE_CONNECTION_ID frame
4548                // MUST NOT refer to the Destination Connection ID field of the
4549                // packet in which the frame is contained.
4550                let dcid_seq = path.active_dcid_seq.ok_or(Error::InvalidState)?;
4551
4552                if seq_num == dcid_seq {
4553                    continue;
4554                }
4555
4556                let frame = frame::Frame::RetireConnectionId { seq_num };
4557
4558                if push_frame_to_pkt!(b, frames, frame, left) {
4559                    self.ids.mark_retire_dcid_seq(seq_num, false)?;
4560
4561                    ack_eliciting = true;
4562                    in_flight = true;
4563                } else {
4564                    break;
4565                }
4566            }
4567        }
4568
4569        // Create CONNECTION_CLOSE frame. Try to send this only on the active
4570        // path, unless it is the last one available.
4571        if path.active() || n_paths == 1 {
4572            if let Some(conn_err) = self.local_error.as_ref() {
4573                if conn_err.is_app {
4574                    // Create ApplicationClose frame.
4575                    if pkt_type == Type::Short {
4576                        let frame = frame::Frame::ApplicationClose {
4577                            error_code: conn_err.error_code,
4578                            reason: conn_err.reason.clone(),
4579                        };
4580
4581                        if push_frame_to_pkt!(b, frames, frame, left) {
4582                            let pto = path.recovery.pto();
4583                            self.draining_timer = Some(now + (pto * 3));
4584
4585                            ack_eliciting = true;
4586                            in_flight = true;
4587                        }
4588                    }
4589                } else {
4590                    // Create ConnectionClose frame.
4591                    let frame = frame::Frame::ConnectionClose {
4592                        error_code: conn_err.error_code,
4593                        frame_type: 0,
4594                        reason: conn_err.reason.clone(),
4595                    };
4596
4597                    if push_frame_to_pkt!(b, frames, frame, left) {
4598                        let pto = path.recovery.pto();
4599                        self.draining_timer = Some(now + (pto * 3));
4600
4601                        ack_eliciting = true;
4602                        in_flight = true;
4603                    }
4604                }
4605            }
4606        }
4607
4608        // Create CRYPTO frame.
4609        if crypto_ctx.crypto_stream.is_flushable() &&
4610            left > frame::MAX_CRYPTO_OVERHEAD &&
4611            !is_closing &&
4612            path.active()
4613        {
4614            let crypto_off = crypto_ctx.crypto_stream.send.off_front();
4615
4616            // Encode the frame.
4617            //
4618            // Instead of creating a `frame::Frame` object, encode the frame
4619            // directly into the packet buffer.
4620            //
4621            // First we reserve some space in the output buffer for writing the
4622            // frame header (we assume the length field is always a 2-byte
4623            // varint as we don't know the value yet).
4624            //
4625            // Then we emit the data from the crypto stream's send buffer.
4626            //
4627            // Finally we go back and encode the frame header with the now
4628            // available information.
4629            let hdr_off = b.off();
4630            let hdr_len = 1 + // frame type
4631                octets::varint_len(crypto_off) + // offset
4632                2; // length, always encode as 2-byte varint
4633
4634            if let Some(max_len) = left.checked_sub(hdr_len) {
4635                let (mut crypto_hdr, mut crypto_payload) =
4636                    b.split_at(hdr_off + hdr_len)?;
4637
4638                // Write stream data into the packet buffer.
4639                let (len, _) = crypto_ctx
4640                    .crypto_stream
4641                    .send
4642                    .emit(&mut crypto_payload.as_mut()[..max_len])?;
4643
4644                // Encode the frame's header.
4645                //
4646                // Due to how `OctetsMut::split_at()` works, `crypto_hdr` starts
4647                // from the initial offset of `b` (rather than the current
4648                // offset), so it needs to be advanced to the
4649                // initial frame offset.
4650                crypto_hdr.skip(hdr_off)?;
4651
4652                frame::encode_crypto_header(
4653                    crypto_off,
4654                    len as u64,
4655                    &mut crypto_hdr,
4656                )?;
4657
4658                // Advance the packet buffer's offset.
4659                b.skip(hdr_len + len)?;
4660
4661                let frame = frame::Frame::CryptoHeader {
4662                    offset: crypto_off,
4663                    length: len,
4664                };
4665
4666                if push_frame_to_pkt!(b, frames, frame, left) {
4667                    ack_eliciting = true;
4668                    in_flight = true;
4669                    has_data = true;
4670                }
4671            }
4672        }
4673
4674        // The preference of data-bearing frame to include in a packet
4675        // is managed by `self.emit_dgram`. However, whether any frames
4676        // can be sent depends on the state of their buffers. In the case
4677        // where one type is preferred but its buffer is empty, fall back
4678        // to the other type in order not to waste this function call.
4679        let mut dgram_emitted = false;
4680        let dgrams_to_emit = max_dgram_len.is_some();
4681        let stream_to_emit = self.streams.has_flushable();
4682
4683        let mut do_dgram = self.emit_dgram && dgrams_to_emit;
4684        let do_stream = !self.emit_dgram && stream_to_emit;
4685
4686        if !do_stream && dgrams_to_emit {
4687            do_dgram = true;
4688        }
4689
4690        // Create DATAGRAM frame.
4691        if (pkt_type == Type::Short || pkt_type == Type::ZeroRTT) &&
4692            left > frame::MAX_DGRAM_OVERHEAD &&
4693            !is_closing &&
4694            path.active() &&
4695            do_dgram
4696        {
4697            if let Some(max_dgram_payload) = max_dgram_len {
4698                while let Some(len) = self.dgram_send_queue.peek_front_len() {
4699                    let hdr_off = b.off();
4700                    let hdr_len = 1 + // frame type
4701                        2; // length, always encode as 2-byte varint
4702
4703                    if (hdr_len + len) <= left {
4704                        // Front of the queue fits this packet, send it.
4705                        match self.dgram_send_queue.pop() {
4706                            Some(data) => {
4707                                // Encode the frame.
4708                                //
4709                                // Instead of creating a `frame::Frame` object,
4710                                // encode the frame directly into the packet
4711                                // buffer.
4712                                //
4713                                // First we reserve some space in the output
4714                                // buffer for writing the frame header (we
4715                                // assume the length field is always a 2-byte
4716                                // varint as we don't know the value yet).
4717                                //
4718                                // Then we emit the data from the DATAGRAM's
4719                                // buffer.
4720                                //
4721                                // Finally we go back and encode the frame
4722                                // header with the now available information.
4723                                let (mut dgram_hdr, mut dgram_payload) =
4724                                    b.split_at(hdr_off + hdr_len)?;
4725
4726                                dgram_payload.as_mut()[..len]
4727                                    .copy_from_slice(&data);
4728
4729                                // Encode the frame's header.
4730                                //
4731                                // Due to how `OctetsMut::split_at()` works,
4732                                // `dgram_hdr` starts from the initial offset
4733                                // of `b` (rather than the current offset), so
4734                                // it needs to be advanced to the initial frame
4735                                // offset.
4736                                dgram_hdr.skip(hdr_off)?;
4737
4738                                frame::encode_dgram_header(
4739                                    len as u64,
4740                                    &mut dgram_hdr,
4741                                )?;
4742
4743                                // Advance the packet buffer's offset.
4744                                b.skip(hdr_len + len)?;
4745
4746                                let frame =
4747                                    frame::Frame::DatagramHeader { length: len };
4748
4749                                if push_frame_to_pkt!(b, frames, frame, left) {
4750                                    ack_eliciting = true;
4751                                    in_flight = true;
4752                                    dgram_emitted = true;
4753                                    self.dgram_sent_count =
4754                                        self.dgram_sent_count.saturating_add(1);
4755                                    path.dgram_sent_count =
4756                                        path.dgram_sent_count.saturating_add(1);
4757                                }
4758                            },
4759
4760                            None => continue,
4761                        };
4762                    } else if len > max_dgram_payload {
4763                        // This dgram frame will never fit. Let's purge it.
4764                        self.dgram_send_queue.pop();
4765                    } else {
4766                        break;
4767                    }
4768                }
4769            }
4770        }
4771
4772        // Create a single STREAM frame for the first stream that is flushable.
4773        if (pkt_type == Type::Short || pkt_type == Type::ZeroRTT) &&
4774            left > frame::MAX_STREAM_OVERHEAD &&
4775            !is_closing &&
4776            path.active() &&
4777            !dgram_emitted
4778        {
4779            while let Some(priority_key) = self.streams.peek_flushable() {
4780                let stream_id = priority_key.id;
4781                let stream = match self.streams.get_mut(stream_id) {
4782                    // Avoid sending frames for streams that were already stopped.
4783                    //
4784                    // This might happen if stream data was buffered but not yet
4785                    // flushed on the wire when a STOP_SENDING frame is received.
4786                    Some(v) if !v.send.is_stopped() => v,
4787                    _ => {
4788                        self.streams.remove_flushable(&priority_key);
4789                        continue;
4790                    },
4791                };
4792
4793                let stream_off = stream.send.off_front();
4794
4795                // Encode the frame.
4796                //
4797                // Instead of creating a `frame::Frame` object, encode the frame
4798                // directly into the packet buffer.
4799                //
4800                // First we reserve some space in the output buffer for writing
4801                // the frame header (we assume the length field is always a
4802                // 2-byte varint as we don't know the value yet).
4803                //
4804                // Then we emit the data from the stream's send buffer.
4805                //
4806                // Finally we go back and encode the frame header with the now
4807                // available information.
4808                let hdr_off = b.off();
4809                let hdr_len = 1 + // frame type
4810                    octets::varint_len(stream_id) + // stream_id
4811                    octets::varint_len(stream_off) + // offset
4812                    2; // length, always encode as 2-byte varint
4813
4814                let max_len = match left.checked_sub(hdr_len) {
4815                    Some(v) => v,
4816                    None => {
4817                        let priority_key = Arc::clone(&stream.priority_key);
4818                        self.streams.remove_flushable(&priority_key);
4819
4820                        continue;
4821                    },
4822                };
4823
4824                let (mut stream_hdr, mut stream_payload) =
4825                    b.split_at(hdr_off + hdr_len)?;
4826
4827                // Write stream data into the packet buffer.
4828                let (len, fin) =
4829                    stream.send.emit(&mut stream_payload.as_mut()[..max_len])?;
4830
4831                // Encode the frame's header.
4832                //
4833                // Due to how `OctetsMut::split_at()` works, `stream_hdr` starts
4834                // from the initial offset of `b` (rather than the current
4835                // offset), so it needs to be advanced to the initial frame
4836                // offset.
4837                stream_hdr.skip(hdr_off)?;
4838
4839                frame::encode_stream_header(
4840                    stream_id,
4841                    stream_off,
4842                    len as u64,
4843                    fin,
4844                    &mut stream_hdr,
4845                )?;
4846
4847                // Advance the packet buffer's offset.
4848                b.skip(hdr_len + len)?;
4849
4850                let frame = frame::Frame::StreamHeader {
4851                    stream_id,
4852                    offset: stream_off,
4853                    length: len,
4854                    fin,
4855                };
4856
4857                if push_frame_to_pkt!(b, frames, frame, left) {
4858                    ack_eliciting = true;
4859                    in_flight = true;
4860                    has_data = true;
4861                }
4862
4863                let priority_key = Arc::clone(&stream.priority_key);
4864                // If the stream is no longer flushable, remove it from the queue
4865                if !stream.is_flushable() {
4866                    self.streams.remove_flushable(&priority_key);
4867                } else if stream.incremental {
4868                    // Shuffle the incremental stream to the back of the
4869                    // queue.
4870                    self.streams.remove_flushable(&priority_key);
4871                    self.streams.insert_flushable(&priority_key);
4872                }
4873
4874                #[cfg(feature = "fuzzing")]
4875                // Coalesce STREAM frames when fuzzing.
4876                if left > frame::MAX_STREAM_OVERHEAD {
4877                    continue;
4878                }
4879
4880                break;
4881            }
4882        }
4883
4884        // Alternate trying to send DATAGRAMs next time.
4885        self.emit_dgram = !dgram_emitted;
4886
4887        // If no other ack-eliciting frame is sent, include a PING frame
4888        // - if PTO probe needed; OR
4889        // - if we've sent too many non ack-eliciting packets without having
4890        // sent an ACK eliciting one; OR
4891        // - the application requested an ack-eliciting frame be sent.
4892        if (ack_elicit_required || path.needs_ack_eliciting) &&
4893            !ack_eliciting &&
4894            left >= 1 &&
4895            !is_closing
4896        {
4897            let frame = frame::Frame::Ping { mtu_probe: None };
4898
4899            if push_frame_to_pkt!(b, frames, frame, left) {
4900                ack_eliciting = true;
4901                in_flight = true;
4902            }
4903        }
4904
4905        if ack_eliciting && !is_pmtud_probe {
4906            path.needs_ack_eliciting = false;
4907            path.recovery.ping_sent(epoch);
4908        }
4909
4910        if !has_data &&
4911            !dgram_emitted &&
4912            cwnd_available > frame::MAX_STREAM_OVERHEAD
4913        {
4914            path.recovery.on_app_limited();
4915        }
4916
4917        if frames.is_empty() {
4918            // When we reach this point we are not able to write more, so set
4919            // app_limited to false.
4920            path.recovery.update_app_limited(false);
4921            return Err(Error::Done);
4922        }
4923
4924        // When coalescing a 1-RTT packet, we can't add padding in the UDP
4925        // datagram, so use PADDING frames instead.
4926        //
4927        // This is only needed if
4928        // 1) an Initial packet has already been written to the UDP datagram,
4929        // as Initial always requires padding.
4930        //
4931        // 2) this is a probing packet towards an unvalidated peer address.
4932        if (has_initial || !path.validated()) &&
4933            pkt_type == Type::Short &&
4934            left >= 1
4935        {
4936            let frame = frame::Frame::Padding { len: left };
4937
4938            if push_frame_to_pkt!(b, frames, frame, left) {
4939                in_flight = true;
4940            }
4941        }
4942
4943        // Pad payload so that it's always at least 4 bytes.
4944        if b.off() - payload_offset < PAYLOAD_MIN_LEN {
4945            let payload_len = b.off() - payload_offset;
4946
4947            let frame = frame::Frame::Padding {
4948                len: PAYLOAD_MIN_LEN - payload_len,
4949            };
4950
4951            #[allow(unused_assignments)]
4952            if push_frame_to_pkt!(b, frames, frame, left) {
4953                in_flight = true;
4954            }
4955        }
4956
4957        let payload_len = b.off() - payload_offset;
4958
4959        // Fill in payload length.
4960        if pkt_type != Type::Short {
4961            let len = pn_len + payload_len + crypto_overhead;
4962
4963            let (_, mut payload_with_len) = b.split_at(header_offset)?;
4964            payload_with_len
4965                .put_varint_with_len(len as u64, PAYLOAD_LENGTH_LEN)?;
4966        }
4967
4968        trace!(
4969            "{} tx pkt {} len={} pn={} {}",
4970            self.trace_id,
4971            hdr_trace.unwrap_or_default(),
4972            payload_len,
4973            pn,
4974            AddrTupleFmt(path.local_addr(), path.peer_addr())
4975        );
4976
4977        #[cfg(feature = "qlog")]
4978        let mut qlog_frames: SmallVec<
4979            [qlog::events::quic::QuicFrame; 1],
4980        > = SmallVec::with_capacity(frames.len());
4981
4982        for frame in &mut frames {
4983            trace!("{} tx frm {:?}", self.trace_id, frame);
4984
4985            qlog_with_type!(QLOG_PACKET_TX, self.qlog, _q, {
4986                qlog_frames.push(frame.to_qlog());
4987            });
4988        }
4989
4990        qlog_with_type!(QLOG_PACKET_TX, self.qlog, q, {
4991            if let Some(header) = qlog_pkt_hdr {
4992                // Qlog packet raw info described at
4993                // https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-main-schema-00#section-5.1
4994                //
4995                // `length` includes packet headers and trailers (AEAD tag).
4996                let length = payload_len + payload_offset + crypto_overhead;
4997                let qlog_raw_info = RawInfo {
4998                    length: Some(length as u64),
4999                    payload_length: Some(payload_len as u64),
5000                    data: None,
5001                };
5002
5003                let send_at_time =
5004                    now.duration_since(q.start_time()).as_secs_f32() * 1000.0;
5005
5006                let ev_data =
5007                    EventData::PacketSent(qlog::events::quic::PacketSent {
5008                        header,
5009                        frames: Some(qlog_frames),
5010                        raw: Some(qlog_raw_info),
5011                        send_at_time: Some(send_at_time),
5012                        ..Default::default()
5013                    });
5014
5015                q.add_event_data_with_instant(ev_data, now).ok();
5016            }
5017        });
5018
5019        let aead = match crypto_ctx.crypto_seal {
5020            Some(ref v) => v,
5021            None => return Err(Error::InvalidState),
5022        };
5023
5024        let written = packet::encrypt_pkt(
5025            &mut b,
5026            pn,
5027            pn_len,
5028            payload_len,
5029            payload_offset,
5030            None,
5031            aead,
5032        )?;
5033
5034        let sent_pkt_has_data = if path.recovery.gcongestion_enabled() {
5035            has_data || dgram_emitted
5036        } else {
5037            has_data
5038        };
5039
5040        let sent_pkt = recovery::Sent {
5041            pkt_num: pn,
5042            frames,
5043            time_sent: now,
5044            time_acked: None,
5045            time_lost: None,
5046            size: if ack_eliciting { written } else { 0 },
5047            ack_eliciting,
5048            in_flight,
5049            delivered: 0,
5050            delivered_time: now,
5051            first_sent_time: now,
5052            is_app_limited: false,
5053            tx_in_flight: 0,
5054            lost: 0,
5055            has_data: sent_pkt_has_data,
5056            is_pmtud_probe,
5057        };
5058
5059        if in_flight && is_app_limited {
5060            path.recovery.delivery_rate_update_app_limited(true);
5061        }
5062
5063        self.next_pkt_num += 1;
5064
5065        let handshake_status = recovery::HandshakeStatus {
5066            has_handshake_keys: self.crypto_ctx[packet::Epoch::Handshake]
5067                .has_keys(),
5068            peer_verified_address: self.peer_verified_initial_address,
5069            completed: self.handshake_completed,
5070        };
5071
5072        self.on_packet_sent(send_pid, sent_pkt, epoch, handshake_status, now)?;
5073
5074        let path = self.paths.get_mut(send_pid)?;
5075        qlog_with_type!(QLOG_METRICS, self.qlog, q, {
5076            path.recovery.maybe_qlog(q, now);
5077        });
5078
5079        // Record sent packet size if we probe the path.
5080        if let Some(data) = challenge_data {
5081            path.add_challenge_sent(data, written, now);
5082        }
5083
5084        self.sent_count += 1;
5085        self.sent_bytes += written as u64;
5086        path.sent_count += 1;
5087        path.sent_bytes += written as u64;
5088
5089        if self.dgram_send_queue.byte_size() > path.recovery.cwnd_available() {
5090            path.recovery.update_app_limited(false);
5091        }
5092
5093        path.max_send_bytes = path.max_send_bytes.saturating_sub(written);
5094
5095        // On the client, drop initial state after sending an Handshake packet.
5096        if !self.is_server && hdr_ty == Type::Handshake {
5097            self.drop_epoch_state(packet::Epoch::Initial, now);
5098        }
5099
5100        // (Re)start the idle timer if we are sending the first ack-eliciting
5101        // packet since last receiving a packet.
5102        if ack_eliciting && !self.ack_eliciting_sent {
5103            if let Some(idle_timeout) = self.idle_timeout() {
5104                self.idle_timer = Some(now + idle_timeout);
5105            }
5106        }
5107
5108        if ack_eliciting {
5109            self.ack_eliciting_sent = true;
5110        }
5111
5112        Ok((pkt_type, written))
5113    }
5114
5115    fn on_packet_sent(
5116        &mut self, send_pid: usize, sent_pkt: recovery::Sent,
5117        epoch: packet::Epoch, handshake_status: recovery::HandshakeStatus,
5118        now: Instant,
5119    ) -> Result<()> {
5120        let path = self.paths.get_mut(send_pid)?;
5121
5122        // It's fine to set the skip counter based on a non-active path's values.
5123        let cwnd = path.recovery.cwnd();
5124        let max_datagram_size = path.recovery.max_datagram_size();
5125        self.pkt_num_spaces[epoch].on_packet_sent(&sent_pkt);
5126        self.pkt_num_manager.on_packet_sent(
5127            cwnd,
5128            max_datagram_size,
5129            self.handshake_completed,
5130        );
5131
5132        path.recovery.on_packet_sent(
5133            sent_pkt,
5134            epoch,
5135            handshake_status,
5136            now,
5137            &self.trace_id,
5138        );
5139
5140        Ok(())
5141    }
5142
5143    /// Returns the desired send time for the next packet.
5144    #[inline]
5145    pub fn get_next_release_time(&self) -> Option<ReleaseDecision> {
5146        Some(
5147            self.paths
5148                .get_active()
5149                .ok()?
5150                .recovery
5151                .get_next_release_time(),
5152        )
5153    }
5154
5155    /// Returns whether gcongestion is enabled.
5156    #[inline]
5157    pub fn gcongestion_enabled(&self) -> Option<bool> {
5158        Some(self.paths.get_active().ok()?.recovery.gcongestion_enabled())
5159    }
5160
5161    /// Returns the maximum pacing into the future.
5162    ///
5163    /// Equals 1/8 of the smoothed RTT, but at least 1ms and not greater than
5164    /// 5ms.
5165    pub fn max_release_into_future(&self) -> Duration {
5166        self.paths
5167            .get_active()
5168            .map(|p| p.recovery.rtt().mul_f64(0.125))
5169            .unwrap_or(Duration::from_millis(1))
5170            .max(Duration::from_millis(1))
5171            .min(Duration::from_millis(5))
5172    }
5173
5174    /// Returns whether pacing is enabled.
5175    #[inline]
5176    pub fn pacing_enabled(&self) -> bool {
5177        self.recovery_config.pacing
5178    }
5179
5180    /// Returns the size of the send quantum, in bytes.
5181    ///
5182    /// This represents the maximum size of a packet burst as determined by the
5183    /// congestion control algorithm in use.
5184    ///
5185    /// Applications can, for example, use it in conjunction with segmentation
5186    /// offloading mechanisms as the maximum limit for outgoing aggregates of
5187    /// multiple packets.
5188    #[inline]
5189    pub fn send_quantum(&self) -> usize {
5190        match self.paths.get_active() {
5191            Ok(p) => p.recovery.send_quantum(),
5192            _ => 0,
5193        }
5194    }
5195
5196    /// Returns the size of the send quantum over the given 4-tuple, in bytes.
5197    ///
5198    /// This represents the maximum size of a packet burst as determined by the
5199    /// congestion control algorithm in use.
5200    ///
5201    /// Applications can, for example, use it in conjunction with segmentation
5202    /// offloading mechanisms as the maximum limit for outgoing aggregates of
5203    /// multiple packets.
5204    ///
5205    /// If the (`local_addr`, peer_addr`) 4-tuple relates to a non-existing
5206    /// path, this method returns 0.
5207    pub fn send_quantum_on_path(
5208        &self, local_addr: SocketAddr, peer_addr: SocketAddr,
5209    ) -> usize {
5210        self.paths
5211            .path_id_from_addrs(&(local_addr, peer_addr))
5212            .and_then(|pid| self.paths.get(pid).ok())
5213            .map(|path| path.recovery.send_quantum())
5214            .unwrap_or(0)
5215    }
5216
5217    /// Reads contiguous data from a stream into the provided slice.
5218    ///
5219    /// The slice must be sized by the caller and will be populated up to its
5220    /// capacity.
5221    ///
5222    /// On success the amount of bytes read and a flag indicating the fin state
5223    /// is returned as a tuple, or [`Done`] if there is no data to read.
5224    ///
5225    /// Reading data from a stream may trigger queueing of control messages
5226    /// (e.g. MAX_STREAM_DATA). [`send()`] should be called afterwards.
5227    ///
5228    /// [`Done`]: enum.Error.html#variant.Done
5229    /// [`send()`]: struct.Connection.html#method.send
5230    ///
5231    /// ## Examples:
5232    ///
5233    /// ```no_run
5234    /// # let mut buf = [0; 512];
5235    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5236    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5237    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5238    /// # let peer = "127.0.0.1:1234".parse().unwrap();
5239    /// # let local = socket.local_addr().unwrap();
5240    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5241    /// # let stream_id = 0;
5242    /// while let Ok((read, fin)) = conn.stream_recv(stream_id, &mut buf) {
5243    ///     println!("Got {} bytes on stream {}", read, stream_id);
5244    /// }
5245    /// # Ok::<(), quiche::Error>(())
5246    /// ```
5247    pub fn stream_recv(
5248        &mut self, stream_id: u64, out: &mut [u8],
5249    ) -> Result<(usize, bool)> {
5250        self.do_stream_recv(stream_id, RecvAction::Emit { out })
5251    }
5252
5253    /// Discard contiguous data from a stream without copying.
5254    ///
5255    /// On success the amount of bytes discarded and a flag indicating the fin
5256    /// state is returned as a tuple, or [`Done`] if there is no data to
5257    /// discard.
5258    ///
5259    /// Discarding data from a stream may trigger queueing of control messages
5260    /// (e.g. MAX_STREAM_DATA). [`send()`] should be called afterwards.
5261    ///
5262    /// [`Done`]: enum.Error.html#variant.Done
5263    /// [`send()`]: struct.Connection.html#method.send
5264    ///
5265    /// ## Examples:
5266    ///
5267    /// ```no_run
5268    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5269    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5270    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5271    /// # let peer = "127.0.0.1:1234".parse().unwrap();
5272    /// # let local = socket.local_addr().unwrap();
5273    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5274    /// # let stream_id = 0;
5275    /// while let Ok((read, fin)) = conn.stream_discard(stream_id, 1) {
5276    ///     println!("Discarded {} byte(s) on stream {}", read, stream_id);
5277    /// }
5278    /// # Ok::<(), quiche::Error>(())
5279    /// ```
5280    pub fn stream_discard(
5281        &mut self, stream_id: u64, len: usize,
5282    ) -> Result<(usize, bool)> {
5283        self.do_stream_recv(stream_id, RecvAction::Discard { len })
5284    }
5285
5286    // Reads or discards contiguous data from a stream.
5287    //
5288    // Passing an `action` of `StreamRecvAction::Emit` results in a read into
5289    // the provided slice. It must be sized by the caller and will be populated
5290    // up to its capacity.
5291    //
5292    // Passing an `action` of `StreamRecvAction::Discard` results in discard up
5293    // to the indicated length.
5294    //
5295    // On success the amount of bytes read or discarded, and a flag indicating
5296    // the fin state, is returned as a tuple, or [`Done`] if there is no data to
5297    // read or discard.
5298    //
5299    // Reading or discarding data from a stream may trigger queueing of control
5300    // messages (e.g. MAX_STREAM_DATA). [`send()`] should be called afterwards.
5301    //
5302    // [`Done`]: enum.Error.html#variant.Done
5303    // [`send()`]: struct.Connection.html#method.send
5304    fn do_stream_recv(
5305        &mut self, stream_id: u64, action: RecvAction,
5306    ) -> Result<(usize, bool)> {
5307        // We can't read on our own unidirectional streams.
5308        if !stream::is_bidi(stream_id) &&
5309            stream::is_local(stream_id, self.is_server)
5310        {
5311            return Err(Error::InvalidStreamState(stream_id));
5312        }
5313
5314        let stream = self
5315            .streams
5316            .get_mut(stream_id)
5317            .ok_or(Error::InvalidStreamState(stream_id))?;
5318
5319        if !stream.is_readable() {
5320            return Err(Error::Done);
5321        }
5322
5323        let local = stream.local;
5324        let priority_key = Arc::clone(&stream.priority_key);
5325
5326        #[cfg(feature = "qlog")]
5327        let offset = stream.recv.off_front();
5328
5329        #[cfg(feature = "qlog")]
5330        let to = match action {
5331            RecvAction::Emit { .. } => Some(DataRecipient::Application),
5332
5333            RecvAction::Discard { .. } => Some(DataRecipient::Dropped),
5334        };
5335
5336        let (read, fin) = match stream.recv.emit_or_discard(action) {
5337            Ok(v) => v,
5338
5339            Err(e) => {
5340                // Collect the stream if it is now complete. This can happen if
5341                // we got a `StreamReset` error which will now be propagated to
5342                // the application, so we don't need to keep the stream's state
5343                // anymore.
5344                if stream.is_complete() {
5345                    self.streams.collect(stream_id, local);
5346                }
5347
5348                self.streams.remove_readable(&priority_key);
5349                return Err(e);
5350            },
5351        };
5352
5353        self.flow_control.add_consumed(read as u64);
5354
5355        let readable = stream.is_readable();
5356
5357        let complete = stream.is_complete();
5358
5359        if stream.recv.almost_full() {
5360            self.streams.insert_almost_full(stream_id);
5361        }
5362
5363        if !readable {
5364            self.streams.remove_readable(&priority_key);
5365        }
5366
5367        if complete {
5368            self.streams.collect(stream_id, local);
5369        }
5370
5371        qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
5372            let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved {
5373                stream_id: Some(stream_id),
5374                offset: Some(offset),
5375                length: Some(read as u64),
5376                from: Some(DataRecipient::Transport),
5377                to,
5378                ..Default::default()
5379            });
5380
5381            let now = Instant::now();
5382            q.add_event_data_with_instant(ev_data, now).ok();
5383        });
5384
5385        if self.should_update_max_data() {
5386            self.almost_full = true;
5387        }
5388
5389        if priority_key.incremental && readable {
5390            // Shuffle the incremental stream to the back of the queue.
5391            self.streams.remove_readable(&priority_key);
5392            self.streams.insert_readable(&priority_key);
5393        }
5394
5395        Ok((read, fin))
5396    }
5397
5398    /// Writes data to a stream.
5399    ///
5400    /// On success the number of bytes written is returned, or [`Done`] if no
5401    /// data was written (e.g. because the stream has no capacity).
5402    ///
5403    /// Applications can provide a 0-length buffer with the fin flag set to
5404    /// true. This will lead to a 0-length FIN STREAM frame being sent at the
5405    /// latest offset. The `Ok(0)` value is only returned when the application
5406    /// provided a 0-length buffer.
5407    ///
5408    /// In addition, if the peer has signalled that it doesn't want to receive
5409    /// any more data from this stream by sending the `STOP_SENDING` frame, the
5410    /// [`StreamStopped`] error will be returned instead of any data.
5411    ///
5412    /// Note that in order to avoid buffering an infinite amount of data in the
5413    /// stream's send buffer, streams are only allowed to buffer outgoing data
5414    /// up to the amount that the peer allows it to send (that is, up to the
5415    /// stream's outgoing flow control capacity).
5416    ///
5417    /// This means that the number of written bytes returned can be lower than
5418    /// the length of the input buffer when the stream doesn't have enough
5419    /// capacity for the operation to complete. The application should retry the
5420    /// operation once the stream is reported as writable again.
5421    ///
5422    /// Applications should call this method only after the handshake is
5423    /// completed (whenever [`is_established()`] returns `true`) or during
5424    /// early data if enabled (whenever [`is_in_early_data()`] returns `true`).
5425    ///
5426    /// [`Done`]: enum.Error.html#variant.Done
5427    /// [`StreamStopped`]: enum.Error.html#variant.StreamStopped
5428    /// [`is_established()`]: struct.Connection.html#method.is_established
5429    /// [`is_in_early_data()`]: struct.Connection.html#method.is_in_early_data
5430    ///
5431    /// ## Examples:
5432    ///
5433    /// ```no_run
5434    /// # let mut buf = [0; 512];
5435    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5436    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5437    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5438    /// # let peer = "127.0.0.1:1234".parse().unwrap();
5439    /// # let local = "127.0.0.1:4321".parse().unwrap();
5440    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5441    /// # let stream_id = 0;
5442    /// conn.stream_send(stream_id, b"hello", true)?;
5443    /// # Ok::<(), quiche::Error>(())
5444    /// ```
5445    pub fn stream_send(
5446        &mut self, stream_id: u64, buf: &[u8], fin: bool,
5447    ) -> Result<usize> {
5448        self.stream_do_send(
5449            stream_id,
5450            buf,
5451            fin,
5452            |stream: &mut stream::Stream<F>,
5453             buf: &[u8],
5454             cap: usize,
5455             fin: bool| {
5456                stream.send.write(&buf[..cap], fin).map(|v| (v, v))
5457            },
5458        )
5459    }
5460
5461    /// Writes data to a stream with zero copying, instead, it appends the
5462    /// provided buffer directly to the send queue if the capacity allows
5463    /// it.
5464    ///
5465    /// When a partial write happens (including when [`Error::Done`] is
5466    /// returned) the remaining (unwritten) buffer will also be returned.
5467    /// The application should retry the operation once the stream is
5468    /// reported as writable again.
5469    pub fn stream_send_zc(
5470        &mut self, stream_id: u64, buf: F::Buf, len: Option<usize>, fin: bool,
5471    ) -> Result<(usize, Option<F::Buf>)>
5472    where
5473        F::Buf: BufSplit,
5474    {
5475        self.stream_do_send(
5476            stream_id,
5477            buf,
5478            fin,
5479            |stream: &mut stream::Stream<F>,
5480             buf: F::Buf,
5481             cap: usize,
5482             fin: bool| {
5483                let len = len.unwrap_or(usize::MAX).min(cap);
5484                let (sent, remaining) = stream.send.append_buf(buf, len, fin)?;
5485                Ok((sent, (sent, remaining)))
5486            },
5487        )
5488    }
5489
5490    fn stream_do_send<B, R, SND>(
5491        &mut self, stream_id: u64, buf: B, fin: bool, write_fn: SND,
5492    ) -> Result<R>
5493    where
5494        B: AsRef<[u8]>,
5495        SND: FnOnce(&mut stream::Stream<F>, B, usize, bool) -> Result<(usize, R)>,
5496    {
5497        // We can't write on the peer's unidirectional streams.
5498        if !stream::is_bidi(stream_id) &&
5499            !stream::is_local(stream_id, self.is_server)
5500        {
5501            return Err(Error::InvalidStreamState(stream_id));
5502        }
5503
5504        let len = buf.as_ref().len();
5505
5506        // Mark the connection as blocked if the connection-level flow control
5507        // limit doesn't let us buffer all the data.
5508        //
5509        // Note that this is separate from "send capacity" as that also takes
5510        // congestion control into consideration.
5511        if self.max_tx_data - self.tx_data < len as u64 {
5512            self.blocked_limit = Some(self.max_tx_data);
5513        }
5514
5515        let cap = self.tx_cap;
5516
5517        // Get existing stream or create a new one.
5518        let stream = self.get_or_create_stream(stream_id, true)?;
5519
5520        #[cfg(feature = "qlog")]
5521        let offset = stream.send.off_back();
5522
5523        let was_writable = stream.is_writable();
5524
5525        let was_flushable = stream.is_flushable();
5526
5527        let is_complete = stream.is_complete();
5528        let is_readable = stream.is_readable();
5529
5530        let priority_key = Arc::clone(&stream.priority_key);
5531
5532        // Return early if the stream has been stopped, and collect its state
5533        // if complete.
5534        if let Err(Error::StreamStopped(e)) = stream.send.cap() {
5535            // Only collect the stream if it is complete and not readable.
5536            // If it is readable, it will get collected when stream_recv()
5537            // is used.
5538            //
5539            // The stream can't be writable if it has been stopped.
5540            if is_complete && !is_readable {
5541                let local = stream.local;
5542                self.streams.collect(stream_id, local);
5543            }
5544
5545            return Err(Error::StreamStopped(e));
5546        };
5547
5548        // Truncate the input buffer based on the connection's send capacity if
5549        // necessary.
5550        //
5551        // When the cap is zero, the method returns Ok(0) *only* when the passed
5552        // buffer is empty. We return Error::Done otherwise.
5553        if cap == 0 && len > 0 {
5554            if was_writable {
5555                // When `stream_writable_next()` returns a stream, the writable
5556                // mark is removed, but because the stream is blocked by the
5557                // connection-level send capacity it won't be marked as writable
5558                // again once the capacity increases.
5559                //
5560                // Since the stream is writable already, mark it here instead.
5561                self.streams.insert_writable(&priority_key);
5562            }
5563
5564            return Err(Error::Done);
5565        }
5566
5567        let (cap, fin, blocked_by_cap) = if cap < len {
5568            (cap, false, true)
5569        } else {
5570            (len, fin, false)
5571        };
5572
5573        let (sent, ret) = match write_fn(stream, buf, cap, fin) {
5574            Ok(v) => v,
5575
5576            Err(e) => {
5577                self.streams.remove_writable(&priority_key);
5578                return Err(e);
5579            },
5580        };
5581
5582        let incremental = stream.incremental;
5583        let priority_key = Arc::clone(&stream.priority_key);
5584
5585        let flushable = stream.is_flushable();
5586
5587        let writable = stream.is_writable();
5588
5589        let empty_fin = len == 0 && fin;
5590
5591        if sent < cap {
5592            let max_off = stream.send.max_off();
5593
5594            if stream.send.blocked_at() != Some(max_off) {
5595                stream.send.update_blocked_at(Some(max_off));
5596                self.streams.insert_blocked(stream_id, max_off);
5597            }
5598        } else {
5599            stream.send.update_blocked_at(None);
5600            self.streams.remove_blocked(stream_id);
5601        }
5602
5603        // If the stream is now flushable push it to the flushable queue, but
5604        // only if it wasn't already queued.
5605        //
5606        // Consider the stream flushable also when we are sending a zero-length
5607        // frame that has the fin flag set.
5608        if (flushable || empty_fin) && !was_flushable {
5609            self.streams.insert_flushable(&priority_key);
5610        }
5611
5612        if !writable {
5613            self.streams.remove_writable(&priority_key);
5614        } else if was_writable && blocked_by_cap {
5615            // When `stream_writable_next()` returns a stream, the writable
5616            // mark is removed, but because the stream is blocked by the
5617            // connection-level send capacity it won't be marked as writable
5618            // again once the capacity increases.
5619            //
5620            // Since the stream is writable already, mark it here instead.
5621            self.streams.insert_writable(&priority_key);
5622        }
5623
5624        self.tx_cap -= sent;
5625
5626        self.tx_data += sent as u64;
5627
5628        self.tx_buffered += sent;
5629        self.check_tx_buffered_invariant();
5630
5631        qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
5632            let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved {
5633                stream_id: Some(stream_id),
5634                offset: Some(offset),
5635                length: Some(sent as u64),
5636                from: Some(DataRecipient::Application),
5637                to: Some(DataRecipient::Transport),
5638                ..Default::default()
5639            });
5640
5641            let now = Instant::now();
5642            q.add_event_data_with_instant(ev_data, now).ok();
5643        });
5644
5645        if sent == 0 && cap > 0 {
5646            return Err(Error::Done);
5647        }
5648
5649        if incremental && writable {
5650            // Shuffle the incremental stream to the back of the queue.
5651            self.streams.remove_writable(&priority_key);
5652            self.streams.insert_writable(&priority_key);
5653        }
5654
5655        Ok(ret)
5656    }
5657
5658    /// Sets the priority for a stream.
5659    ///
5660    /// A stream's priority determines the order in which stream data is sent
5661    /// on the wire (streams with lower priority are sent first). Streams are
5662    /// created with a default priority of `127`.
5663    ///
5664    /// The target stream is created if it did not exist before calling this
5665    /// method.
5666    pub fn stream_priority(
5667        &mut self, stream_id: u64, urgency: u8, incremental: bool,
5668    ) -> Result<()> {
5669        // Get existing stream or create a new one, but if the stream
5670        // has already been closed and collected, ignore the prioritization.
5671        let stream = match self.get_or_create_stream(stream_id, true) {
5672            Ok(v) => v,
5673
5674            Err(Error::Done) => return Ok(()),
5675
5676            Err(e) => return Err(e),
5677        };
5678
5679        if stream.urgency == urgency && stream.incremental == incremental {
5680            return Ok(());
5681        }
5682
5683        stream.urgency = urgency;
5684        stream.incremental = incremental;
5685
5686        let new_priority_key = Arc::new(StreamPriorityKey {
5687            urgency: stream.urgency,
5688            incremental: stream.incremental,
5689            id: stream_id,
5690            ..Default::default()
5691        });
5692
5693        let old_priority_key =
5694            std::mem::replace(&mut stream.priority_key, new_priority_key.clone());
5695
5696        self.streams
5697            .update_priority(&old_priority_key, &new_priority_key);
5698
5699        Ok(())
5700    }
5701
5702    /// Shuts down reading or writing from/to the specified stream.
5703    ///
5704    /// When the `direction` argument is set to [`Shutdown::Read`], outstanding
5705    /// data in the stream's receive buffer is dropped, and no additional data
5706    /// is added to it. Data received after calling this method is still
5707    /// validated and acked but not stored, and [`stream_recv()`] will not
5708    /// return it to the application. In addition, a `STOP_SENDING` frame will
5709    /// be sent to the peer to signal it to stop sending data.
5710    ///
5711    /// When the `direction` argument is set to [`Shutdown::Write`], outstanding
5712    /// data in the stream's send buffer is dropped, and no additional data is
5713    /// added to it. Data passed to [`stream_send()`] after calling this method
5714    /// will be ignored. In addition, a `RESET_STREAM` frame will be sent to the
5715    /// peer to signal the reset.
5716    ///
5717    /// Locally-initiated unidirectional streams can only be closed in the
5718    /// [`Shutdown::Write`] direction. Remotely-initiated unidirectional streams
5719    /// can only be closed in the [`Shutdown::Read`] direction. Using an
5720    /// incorrect direction will return [`InvalidStreamState`].
5721    ///
5722    /// [`Shutdown::Read`]: enum.Shutdown.html#variant.Read
5723    /// [`Shutdown::Write`]: enum.Shutdown.html#variant.Write
5724    /// [`stream_recv()`]: struct.Connection.html#method.stream_recv
5725    /// [`stream_send()`]: struct.Connection.html#method.stream_send
5726    /// [`InvalidStreamState`]: enum.Error.html#variant.InvalidStreamState
5727    pub fn stream_shutdown(
5728        &mut self, stream_id: u64, direction: Shutdown, err: u64,
5729    ) -> Result<()> {
5730        // Don't try to stop a local unidirectional stream.
5731        if direction == Shutdown::Read &&
5732            stream::is_local(stream_id, self.is_server) &&
5733            !stream::is_bidi(stream_id)
5734        {
5735            return Err(Error::InvalidStreamState(stream_id));
5736        }
5737
5738        // Don't try to reset a remote unidirectional stream.
5739        if direction == Shutdown::Write &&
5740            !stream::is_local(stream_id, self.is_server) &&
5741            !stream::is_bidi(stream_id)
5742        {
5743            return Err(Error::InvalidStreamState(stream_id));
5744        }
5745
5746        // Get existing stream.
5747        let stream = self.streams.get_mut(stream_id).ok_or(Error::Done)?;
5748
5749        let priority_key = Arc::clone(&stream.priority_key);
5750
5751        match direction {
5752            Shutdown::Read => {
5753                let consumed = stream.recv.shutdown()?;
5754                self.flow_control.add_consumed(consumed);
5755                if self.flow_control.should_update_max_data() {
5756                    self.almost_full = true;
5757                }
5758
5759                if !stream.recv.is_fin() {
5760                    self.streams.insert_stopped(stream_id, err);
5761                }
5762
5763                // Once shutdown, the stream is guaranteed to be non-readable.
5764                self.streams.remove_readable(&priority_key);
5765
5766                self.stopped_stream_local_count =
5767                    self.stopped_stream_local_count.saturating_add(1);
5768            },
5769
5770            Shutdown::Write => {
5771                let (final_size, unsent) = stream.send.shutdown()?;
5772
5773                // Claw back some flow control allowance from data that was
5774                // buffered but not actually sent before the stream was reset.
5775                self.tx_data = self.tx_data.saturating_sub(unsent);
5776
5777                self.tx_buffered =
5778                    self.tx_buffered.saturating_sub(unsent as usize);
5779
5780                // These drops in qlog are a bit weird, but the only way to ensure
5781                // that all bytes that are moved from App to Transport in
5782                // stream_do_send are eventually moved from Transport to Dropped.
5783                // Ideally we would add a Transport to Network transition also as
5784                // a way to indicate when bytes were transmitted vs dropped
5785                // without ever being sent.
5786                qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
5787                    let ev_data =
5788                        EventData::DataMoved(qlog::events::quic::DataMoved {
5789                            stream_id: Some(stream_id),
5790                            offset: Some(final_size),
5791                            length: Some(unsent),
5792                            from: Some(DataRecipient::Transport),
5793                            to: Some(DataRecipient::Dropped),
5794                            ..Default::default()
5795                        });
5796
5797                    q.add_event_data_with_instant(ev_data, Instant::now()).ok();
5798                });
5799
5800                // Update send capacity.
5801                self.update_tx_cap();
5802
5803                self.streams.insert_reset(stream_id, err, final_size);
5804
5805                // Once shutdown, the stream is guaranteed to be non-writable.
5806                self.streams.remove_writable(&priority_key);
5807
5808                self.reset_stream_local_count =
5809                    self.reset_stream_local_count.saturating_add(1);
5810            },
5811        }
5812
5813        Ok(())
5814    }
5815
5816    /// Returns the stream's send capacity in bytes.
5817    ///
5818    /// If the specified stream doesn't exist (including when it has already
5819    /// been completed and closed), the [`InvalidStreamState`] error will be
5820    /// returned.
5821    ///
5822    /// In addition, if the peer has signalled that it doesn't want to receive
5823    /// any more data from this stream by sending the `STOP_SENDING` frame, the
5824    /// [`StreamStopped`] error will be returned.
5825    ///
5826    /// [`InvalidStreamState`]: enum.Error.html#variant.InvalidStreamState
5827    /// [`StreamStopped`]: enum.Error.html#variant.StreamStopped
5828    #[inline]
5829    pub fn stream_capacity(&mut self, stream_id: u64) -> Result<usize> {
5830        if let Some(stream) = self.streams.get(stream_id) {
5831            let stream_cap = match stream.send.cap() {
5832                Ok(v) => v,
5833
5834                Err(Error::StreamStopped(e)) => {
5835                    // Only collect the stream if it is complete and not
5836                    // readable. If it is readable, it will get collected when
5837                    // stream_recv() is used.
5838                    if stream.is_complete() && !stream.is_readable() {
5839                        let local = stream.local;
5840                        self.streams.collect(stream_id, local);
5841                    }
5842
5843                    return Err(Error::StreamStopped(e));
5844                },
5845
5846                Err(e) => return Err(e),
5847            };
5848
5849            let cap = cmp::min(self.tx_cap, stream_cap);
5850            return Ok(cap);
5851        };
5852
5853        Err(Error::InvalidStreamState(stream_id))
5854    }
5855
5856    /// Returns the next stream that has data to read.
5857    ///
5858    /// Note that once returned by this method, a stream ID will not be returned
5859    /// again until it is "re-armed".
5860    ///
5861    /// The application will need to read all of the pending data on the stream,
5862    /// and new data has to be received before the stream is reported again.
5863    ///
5864    /// This is unlike the [`readable()`] method, that returns the same list of
5865    /// readable streams when called multiple times in succession.
5866    ///
5867    /// [`readable()`]: struct.Connection.html#method.readable
5868    pub fn stream_readable_next(&mut self) -> Option<u64> {
5869        let priority_key = self.streams.readable.front().clone_pointer()?;
5870
5871        self.streams.remove_readable(&priority_key);
5872
5873        Some(priority_key.id)
5874    }
5875
5876    /// Returns true if the stream has data that can be read.
5877    pub fn stream_readable(&self, stream_id: u64) -> bool {
5878        let stream = match self.streams.get(stream_id) {
5879            Some(v) => v,
5880
5881            None => return false,
5882        };
5883
5884        stream.is_readable()
5885    }
5886
5887    /// Returns the next stream that can be written to.
5888    ///
5889    /// Note that once returned by this method, a stream ID will not be returned
5890    /// again until it is "re-armed".
5891    ///
5892    /// This is unlike the [`writable()`] method, that returns the same list of
5893    /// writable streams when called multiple times in succession. It is not
5894    /// advised to use both `stream_writable_next()` and [`writable()`] on the
5895    /// same connection, as it may lead to unexpected results.
5896    ///
5897    /// The [`stream_writable()`] method can also be used to fine-tune when a
5898    /// stream is reported as writable again.
5899    ///
5900    /// [`stream_writable()`]: struct.Connection.html#method.stream_writable
5901    /// [`writable()`]: struct.Connection.html#method.writable
5902    pub fn stream_writable_next(&mut self) -> Option<u64> {
5903        // If there is not enough connection-level send capacity, none of the
5904        // streams are writable.
5905        if self.tx_cap == 0 {
5906            return None;
5907        }
5908
5909        let mut cursor = self.streams.writable.front();
5910
5911        while let Some(priority_key) = cursor.clone_pointer() {
5912            if let Some(stream) = self.streams.get(priority_key.id) {
5913                let cap = match stream.send.cap() {
5914                    Ok(v) => v,
5915
5916                    // Return the stream to the application immediately if it's
5917                    // stopped.
5918                    Err(_) =>
5919                        return {
5920                            self.streams.remove_writable(&priority_key);
5921
5922                            Some(priority_key.id)
5923                        },
5924                };
5925
5926                if cmp::min(self.tx_cap, cap) >= stream.send_lowat {
5927                    self.streams.remove_writable(&priority_key);
5928                    return Some(priority_key.id);
5929                }
5930            }
5931
5932            cursor.move_next();
5933        }
5934
5935        None
5936    }
5937
5938    /// Returns true if the stream has enough send capacity.
5939    ///
5940    /// When `len` more bytes can be buffered into the given stream's send
5941    /// buffer, `true` will be returned, `false` otherwise.
5942    ///
5943    /// In the latter case, if the additional data can't be buffered due to
5944    /// flow control limits, the peer will also be notified, and a "low send
5945    /// watermark" will be set for the stream, such that it is not going to be
5946    /// reported as writable again by [`stream_writable_next()`] until its send
5947    /// capacity reaches `len`.
5948    ///
5949    /// If the specified stream doesn't exist (including when it has already
5950    /// been completed and closed), the [`InvalidStreamState`] error will be
5951    /// returned.
5952    ///
5953    /// In addition, if the peer has signalled that it doesn't want to receive
5954    /// any more data from this stream by sending the `STOP_SENDING` frame, the
5955    /// [`StreamStopped`] error will be returned.
5956    ///
5957    /// [`stream_writable_next()`]: struct.Connection.html#method.stream_writable_next
5958    /// [`InvalidStreamState`]: enum.Error.html#variant.InvalidStreamState
5959    /// [`StreamStopped`]: enum.Error.html#variant.StreamStopped
5960    #[inline]
5961    pub fn stream_writable(
5962        &mut self, stream_id: u64, len: usize,
5963    ) -> Result<bool> {
5964        if self.stream_capacity(stream_id)? >= len {
5965            return Ok(true);
5966        }
5967
5968        let stream = match self.streams.get_mut(stream_id) {
5969            Some(v) => v,
5970
5971            None => return Err(Error::InvalidStreamState(stream_id)),
5972        };
5973
5974        stream.send_lowat = cmp::max(1, len);
5975
5976        let is_writable = stream.is_writable();
5977
5978        let priority_key = Arc::clone(&stream.priority_key);
5979
5980        if self.max_tx_data - self.tx_data < len as u64 {
5981            self.blocked_limit = Some(self.max_tx_data);
5982        }
5983
5984        if stream.send.cap()? < len {
5985            let max_off = stream.send.max_off();
5986            if stream.send.blocked_at() != Some(max_off) {
5987                stream.send.update_blocked_at(Some(max_off));
5988                self.streams.insert_blocked(stream_id, max_off);
5989            }
5990        } else if is_writable {
5991            // When `stream_writable_next()` returns a stream, the writable
5992            // mark is removed, but because the stream is blocked by the
5993            // connection-level send capacity it won't be marked as writable
5994            // again once the capacity increases.
5995            //
5996            // Since the stream is writable already, mark it here instead.
5997            self.streams.insert_writable(&priority_key);
5998        }
5999
6000        Ok(false)
6001    }
6002
6003    /// Returns true if all the data has been read from the specified stream.
6004    ///
6005    /// This instructs the application that all the data received from the
6006    /// peer on the stream has been read, and there won't be anymore in the
6007    /// future.
6008    ///
6009    /// Basically this returns true when the peer either set the `fin` flag
6010    /// for the stream, or sent `RESET_STREAM`.
6011    #[inline]
6012    pub fn stream_finished(&self, stream_id: u64) -> bool {
6013        let stream = match self.streams.get(stream_id) {
6014            Some(v) => v,
6015
6016            None => return true,
6017        };
6018
6019        stream.recv.is_fin()
6020    }
6021
6022    /// Returns the number of bidirectional streams that can be created
6023    /// before the peer's stream count limit is reached.
6024    ///
6025    /// This can be useful to know if it's possible to create a bidirectional
6026    /// stream without trying it first.
6027    #[inline]
6028    pub fn peer_streams_left_bidi(&self) -> u64 {
6029        self.streams.peer_streams_left_bidi()
6030    }
6031
6032    /// Returns the number of unidirectional streams that can be created
6033    /// before the peer's stream count limit is reached.
6034    ///
6035    /// This can be useful to know if it's possible to create a unidirectional
6036    /// stream without trying it first.
6037    #[inline]
6038    pub fn peer_streams_left_uni(&self) -> u64 {
6039        self.streams.peer_streams_left_uni()
6040    }
6041
6042    /// Returns an iterator over streams that have outstanding data to read.
6043    ///
6044    /// Note that the iterator will only include streams that were readable at
6045    /// the time the iterator itself was created (i.e. when `readable()` was
6046    /// called). To account for newly readable streams, the iterator needs to
6047    /// be created again.
6048    ///
6049    /// ## Examples:
6050    ///
6051    /// ```no_run
6052    /// # let mut buf = [0; 512];
6053    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
6054    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
6055    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
6056    /// # let peer = "127.0.0.1:1234".parse().unwrap();
6057    /// # let local = socket.local_addr().unwrap();
6058    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
6059    /// // Iterate over readable streams.
6060    /// for stream_id in conn.readable() {
6061    ///     // Stream is readable, read until there's no more data.
6062    ///     while let Ok((read, fin)) = conn.stream_recv(stream_id, &mut buf) {
6063    ///         println!("Got {} bytes on stream {}", read, stream_id);
6064    ///     }
6065    /// }
6066    /// # Ok::<(), quiche::Error>(())
6067    /// ```
6068    #[inline]
6069    pub fn readable(&self) -> StreamIter {
6070        self.streams.readable()
6071    }
6072
6073    /// Returns an iterator over streams that can be written in priority order.
6074    ///
6075    /// The priority order is based on RFC 9218 scheduling recommendations.
6076    /// Stream priority can be controlled using [`stream_priority()`]. In order
6077    /// to support fairness requirements, each time this method is called,
6078    /// internal state is updated. Therefore the iterator ordering can change
6079    /// between calls, even if no streams were added or removed.
6080    ///
6081    /// A "writable" stream is a stream that has enough flow control capacity to
6082    /// send data to the peer. To avoid buffering an infinite amount of data,
6083    /// streams are only allowed to buffer outgoing data up to the amount that
6084    /// the peer allows to send.
6085    ///
6086    /// Note that the iterator will only include streams that were writable at
6087    /// the time the iterator itself was created (i.e. when `writable()` was
6088    /// called). To account for newly writable streams, the iterator needs to be
6089    /// created again.
6090    ///
6091    /// ## Examples:
6092    ///
6093    /// ```no_run
6094    /// # let mut buf = [0; 512];
6095    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
6096    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
6097    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
6098    /// # let local = socket.local_addr().unwrap();
6099    /// # let peer = "127.0.0.1:1234".parse().unwrap();
6100    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
6101    /// // Iterate over writable streams.
6102    /// for stream_id in conn.writable() {
6103    ///     // Stream is writable, write some data.
6104    ///     if let Ok(written) = conn.stream_send(stream_id, &buf, false) {
6105    ///         println!("Written {} bytes on stream {}", written, stream_id);
6106    ///     }
6107    /// }
6108    /// # Ok::<(), quiche::Error>(())
6109    /// ```
6110    /// [`stream_priority()`]: struct.Connection.html#method.stream_priority
6111    #[inline]
6112    pub fn writable(&self) -> StreamIter {
6113        // If there is not enough connection-level send capacity, none of the
6114        // streams are writable, so return an empty iterator.
6115        if self.tx_cap == 0 {
6116            return StreamIter::default();
6117        }
6118
6119        self.streams.writable()
6120    }
6121
6122    /// Returns the maximum possible size of egress UDP payloads.
6123    ///
6124    /// This is the maximum size of UDP payloads that can be sent, and depends
6125    /// on both the configured maximum send payload size of the local endpoint
6126    /// (as configured with [`set_max_send_udp_payload_size()`]), as well as
6127    /// the transport parameter advertised by the remote peer.
6128    ///
6129    /// Note that this value can change during the lifetime of the connection,
6130    /// but should remain stable across consecutive calls to [`send()`].
6131    ///
6132    /// [`set_max_send_udp_payload_size()`]:
6133    ///     struct.Config.html#method.set_max_send_udp_payload_size
6134    /// [`send()`]: struct.Connection.html#method.send
6135    pub fn max_send_udp_payload_size(&self) -> usize {
6136        let max_datagram_size = self
6137            .paths
6138            .get_active()
6139            .ok()
6140            .map(|p| p.recovery.max_datagram_size());
6141
6142        if let Some(max_datagram_size) = max_datagram_size {
6143            if self.is_established() {
6144                // We cap the maximum packet size to 16KB or so, so that it can be
6145                // always encoded with a 2-byte varint.
6146                return cmp::min(16383, max_datagram_size);
6147            }
6148        }
6149
6150        // Allow for 1200 bytes (minimum QUIC packet size) during the
6151        // handshake.
6152        MIN_CLIENT_INITIAL_LEN
6153    }
6154
6155    /// Schedule an ack-eliciting packet on the active path.
6156    ///
6157    /// QUIC packets might not contain ack-eliciting frames during normal
6158    /// operating conditions. If the packet would already contain
6159    /// ack-eliciting frames, this method does not change any behavior.
6160    /// However, if the packet would not ordinarily contain ack-eliciting
6161    /// frames, this method ensures that a PING frame sent.
6162    ///
6163    /// Calling this method multiple times before [`send()`] has no effect.
6164    ///
6165    /// [`send()`]: struct.Connection.html#method.send
6166    pub fn send_ack_eliciting(&mut self) -> Result<()> {
6167        if self.is_closed() || self.is_draining() {
6168            return Ok(());
6169        }
6170        self.paths.get_active_mut()?.needs_ack_eliciting = true;
6171        Ok(())
6172    }
6173
6174    /// Schedule an ack-eliciting packet on the specified path.
6175    ///
6176    /// See [`send_ack_eliciting()`] for more detail. [`InvalidState`] is
6177    /// returned if there is no record of the path.
6178    ///
6179    /// [`send_ack_eliciting()`]: struct.Connection.html#method.send_ack_eliciting
6180    /// [`InvalidState`]: enum.Error.html#variant.InvalidState
6181    pub fn send_ack_eliciting_on_path(
6182        &mut self, local: SocketAddr, peer: SocketAddr,
6183    ) -> Result<()> {
6184        if self.is_closed() || self.is_draining() {
6185            return Ok(());
6186        }
6187        let path_id = self
6188            .paths
6189            .path_id_from_addrs(&(local, peer))
6190            .ok_or(Error::InvalidState)?;
6191        self.paths.get_mut(path_id)?.needs_ack_eliciting = true;
6192        Ok(())
6193    }
6194
6195    /// Reads the first received DATAGRAM.
6196    ///
6197    /// On success the DATAGRAM's data is returned along with its size.
6198    ///
6199    /// [`Done`] is returned if there is no data to read.
6200    ///
6201    /// [`BufferTooShort`] is returned if the provided buffer is too small for
6202    /// the DATAGRAM.
6203    ///
6204    /// [`Done`]: enum.Error.html#variant.Done
6205    /// [`BufferTooShort`]: enum.Error.html#variant.BufferTooShort
6206    ///
6207    /// ## Examples:
6208    ///
6209    /// ```no_run
6210    /// # let mut buf = [0; 512];
6211    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
6212    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
6213    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
6214    /// # let peer = "127.0.0.1:1234".parse().unwrap();
6215    /// # let local = socket.local_addr().unwrap();
6216    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
6217    /// let mut dgram_buf = [0; 512];
6218    /// while let Ok((len)) = conn.dgram_recv(&mut dgram_buf) {
6219    ///     println!("Got {} bytes of DATAGRAM", len);
6220    /// }
6221    /// # Ok::<(), quiche::Error>(())
6222    /// ```
6223    #[inline]
6224    pub fn dgram_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
6225        match self.dgram_recv_queue.pop() {
6226            Some(d) => {
6227                if d.len() > buf.len() {
6228                    return Err(Error::BufferTooShort);
6229                }
6230
6231                buf[..d.len()].copy_from_slice(&d);
6232                Ok(d.len())
6233            },
6234
6235            None => Err(Error::Done),
6236        }
6237    }
6238
6239    /// Reads the first received DATAGRAM.
6240    ///
6241    /// This is the same as [`dgram_recv()`] but returns the DATAGRAM as a
6242    /// `Vec<u8>` instead of copying into the provided buffer.
6243    ///
6244    /// [`dgram_recv()`]: struct.Connection.html#method.dgram_recv
6245    #[inline]
6246    pub fn dgram_recv_vec(&mut self) -> Result<Vec<u8>> {
6247        match self.dgram_recv_queue.pop() {
6248            Some(d) => Ok(d),
6249
6250            None => Err(Error::Done),
6251        }
6252    }
6253
6254    /// Reads the first received DATAGRAM without removing it from the queue.
6255    ///
6256    /// On success the DATAGRAM's data is returned along with the actual number
6257    /// of bytes peeked. The requested length cannot exceed the DATAGRAM's
6258    /// actual length.
6259    ///
6260    /// [`Done`] is returned if there is no data to read.
6261    ///
6262    /// [`BufferTooShort`] is returned if the provided buffer is smaller the
6263    /// number of bytes to peek.
6264    ///
6265    /// [`Done`]: enum.Error.html#variant.Done
6266    /// [`BufferTooShort`]: enum.Error.html#variant.BufferTooShort
6267    #[inline]
6268    pub fn dgram_recv_peek(&self, buf: &mut [u8], len: usize) -> Result<usize> {
6269        self.dgram_recv_queue.peek_front_bytes(buf, len)
6270    }
6271
6272    /// Returns the length of the first stored DATAGRAM.
6273    #[inline]
6274    pub fn dgram_recv_front_len(&self) -> Option<usize> {
6275        self.dgram_recv_queue.peek_front_len()
6276    }
6277
6278    /// Returns the number of items in the DATAGRAM receive queue.
6279    #[inline]
6280    pub fn dgram_recv_queue_len(&self) -> usize {
6281        self.dgram_recv_queue.len()
6282    }
6283
6284    /// Returns the total size of all items in the DATAGRAM receive queue.
6285    #[inline]
6286    pub fn dgram_recv_queue_byte_size(&self) -> usize {
6287        self.dgram_recv_queue.byte_size()
6288    }
6289
6290    /// Returns the number of items in the DATAGRAM send queue.
6291    #[inline]
6292    pub fn dgram_send_queue_len(&self) -> usize {
6293        self.dgram_send_queue.len()
6294    }
6295
6296    /// Returns the total size of all items in the DATAGRAM send queue.
6297    #[inline]
6298    pub fn dgram_send_queue_byte_size(&self) -> usize {
6299        self.dgram_send_queue.byte_size()
6300    }
6301
6302    /// Returns whether or not the DATAGRAM send queue is full.
6303    #[inline]
6304    pub fn is_dgram_send_queue_full(&self) -> bool {
6305        self.dgram_send_queue.is_full()
6306    }
6307
6308    /// Returns whether or not the DATAGRAM recv queue is full.
6309    #[inline]
6310    pub fn is_dgram_recv_queue_full(&self) -> bool {
6311        self.dgram_recv_queue.is_full()
6312    }
6313
6314    /// Sends data in a DATAGRAM frame.
6315    ///
6316    /// [`Done`] is returned if no data was written.
6317    /// [`InvalidState`] is returned if the peer does not support DATAGRAM.
6318    /// [`BufferTooShort`] is returned if the DATAGRAM frame length is larger
6319    /// than peer's supported DATAGRAM frame length. Use
6320    /// [`dgram_max_writable_len()`] to get the largest supported DATAGRAM
6321    /// frame length.
6322    ///
6323    /// Note that there is no flow control of DATAGRAM frames, so in order to
6324    /// avoid buffering an infinite amount of frames we apply an internal
6325    /// limit.
6326    ///
6327    /// [`Done`]: enum.Error.html#variant.Done
6328    /// [`InvalidState`]: enum.Error.html#variant.InvalidState
6329    /// [`BufferTooShort`]: enum.Error.html#variant.BufferTooShort
6330    /// [`dgram_max_writable_len()`]:
6331    /// struct.Connection.html#method.dgram_max_writable_len
6332    ///
6333    /// ## Examples:
6334    ///
6335    /// ```no_run
6336    /// # let mut buf = [0; 512];
6337    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
6338    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
6339    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
6340    /// # let peer = "127.0.0.1:1234".parse().unwrap();
6341    /// # let local = socket.local_addr().unwrap();
6342    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
6343    /// conn.dgram_send(b"hello")?;
6344    /// # Ok::<(), quiche::Error>(())
6345    /// ```
6346    pub fn dgram_send(&mut self, buf: &[u8]) -> Result<()> {
6347        let max_payload_len = match self.dgram_max_writable_len() {
6348            Some(v) => v,
6349
6350            None => return Err(Error::InvalidState),
6351        };
6352
6353        if buf.len() > max_payload_len {
6354            return Err(Error::BufferTooShort);
6355        }
6356
6357        self.dgram_send_queue.push(buf.to_vec())?;
6358
6359        let active_path = self.paths.get_active_mut()?;
6360
6361        if self.dgram_send_queue.byte_size() >
6362            active_path.recovery.cwnd_available()
6363        {
6364            active_path.recovery.update_app_limited(false);
6365        }
6366
6367        Ok(())
6368    }
6369
6370    /// Sends data in a DATAGRAM frame.
6371    ///
6372    /// This is the same as [`dgram_send()`] but takes a `Vec<u8>` instead of
6373    /// a slice.
6374    ///
6375    /// [`dgram_send()`]: struct.Connection.html#method.dgram_send
6376    pub fn dgram_send_vec(&mut self, buf: Vec<u8>) -> Result<()> {
6377        let max_payload_len = match self.dgram_max_writable_len() {
6378            Some(v) => v,
6379
6380            None => return Err(Error::InvalidState),
6381        };
6382
6383        if buf.len() > max_payload_len {
6384            return Err(Error::BufferTooShort);
6385        }
6386
6387        self.dgram_send_queue.push(buf)?;
6388
6389        let active_path = self.paths.get_active_mut()?;
6390
6391        if self.dgram_send_queue.byte_size() >
6392            active_path.recovery.cwnd_available()
6393        {
6394            active_path.recovery.update_app_limited(false);
6395        }
6396
6397        Ok(())
6398    }
6399
6400    /// Purges queued outgoing DATAGRAMs matching the predicate.
6401    ///
6402    /// In other words, remove all elements `e` such that `f(&e)` returns true.
6403    ///
6404    /// ## Examples:
6405    /// ```no_run
6406    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
6407    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
6408    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
6409    /// # let peer = "127.0.0.1:1234".parse().unwrap();
6410    /// # let local = socket.local_addr().unwrap();
6411    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
6412    /// conn.dgram_send(b"hello")?;
6413    /// conn.dgram_purge_outgoing(&|d: &[u8]| -> bool { d[0] == 0 });
6414    /// # Ok::<(), quiche::Error>(())
6415    /// ```
6416    #[inline]
6417    pub fn dgram_purge_outgoing<FN: Fn(&[u8]) -> bool>(&mut self, f: FN) {
6418        self.dgram_send_queue.purge(f);
6419    }
6420
6421    /// Returns the maximum DATAGRAM payload that can be sent.
6422    ///
6423    /// [`None`] is returned if the peer hasn't advertised a maximum DATAGRAM
6424    /// frame size.
6425    ///
6426    /// ## Examples:
6427    ///
6428    /// ```no_run
6429    /// # let mut buf = [0; 512];
6430    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
6431    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
6432    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
6433    /// # let peer = "127.0.0.1:1234".parse().unwrap();
6434    /// # let local = socket.local_addr().unwrap();
6435    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
6436    /// if let Some(payload_size) = conn.dgram_max_writable_len() {
6437    ///     if payload_size > 5 {
6438    ///         conn.dgram_send(b"hello")?;
6439    ///     }
6440    /// }
6441    /// # Ok::<(), quiche::Error>(())
6442    /// ```
6443    #[inline]
6444    pub fn dgram_max_writable_len(&self) -> Option<usize> {
6445        match self.peer_transport_params.max_datagram_frame_size {
6446            None => None,
6447            Some(peer_frame_len) => {
6448                let dcid = self.destination_id();
6449                // Start from the maximum packet size...
6450                let mut max_len = self.max_send_udp_payload_size();
6451                // ...subtract the Short packet header overhead...
6452                // (1 byte of pkt_len + len of dcid)
6453                max_len = max_len.saturating_sub(1 + dcid.len());
6454                // ...subtract the packet number (max len)...
6455                max_len = max_len.saturating_sub(packet::MAX_PKT_NUM_LEN);
6456                // ...subtract the crypto overhead...
6457                max_len = max_len.saturating_sub(
6458                    self.crypto_ctx[packet::Epoch::Application]
6459                        .crypto_overhead()?,
6460                );
6461                // ...clamp to what peer can support...
6462                max_len = cmp::min(peer_frame_len as usize, max_len);
6463                // ...subtract frame overhead, checked for underflow.
6464                // (1 byte of frame type + len of length )
6465                max_len.checked_sub(1 + frame::MAX_DGRAM_OVERHEAD)
6466            },
6467        }
6468    }
6469
6470    fn dgram_enabled(&self) -> bool {
6471        self.local_transport_params
6472            .max_datagram_frame_size
6473            .is_some()
6474    }
6475
6476    /// Returns when the next timeout event will occur.
6477    ///
6478    /// Once the timeout Instant has been reached, the [`on_timeout()`] method
6479    /// should be called. A timeout of `None` means that the timer should be
6480    /// disarmed.
6481    ///
6482    /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
6483    pub fn timeout_instant(&self) -> Option<Instant> {
6484        if self.is_closed() {
6485            return None;
6486        }
6487
6488        if self.is_draining() {
6489            // Draining timer takes precedence over all other timers. If it is
6490            // set it means the connection is closing so there's no point in
6491            // processing the other timers.
6492            self.draining_timer
6493        } else {
6494            // Use the lowest timer value (i.e. "sooner") among idle and loss
6495            // detection timers. If they are both unset (i.e. `None`) then the
6496            // result is `None`, but if at least one of them is set then a
6497            // `Some(...)` value is returned.
6498            let path_timer = self
6499                .paths
6500                .iter()
6501                .filter_map(|(_, p)| p.recovery.loss_detection_timer())
6502                .min();
6503
6504            let key_update_timer = self.crypto_ctx[packet::Epoch::Application]
6505                .key_update
6506                .as_ref()
6507                .map(|key_update| key_update.timer);
6508
6509            let timers = [self.idle_timer, path_timer, key_update_timer];
6510
6511            timers.iter().filter_map(|&x| x).min()
6512        }
6513    }
6514
6515    /// Returns the amount of time until the next timeout event.
6516    ///
6517    /// Once the given duration has elapsed, the [`on_timeout()`] method should
6518    /// be called. A timeout of `None` means that the timer should be disarmed.
6519    ///
6520    /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
6521    pub fn timeout(&self) -> Option<Duration> {
6522        self.timeout_instant().map(|timeout| {
6523            let now = Instant::now();
6524
6525            if timeout <= now {
6526                Duration::ZERO
6527            } else {
6528                timeout.duration_since(now)
6529            }
6530        })
6531    }
6532
6533    /// Processes a timeout event.
6534    ///
6535    /// If no timeout has occurred it does nothing.
6536    pub fn on_timeout(&mut self) {
6537        let now = Instant::now();
6538
6539        if let Some(draining_timer) = self.draining_timer {
6540            if draining_timer <= now {
6541                trace!("{} draining timeout expired", self.trace_id);
6542
6543                self.mark_closed();
6544            }
6545
6546            // Draining timer takes precedence over all other timers. If it is
6547            // set it means the connection is closing so there's no point in
6548            // processing the other timers.
6549            return;
6550        }
6551
6552        if let Some(timer) = self.idle_timer {
6553            if timer <= now {
6554                trace!("{} idle timeout expired", self.trace_id);
6555
6556                self.mark_closed();
6557                self.timed_out = true;
6558                return;
6559            }
6560        }
6561
6562        if let Some(timer) = self.crypto_ctx[packet::Epoch::Application]
6563            .key_update
6564            .as_ref()
6565            .map(|key_update| key_update.timer)
6566        {
6567            if timer <= now {
6568                // Discard previous key once key update timer expired.
6569                let _ = self.crypto_ctx[packet::Epoch::Application]
6570                    .key_update
6571                    .take();
6572            }
6573        }
6574
6575        let handshake_status = self.handshake_status();
6576
6577        for (_, p) in self.paths.iter_mut() {
6578            if let Some(timer) = p.recovery.loss_detection_timer() {
6579                if timer <= now {
6580                    trace!("{} loss detection timeout expired", self.trace_id);
6581
6582                    let OnLossDetectionTimeoutOutcome {
6583                        lost_packets,
6584                        lost_bytes,
6585                    } = p.on_loss_detection_timeout(
6586                        handshake_status,
6587                        now,
6588                        self.is_server,
6589                        &self.trace_id,
6590                    );
6591
6592                    self.lost_count += lost_packets;
6593                    self.lost_bytes += lost_bytes as u64;
6594
6595                    qlog_with_type!(QLOG_METRICS, self.qlog, q, {
6596                        p.recovery.maybe_qlog(q, now);
6597                    });
6598                }
6599            }
6600        }
6601
6602        // Notify timeout events to the application.
6603        self.paths.notify_failed_validations();
6604
6605        // If the active path failed, try to find a new candidate.
6606        if self.paths.get_active_path_id().is_err() {
6607            match self.paths.find_candidate_path() {
6608                Some(pid) => {
6609                    if self.set_active_path(pid, now).is_err() {
6610                        // The connection cannot continue.
6611                        self.mark_closed();
6612                    }
6613                },
6614
6615                // The connection cannot continue.
6616                None => {
6617                    self.mark_closed();
6618                },
6619            }
6620        }
6621    }
6622
6623    /// Requests the stack to perform path validation of the proposed 4-tuple.
6624    ///
6625    /// Probing new paths requires spare Connection IDs at both the host and the
6626    /// peer sides. If it is not the case, it raises an [`OutOfIdentifiers`].
6627    ///
6628    /// The probing of new addresses can only be done by the client. The server
6629    /// can only probe network paths that were previously advertised by
6630    /// [`PathEvent::New`]. If the server tries to probe such an unseen network
6631    /// path, this call raises an [`InvalidState`].
6632    ///
6633    /// The caller might also want to probe an existing path. In such case, it
6634    /// triggers a PATH_CHALLENGE frame, but it does not require spare CIDs.
6635    ///
6636    /// A server always probes a new path it observes. Calling this method is
6637    /// hence not required to validate a new path. However, a server can still
6638    /// request an additional path validation of the proposed 4-tuple.
6639    ///
6640    /// Calling this method several times before calling [`send()`] or
6641    /// [`send_on_path()`] results in a single probe being generated. An
6642    /// application wanting to send multiple in-flight probes must call this
6643    /// method again after having sent packets.
6644    ///
6645    /// Returns the Destination Connection ID sequence number associated to that
6646    /// path.
6647    ///
6648    /// [`PathEvent::New`]: enum.PathEvent.html#variant.New
6649    /// [`OutOfIdentifiers`]: enum.Error.html#OutOfIdentifiers
6650    /// [`InvalidState`]: enum.Error.html#InvalidState
6651    /// [`send()`]: struct.Connection.html#method.send
6652    /// [`send_on_path()`]: struct.Connection.html#method.send_on_path
6653    pub fn probe_path(
6654        &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
6655    ) -> Result<u64> {
6656        // We may want to probe an existing path.
6657        let pid = match self.paths.path_id_from_addrs(&(local_addr, peer_addr)) {
6658            Some(pid) => pid,
6659            None => self.create_path_on_client(local_addr, peer_addr)?,
6660        };
6661
6662        let path = self.paths.get_mut(pid)?;
6663        path.request_validation();
6664
6665        path.active_dcid_seq.ok_or(Error::InvalidState)
6666    }
6667
6668    /// Migrates the connection to a new local address `local_addr`.
6669    ///
6670    /// The behavior is similar to [`migrate()`], with the nuance that the
6671    /// connection only changes the local address, but not the peer one.
6672    ///
6673    /// See [`migrate()`] for the full specification of this method.
6674    ///
6675    /// [`migrate()`]: struct.Connection.html#method.migrate
6676    pub fn migrate_source(&mut self, local_addr: SocketAddr) -> Result<u64> {
6677        let peer_addr = self.paths.get_active()?.peer_addr();
6678        self.migrate(local_addr, peer_addr)
6679    }
6680
6681    /// Migrates the connection over the given network path between `local_addr`
6682    /// and `peer_addr`.
6683    ///
6684    /// Connection migration can only be initiated by the client. Calling this
6685    /// method as a server returns [`InvalidState`].
6686    ///
6687    /// To initiate voluntary migration, there should be enough Connection IDs
6688    /// at both sides. If this requirement is not satisfied, this call returns
6689    /// [`OutOfIdentifiers`].
6690    ///
6691    /// Returns the Destination Connection ID associated to that migrated path.
6692    ///
6693    /// [`OutOfIdentifiers`]: enum.Error.html#OutOfIdentifiers
6694    /// [`InvalidState`]: enum.Error.html#InvalidState
6695    pub fn migrate(
6696        &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
6697    ) -> Result<u64> {
6698        if self.is_server {
6699            return Err(Error::InvalidState);
6700        }
6701
6702        // If the path already exists, mark it as the active one.
6703        let (pid, dcid_seq) = if let Some(pid) =
6704            self.paths.path_id_from_addrs(&(local_addr, peer_addr))
6705        {
6706            let path = self.paths.get_mut(pid)?;
6707
6708            // If it is already active, do nothing.
6709            if path.active() {
6710                return path.active_dcid_seq.ok_or(Error::OutOfIdentifiers);
6711            }
6712
6713            // Ensures that a Source Connection ID has been dedicated to this
6714            // path, or a free one is available. This is only required if the
6715            // host uses non-zero length Source Connection IDs.
6716            if !self.ids.zero_length_scid() &&
6717                path.active_scid_seq.is_none() &&
6718                self.ids.available_scids() == 0
6719            {
6720                return Err(Error::OutOfIdentifiers);
6721            }
6722
6723            // Ensures that the migrated path has a Destination Connection ID.
6724            let dcid_seq = if let Some(dcid_seq) = path.active_dcid_seq {
6725                dcid_seq
6726            } else {
6727                let dcid_seq = self
6728                    .ids
6729                    .lowest_available_dcid_seq()
6730                    .ok_or(Error::OutOfIdentifiers)?;
6731
6732                self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
6733                path.active_dcid_seq = Some(dcid_seq);
6734
6735                dcid_seq
6736            };
6737
6738            (pid, dcid_seq)
6739        } else {
6740            let pid = self.create_path_on_client(local_addr, peer_addr)?;
6741
6742            let dcid_seq = self
6743                .paths
6744                .get(pid)?
6745                .active_dcid_seq
6746                .ok_or(Error::InvalidState)?;
6747
6748            (pid, dcid_seq)
6749        };
6750
6751        // Change the active path.
6752        self.set_active_path(pid, Instant::now())?;
6753
6754        Ok(dcid_seq)
6755    }
6756
6757    /// Provides additional source Connection IDs that the peer can use to reach
6758    /// this host.
6759    ///
6760    /// This triggers sending NEW_CONNECTION_ID frames if the provided Source
6761    /// Connection ID is not already present. In the case the caller tries to
6762    /// reuse a Connection ID with a different reset token, this raises an
6763    /// `InvalidState`.
6764    ///
6765    /// At any time, the peer cannot have more Destination Connection IDs than
6766    /// the maximum number of active Connection IDs it negotiated. In such case
6767    /// (i.e., when [`scids_left()`] returns 0), if the host agrees to
6768    /// request the removal of previous connection IDs, it sets the
6769    /// `retire_if_needed` parameter. Otherwise, an [`IdLimit`] is returned.
6770    ///
6771    /// Note that setting `retire_if_needed` does not prevent this function from
6772    /// returning an [`IdLimit`] in the case the caller wants to retire still
6773    /// unannounced Connection IDs.
6774    ///
6775    /// The caller is responsible for ensuring that the provided `scid` is not
6776    /// repeated several times over the connection. quiche ensures that as long
6777    /// as the provided Connection ID is still in use (i.e., not retired), it
6778    /// does not assign a different sequence number.
6779    ///
6780    /// Note that if the host uses zero-length Source Connection IDs, it cannot
6781    /// advertise Source Connection IDs and calling this method returns an
6782    /// [`InvalidState`].
6783    ///
6784    /// Returns the sequence number associated to the provided Connection ID.
6785    ///
6786    /// [`scids_left()`]: struct.Connection.html#method.scids_left
6787    /// [`IdLimit`]: enum.Error.html#IdLimit
6788    /// [`InvalidState`]: enum.Error.html#InvalidState
6789    pub fn new_scid(
6790        &mut self, scid: &ConnectionId, reset_token: u128, retire_if_needed: bool,
6791    ) -> Result<u64> {
6792        self.ids.new_scid(
6793            scid.to_vec().into(),
6794            Some(reset_token),
6795            true,
6796            None,
6797            retire_if_needed,
6798        )
6799    }
6800
6801    /// Returns the number of source Connection IDs that are active. This is
6802    /// only meaningful if the host uses non-zero length Source Connection IDs.
6803    pub fn active_scids(&self) -> usize {
6804        self.ids.active_source_cids()
6805    }
6806
6807    /// Returns the number of source Connection IDs that should be provided
6808    /// to the peer without exceeding the limit it advertised.
6809    ///
6810    /// This will automatically limit the number of Connection IDs to the
6811    /// minimum between the locally configured active connection ID limit,
6812    /// and the one sent by the peer.
6813    ///
6814    /// To obtain the maximum possible value allowed by the peer an application
6815    /// can instead inspect the [`peer_active_conn_id_limit`] value.
6816    ///
6817    /// [`peer_active_conn_id_limit`]: struct.Stats.html#structfield.peer_active_conn_id_limit
6818    #[inline]
6819    pub fn scids_left(&self) -> usize {
6820        let max_active_source_cids = cmp::min(
6821            self.peer_transport_params.active_conn_id_limit,
6822            self.local_transport_params.active_conn_id_limit,
6823        ) as usize;
6824
6825        max_active_source_cids - self.active_scids()
6826    }
6827
6828    /// Requests the retirement of the destination Connection ID used by the
6829    /// host to reach its peer.
6830    ///
6831    /// This triggers sending RETIRE_CONNECTION_ID frames.
6832    ///
6833    /// If the application tries to retire a non-existing Destination Connection
6834    /// ID sequence number, or if it uses zero-length Destination Connection ID,
6835    /// this method returns an [`InvalidState`].
6836    ///
6837    /// At any time, the host must have at least one Destination ID. If the
6838    /// application tries to retire the last one, or if the caller tries to
6839    /// retire the destination Connection ID used by the current active path
6840    /// while having neither spare Destination Connection IDs nor validated
6841    /// network paths, this method returns an [`OutOfIdentifiers`]. This
6842    /// behavior prevents the caller from stalling the connection due to the
6843    /// lack of validated path to send non-probing packets.
6844    ///
6845    /// [`InvalidState`]: enum.Error.html#InvalidState
6846    /// [`OutOfIdentifiers`]: enum.Error.html#OutOfIdentifiers
6847    pub fn retire_dcid(&mut self, dcid_seq: u64) -> Result<()> {
6848        if self.ids.zero_length_dcid() {
6849            return Err(Error::InvalidState);
6850        }
6851
6852        let active_path_dcid_seq = self
6853            .paths
6854            .get_active()?
6855            .active_dcid_seq
6856            .ok_or(Error::InvalidState)?;
6857
6858        let active_path_id = self.paths.get_active_path_id()?;
6859
6860        if active_path_dcid_seq == dcid_seq &&
6861            self.ids.lowest_available_dcid_seq().is_none() &&
6862            !self
6863                .paths
6864                .iter()
6865                .any(|(pid, p)| pid != active_path_id && p.usable())
6866        {
6867            return Err(Error::OutOfIdentifiers);
6868        }
6869
6870        if let Some(pid) = self.ids.retire_dcid(dcid_seq)? {
6871            // The retired Destination CID was associated to a given path. Let's
6872            // find an available DCID to associate to that path.
6873            let path = self.paths.get_mut(pid)?;
6874            let dcid_seq = self.ids.lowest_available_dcid_seq();
6875
6876            if let Some(dcid_seq) = dcid_seq {
6877                self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
6878            }
6879
6880            path.active_dcid_seq = dcid_seq;
6881        }
6882
6883        Ok(())
6884    }
6885
6886    /// Processes path-specific events.
6887    ///
6888    /// On success it returns a [`PathEvent`], or `None` when there are no
6889    /// events to report. Please refer to [`PathEvent`] for the exhaustive event
6890    /// list.
6891    ///
6892    /// Note that all events are edge-triggered, meaning that once reported they
6893    /// will not be reported again by calling this method again, until the event
6894    /// is re-armed.
6895    ///
6896    /// [`PathEvent`]: enum.PathEvent.html
6897    pub fn path_event_next(&mut self) -> Option<PathEvent> {
6898        self.paths.pop_event()
6899    }
6900
6901    /// Returns the number of source Connection IDs that are retired.
6902    pub fn retired_scids(&self) -> usize {
6903        self.ids.retired_source_cids()
6904    }
6905
6906    /// Returns a source `ConnectionId` that has been retired.
6907    ///
6908    /// On success it returns a [`ConnectionId`], or `None` when there are no
6909    /// more retired connection IDs.
6910    ///
6911    /// [`ConnectionId`]: struct.ConnectionId.html
6912    pub fn retired_scid_next(&mut self) -> Option<ConnectionId<'static>> {
6913        self.ids.pop_retired_scid()
6914    }
6915
6916    /// Returns the number of spare Destination Connection IDs, i.e.,
6917    /// Destination Connection IDs that are still unused.
6918    ///
6919    /// Note that this function returns 0 if the host uses zero length
6920    /// Destination Connection IDs.
6921    pub fn available_dcids(&self) -> usize {
6922        self.ids.available_dcids()
6923    }
6924
6925    /// Returns an iterator over destination `SockAddr`s whose association
6926    /// with `from` forms a known QUIC path on which packets can be sent to.
6927    ///
6928    /// This function is typically used in combination with [`send_on_path()`].
6929    ///
6930    /// Note that the iterator includes all the possible combination of
6931    /// destination `SockAddr`s, even those whose sending is not required now.
6932    /// In other words, this is another way for the application to recall from
6933    /// past [`PathEvent::New`] events.
6934    ///
6935    /// [`PathEvent::New`]: enum.PathEvent.html#variant.New
6936    /// [`send_on_path()`]: struct.Connection.html#method.send_on_path
6937    ///
6938    /// ## Examples:
6939    ///
6940    /// ```no_run
6941    /// # let mut out = [0; 512];
6942    /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
6943    /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
6944    /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
6945    /// # let local = socket.local_addr().unwrap();
6946    /// # let peer = "127.0.0.1:1234".parse().unwrap();
6947    /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
6948    /// // Iterate over possible destinations for the given local `SockAddr`.
6949    /// for dest in conn.paths_iter(local) {
6950    ///     loop {
6951    ///         let (write, send_info) =
6952    ///             match conn.send_on_path(&mut out, Some(local), Some(dest)) {
6953    ///                 Ok(v) => v,
6954    ///
6955    ///                 Err(quiche::Error::Done) => {
6956    ///                     // Done writing for this destination.
6957    ///                     break;
6958    ///                 },
6959    ///
6960    ///                 Err(e) => {
6961    ///                     // An error occurred, handle it.
6962    ///                     break;
6963    ///                 },
6964    ///             };
6965    ///
6966    ///         socket.send_to(&out[..write], &send_info.to).unwrap();
6967    ///     }
6968    /// }
6969    /// # Ok::<(), quiche::Error>(())
6970    /// ```
6971    #[inline]
6972    pub fn paths_iter(&self, from: SocketAddr) -> SocketAddrIter {
6973        // Instead of trying to identify whether packets will be sent on the
6974        // given 4-tuple, simply filter paths that cannot be used.
6975        SocketAddrIter {
6976            sockaddrs: self
6977                .paths
6978                .iter()
6979                .filter(|(_, p)| p.active_dcid_seq.is_some())
6980                .filter(|(_, p)| p.usable() || p.probing_required())
6981                .filter(|(_, p)| p.local_addr() == from)
6982                .map(|(_, p)| p.peer_addr())
6983                .collect(),
6984
6985            index: 0,
6986        }
6987    }
6988
6989    /// Closes the connection with the given error and reason.
6990    ///
6991    /// The `app` parameter specifies whether an application close should be
6992    /// sent to the peer. Otherwise a normal connection close is sent.
6993    ///
6994    /// If `app` is true but the connection is not in a state that is safe to
6995    /// send an application error (not established nor in early data), in
6996    /// accordance with [RFC
6997    /// 9000](https://www.rfc-editor.org/rfc/rfc9000.html#section-10.2.3-3), the
6998    /// error code is changed to APPLICATION_ERROR and the reason phrase is
6999    /// cleared.
7000    ///
7001    /// Returns [`Done`] if the connection had already been closed.
7002    ///
7003    /// Note that the connection will not be closed immediately. An application
7004    /// should continue calling the [`recv()`], [`send()`], [`timeout()`] and
7005    /// [`on_timeout()`] methods as normal, until the [`is_closed()`] method
7006    /// returns `true`.
7007    ///
7008    /// [`Done`]: enum.Error.html#variant.Done
7009    /// [`recv()`]: struct.Connection.html#method.recv
7010    /// [`send()`]: struct.Connection.html#method.send
7011    /// [`timeout()`]: struct.Connection.html#method.timeout
7012    /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
7013    /// [`is_closed()`]: struct.Connection.html#method.is_closed
7014    pub fn close(&mut self, app: bool, err: u64, reason: &[u8]) -> Result<()> {
7015        if self.is_closed() || self.is_draining() {
7016            return Err(Error::Done);
7017        }
7018
7019        if self.local_error.is_some() {
7020            return Err(Error::Done);
7021        }
7022
7023        let is_safe_to_send_app_data =
7024            self.is_established() || self.is_in_early_data();
7025
7026        if app && !is_safe_to_send_app_data {
7027            // Clear error information.
7028            self.local_error = Some(ConnectionError {
7029                is_app: false,
7030                error_code: 0x0c,
7031                reason: vec![],
7032            });
7033        } else {
7034            self.local_error = Some(ConnectionError {
7035                is_app: app,
7036                error_code: err,
7037                reason: reason.to_vec(),
7038            });
7039        }
7040
7041        // When no packet was successfully processed close connection immediately.
7042        if self.recv_count == 0 {
7043            self.mark_closed();
7044        }
7045
7046        Ok(())
7047    }
7048
7049    /// Returns a string uniquely representing the connection.
7050    ///
7051    /// This can be used for logging purposes to differentiate between multiple
7052    /// connections.
7053    #[inline]
7054    pub fn trace_id(&self) -> &str {
7055        &self.trace_id
7056    }
7057
7058    /// Returns the negotiated ALPN protocol.
7059    ///
7060    /// If no protocol has been negotiated, the returned value is empty.
7061    #[inline]
7062    pub fn application_proto(&self) -> &[u8] {
7063        self.alpn.as_ref()
7064    }
7065
7066    /// Returns the server name requested by the client.
7067    #[inline]
7068    pub fn server_name(&self) -> Option<&str> {
7069        self.handshake.server_name()
7070    }
7071
7072    /// Returns the peer's leaf certificate (if any) as a DER-encoded buffer.
7073    #[inline]
7074    pub fn peer_cert(&self) -> Option<&[u8]> {
7075        self.handshake.peer_cert()
7076    }
7077
7078    /// Returns the peer's certificate chain (if any) as a vector of DER-encoded
7079    /// buffers.
7080    ///
7081    /// The certificate at index 0 is the peer's leaf certificate, the other
7082    /// certificates (if any) are the chain certificate authorities used to
7083    /// sign the leaf certificate.
7084    #[inline]
7085    pub fn peer_cert_chain(&self) -> Option<Vec<&[u8]>> {
7086        self.handshake.peer_cert_chain()
7087    }
7088
7089    /// Returns the serialized cryptographic session for the connection.
7090    ///
7091    /// This can be used by a client to cache a connection's session, and resume
7092    /// it later using the [`set_session()`] method.
7093    ///
7094    /// [`set_session()`]: struct.Connection.html#method.set_session
7095    #[inline]
7096    pub fn session(&self) -> Option<&[u8]> {
7097        self.session.as_deref()
7098    }
7099
7100    /// Returns the source connection ID.
7101    ///
7102    /// When there are multiple IDs, and if there is an active path, the ID used
7103    /// on that path is returned. Otherwise the oldest ID is returned.
7104    ///
7105    /// Note that the value returned can change throughout the connection's
7106    /// lifetime.
7107    #[inline]
7108    pub fn source_id(&self) -> ConnectionId<'_> {
7109        if let Ok(path) = self.paths.get_active() {
7110            if let Some(active_scid_seq) = path.active_scid_seq {
7111                if let Ok(e) = self.ids.get_scid(active_scid_seq) {
7112                    return ConnectionId::from_ref(e.cid.as_ref());
7113                }
7114            }
7115        }
7116
7117        let e = self.ids.oldest_scid();
7118        ConnectionId::from_ref(e.cid.as_ref())
7119    }
7120
7121    /// Returns all active source connection IDs.
7122    ///
7123    /// An iterator is returned for all active IDs (i.e. ones that have not
7124    /// been explicitly retired yet).
7125    #[inline]
7126    pub fn source_ids(&self) -> impl Iterator<Item = &ConnectionId<'_>> {
7127        self.ids.scids_iter()
7128    }
7129
7130    /// Returns the destination connection ID.
7131    ///
7132    /// Note that the value returned can change throughout the connection's
7133    /// lifetime.
7134    #[inline]
7135    pub fn destination_id(&self) -> ConnectionId<'_> {
7136        if let Ok(path) = self.paths.get_active() {
7137            if let Some(active_dcid_seq) = path.active_dcid_seq {
7138                if let Ok(e) = self.ids.get_dcid(active_dcid_seq) {
7139                    return ConnectionId::from_ref(e.cid.as_ref());
7140                }
7141            }
7142        }
7143
7144        let e = self.ids.oldest_dcid();
7145        ConnectionId::from_ref(e.cid.as_ref())
7146    }
7147
7148    /// Returns the PMTU for the active path if it exists.
7149    ///
7150    /// This requires no additonal packets to be sent but simply checks if PMTUD
7151    /// has completed and has found a valid PMTU.
7152    #[inline]
7153    pub fn pmtu(&self) -> Option<usize> {
7154        if let Ok(path) = self.paths.get_active() {
7155            path.pmtud.as_ref().and_then(|pmtud| pmtud.get_pmtu())
7156        } else {
7157            None
7158        }
7159    }
7160
7161    /// Revalidates the PMTU for the active path by sending a new probe packet
7162    /// of PMTU size. If the probe is dropped PMTUD will restart and find a new
7163    /// valid PMTU.
7164    #[inline]
7165    pub fn revalidate_pmtu(&mut self) {
7166        if let Ok(active_path) = self.paths.get_active_mut() {
7167            if let Some(pmtud) = active_path.pmtud.as_mut() {
7168                pmtud.revalidate_pmtu();
7169            }
7170        }
7171    }
7172
7173    /// Returns true if the connection handshake is complete.
7174    #[inline]
7175    pub fn is_established(&self) -> bool {
7176        self.handshake_completed
7177    }
7178
7179    /// Returns true if the connection is resumed.
7180    #[inline]
7181    pub fn is_resumed(&self) -> bool {
7182        self.handshake.is_resumed()
7183    }
7184
7185    /// Returns true if the connection has a pending handshake that has
7186    /// progressed enough to send or receive early data.
7187    #[inline]
7188    pub fn is_in_early_data(&self) -> bool {
7189        self.handshake.is_in_early_data()
7190    }
7191
7192    /// Returns the early data reason for the connection.
7193    ///
7194    /// This status can be useful for logging and debugging. See [BoringSSL]
7195    /// documentation for a definition of the reasons.
7196    ///
7197    /// [BoringSSL]: https://commondatastorage.googleapis.com/chromium-boringssl-docs/ssl.h.html#ssl_early_data_reason_t
7198    #[inline]
7199    pub fn early_data_reason(&self) -> u32 {
7200        self.handshake.early_data_reason()
7201    }
7202
7203    /// Returns whether there is stream or DATAGRAM data available to read.
7204    #[inline]
7205    pub fn is_readable(&self) -> bool {
7206        self.streams.has_readable() || self.dgram_recv_front_len().is_some()
7207    }
7208
7209    /// Returns whether the network path with local address `from` and remote
7210    /// address `peer` has been validated.
7211    ///
7212    /// If the 4-tuple does not exist over the connection, returns an
7213    /// [`InvalidState`].
7214    ///
7215    /// [`InvalidState`]: enum.Error.html#variant.InvalidState
7216    pub fn is_path_validated(
7217        &self, from: SocketAddr, to: SocketAddr,
7218    ) -> Result<bool> {
7219        let pid = self
7220            .paths
7221            .path_id_from_addrs(&(from, to))
7222            .ok_or(Error::InvalidState)?;
7223
7224        Ok(self.paths.get(pid)?.validated())
7225    }
7226
7227    /// Returns true if the connection is draining.
7228    ///
7229    /// If this returns `true`, the connection object cannot yet be dropped, but
7230    /// no new application data can be sent or received. An application should
7231    /// continue calling the [`recv()`], [`timeout()`], and [`on_timeout()`]
7232    /// methods as normal, until the [`is_closed()`] method returns `true`.
7233    ///
7234    /// In contrast, once `is_draining()` returns `true`, calling [`send()`]
7235    /// is not required because no new outgoing packets will be generated.
7236    ///
7237    /// [`recv()`]: struct.Connection.html#method.recv
7238    /// [`send()`]: struct.Connection.html#method.send
7239    /// [`timeout()`]: struct.Connection.html#method.timeout
7240    /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
7241    /// [`is_closed()`]: struct.Connection.html#method.is_closed
7242    #[inline]
7243    pub fn is_draining(&self) -> bool {
7244        self.draining_timer.is_some()
7245    }
7246
7247    /// Returns true if the connection is closed.
7248    ///
7249    /// If this returns true, the connection object can be dropped.
7250    #[inline]
7251    pub fn is_closed(&self) -> bool {
7252        self.closed
7253    }
7254
7255    /// Returns true if the connection was closed due to the idle timeout.
7256    #[inline]
7257    pub fn is_timed_out(&self) -> bool {
7258        self.timed_out
7259    }
7260
7261    /// Returns the error received from the peer, if any.
7262    ///
7263    /// Note that a `Some` return value does not necessarily imply
7264    /// [`is_closed()`] or any other connection state.
7265    ///
7266    /// [`is_closed()`]: struct.Connection.html#method.is_closed
7267    #[inline]
7268    pub fn peer_error(&self) -> Option<&ConnectionError> {
7269        self.peer_error.as_ref()
7270    }
7271
7272    /// Returns the error [`close()`] was called with, or internally
7273    /// created quiche errors, if any.
7274    ///
7275    /// Note that a `Some` return value does not necessarily imply
7276    /// [`is_closed()`] or any other connection state.
7277    /// `Some` also does not guarantee that the error has been sent to
7278    /// or received by the peer.
7279    ///
7280    /// [`close()`]: struct.Connection.html#method.close
7281    /// [`is_closed()`]: struct.Connection.html#method.is_closed
7282    #[inline]
7283    pub fn local_error(&self) -> Option<&ConnectionError> {
7284        self.local_error.as_ref()
7285    }
7286
7287    /// Collects and returns statistics about the connection.
7288    #[inline]
7289    pub fn stats(&self) -> Stats {
7290        Stats {
7291            recv: self.recv_count,
7292            sent: self.sent_count,
7293            lost: self.lost_count,
7294            spurious_lost: self.spurious_lost_count,
7295            retrans: self.retrans_count,
7296            sent_bytes: self.sent_bytes,
7297            recv_bytes: self.recv_bytes,
7298            acked_bytes: self.acked_bytes,
7299            lost_bytes: self.lost_bytes,
7300            stream_retrans_bytes: self.stream_retrans_bytes,
7301            dgram_recv: self.dgram_recv_count,
7302            dgram_sent: self.dgram_sent_count,
7303            paths_count: self.paths.len(),
7304            reset_stream_count_local: self.reset_stream_local_count,
7305            stopped_stream_count_local: self.stopped_stream_local_count,
7306            reset_stream_count_remote: self.reset_stream_remote_count,
7307            stopped_stream_count_remote: self.stopped_stream_remote_count,
7308            data_blocked_sent_count: self.data_blocked_sent_count,
7309            stream_data_blocked_sent_count: self.stream_data_blocked_sent_count,
7310            data_blocked_recv_count: self.data_blocked_recv_count,
7311            stream_data_blocked_recv_count: self.stream_data_blocked_recv_count,
7312            path_challenge_rx_count: self.path_challenge_rx_count,
7313            bytes_in_flight_duration: self.bytes_in_flight_duration(),
7314            tx_buffered_state: self.tx_buffered_state,
7315        }
7316    }
7317
7318    /// Returns the sum of the durations when each path in the
7319    /// connection was actively sending bytes or waiting for acks.
7320    /// Note that this could result in a duration that is longer than
7321    /// the actual connection duration in cases where multiple paths
7322    /// are active for extended periods of time.  In practice only 1
7323    /// path is typically active at a time.
7324    /// TODO revisit computation if in the future multiple paths are
7325    /// often active at the same time.
7326    fn bytes_in_flight_duration(&self) -> Duration {
7327        self.paths.iter().fold(Duration::ZERO, |acc, (_, path)| {
7328            acc + path.bytes_in_flight_duration()
7329        })
7330    }
7331
7332    /// Returns reference to peer's transport parameters. Returns `None` if we
7333    /// have not yet processed the peer's transport parameters.
7334    pub fn peer_transport_params(&self) -> Option<&TransportParams> {
7335        if !self.parsed_peer_transport_params {
7336            return None;
7337        }
7338
7339        Some(&self.peer_transport_params)
7340    }
7341
7342    /// Collects and returns statistics about each known path for the
7343    /// connection.
7344    pub fn path_stats(&self) -> impl Iterator<Item = PathStats> + '_ {
7345        self.paths.iter().map(|(_, p)| p.stats())
7346    }
7347
7348    /// Returns whether or not this is a server-side connection.
7349    pub fn is_server(&self) -> bool {
7350        self.is_server
7351    }
7352
7353    fn encode_transport_params(&mut self) -> Result<()> {
7354        self.handshake.set_quic_transport_params(
7355            &self.local_transport_params,
7356            self.is_server,
7357        )
7358    }
7359
7360    fn parse_peer_transport_params(
7361        &mut self, peer_params: TransportParams,
7362    ) -> Result<()> {
7363        // Validate initial_source_connection_id.
7364        match &peer_params.initial_source_connection_id {
7365            Some(v) if v != &self.destination_id() =>
7366                return Err(Error::InvalidTransportParam),
7367
7368            Some(_) => (),
7369
7370            // initial_source_connection_id must be sent by
7371            // both endpoints.
7372            None => return Err(Error::InvalidTransportParam),
7373        }
7374
7375        // Validate original_destination_connection_id.
7376        if let Some(odcid) = &self.odcid {
7377            match &peer_params.original_destination_connection_id {
7378                Some(v) if v != odcid =>
7379                    return Err(Error::InvalidTransportParam),
7380
7381                Some(_) => (),
7382
7383                // original_destination_connection_id must be
7384                // sent by the server.
7385                None if !self.is_server =>
7386                    return Err(Error::InvalidTransportParam),
7387
7388                None => (),
7389            }
7390        }
7391
7392        // Validate retry_source_connection_id.
7393        if let Some(rscid) = &self.rscid {
7394            match &peer_params.retry_source_connection_id {
7395                Some(v) if v != rscid =>
7396                    return Err(Error::InvalidTransportParam),
7397
7398                Some(_) => (),
7399
7400                // retry_source_connection_id must be sent by
7401                // the server.
7402                None => return Err(Error::InvalidTransportParam),
7403            }
7404        }
7405
7406        self.process_peer_transport_params(peer_params)?;
7407
7408        self.parsed_peer_transport_params = true;
7409
7410        Ok(())
7411    }
7412
7413    fn process_peer_transport_params(
7414        &mut self, peer_params: TransportParams,
7415    ) -> Result<()> {
7416        self.max_tx_data = peer_params.initial_max_data;
7417
7418        // Update send capacity.
7419        self.update_tx_cap();
7420
7421        self.streams
7422            .update_peer_max_streams_bidi(peer_params.initial_max_streams_bidi);
7423        self.streams
7424            .update_peer_max_streams_uni(peer_params.initial_max_streams_uni);
7425
7426        let max_ack_delay = Duration::from_millis(peer_params.max_ack_delay);
7427
7428        self.recovery_config.max_ack_delay = max_ack_delay;
7429
7430        let active_path = self.paths.get_active_mut()?;
7431
7432        active_path.recovery.update_max_ack_delay(max_ack_delay);
7433
7434        if active_path
7435            .pmtud
7436            .as_ref()
7437            .map(|pmtud| pmtud.should_probe())
7438            .unwrap_or(false)
7439        {
7440            active_path.recovery.pmtud_update_max_datagram_size(
7441                active_path
7442                    .pmtud
7443                    .as_mut()
7444                    .expect("PMTUD existence verified above")
7445                    .get_probe_size()
7446                    .min(peer_params.max_udp_payload_size as usize),
7447            );
7448        } else {
7449            active_path.recovery.update_max_datagram_size(
7450                peer_params.max_udp_payload_size as usize,
7451            );
7452        }
7453
7454        // Record the max_active_conn_id parameter advertised by the peer.
7455        self.ids
7456            .set_source_conn_id_limit(peer_params.active_conn_id_limit);
7457
7458        self.peer_transport_params = peer_params;
7459
7460        Ok(())
7461    }
7462
7463    /// Continues the handshake.
7464    ///
7465    /// If the connection is already established, it does nothing.
7466    fn do_handshake(&mut self, now: Instant) -> Result<()> {
7467        let mut ex_data = tls::ExData {
7468            application_protos: &self.application_protos,
7469
7470            crypto_ctx: &mut self.crypto_ctx,
7471
7472            session: &mut self.session,
7473
7474            local_error: &mut self.local_error,
7475
7476            keylog: self.keylog.as_mut(),
7477
7478            trace_id: &self.trace_id,
7479
7480            local_transport_params: self.local_transport_params.clone(),
7481
7482            recovery_config: self.recovery_config,
7483
7484            tx_cap_factor: self.tx_cap_factor,
7485
7486            pmtud: None,
7487
7488            is_server: self.is_server,
7489        };
7490
7491        if self.handshake_completed {
7492            return self.handshake.process_post_handshake(&mut ex_data);
7493        }
7494
7495        match self.handshake.do_handshake(&mut ex_data) {
7496            Ok(_) => (),
7497
7498            Err(Error::Done) => {
7499                // Apply in-handshake configuration from callbacks if the path's
7500                // Recovery module can still be reinitilized.
7501                if self
7502                    .paths
7503                    .get_active()
7504                    .map(|p| p.can_reinit_recovery())
7505                    .unwrap_or(false)
7506                {
7507                    if ex_data.recovery_config != self.recovery_config {
7508                        if let Ok(path) = self.paths.get_active_mut() {
7509                            self.recovery_config = ex_data.recovery_config;
7510                            path.reinit_recovery(&self.recovery_config);
7511                        }
7512                    }
7513
7514                    if ex_data.tx_cap_factor != self.tx_cap_factor {
7515                        self.tx_cap_factor = ex_data.tx_cap_factor;
7516                    }
7517
7518                    if let Some((discover, max_probes)) = ex_data.pmtud {
7519                        self.paths.set_discover_pmtu_on_existing_paths(
7520                            discover,
7521                            self.recovery_config.max_send_udp_payload_size,
7522                            max_probes,
7523                        );
7524                    }
7525
7526                    if ex_data.local_transport_params !=
7527                        self.local_transport_params
7528                    {
7529                        self.streams.set_max_streams_bidi(
7530                            ex_data
7531                                .local_transport_params
7532                                .initial_max_streams_bidi,
7533                        );
7534
7535                        self.local_transport_params =
7536                            ex_data.local_transport_params;
7537                    }
7538                }
7539
7540                // Try to parse transport parameters as soon as the first flight
7541                // of handshake data is processed.
7542                //
7543                // This is potentially dangerous as the handshake hasn't been
7544                // completed yet, though it's required to be able to send data
7545                // in 0.5 RTT.
7546                let raw_params = self.handshake.quic_transport_params();
7547
7548                if !self.parsed_peer_transport_params && !raw_params.is_empty() {
7549                    let peer_params = TransportParams::decode(
7550                        raw_params,
7551                        self.is_server,
7552                        self.peer_transport_params_track_unknown,
7553                    )?;
7554
7555                    self.parse_peer_transport_params(peer_params)?;
7556                }
7557
7558                return Ok(());
7559            },
7560
7561            Err(e) => return Err(e),
7562        };
7563
7564        self.handshake_completed = self.handshake.is_completed();
7565
7566        self.alpn = self.handshake.alpn_protocol().to_vec();
7567
7568        let raw_params = self.handshake.quic_transport_params();
7569
7570        if !self.parsed_peer_transport_params && !raw_params.is_empty() {
7571            let peer_params = TransportParams::decode(
7572                raw_params,
7573                self.is_server,
7574                self.peer_transport_params_track_unknown,
7575            )?;
7576
7577            self.parse_peer_transport_params(peer_params)?;
7578        }
7579
7580        if self.handshake_completed {
7581            // The handshake is considered confirmed at the server when the
7582            // handshake completes, at which point we can also drop the
7583            // handshake epoch.
7584            if self.is_server {
7585                self.handshake_confirmed = true;
7586
7587                self.drop_epoch_state(packet::Epoch::Handshake, now);
7588            }
7589
7590            // Once the handshake is completed there's no point in processing
7591            // 0-RTT packets anymore, so clear the buffer now.
7592            self.undecryptable_pkts.clear();
7593
7594            trace!("{} connection established: proto={:?} cipher={:?} curve={:?} sigalg={:?} resumed={} {:?}",
7595                   &self.trace_id,
7596                   std::str::from_utf8(self.application_proto()),
7597                   self.handshake.cipher(),
7598                   self.handshake.curve(),
7599                   self.handshake.sigalg(),
7600                   self.handshake.is_resumed(),
7601                   self.peer_transport_params);
7602        }
7603
7604        Ok(())
7605    }
7606
7607    /// Selects the packet type for the next outgoing packet.
7608    fn write_pkt_type(&self, send_pid: usize) -> Result<Type> {
7609        // On error send packet in the latest epoch available, but only send
7610        // 1-RTT ones when the handshake is completed.
7611        if self
7612            .local_error
7613            .as_ref()
7614            .is_some_and(|conn_err| !conn_err.is_app)
7615        {
7616            let epoch = match self.handshake.write_level() {
7617                crypto::Level::Initial => packet::Epoch::Initial,
7618                crypto::Level::ZeroRTT => unreachable!(),
7619                crypto::Level::Handshake => packet::Epoch::Handshake,
7620                crypto::Level::OneRTT => packet::Epoch::Application,
7621            };
7622
7623            if !self.handshake_confirmed {
7624                match epoch {
7625                    // Downgrade the epoch to Handshake as the handshake is not
7626                    // completed yet.
7627                    packet::Epoch::Application => return Ok(Type::Handshake),
7628
7629                    // Downgrade the epoch to Initial as the remote peer might
7630                    // not be able to decrypt handshake packets yet.
7631                    packet::Epoch::Handshake
7632                        if self.crypto_ctx[packet::Epoch::Initial].has_keys() =>
7633                        return Ok(Type::Initial),
7634
7635                    _ => (),
7636                };
7637            }
7638
7639            return Ok(Type::from_epoch(epoch));
7640        }
7641
7642        for &epoch in packet::Epoch::epochs(
7643            packet::Epoch::Initial..=packet::Epoch::Application,
7644        ) {
7645            let crypto_ctx = &self.crypto_ctx[epoch];
7646            let pkt_space = &self.pkt_num_spaces[epoch];
7647
7648            // Only send packets in a space when we have the send keys for it.
7649            if crypto_ctx.crypto_seal.is_none() {
7650                continue;
7651            }
7652
7653            // We are ready to send data for this packet number space.
7654            if crypto_ctx.data_available() || pkt_space.ready() {
7655                return Ok(Type::from_epoch(epoch));
7656            }
7657
7658            // There are lost frames in this packet number space.
7659            for (_, p) in self.paths.iter() {
7660                if p.recovery.has_lost_frames(epoch) {
7661                    return Ok(Type::from_epoch(epoch));
7662                }
7663
7664                // We need to send PTO probe packets.
7665                if p.recovery.loss_probes(epoch) > 0 {
7666                    return Ok(Type::from_epoch(epoch));
7667                }
7668            }
7669        }
7670
7671        // If there are flushable, almost full or blocked streams, use the
7672        // Application epoch.
7673        let send_path = self.paths.get(send_pid)?;
7674        if (self.is_established() || self.is_in_early_data()) &&
7675            (self.should_send_handshake_done() ||
7676                self.almost_full ||
7677                self.blocked_limit.is_some() ||
7678                self.dgram_send_queue.has_pending() ||
7679                self.local_error
7680                    .as_ref()
7681                    .is_some_and(|conn_err| conn_err.is_app) ||
7682                self.streams.should_update_max_streams_bidi() ||
7683                self.streams.should_update_max_streams_uni() ||
7684                self.streams.has_flushable() ||
7685                self.streams.has_almost_full() ||
7686                self.streams.has_blocked() ||
7687                self.streams.has_reset() ||
7688                self.streams.has_stopped() ||
7689                self.ids.has_new_scids() ||
7690                self.ids.has_retire_dcids() ||
7691                send_path
7692                    .pmtud
7693                    .as_ref()
7694                    .is_some_and(|pmtud| pmtud.should_probe()) ||
7695                send_path.needs_ack_eliciting ||
7696                send_path.probing_required())
7697        {
7698            // Only clients can send 0-RTT packets.
7699            if !self.is_server && self.is_in_early_data() {
7700                return Ok(Type::ZeroRTT);
7701            }
7702
7703            return Ok(Type::Short);
7704        }
7705
7706        Err(Error::Done)
7707    }
7708
7709    /// Returns the mutable stream with the given ID if it exists, or creates
7710    /// a new one otherwise.
7711    fn get_or_create_stream(
7712        &mut self, id: u64, local: bool,
7713    ) -> Result<&mut stream::Stream<F>> {
7714        self.streams.get_or_create(
7715            id,
7716            &self.local_transport_params,
7717            &self.peer_transport_params,
7718            local,
7719            self.is_server,
7720        )
7721    }
7722
7723    /// Processes an incoming frame.
7724    fn process_frame(
7725        &mut self, frame: frame::Frame, hdr: &Header, recv_path_id: usize,
7726        epoch: packet::Epoch, now: Instant,
7727    ) -> Result<()> {
7728        trace!("{} rx frm {:?}", self.trace_id, frame);
7729
7730        match frame {
7731            frame::Frame::Padding { .. } => (),
7732
7733            frame::Frame::Ping { .. } => (),
7734
7735            frame::Frame::ACK {
7736                ranges, ack_delay, ..
7737            } => {
7738                let ack_delay = ack_delay
7739                    .checked_mul(2_u64.pow(
7740                        self.peer_transport_params.ack_delay_exponent as u32,
7741                    ))
7742                    .ok_or(Error::InvalidFrame)?;
7743
7744                if epoch == packet::Epoch::Handshake ||
7745                    (epoch == packet::Epoch::Application &&
7746                        self.is_established())
7747                {
7748                    self.peer_verified_initial_address = true;
7749                }
7750
7751                let handshake_status = self.handshake_status();
7752
7753                let is_app_limited = self.delivery_rate_check_if_app_limited();
7754
7755                let largest_acked = ranges.last().expect(
7756                    "ACK frames should always have at least one ack range",
7757                );
7758
7759                for (_, p) in self.paths.iter_mut() {
7760                    if self.pkt_num_spaces[epoch]
7761                        .largest_tx_pkt_num
7762                        .is_some_and(|largest_sent| largest_sent < largest_acked)
7763                    {
7764                        // https://www.rfc-editor.org/rfc/rfc9000#section-13.1
7765                        // An endpoint SHOULD treat receipt of an acknowledgment
7766                        // for a packet it did not send as
7767                        // a connection error of type PROTOCOL_VIOLATION
7768                        return Err(Error::InvalidAckRange);
7769                    }
7770
7771                    if is_app_limited {
7772                        p.recovery.delivery_rate_update_app_limited(true);
7773                    }
7774
7775                    let OnAckReceivedOutcome {
7776                        lost_packets,
7777                        lost_bytes,
7778                        acked_bytes,
7779                        spurious_losses,
7780                    } = p.recovery.on_ack_received(
7781                        &ranges,
7782                        ack_delay,
7783                        epoch,
7784                        handshake_status,
7785                        now,
7786                        self.pkt_num_manager.skip_pn(),
7787                        &self.trace_id,
7788                    )?;
7789
7790                    let skip_pn = self.pkt_num_manager.skip_pn();
7791                    let largest_acked =
7792                        p.recovery.get_largest_acked_on_epoch(epoch);
7793
7794                    // Consider the skip_pn validated if the peer has sent an ack
7795                    // for a larger pkt number.
7796                    if let Some((largest_acked, skip_pn)) =
7797                        largest_acked.zip(skip_pn)
7798                    {
7799                        if largest_acked > skip_pn {
7800                            self.pkt_num_manager.set_skip_pn(None);
7801                        }
7802                    }
7803
7804                    self.lost_count += lost_packets;
7805                    self.lost_bytes += lost_bytes as u64;
7806                    self.acked_bytes += acked_bytes as u64;
7807                    self.spurious_lost_count += spurious_losses;
7808                }
7809            },
7810
7811            frame::Frame::ResetStream {
7812                stream_id,
7813                error_code,
7814                final_size,
7815            } => {
7816                // Peer can't send on our unidirectional streams.
7817                if !stream::is_bidi(stream_id) &&
7818                    stream::is_local(stream_id, self.is_server)
7819                {
7820                    return Err(Error::InvalidStreamState(stream_id));
7821                }
7822
7823                let max_rx_data_left = self.max_rx_data() - self.rx_data;
7824
7825                // Get existing stream or create a new one, but if the stream
7826                // has already been closed and collected, ignore the frame.
7827                //
7828                // This can happen if e.g. an ACK frame is lost, and the peer
7829                // retransmits another frame before it realizes that the stream
7830                // is gone.
7831                //
7832                // Note that it makes it impossible to check if the frame is
7833                // illegal, since we have no state, but since we ignore the
7834                // frame, it should be fine.
7835                let stream = match self.get_or_create_stream(stream_id, false) {
7836                    Ok(v) => v,
7837
7838                    Err(Error::Done) => return Ok(()),
7839
7840                    Err(e) => return Err(e),
7841                };
7842
7843                let was_readable = stream.is_readable();
7844                let priority_key = Arc::clone(&stream.priority_key);
7845
7846                let stream::RecvBufResetReturn {
7847                    max_data_delta,
7848                    consumed_flowcontrol,
7849                } = stream.recv.reset(error_code, final_size)?;
7850
7851                if max_data_delta > max_rx_data_left {
7852                    return Err(Error::FlowControl);
7853                }
7854
7855                if !was_readable && stream.is_readable() {
7856                    self.streams.insert_readable(&priority_key);
7857                }
7858
7859                self.rx_data += max_data_delta;
7860                // We dropped the receive buffer, return connection level
7861                // flow-control
7862                self.flow_control.add_consumed(consumed_flowcontrol);
7863
7864                // ... and check if need to send an updated MAX_DATA frame
7865                if self.should_update_max_data() {
7866                    self.almost_full = true;
7867                }
7868
7869                self.reset_stream_remote_count =
7870                    self.reset_stream_remote_count.saturating_add(1);
7871            },
7872
7873            frame::Frame::StopSending {
7874                stream_id,
7875                error_code,
7876            } => {
7877                // STOP_SENDING on a receive-only stream is a fatal error.
7878                if !stream::is_local(stream_id, self.is_server) &&
7879                    !stream::is_bidi(stream_id)
7880                {
7881                    return Err(Error::InvalidStreamState(stream_id));
7882                }
7883
7884                // Get existing stream or create a new one, but if the stream
7885                // has already been closed and collected, ignore the frame.
7886                //
7887                // This can happen if e.g. an ACK frame is lost, and the peer
7888                // retransmits another frame before it realizes that the stream
7889                // is gone.
7890                //
7891                // Note that it makes it impossible to check if the frame is
7892                // illegal, since we have no state, but since we ignore the
7893                // frame, it should be fine.
7894                let stream = match self.get_or_create_stream(stream_id, false) {
7895                    Ok(v) => v,
7896
7897                    Err(Error::Done) => return Ok(()),
7898
7899                    Err(e) => return Err(e),
7900                };
7901
7902                let was_writable = stream.is_writable();
7903
7904                let priority_key = Arc::clone(&stream.priority_key);
7905
7906                // Try stopping the stream.
7907                if let Ok((final_size, unsent)) = stream.send.stop(error_code) {
7908                    // Claw back some flow control allowance from data that was
7909                    // buffered but not actually sent before the stream was
7910                    // reset.
7911                    //
7912                    // Note that `tx_cap` will be updated later on, so no need
7913                    // to touch it here.
7914                    self.tx_data = self.tx_data.saturating_sub(unsent);
7915
7916                    self.tx_buffered =
7917                        self.tx_buffered.saturating_sub(unsent as usize);
7918
7919                    // These drops in qlog are a bit weird, but the only way to
7920                    // ensure that all bytes that are moved from App to Transport
7921                    // in stream_do_send are eventually moved from Transport to
7922                    // Dropped.  Ideally we would add a Transport to Network
7923                    // transition also as a way to indicate when bytes were
7924                    // transmitted vs dropped without ever being sent.
7925                    qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
7926                        let ev_data =
7927                            EventData::DataMoved(qlog::events::quic::DataMoved {
7928                                stream_id: Some(stream_id),
7929                                offset: Some(final_size),
7930                                length: Some(unsent),
7931                                from: Some(DataRecipient::Transport),
7932                                to: Some(DataRecipient::Dropped),
7933                                ..Default::default()
7934                            });
7935
7936                        q.add_event_data_with_instant(ev_data, now).ok();
7937                    });
7938
7939                    self.streams.insert_reset(stream_id, error_code, final_size);
7940
7941                    if !was_writable {
7942                        self.streams.insert_writable(&priority_key);
7943                    }
7944
7945                    self.stopped_stream_remote_count =
7946                        self.stopped_stream_remote_count.saturating_add(1);
7947                    self.reset_stream_local_count =
7948                        self.reset_stream_local_count.saturating_add(1);
7949                }
7950            },
7951
7952            frame::Frame::Crypto { data } => {
7953                if data.max_off() >= MAX_CRYPTO_STREAM_OFFSET {
7954                    return Err(Error::CryptoBufferExceeded);
7955                }
7956
7957                // Push the data to the stream so it can be re-ordered.
7958                self.crypto_ctx[epoch].crypto_stream.recv.write(data)?;
7959
7960                // Feed crypto data to the TLS state, if there's data
7961                // available at the expected offset.
7962                let mut crypto_buf = [0; 512];
7963
7964                let level = crypto::Level::from_epoch(epoch);
7965
7966                let stream = &mut self.crypto_ctx[epoch].crypto_stream;
7967
7968                while let Ok((read, _)) = stream.recv.emit(&mut crypto_buf) {
7969                    let recv_buf = &crypto_buf[..read];
7970                    self.handshake.provide_data(level, recv_buf)?;
7971                }
7972
7973                self.do_handshake(now)?;
7974            },
7975
7976            frame::Frame::CryptoHeader { .. } => unreachable!(),
7977
7978            // TODO: implement stateless retry
7979            frame::Frame::NewToken { .. } =>
7980                if self.is_server {
7981                    return Err(Error::InvalidPacket);
7982                },
7983
7984            frame::Frame::Stream { stream_id, data } => {
7985                // Peer can't send on our unidirectional streams.
7986                if !stream::is_bidi(stream_id) &&
7987                    stream::is_local(stream_id, self.is_server)
7988                {
7989                    return Err(Error::InvalidStreamState(stream_id));
7990                }
7991
7992                let max_rx_data_left = self.max_rx_data() - self.rx_data;
7993
7994                // Get existing stream or create a new one, but if the stream
7995                // has already been closed and collected, ignore the frame.
7996                //
7997                // This can happen if e.g. an ACK frame is lost, and the peer
7998                // retransmits another frame before it realizes that the stream
7999                // is gone.
8000                //
8001                // Note that it makes it impossible to check if the frame is
8002                // illegal, since we have no state, but since we ignore the
8003                // frame, it should be fine.
8004                let stream = match self.get_or_create_stream(stream_id, false) {
8005                    Ok(v) => v,
8006
8007                    Err(Error::Done) => return Ok(()),
8008
8009                    Err(e) => return Err(e),
8010                };
8011
8012                // Check for the connection-level flow control limit.
8013                let max_off_delta =
8014                    data.max_off().saturating_sub(stream.recv.max_off());
8015
8016                if max_off_delta > max_rx_data_left {
8017                    return Err(Error::FlowControl);
8018                }
8019
8020                let was_readable = stream.is_readable();
8021                let priority_key = Arc::clone(&stream.priority_key);
8022
8023                let was_draining = stream.recv.is_draining();
8024
8025                stream.recv.write(data)?;
8026
8027                if !was_readable && stream.is_readable() {
8028                    self.streams.insert_readable(&priority_key);
8029                }
8030
8031                self.rx_data += max_off_delta;
8032
8033                if was_draining {
8034                    // When a stream is in draining state it will not queue
8035                    // incoming data for the application to read, so consider
8036                    // the received data as consumed, which might trigger a flow
8037                    // control update.
8038                    self.flow_control.add_consumed(max_off_delta);
8039
8040                    if self.should_update_max_data() {
8041                        self.almost_full = true;
8042                    }
8043                }
8044            },
8045
8046            frame::Frame::StreamHeader { .. } => unreachable!(),
8047
8048            frame::Frame::MaxData { max } => {
8049                self.max_tx_data = cmp::max(self.max_tx_data, max);
8050            },
8051
8052            frame::Frame::MaxStreamData { stream_id, max } => {
8053                // Peer can't receive on its own unidirectional streams.
8054                if !stream::is_bidi(stream_id) &&
8055                    !stream::is_local(stream_id, self.is_server)
8056                {
8057                    return Err(Error::InvalidStreamState(stream_id));
8058                }
8059
8060                // Get existing stream or create a new one, but if the stream
8061                // has already been closed and collected, ignore the frame.
8062                //
8063                // This can happen if e.g. an ACK frame is lost, and the peer
8064                // retransmits another frame before it realizes that the stream
8065                // is gone.
8066                //
8067                // Note that it makes it impossible to check if the frame is
8068                // illegal, since we have no state, but since we ignore the
8069                // frame, it should be fine.
8070                let stream = match self.get_or_create_stream(stream_id, false) {
8071                    Ok(v) => v,
8072
8073                    Err(Error::Done) => return Ok(()),
8074
8075                    Err(e) => return Err(e),
8076                };
8077
8078                let was_flushable = stream.is_flushable();
8079
8080                stream.send.update_max_data(max);
8081
8082                let writable = stream.is_writable();
8083
8084                let priority_key = Arc::clone(&stream.priority_key);
8085
8086                // If the stream is now flushable push it to the flushable queue,
8087                // but only if it wasn't already queued.
8088                if stream.is_flushable() && !was_flushable {
8089                    let priority_key = Arc::clone(&stream.priority_key);
8090                    self.streams.insert_flushable(&priority_key);
8091                }
8092
8093                if writable {
8094                    self.streams.insert_writable(&priority_key);
8095                }
8096            },
8097
8098            frame::Frame::MaxStreamsBidi { max } => {
8099                if max > MAX_STREAM_ID {
8100                    return Err(Error::InvalidFrame);
8101                }
8102
8103                self.streams.update_peer_max_streams_bidi(max);
8104            },
8105
8106            frame::Frame::MaxStreamsUni { max } => {
8107                if max > MAX_STREAM_ID {
8108                    return Err(Error::InvalidFrame);
8109                }
8110
8111                self.streams.update_peer_max_streams_uni(max);
8112            },
8113
8114            frame::Frame::DataBlocked { .. } => {
8115                self.data_blocked_recv_count =
8116                    self.data_blocked_recv_count.saturating_add(1);
8117            },
8118
8119            frame::Frame::StreamDataBlocked { .. } => {
8120                self.stream_data_blocked_recv_count =
8121                    self.stream_data_blocked_recv_count.saturating_add(1);
8122            },
8123
8124            frame::Frame::StreamsBlockedBidi { limit } => {
8125                if limit > MAX_STREAM_ID {
8126                    return Err(Error::InvalidFrame);
8127                }
8128            },
8129
8130            frame::Frame::StreamsBlockedUni { limit } => {
8131                if limit > MAX_STREAM_ID {
8132                    return Err(Error::InvalidFrame);
8133                }
8134            },
8135
8136            frame::Frame::NewConnectionId {
8137                seq_num,
8138                retire_prior_to,
8139                conn_id,
8140                reset_token,
8141            } => {
8142                if self.ids.zero_length_dcid() {
8143                    return Err(Error::InvalidState);
8144                }
8145
8146                let mut retired_path_ids = SmallVec::new();
8147
8148                // Retire pending path IDs before propagating the error code to
8149                // make sure retired connection IDs are not in use anymore.
8150                let new_dcid_res = self.ids.new_dcid(
8151                    conn_id.into(),
8152                    seq_num,
8153                    u128::from_be_bytes(reset_token),
8154                    retire_prior_to,
8155                    &mut retired_path_ids,
8156                );
8157
8158                for (dcid_seq, pid) in retired_path_ids {
8159                    let path = self.paths.get_mut(pid)?;
8160
8161                    // Maybe the path already switched to another DCID.
8162                    if path.active_dcid_seq != Some(dcid_seq) {
8163                        continue;
8164                    }
8165
8166                    if let Some(new_dcid_seq) =
8167                        self.ids.lowest_available_dcid_seq()
8168                    {
8169                        path.active_dcid_seq = Some(new_dcid_seq);
8170
8171                        self.ids.link_dcid_to_path_id(new_dcid_seq, pid)?;
8172
8173                        trace!(
8174                            "{} path ID {} changed DCID: old seq num {} new seq num {}",
8175                            self.trace_id, pid, dcid_seq, new_dcid_seq,
8176                        );
8177                    } else {
8178                        // We cannot use this path anymore for now.
8179                        path.active_dcid_seq = None;
8180
8181                        trace!(
8182                            "{} path ID {} cannot be used; DCID seq num {} has been retired",
8183                            self.trace_id, pid, dcid_seq,
8184                        );
8185                    }
8186                }
8187
8188                // Propagate error (if any) now...
8189                new_dcid_res?;
8190            },
8191
8192            frame::Frame::RetireConnectionId { seq_num } => {
8193                if self.ids.zero_length_scid() {
8194                    return Err(Error::InvalidState);
8195                }
8196
8197                if let Some(pid) = self.ids.retire_scid(seq_num, &hdr.dcid)? {
8198                    let path = self.paths.get_mut(pid)?;
8199
8200                    // Maybe we already linked a new SCID to that path.
8201                    if path.active_scid_seq == Some(seq_num) {
8202                        // XXX: We do not remove unused paths now, we instead
8203                        // wait until we need to maintain more paths than the
8204                        // host is willing to.
8205                        path.active_scid_seq = None;
8206                    }
8207                }
8208            },
8209
8210            frame::Frame::PathChallenge { data } => {
8211                self.path_challenge_rx_count += 1;
8212
8213                self.paths
8214                    .get_mut(recv_path_id)?
8215                    .on_challenge_received(data);
8216            },
8217
8218            frame::Frame::PathResponse { data } => {
8219                self.paths.on_response_received(data)?;
8220            },
8221
8222            frame::Frame::ConnectionClose {
8223                error_code, reason, ..
8224            } => {
8225                self.peer_error = Some(ConnectionError {
8226                    is_app: false,
8227                    error_code,
8228                    reason,
8229                });
8230
8231                let path = self.paths.get_active()?;
8232                self.draining_timer = Some(now + (path.recovery.pto() * 3));
8233            },
8234
8235            frame::Frame::ApplicationClose { error_code, reason } => {
8236                self.peer_error = Some(ConnectionError {
8237                    is_app: true,
8238                    error_code,
8239                    reason,
8240                });
8241
8242                let path = self.paths.get_active()?;
8243                self.draining_timer = Some(now + (path.recovery.pto() * 3));
8244            },
8245
8246            frame::Frame::HandshakeDone => {
8247                if self.is_server {
8248                    return Err(Error::InvalidPacket);
8249                }
8250
8251                self.peer_verified_initial_address = true;
8252
8253                self.handshake_confirmed = true;
8254
8255                // Once the handshake is confirmed, we can drop Handshake keys.
8256                self.drop_epoch_state(packet::Epoch::Handshake, now);
8257            },
8258
8259            frame::Frame::Datagram { data } => {
8260                // Close the connection if DATAGRAMs are not enabled.
8261                // quiche always advertises support for 64K sized DATAGRAM
8262                // frames, as recommended by the standard, so we don't need a
8263                // size check.
8264                if !self.dgram_enabled() {
8265                    return Err(Error::InvalidState);
8266                }
8267
8268                // If recv queue is full, discard oldest
8269                if self.dgram_recv_queue.is_full() {
8270                    self.dgram_recv_queue.pop();
8271                }
8272
8273                self.dgram_recv_queue.push(data)?;
8274
8275                self.dgram_recv_count = self.dgram_recv_count.saturating_add(1);
8276
8277                let path = self.paths.get_mut(recv_path_id)?;
8278                path.dgram_recv_count = path.dgram_recv_count.saturating_add(1);
8279            },
8280
8281            frame::Frame::DatagramHeader { .. } => unreachable!(),
8282        }
8283
8284        Ok(())
8285    }
8286
8287    /// Drops the keys and recovery state for the given epoch.
8288    fn drop_epoch_state(&mut self, epoch: packet::Epoch, now: Instant) {
8289        let crypto_ctx = &mut self.crypto_ctx[epoch];
8290        if crypto_ctx.crypto_open.is_none() {
8291            return;
8292        }
8293        crypto_ctx.clear();
8294        self.pkt_num_spaces[epoch].clear();
8295
8296        let handshake_status = self.handshake_status();
8297        for (_, p) in self.paths.iter_mut() {
8298            p.recovery
8299                .on_pkt_num_space_discarded(epoch, handshake_status, now);
8300        }
8301
8302        trace!("{} dropped epoch {} state", self.trace_id, epoch);
8303    }
8304
8305    /// Returns true if the connection-level flow control needs to be updated.
8306    ///
8307    /// This happens when the new max data limit is at least double the amount
8308    /// of data that can be received before blocking.
8309    fn should_update_max_data(&self) -> bool {
8310        self.flow_control.should_update_max_data()
8311    }
8312
8313    /// Returns the connection level flow control limit.
8314    fn max_rx_data(&self) -> u64 {
8315        self.flow_control.max_data()
8316    }
8317
8318    /// Returns true if the HANDSHAKE_DONE frame needs to be sent.
8319    fn should_send_handshake_done(&self) -> bool {
8320        self.is_established() && !self.handshake_done_sent && self.is_server
8321    }
8322
8323    /// Returns the idle timeout value.
8324    ///
8325    /// `None` is returned if both end-points disabled the idle timeout.
8326    fn idle_timeout(&self) -> Option<Duration> {
8327        // If the transport parameter is set to 0, then the respective endpoint
8328        // decided to disable the idle timeout. If both are disabled we should
8329        // not set any timeout.
8330        if self.local_transport_params.max_idle_timeout == 0 &&
8331            self.peer_transport_params.max_idle_timeout == 0
8332        {
8333            return None;
8334        }
8335
8336        // If the local endpoint or the peer disabled the idle timeout, use the
8337        // other peer's value, otherwise use the minimum of the two values.
8338        let idle_timeout = if self.local_transport_params.max_idle_timeout == 0 {
8339            self.peer_transport_params.max_idle_timeout
8340        } else if self.peer_transport_params.max_idle_timeout == 0 {
8341            self.local_transport_params.max_idle_timeout
8342        } else {
8343            cmp::min(
8344                self.local_transport_params.max_idle_timeout,
8345                self.peer_transport_params.max_idle_timeout,
8346            )
8347        };
8348
8349        let path_pto = match self.paths.get_active() {
8350            Ok(p) => p.recovery.pto(),
8351            Err(_) => Duration::ZERO,
8352        };
8353
8354        let idle_timeout = Duration::from_millis(idle_timeout);
8355        let idle_timeout = cmp::max(idle_timeout, 3 * path_pto);
8356
8357        Some(idle_timeout)
8358    }
8359
8360    /// Returns the connection's handshake status for use in loss recovery.
8361    fn handshake_status(&self) -> recovery::HandshakeStatus {
8362        recovery::HandshakeStatus {
8363            has_handshake_keys: self.crypto_ctx[packet::Epoch::Handshake]
8364                .has_keys(),
8365
8366            peer_verified_address: self.peer_verified_initial_address,
8367
8368            completed: self.is_established(),
8369        }
8370    }
8371
8372    /// Updates send capacity.
8373    fn update_tx_cap(&mut self) {
8374        let cwin_available = match self.paths.get_active() {
8375            Ok(p) => p.recovery.cwnd_available() as u64,
8376            Err(_) => 0,
8377        };
8378
8379        let cap =
8380            cmp::min(cwin_available, self.max_tx_data - self.tx_data) as usize;
8381        self.tx_cap = (cap as f64 * self.tx_cap_factor).ceil() as usize;
8382    }
8383
8384    fn delivery_rate_check_if_app_limited(&self) -> bool {
8385        // Enter the app-limited phase of delivery rate when these conditions
8386        // are met:
8387        //
8388        // - The remaining capacity is higher than available bytes in cwnd (there
8389        //   is more room to send).
8390        // - New data since the last send() is smaller than available bytes in
8391        //   cwnd (we queued less than what we can send).
8392        // - There is room to send more data in cwnd.
8393        //
8394        // In application-limited phases the transmission rate is limited by the
8395        // application rather than the congestion control algorithm.
8396        //
8397        // Note that this is equivalent to CheckIfApplicationLimited() from the
8398        // delivery rate draft. This is also separate from `recovery.app_limited`
8399        // and only applies to delivery rate calculation.
8400        let cwin_available = self
8401            .paths
8402            .iter()
8403            .filter(|&(_, p)| p.active())
8404            .map(|(_, p)| p.recovery.cwnd_available())
8405            .sum();
8406
8407        ((self.tx_buffered + self.dgram_send_queue_byte_size()) < cwin_available) &&
8408            (self.tx_data.saturating_sub(self.last_tx_data)) <
8409                cwin_available as u64 &&
8410            cwin_available > 0
8411    }
8412
8413    fn check_tx_buffered_invariant(&mut self) {
8414        // tx_buffered should track bytes queued in the stream buffers
8415        // and unacked retransmitable bytes in the network.
8416        // If tx_buffered > 0 mark the tx_buffered_state if there are no
8417        // flushable streams and there no inflight bytes.
8418        //
8419        // It is normal to have tx_buffered == 0 while there are inflight bytes
8420        // since not QUIC frames are retransmittable; inflight tracks all bytes
8421        // on the network which are subject to congestion control.
8422        if self.tx_buffered > 0 &&
8423            !self.streams.has_flushable() &&
8424            !self
8425                .paths
8426                .iter()
8427                .any(|(_, p)| p.recovery.bytes_in_flight() > 0)
8428        {
8429            self.tx_buffered_state = TxBufferTrackingState::Inconsistent;
8430        }
8431    }
8432
8433    fn set_initial_dcid(
8434        &mut self, cid: ConnectionId<'static>, reset_token: Option<u128>,
8435        path_id: usize,
8436    ) -> Result<()> {
8437        self.ids.set_initial_dcid(cid, reset_token, Some(path_id));
8438        self.paths.get_mut(path_id)?.active_dcid_seq = Some(0);
8439
8440        Ok(())
8441    }
8442
8443    /// Selects the path that the incoming packet belongs to, or creates a new
8444    /// one if no existing path matches.
8445    fn get_or_create_recv_path_id(
8446        &mut self, recv_pid: Option<usize>, dcid: &ConnectionId, buf_len: usize,
8447        info: &RecvInfo,
8448    ) -> Result<usize> {
8449        let ids = &mut self.ids;
8450
8451        let (in_scid_seq, mut in_scid_pid) =
8452            ids.find_scid_seq(dcid).ok_or(Error::InvalidState)?;
8453
8454        if let Some(recv_pid) = recv_pid {
8455            // If the path observes a change of SCID used, note it.
8456            let recv_path = self.paths.get_mut(recv_pid)?;
8457
8458            let cid_entry =
8459                recv_path.active_scid_seq.and_then(|v| ids.get_scid(v).ok());
8460
8461            if cid_entry.map(|e| &e.cid) != Some(dcid) {
8462                let incoming_cid_entry = ids.get_scid(in_scid_seq)?;
8463
8464                let prev_recv_pid =
8465                    incoming_cid_entry.path_id.unwrap_or(recv_pid);
8466
8467                if prev_recv_pid != recv_pid {
8468                    trace!(
8469                        "{} peer reused CID {:?} from path {} on path {}",
8470                        self.trace_id,
8471                        dcid,
8472                        prev_recv_pid,
8473                        recv_pid
8474                    );
8475
8476                    // TODO: reset congestion control.
8477                }
8478
8479                trace!(
8480                    "{} path ID {} now see SCID with seq num {}",
8481                    self.trace_id,
8482                    recv_pid,
8483                    in_scid_seq
8484                );
8485
8486                recv_path.active_scid_seq = Some(in_scid_seq);
8487                ids.link_scid_to_path_id(in_scid_seq, recv_pid)?;
8488            }
8489
8490            return Ok(recv_pid);
8491        }
8492
8493        // This is a new 4-tuple. See if the CID has not been assigned on
8494        // another path.
8495
8496        // Ignore this step if are using zero-length SCID.
8497        if ids.zero_length_scid() {
8498            in_scid_pid = None;
8499        }
8500
8501        if let Some(in_scid_pid) = in_scid_pid {
8502            // This CID has been used by another path. If we have the
8503            // room to do so, create a new `Path` structure holding this
8504            // new 4-tuple. Otherwise, drop the packet.
8505            let old_path = self.paths.get_mut(in_scid_pid)?;
8506            let old_local_addr = old_path.local_addr();
8507            let old_peer_addr = old_path.peer_addr();
8508
8509            trace!(
8510                "{} reused CID seq {} of ({},{}) (path {}) on ({},{})",
8511                self.trace_id,
8512                in_scid_seq,
8513                old_local_addr,
8514                old_peer_addr,
8515                in_scid_pid,
8516                info.to,
8517                info.from
8518            );
8519
8520            // Notify the application.
8521            self.paths.notify_event(PathEvent::ReusedSourceConnectionId(
8522                in_scid_seq,
8523                (old_local_addr, old_peer_addr),
8524                (info.to, info.from),
8525            ));
8526        }
8527
8528        // This is a new path using an unassigned CID; create it!
8529        let mut path = path::Path::new(
8530            info.to,
8531            info.from,
8532            &self.recovery_config,
8533            self.path_challenge_recv_max_queue_len,
8534            false,
8535            None,
8536        );
8537
8538        path.max_send_bytes = buf_len * self.max_amplification_factor;
8539        path.active_scid_seq = Some(in_scid_seq);
8540
8541        // Automatically probes the new path.
8542        path.request_validation();
8543
8544        let pid = self.paths.insert_path(path, self.is_server)?;
8545
8546        // Do not record path reuse.
8547        if in_scid_pid.is_none() {
8548            ids.link_scid_to_path_id(in_scid_seq, pid)?;
8549        }
8550
8551        Ok(pid)
8552    }
8553
8554    /// Selects the path on which the next packet must be sent.
8555    fn get_send_path_id(
8556        &self, from: Option<SocketAddr>, to: Option<SocketAddr>,
8557    ) -> Result<usize> {
8558        // A probing packet must be sent, but only if the connection is fully
8559        // established.
8560        if self.is_established() {
8561            let mut probing = self
8562                .paths
8563                .iter()
8564                .filter(|(_, p)| from.is_none() || Some(p.local_addr()) == from)
8565                .filter(|(_, p)| to.is_none() || Some(p.peer_addr()) == to)
8566                .filter(|(_, p)| p.active_dcid_seq.is_some())
8567                .filter(|(_, p)| p.probing_required())
8568                .map(|(pid, _)| pid);
8569
8570            if let Some(pid) = probing.next() {
8571                return Ok(pid);
8572            }
8573        }
8574
8575        if let Some((pid, p)) = self.paths.get_active_with_pid() {
8576            if from.is_some() && Some(p.local_addr()) != from {
8577                return Err(Error::Done);
8578            }
8579
8580            if to.is_some() && Some(p.peer_addr()) != to {
8581                return Err(Error::Done);
8582            }
8583
8584            return Ok(pid);
8585        };
8586
8587        Err(Error::InvalidState)
8588    }
8589
8590    /// Sets the path with identifier 'path_id' to be active.
8591    fn set_active_path(&mut self, path_id: usize, now: Instant) -> Result<()> {
8592        if let Ok(old_active_path) = self.paths.get_active_mut() {
8593            for &e in packet::Epoch::epochs(
8594                packet::Epoch::Initial..=packet::Epoch::Application,
8595            ) {
8596                let (lost_packets, lost_bytes) = old_active_path
8597                    .recovery
8598                    .on_path_change(e, now, &self.trace_id);
8599
8600                self.lost_count += lost_packets;
8601                self.lost_bytes += lost_bytes as u64;
8602            }
8603        }
8604
8605        self.paths.set_active_path(path_id)
8606    }
8607
8608    /// Handles potential connection migration.
8609    fn on_peer_migrated(
8610        &mut self, new_pid: usize, disable_dcid_reuse: bool, now: Instant,
8611    ) -> Result<()> {
8612        let active_path_id = self.paths.get_active_path_id()?;
8613
8614        if active_path_id == new_pid {
8615            return Ok(());
8616        }
8617
8618        self.set_active_path(new_pid, now)?;
8619
8620        let no_spare_dcid =
8621            self.paths.get_mut(new_pid)?.active_dcid_seq.is_none();
8622
8623        if no_spare_dcid && !disable_dcid_reuse {
8624            self.paths.get_mut(new_pid)?.active_dcid_seq =
8625                self.paths.get_mut(active_path_id)?.active_dcid_seq;
8626        }
8627
8628        Ok(())
8629    }
8630
8631    /// Creates a new client-side path.
8632    fn create_path_on_client(
8633        &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
8634    ) -> Result<usize> {
8635        if self.is_server {
8636            return Err(Error::InvalidState);
8637        }
8638
8639        // If we use zero-length SCID and go over our local active CID limit,
8640        // the `insert_path()` call will raise an error.
8641        if !self.ids.zero_length_scid() && self.ids.available_scids() == 0 {
8642            return Err(Error::OutOfIdentifiers);
8643        }
8644
8645        // Do we have a spare DCID? If we are using zero-length DCID, just use
8646        // the default having sequence 0 (note that if we exceed our local CID
8647        // limit, the `insert_path()` call will raise an error.
8648        let dcid_seq = if self.ids.zero_length_dcid() {
8649            0
8650        } else {
8651            self.ids
8652                .lowest_available_dcid_seq()
8653                .ok_or(Error::OutOfIdentifiers)?
8654        };
8655
8656        let mut path = path::Path::new(
8657            local_addr,
8658            peer_addr,
8659            &self.recovery_config,
8660            self.path_challenge_recv_max_queue_len,
8661            false,
8662            None,
8663        );
8664        path.active_dcid_seq = Some(dcid_seq);
8665
8666        let pid = self
8667            .paths
8668            .insert_path(path, false)
8669            .map_err(|_| Error::OutOfIdentifiers)?;
8670        self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
8671
8672        Ok(pid)
8673    }
8674
8675    // Marks the connection as closed and does any related tidyup.
8676    fn mark_closed(&mut self) {
8677        #[cfg(feature = "qlog")]
8678        {
8679            let cc = match (self.is_established(), self.timed_out, &self.peer_error, &self.local_error) {
8680                (false, _, _, _) => qlog::events::connectivity::ConnectionClosed {
8681                    owner: Some(TransportOwner::Local),
8682                    connection_code: None,
8683                    application_code: None,
8684                    internal_code: None,
8685                    reason: Some("Failed to establish connection".to_string()),
8686                    trigger: Some(qlog::events::connectivity::ConnectionClosedTrigger::HandshakeTimeout)
8687                },
8688
8689                (true, true, _, _) => qlog::events::connectivity::ConnectionClosed {
8690                    owner: Some(TransportOwner::Local),
8691                    connection_code: None,
8692                    application_code: None,
8693                    internal_code: None,
8694                    reason: Some("Idle timeout".to_string()),
8695                    trigger: Some(qlog::events::connectivity::ConnectionClosedTrigger::IdleTimeout)
8696                },
8697
8698                (true, false, Some(peer_error), None) => {
8699                    let (connection_code, application_code, trigger) = if peer_error.is_app {
8700                        (None, Some(qlog::events::ApplicationErrorCode::Value(peer_error.error_code)), None)
8701                    } else {
8702                        let trigger = if peer_error.error_code == WireErrorCode::NoError as u64 {
8703                            Some(qlog::events::connectivity::ConnectionClosedTrigger::Clean)
8704                        } else {
8705                            Some(qlog::events::connectivity::ConnectionClosedTrigger::Error)
8706                        };
8707
8708                        (Some(qlog::events::ConnectionErrorCode::Value(peer_error.error_code)), None, trigger)
8709                    };
8710
8711                    qlog::events::connectivity::ConnectionClosed {
8712                        owner: Some(TransportOwner::Remote),
8713                        connection_code,
8714                        application_code,
8715                        internal_code: None,
8716                        reason: Some(String::from_utf8_lossy(&peer_error.reason).to_string()),
8717                        trigger,
8718                    }
8719                },
8720
8721                (true, false, None, Some(local_error)) => {
8722                    let (connection_code, application_code, trigger) = if local_error.is_app {
8723                        (None, Some(qlog::events::ApplicationErrorCode::Value(local_error.error_code)), None)
8724                    } else {
8725                        let trigger = if local_error.error_code == WireErrorCode::NoError as u64 {
8726                            Some(qlog::events::connectivity::ConnectionClosedTrigger::Clean)
8727                        } else {
8728                            Some(qlog::events::connectivity::ConnectionClosedTrigger::Error)
8729                        };
8730
8731                        (Some(qlog::events::ConnectionErrorCode::Value(local_error.error_code)), None, trigger)
8732                    };
8733
8734                    qlog::events::connectivity::ConnectionClosed {
8735                        owner: Some(TransportOwner::Local),
8736                        connection_code,
8737                        application_code,
8738                        internal_code: None,
8739                        reason: Some(String::from_utf8_lossy(&local_error.reason).to_string()),
8740                        trigger,
8741                    }
8742                },
8743
8744                _ => qlog::events::connectivity::ConnectionClosed {
8745                    owner: None,
8746                    connection_code: None,
8747                    application_code: None,
8748                    internal_code: None,
8749                    reason: None,
8750                    trigger: None,
8751                },
8752            };
8753
8754            qlog_with_type!(QLOG_CONNECTION_CLOSED, self.qlog, q, {
8755                let ev_data = EventData::ConnectionClosed(cc);
8756
8757                q.add_event_data_now(ev_data).ok();
8758            });
8759            self.qlog.streamer = None;
8760        }
8761        self.closed = true;
8762    }
8763}
8764
8765#[cfg(feature = "boringssl-boring-crate")]
8766impl<F: BufFactory> AsMut<boring::ssl::SslRef> for Connection<F> {
8767    fn as_mut(&mut self) -> &mut boring::ssl::SslRef {
8768        self.handshake.ssl_mut()
8769    }
8770}
8771
8772/// Maps an `Error` to `Error::Done`, or itself.
8773///
8774/// When a received packet that hasn't yet been authenticated triggers a failure
8775/// it should, in most cases, be ignored, instead of raising a connection error,
8776/// to avoid potential man-in-the-middle and man-on-the-side attacks.
8777///
8778/// However, if no other packet was previously received, the connection should
8779/// indeed be closed as the received packet might just be network background
8780/// noise, and it shouldn't keep resources occupied indefinitely.
8781///
8782/// This function maps an error to `Error::Done` to ignore a packet failure
8783/// without aborting the connection, except when no other packet was previously
8784/// received, in which case the error itself is returned, but only on the
8785/// server-side as the client will already have armed the idle timer.
8786///
8787/// This must only be used for errors preceding packet authentication. Failures
8788/// happening after a packet has been authenticated should still cause the
8789/// connection to be aborted.
8790fn drop_pkt_on_err(
8791    e: Error, recv_count: usize, is_server: bool, trace_id: &str,
8792) -> Error {
8793    // On the server, if no other packet has been successfully processed, abort
8794    // the connection to avoid keeping the connection open when only junk is
8795    // received.
8796    if is_server && recv_count == 0 {
8797        return e;
8798    }
8799
8800    trace!("{trace_id} dropped invalid packet");
8801
8802    // Ignore other invalid packets that haven't been authenticated to prevent
8803    // man-in-the-middle and man-on-the-side attacks.
8804    Error::Done
8805}
8806
8807struct AddrTupleFmt(SocketAddr, SocketAddr);
8808
8809impl std::fmt::Display for AddrTupleFmt {
8810    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
8811        let AddrTupleFmt(src, dst) = &self;
8812
8813        if src.ip().is_unspecified() || dst.ip().is_unspecified() {
8814            return Ok(());
8815        }
8816
8817        f.write_fmt(format_args!("src:{src} dst:{dst}"))
8818    }
8819}
8820
8821/// Statistics about the connection.
8822///
8823/// A connection's statistics can be collected using the [`stats()`] method.
8824///
8825/// [`stats()`]: struct.Connection.html#method.stats
8826#[derive(Clone, Default)]
8827pub struct Stats {
8828    /// The number of QUIC packets received.
8829    pub recv: usize,
8830
8831    /// The number of QUIC packets sent.
8832    pub sent: usize,
8833
8834    /// The number of QUIC packets that were lost.
8835    pub lost: usize,
8836
8837    /// The number of QUIC packets that were marked as lost but later acked.
8838    pub spurious_lost: usize,
8839
8840    /// The number of sent QUIC packets with retransmitted data.
8841    pub retrans: usize,
8842
8843    /// The number of sent bytes.
8844    pub sent_bytes: u64,
8845
8846    /// The number of received bytes.
8847    pub recv_bytes: u64,
8848
8849    /// The number of bytes sent acked.
8850    pub acked_bytes: u64,
8851
8852    /// The number of bytes sent lost.
8853    pub lost_bytes: u64,
8854
8855    /// The number of stream bytes retransmitted.
8856    pub stream_retrans_bytes: u64,
8857
8858    /// The number of DATAGRAM frames received.
8859    pub dgram_recv: usize,
8860
8861    /// The number of DATAGRAM frames sent.
8862    pub dgram_sent: usize,
8863
8864    /// The number of known paths for the connection.
8865    pub paths_count: usize,
8866
8867    /// The number of streams reset by local.
8868    pub reset_stream_count_local: u64,
8869
8870    /// The number of streams stopped by local.
8871    pub stopped_stream_count_local: u64,
8872
8873    /// The number of streams reset by remote.
8874    pub reset_stream_count_remote: u64,
8875
8876    /// The number of streams stopped by remote.
8877    pub stopped_stream_count_remote: u64,
8878
8879    /// The number of DATA_BLOCKED frames sent due to hitting the connection
8880    /// flow control limit.
8881    pub data_blocked_sent_count: u64,
8882
8883    /// The number of STREAM_DATA_BLOCKED frames sent due to a stream hitting
8884    /// the stream flow control limit.
8885    pub stream_data_blocked_sent_count: u64,
8886
8887    /// The number of DATA_BLOCKED frames received from the remote.
8888    pub data_blocked_recv_count: u64,
8889
8890    /// The number of STREAM_DATA_BLOCKED frames received from the remote.
8891    pub stream_data_blocked_recv_count: u64,
8892
8893    /// The total number of PATH_CHALLENGE frames that were received.
8894    pub path_challenge_rx_count: u64,
8895
8896    /// Total duration during which this side of the connection was
8897    /// actively sending bytes or waiting for those bytes to be acked.
8898    pub bytes_in_flight_duration: Duration,
8899
8900    /// Health state of the connection's tx_buffered.
8901    pub tx_buffered_state: TxBufferTrackingState,
8902}
8903
8904impl std::fmt::Debug for Stats {
8905    #[inline]
8906    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
8907        write!(
8908            f,
8909            "recv={} sent={} lost={} retrans={}",
8910            self.recv, self.sent, self.lost, self.retrans,
8911        )?;
8912
8913        write!(
8914            f,
8915            " sent_bytes={} recv_bytes={} lost_bytes={}",
8916            self.sent_bytes, self.recv_bytes, self.lost_bytes,
8917        )?;
8918
8919        Ok(())
8920    }
8921}
8922
8923#[doc(hidden)]
8924pub mod test_utils;
8925
8926#[cfg(test)]
8927mod tests;
8928
8929pub use crate::packet::ConnectionId;
8930pub use crate::packet::Header;
8931pub use crate::packet::Type;
8932
8933pub use crate::path::PathEvent;
8934pub use crate::path::PathStats;
8935pub use crate::path::SocketAddrIter;
8936
8937pub use crate::recovery::BbrBwLoReductionStrategy;
8938pub use crate::recovery::BbrParams;
8939pub use crate::recovery::CongestionControlAlgorithm;
8940pub use crate::recovery::StartupExit;
8941pub use crate::recovery::StartupExitReason;
8942
8943pub use crate::stream::StreamIter;
8944
8945pub use crate::transport_params::TransportParams;
8946pub use crate::transport_params::UnknownTransportParameter;
8947pub use crate::transport_params::UnknownTransportParameterIterator;
8948pub use crate::transport_params::UnknownTransportParameters;
8949
8950pub use crate::range_buf::BufFactory;
8951pub use crate::range_buf::BufSplit;
8952
8953pub use crate::error::ConnectionError;
8954pub use crate::error::Error;
8955pub use crate::error::Result;
8956pub use crate::error::WireErrorCode;
8957
8958mod cid;
8959mod crypto;
8960mod dgram;
8961mod error;
8962#[cfg(feature = "ffi")]
8963mod ffi;
8964mod flowcontrol;
8965mod frame;
8966pub mod h3;
8967mod minmax;
8968mod packet;
8969mod path;
8970mod pmtud;
8971mod rand;
8972mod range_buf;
8973mod ranges;
8974mod recovery;
8975mod stream;
8976mod tls;
8977mod transport_params;