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