• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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()`].
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()`]: https://docs.quic.tech/quiche/struct.Config.html#method.with_boring_ssl_ctx
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 #![cfg_attr(docsrs, feature(doc_cfg))]
381 
382 #[macro_use]
383 extern crate log;
384 
385 #[cfg(feature = "qlog")]
386 use qlog::events::connectivity::TransportOwner;
387 #[cfg(feature = "qlog")]
388 use qlog::events::quic::RecoveryEventType;
389 #[cfg(feature = "qlog")]
390 use qlog::events::quic::TransportEventType;
391 #[cfg(feature = "qlog")]
392 use qlog::events::DataRecipient;
393 #[cfg(feature = "qlog")]
394 use qlog::events::Event;
395 #[cfg(feature = "qlog")]
396 use qlog::events::EventData;
397 #[cfg(feature = "qlog")]
398 use qlog::events::EventImportance;
399 #[cfg(feature = "qlog")]
400 use qlog::events::EventType;
401 #[cfg(feature = "qlog")]
402 use qlog::events::RawInfo;
403 
404 use std::cmp;
405 use std::convert::TryInto;
406 use std::time;
407 
408 use std::net::SocketAddr;
409 
410 use std::str::FromStr;
411 
412 use std::collections::HashSet;
413 use std::collections::VecDeque;
414 
415 use smallvec::SmallVec;
416 
417 /// The current QUIC wire version.
418 pub const PROTOCOL_VERSION: u32 = PROTOCOL_VERSION_V1;
419 
420 /// Supported QUIC versions.
421 ///
422 /// Note that the older ones might not be fully supported.
423 const PROTOCOL_VERSION_V1: u32 = 0x0000_0001;
424 const PROTOCOL_VERSION_DRAFT27: u32 = 0xff00_001b;
425 const PROTOCOL_VERSION_DRAFT28: u32 = 0xff00_001c;
426 const PROTOCOL_VERSION_DRAFT29: u32 = 0xff00_001d;
427 
428 /// The maximum length of a connection ID.
429 pub const MAX_CONN_ID_LEN: usize = crate::packet::MAX_CID_LEN as usize;
430 
431 /// The minimum length of Initial packets sent by a client.
432 pub const MIN_CLIENT_INITIAL_LEN: usize = 1200;
433 
434 #[cfg(not(feature = "fuzzing"))]
435 const PAYLOAD_MIN_LEN: usize = 4;
436 
437 #[cfg(feature = "fuzzing")]
438 // Due to the fact that in fuzzing mode we use a zero-length AEAD tag (which
439 // would normally be 16 bytes), we need to adjust the minimum payload size to
440 // account for that.
441 const PAYLOAD_MIN_LEN: usize = 20;
442 
443 // PATH_CHALLENGE (9 bytes) + AEAD tag (16 bytes).
444 const MIN_PROBING_SIZE: usize = 25;
445 
446 const MAX_AMPLIFICATION_FACTOR: usize = 3;
447 
448 // The maximum number of tracked packet number ranges that need to be acked.
449 //
450 // This represents more or less how many ack blocks can fit in a typical packet.
451 const MAX_ACK_RANGES: usize = 68;
452 
453 // The highest possible stream ID allowed.
454 const MAX_STREAM_ID: u64 = 1 << 60;
455 
456 // The default max_datagram_size used in congestion control.
457 const MAX_SEND_UDP_PAYLOAD_SIZE: usize = 1200;
458 
459 // The default length of DATAGRAM queues.
460 const DEFAULT_MAX_DGRAM_QUEUE_LEN: usize = 0;
461 
462 // The DATAGRAM standard recommends either none or 65536 as maximum DATAGRAM
463 // frames size. We enforce the recommendation for forward compatibility.
464 const MAX_DGRAM_FRAME_SIZE: u64 = 65536;
465 
466 // The length of the payload length field.
467 const PAYLOAD_LENGTH_LEN: usize = 2;
468 
469 // The number of undecryptable that can be buffered.
470 const MAX_UNDECRYPTABLE_PACKETS: usize = 10;
471 
472 const RESERVED_VERSION_MASK: u32 = 0xfafafafa;
473 
474 // The default size of the receiver connection flow control window.
475 const DEFAULT_CONNECTION_WINDOW: u64 = 48 * 1024;
476 
477 // The maximum size of the receiver connection flow control window.
478 const MAX_CONNECTION_WINDOW: u64 = 24 * 1024 * 1024;
479 
480 // How much larger the connection flow control window need to be larger than
481 // the stream flow control window.
482 const CONNECTION_WINDOW_FACTOR: f64 = 1.5;
483 
484 // How many probing packet timeouts do we tolerate before considering the path
485 // validation as failed.
486 const MAX_PROBING_TIMEOUTS: usize = 3;
487 
488 /// A specialized [`Result`] type for quiche operations.
489 ///
490 /// This type is used throughout quiche's public API for any operation that
491 /// can produce an error.
492 ///
493 /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
494 pub type Result<T> = std::result::Result<T, Error>;
495 
496 /// A QUIC error.
497 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
498 pub enum Error {
499     /// There is no more work to do.
500     Done,
501 
502     /// The provided buffer is too short.
503     BufferTooShort,
504 
505     /// The provided packet cannot be parsed because its version is unknown.
506     UnknownVersion,
507 
508     /// The provided packet cannot be parsed because it contains an invalid
509     /// frame.
510     InvalidFrame,
511 
512     /// The provided packet cannot be parsed.
513     InvalidPacket,
514 
515     /// The operation cannot be completed because the connection is in an
516     /// invalid state.
517     InvalidState,
518 
519     /// The operation cannot be completed because the stream is in an
520     /// invalid state.
521     ///
522     /// The stream ID is provided as associated data.
523     InvalidStreamState(u64),
524 
525     /// The peer's transport params cannot be parsed.
526     InvalidTransportParam,
527 
528     /// A cryptographic operation failed.
529     CryptoFail,
530 
531     /// The TLS handshake failed.
532     TlsFail,
533 
534     /// The peer violated the local flow control limits.
535     FlowControl,
536 
537     /// The peer violated the local stream limits.
538     StreamLimit,
539 
540     /// The specified stream was stopped by the peer.
541     ///
542     /// The error code sent as part of the `STOP_SENDING` frame is provided as
543     /// associated data.
544     StreamStopped(u64),
545 
546     /// The specified stream was reset by the peer.
547     ///
548     /// The error code sent as part of the `RESET_STREAM` frame is provided as
549     /// associated data.
550     StreamReset(u64),
551 
552     /// The received data exceeds the stream's final size.
553     FinalSize,
554 
555     /// Error in congestion control.
556     CongestionControl,
557 
558     /// Too many identifiers were provided.
559     IdLimit,
560 
561     /// Not enough available identifiers.
562     OutOfIdentifiers,
563 
564     /// Error in key update.
565     KeyUpdate,
566 }
567 
568 impl Error {
to_wire(self) -> u64569     fn to_wire(self) -> u64 {
570         match self {
571             Error::Done => 0x0,
572             Error::InvalidFrame => 0x7,
573             Error::InvalidStreamState(..) => 0x5,
574             Error::InvalidTransportParam => 0x8,
575             Error::FlowControl => 0x3,
576             Error::StreamLimit => 0x4,
577             Error::FinalSize => 0x6,
578             Error::KeyUpdate => 0xe,
579             _ => 0xa,
580         }
581     }
582 
583     #[cfg(feature = "ffi")]
to_c(self) -> libc::ssize_t584     fn to_c(self) -> libc::ssize_t {
585         match self {
586             Error::Done => -1,
587             Error::BufferTooShort => -2,
588             Error::UnknownVersion => -3,
589             Error::InvalidFrame => -4,
590             Error::InvalidPacket => -5,
591             Error::InvalidState => -6,
592             Error::InvalidStreamState(_) => -7,
593             Error::InvalidTransportParam => -8,
594             Error::CryptoFail => -9,
595             Error::TlsFail => -10,
596             Error::FlowControl => -11,
597             Error::StreamLimit => -12,
598             Error::FinalSize => -13,
599             Error::CongestionControl => -14,
600             Error::StreamStopped { .. } => -15,
601             Error::StreamReset { .. } => -16,
602             Error::IdLimit => -17,
603             Error::OutOfIdentifiers => -18,
604             Error::KeyUpdate => -19,
605         }
606     }
607 }
608 
609 impl std::fmt::Display for Error {
fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result610     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
611         write!(f, "{self:?}")
612     }
613 }
614 
615 impl std::error::Error for Error {
source(&self) -> Option<&(dyn std::error::Error + 'static)>616     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
617         None
618     }
619 }
620 
621 impl std::convert::From<octets::BufferTooShortError> for Error {
from(_err: octets::BufferTooShortError) -> Self622     fn from(_err: octets::BufferTooShortError) -> Self {
623         Error::BufferTooShort
624     }
625 }
626 
627 /// Ancillary information about incoming packets.
628 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
629 pub struct RecvInfo {
630     /// The remote address the packet was received from.
631     pub from: SocketAddr,
632 
633     /// The local address the packet was received on.
634     pub to: SocketAddr,
635 }
636 
637 /// Ancillary information about outgoing packets.
638 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
639 pub struct SendInfo {
640     /// The local address the packet should be sent from.
641     pub from: SocketAddr,
642 
643     /// The remote address the packet should be sent to.
644     pub to: SocketAddr,
645 
646     /// The time to send the packet out.
647     ///
648     /// See [Pacing] for more details.
649     ///
650     /// [Pacing]: index.html#pacing
651     pub at: time::Instant,
652 }
653 
654 /// Represents information carried by `CONNECTION_CLOSE` frames.
655 #[derive(Clone, Debug, PartialEq, Eq)]
656 pub struct ConnectionError {
657     /// Whether the error came from the application or the transport layer.
658     pub is_app: bool,
659 
660     /// The error code carried by the `CONNECTION_CLOSE` frame.
661     pub error_code: u64,
662 
663     /// The reason carried by the `CONNECTION_CLOSE` frame.
664     pub reason: Vec<u8>,
665 }
666 
667 /// The side of the stream to be shut down.
668 ///
669 /// This should be used when calling [`stream_shutdown()`].
670 ///
671 /// [`stream_shutdown()`]: struct.Connection.html#method.stream_shutdown
672 #[repr(C)]
673 #[derive(PartialEq, Eq)]
674 pub enum Shutdown {
675     /// Stop receiving stream data.
676     Read  = 0,
677 
678     /// Stop sending stream data.
679     Write = 1,
680 }
681 
682 /// Qlog logging level.
683 #[repr(C)]
684 #[cfg(feature = "qlog")]
685 #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
686 pub enum QlogLevel {
687     /// Logs any events of Core importance.
688     Core  = 0,
689 
690     /// Logs any events of Core and Base importance.
691     Base  = 1,
692 
693     /// Logs any events of Core, Base and Extra importance
694     Extra = 2,
695 }
696 
697 /// Stores configuration shared between multiple connections.
698 pub struct Config {
699     local_transport_params: TransportParams,
700 
701     version: u32,
702 
703     tls_ctx: tls::Context,
704 
705     application_protos: Vec<Vec<u8>>,
706 
707     grease: bool,
708 
709     cc_algorithm: CongestionControlAlgorithm,
710 
711     hystart: bool,
712 
713     pacing: bool,
714 
715     dgram_recv_max_queue_len: usize,
716     dgram_send_max_queue_len: usize,
717 
718     max_send_udp_payload_size: usize,
719 
720     max_connection_window: u64,
721     max_stream_window: u64,
722 
723     disable_dcid_reuse: bool,
724 }
725 
726 // See https://quicwg.org/base-drafts/rfc9000.html#section-15
is_reserved_version(version: u32) -> bool727 fn is_reserved_version(version: u32) -> bool {
728     version & RESERVED_VERSION_MASK == version
729 }
730 
731 impl Config {
732     /// Creates a config object with the given version.
733     ///
734     /// ## Examples:
735     ///
736     /// ```
737     /// let config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
738     /// # Ok::<(), quiche::Error>(())
739     /// ```
new(version: u32) -> Result<Config>740     pub fn new(version: u32) -> Result<Config> {
741         Self::with_tls_ctx(version, tls::Context::new()?)
742     }
743 
744     /// Creates a config object with the given version and [`SslContext`].
745     ///
746     /// This is useful for applications that wish to manually configure
747     /// [`SslContext`].
748     ///
749     /// [`SslContext`]: https://docs.rs/boring/latest/boring/ssl/struct.SslContext.html
750     #[cfg(feature = "boringssl-boring-crate")]
751     #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
with_boring_ssl_ctx( version: u32, tls_ctx: boring::ssl::SslContext, ) -> Result<Config>752     pub fn with_boring_ssl_ctx(
753         version: u32, tls_ctx: boring::ssl::SslContext,
754     ) -> Result<Config> {
755         Self::with_tls_ctx(version, tls::Context::from_boring(tls_ctx))
756     }
757 
with_tls_ctx(version: u32, tls_ctx: tls::Context) -> Result<Config>758     fn with_tls_ctx(version: u32, tls_ctx: tls::Context) -> Result<Config> {
759         if !is_reserved_version(version) && !version_is_supported(version) {
760             return Err(Error::UnknownVersion);
761         }
762 
763         Ok(Config {
764             local_transport_params: TransportParams::default(),
765             version,
766             tls_ctx,
767             application_protos: Vec::new(),
768             grease: true,
769             cc_algorithm: CongestionControlAlgorithm::CUBIC,
770             hystart: true,
771             pacing: true,
772 
773             dgram_recv_max_queue_len: DEFAULT_MAX_DGRAM_QUEUE_LEN,
774             dgram_send_max_queue_len: DEFAULT_MAX_DGRAM_QUEUE_LEN,
775 
776             max_send_udp_payload_size: MAX_SEND_UDP_PAYLOAD_SIZE,
777 
778             max_connection_window: MAX_CONNECTION_WINDOW,
779             max_stream_window: stream::MAX_STREAM_WINDOW,
780 
781             disable_dcid_reuse: false,
782         })
783     }
784 
785     /// Configures the given certificate chain.
786     ///
787     /// The content of `file` is parsed as a PEM-encoded leaf certificate,
788     /// followed by optional intermediate certificates.
789     ///
790     /// ## Examples:
791     ///
792     /// ```no_run
793     /// # let mut config = quiche::Config::new(0xbabababa)?;
794     /// config.load_cert_chain_from_pem_file("/path/to/cert.pem")?;
795     /// # Ok::<(), quiche::Error>(())
796     /// ```
load_cert_chain_from_pem_file(&mut self, file: &str) -> Result<()>797     pub fn load_cert_chain_from_pem_file(&mut self, file: &str) -> Result<()> {
798         self.tls_ctx.use_certificate_chain_file(file)
799     }
800 
801     /// Configures the given private key.
802     ///
803     /// The content of `file` is parsed as a PEM-encoded private key.
804     ///
805     /// ## Examples:
806     ///
807     /// ```no_run
808     /// # let mut config = quiche::Config::new(0xbabababa)?;
809     /// config.load_priv_key_from_pem_file("/path/to/key.pem")?;
810     /// # Ok::<(), quiche::Error>(())
811     /// ```
load_priv_key_from_pem_file(&mut self, file: &str) -> Result<()>812     pub fn load_priv_key_from_pem_file(&mut self, file: &str) -> Result<()> {
813         self.tls_ctx.use_privkey_file(file)
814     }
815 
816     /// Specifies a file where trusted CA certificates are stored for the
817     /// purposes of certificate verification.
818     ///
819     /// The content of `file` is parsed as a PEM-encoded certificate chain.
820     ///
821     /// ## Examples:
822     ///
823     /// ```no_run
824     /// # let mut config = quiche::Config::new(0xbabababa)?;
825     /// config.load_verify_locations_from_file("/path/to/cert.pem")?;
826     /// # Ok::<(), quiche::Error>(())
827     /// ```
load_verify_locations_from_file(&mut self, file: &str) -> Result<()>828     pub fn load_verify_locations_from_file(&mut self, file: &str) -> Result<()> {
829         self.tls_ctx.load_verify_locations_from_file(file)
830     }
831 
832     /// Specifies a directory where trusted CA certificates are stored for the
833     /// purposes of certificate verification.
834     ///
835     /// The content of `dir` a set of PEM-encoded certificate chains.
836     ///
837     /// ## Examples:
838     ///
839     /// ```no_run
840     /// # let mut config = quiche::Config::new(0xbabababa)?;
841     /// config.load_verify_locations_from_directory("/path/to/certs")?;
842     /// # Ok::<(), quiche::Error>(())
843     /// ```
load_verify_locations_from_directory( &mut self, dir: &str, ) -> Result<()>844     pub fn load_verify_locations_from_directory(
845         &mut self, dir: &str,
846     ) -> Result<()> {
847         self.tls_ctx.load_verify_locations_from_directory(dir)
848     }
849 
850     /// Configures whether to verify the peer's certificate.
851     ///
852     /// The default value is `true` for client connections, and `false` for
853     /// server ones.
verify_peer(&mut self, verify: bool)854     pub fn verify_peer(&mut self, verify: bool) {
855         self.tls_ctx.set_verify(verify);
856     }
857 
858     /// Configures whether to send GREASE values.
859     ///
860     /// The default value is `true`.
grease(&mut self, grease: bool)861     pub fn grease(&mut self, grease: bool) {
862         self.grease = grease;
863     }
864 
865     /// Enables logging of secrets.
866     ///
867     /// When logging is enabled, the [`set_keylog()`] method must be called on
868     /// the connection for its cryptographic secrets to be logged in the
869     /// [keylog] format to the specified writer.
870     ///
871     /// [`set_keylog()`]: struct.Connection.html#method.set_keylog
872     /// [keylog]: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
log_keys(&mut self)873     pub fn log_keys(&mut self) {
874         self.tls_ctx.enable_keylog();
875     }
876 
877     /// Configures the session ticket key material.
878     ///
879     /// On the server this key will be used to encrypt and decrypt session
880     /// tickets, used to perform session resumption without server-side state.
881     ///
882     /// By default a key is generated internally, and rotated regularly, so
883     /// applications don't need to call this unless they need to use a
884     /// specific key (e.g. in order to support resumption across multiple
885     /// servers), in which case the application is also responsible for
886     /// rotating the key to provide forward secrecy.
set_ticket_key(&mut self, key: &[u8]) -> Result<()>887     pub fn set_ticket_key(&mut self, key: &[u8]) -> Result<()> {
888         self.tls_ctx.set_ticket_key(key)
889     }
890 
891     /// Enables sending or receiving early data.
enable_early_data(&mut self)892     pub fn enable_early_data(&mut self) {
893         self.tls_ctx.set_early_data_enabled(true);
894     }
895 
896     /// Configures the list of supported application protocols.
897     ///
898     /// On the client this configures the list of protocols to send to the
899     /// server as part of the ALPN extension.
900     ///
901     /// On the server this configures the list of supported protocols to match
902     /// against the client-supplied list.
903     ///
904     /// Applications must set a value, but no default is provided.
905     ///
906     /// ## Examples:
907     ///
908     /// ```
909     /// # let mut config = quiche::Config::new(0xbabababa)?;
910     /// config.set_application_protos(&[b"http/1.1", b"http/0.9"]);
911     /// # Ok::<(), quiche::Error>(())
912     /// ```
set_application_protos( &mut self, protos_list: &[&[u8]], ) -> Result<()>913     pub fn set_application_protos(
914         &mut self, protos_list: &[&[u8]],
915     ) -> Result<()> {
916         self.application_protos =
917             protos_list.iter().map(|s| s.to_vec()).collect();
918 
919         self.tls_ctx.set_alpn(protos_list)
920     }
921 
922     /// Configures the list of supported application protocols using wire
923     /// format.
924     ///
925     /// The list of protocols `protos` must be a series of non-empty, 8-bit
926     /// length-prefixed strings.
927     ///
928     /// See [`set_application_protos`](Self::set_application_protos) for more
929     /// background about application protocols.
930     ///
931     /// ## Examples:
932     ///
933     /// ```
934     /// # let mut config = quiche::Config::new(0xbabababa)?;
935     /// config.set_application_protos_wire_format(b"\x08http/1.1\x08http/0.9")?;
936     /// # Ok::<(), quiche::Error>(())
937     /// ```
set_application_protos_wire_format( &mut self, protos: &[u8], ) -> Result<()>938     pub fn set_application_protos_wire_format(
939         &mut self, protos: &[u8],
940     ) -> Result<()> {
941         let mut b = octets::Octets::with_slice(protos);
942 
943         let mut protos_list = Vec::new();
944 
945         while let Ok(proto) = b.get_bytes_with_u8_length() {
946             protos_list.push(proto.buf());
947         }
948 
949         self.set_application_protos(&protos_list)
950     }
951 
952     /// Sets the `max_idle_timeout` transport parameter, in milliseconds.
953     ///
954     /// The default value is infinite, that is, no timeout is used.
set_max_idle_timeout(&mut self, v: u64)955     pub fn set_max_idle_timeout(&mut self, v: u64) {
956         self.local_transport_params.max_idle_timeout = v;
957     }
958 
959     /// Sets the `max_udp_payload_size transport` parameter.
960     ///
961     /// The default value is `65527`.
set_max_recv_udp_payload_size(&mut self, v: usize)962     pub fn set_max_recv_udp_payload_size(&mut self, v: usize) {
963         self.local_transport_params.max_udp_payload_size = v as u64;
964     }
965 
966     /// Sets the maximum outgoing UDP payload size.
967     ///
968     /// The default and minimum value is `1200`.
set_max_send_udp_payload_size(&mut self, v: usize)969     pub fn set_max_send_udp_payload_size(&mut self, v: usize) {
970         self.max_send_udp_payload_size = cmp::max(v, MAX_SEND_UDP_PAYLOAD_SIZE);
971     }
972 
973     /// Sets the `initial_max_data` transport parameter.
974     ///
975     /// When set to a non-zero value quiche will only allow at most `v` bytes of
976     /// incoming stream data to be buffered for the whole connection (that is,
977     /// data that is not yet read by the application) and will allow more data
978     /// to be received as the buffer is consumed by the application.
979     ///
980     /// When set to zero, either explicitly or via the default, quiche will not
981     /// give any flow control to the peer, preventing it from sending any stream
982     /// data.
983     ///
984     /// The default value is `0`.
set_initial_max_data(&mut self, v: u64)985     pub fn set_initial_max_data(&mut self, v: u64) {
986         self.local_transport_params.initial_max_data = v;
987     }
988 
989     /// Sets the `initial_max_stream_data_bidi_local` transport parameter.
990     ///
991     /// When set to a non-zero value quiche will only allow at most `v` bytes
992     /// of incoming stream data to be buffered for each locally-initiated
993     /// bidirectional stream (that is, data that is not yet read by the
994     /// application) and will allow more data to be received as the buffer is
995     /// consumed by the application.
996     ///
997     /// When set to zero, either explicitly or via the default, quiche will not
998     /// give any flow control to the peer, preventing it from sending any stream
999     /// data.
1000     ///
1001     /// The default value is `0`.
set_initial_max_stream_data_bidi_local(&mut self, v: u64)1002     pub fn set_initial_max_stream_data_bidi_local(&mut self, v: u64) {
1003         self.local_transport_params
1004             .initial_max_stream_data_bidi_local = v;
1005     }
1006 
1007     /// Sets the `initial_max_stream_data_bidi_remote` transport parameter.
1008     ///
1009     /// When set to a non-zero value quiche will only allow at most `v` bytes
1010     /// of incoming stream data to be buffered for each remotely-initiated
1011     /// bidirectional stream (that is, data that is not yet read by the
1012     /// application) and will allow more data to be received as the buffer is
1013     /// consumed by the application.
1014     ///
1015     /// When set to zero, either explicitly or via the default, quiche will not
1016     /// give any flow control to the peer, preventing it from sending any stream
1017     /// data.
1018     ///
1019     /// The default value is `0`.
set_initial_max_stream_data_bidi_remote(&mut self, v: u64)1020     pub fn set_initial_max_stream_data_bidi_remote(&mut self, v: u64) {
1021         self.local_transport_params
1022             .initial_max_stream_data_bidi_remote = v;
1023     }
1024 
1025     /// Sets the `initial_max_stream_data_uni` transport parameter.
1026     ///
1027     /// When set to a non-zero value quiche will only allow at most `v` bytes
1028     /// of incoming stream data to be buffered for each unidirectional stream
1029     /// (that is, data that is not yet read by the application) and will allow
1030     /// more data to be received as the buffer is consumed by the application.
1031     ///
1032     /// When set to zero, either explicitly or via the default, quiche will not
1033     /// give any flow control to the peer, preventing it from sending any stream
1034     /// data.
1035     ///
1036     /// The default value is `0`.
set_initial_max_stream_data_uni(&mut self, v: u64)1037     pub fn set_initial_max_stream_data_uni(&mut self, v: u64) {
1038         self.local_transport_params.initial_max_stream_data_uni = v;
1039     }
1040 
1041     /// Sets the `initial_max_streams_bidi` transport parameter.
1042     ///
1043     /// When set to a non-zero value quiche will only allow `v` number of
1044     /// concurrent remotely-initiated bidirectional streams to be open at any
1045     /// given time and will increase the limit automatically as streams are
1046     /// completed.
1047     ///
1048     /// When set to zero, either explicitly or via the default, quiche will not
1049     /// not allow the peer to open any bidirectional streams.
1050     ///
1051     /// A bidirectional stream is considered completed when all incoming data
1052     /// has been read by the application (up to the `fin` offset) or the
1053     /// stream's read direction has been shutdown, and all outgoing data has
1054     /// been acked by the peer (up to the `fin` offset) or the stream's write
1055     /// direction has been shutdown.
1056     ///
1057     /// The default value is `0`.
set_initial_max_streams_bidi(&mut self, v: u64)1058     pub fn set_initial_max_streams_bidi(&mut self, v: u64) {
1059         self.local_transport_params.initial_max_streams_bidi = v;
1060     }
1061 
1062     /// Sets the `initial_max_streams_uni` transport parameter.
1063     ///
1064     /// When set to a non-zero value quiche will only allow `v` number of
1065     /// concurrent remotely-initiated unidirectional streams to be open at any
1066     /// given time and will increase the limit automatically as streams are
1067     /// completed.
1068     ///
1069     /// When set to zero, either explicitly or via the default, quiche will not
1070     /// not allow the peer to open any unidirectional streams.
1071     ///
1072     /// A unidirectional stream is considered completed when all incoming data
1073     /// has been read by the application (up to the `fin` offset) or the
1074     /// stream's read direction has been shutdown.
1075     ///
1076     /// The default value is `0`.
set_initial_max_streams_uni(&mut self, v: u64)1077     pub fn set_initial_max_streams_uni(&mut self, v: u64) {
1078         self.local_transport_params.initial_max_streams_uni = v;
1079     }
1080 
1081     /// Sets the `ack_delay_exponent` transport parameter.
1082     ///
1083     /// The default value is `3`.
set_ack_delay_exponent(&mut self, v: u64)1084     pub fn set_ack_delay_exponent(&mut self, v: u64) {
1085         self.local_transport_params.ack_delay_exponent = v;
1086     }
1087 
1088     /// Sets the `max_ack_delay` transport parameter.
1089     ///
1090     /// The default value is `25`.
set_max_ack_delay(&mut self, v: u64)1091     pub fn set_max_ack_delay(&mut self, v: u64) {
1092         self.local_transport_params.max_ack_delay = v;
1093     }
1094 
1095     /// Sets the `active_connection_id_limit` transport parameter.
1096     ///
1097     /// The default value is `2`. Lower values will be ignored.
set_active_connection_id_limit(&mut self, v: u64)1098     pub fn set_active_connection_id_limit(&mut self, v: u64) {
1099         if v >= 2 {
1100             self.local_transport_params.active_conn_id_limit = v;
1101         }
1102     }
1103 
1104     /// Sets the `disable_active_migration` transport parameter.
1105     ///
1106     /// The default value is `false`.
set_disable_active_migration(&mut self, v: bool)1107     pub fn set_disable_active_migration(&mut self, v: bool) {
1108         self.local_transport_params.disable_active_migration = v;
1109     }
1110 
1111     /// Sets the congestion control algorithm used by string.
1112     ///
1113     /// The default value is `cubic`. On error `Error::CongestionControl`
1114     /// will be returned.
1115     ///
1116     /// ## Examples:
1117     ///
1118     /// ```
1119     /// # let mut config = quiche::Config::new(0xbabababa)?;
1120     /// config.set_cc_algorithm_name("reno");
1121     /// # Ok::<(), quiche::Error>(())
1122     /// ```
set_cc_algorithm_name(&mut self, name: &str) -> Result<()>1123     pub fn set_cc_algorithm_name(&mut self, name: &str) -> Result<()> {
1124         self.cc_algorithm = CongestionControlAlgorithm::from_str(name)?;
1125 
1126         Ok(())
1127     }
1128 
1129     /// Sets the congestion control algorithm used.
1130     ///
1131     /// The default value is `CongestionControlAlgorithm::CUBIC`.
set_cc_algorithm(&mut self, algo: CongestionControlAlgorithm)1132     pub fn set_cc_algorithm(&mut self, algo: CongestionControlAlgorithm) {
1133         self.cc_algorithm = algo;
1134     }
1135 
1136     /// Configures whether to enable HyStart++.
1137     ///
1138     /// The default value is `true`.
enable_hystart(&mut self, v: bool)1139     pub fn enable_hystart(&mut self, v: bool) {
1140         self.hystart = v;
1141     }
1142 
1143     /// Configures whether to enable pacing.
1144     ///
1145     /// The default value is `true`.
enable_pacing(&mut self, v: bool)1146     pub fn enable_pacing(&mut self, v: bool) {
1147         self.pacing = v;
1148     }
1149 
1150     /// Configures whether to enable receiving DATAGRAM frames.
1151     ///
1152     /// When enabled, the `max_datagram_frame_size` transport parameter is set
1153     /// to 65536 as recommended by draft-ietf-quic-datagram-01.
1154     ///
1155     /// The default is `false`.
enable_dgram( &mut self, enabled: bool, recv_queue_len: usize, send_queue_len: usize, )1156     pub fn enable_dgram(
1157         &mut self, enabled: bool, recv_queue_len: usize, send_queue_len: usize,
1158     ) {
1159         self.local_transport_params.max_datagram_frame_size = if enabled {
1160             Some(MAX_DGRAM_FRAME_SIZE)
1161         } else {
1162             None
1163         };
1164         self.dgram_recv_max_queue_len = recv_queue_len;
1165         self.dgram_send_max_queue_len = send_queue_len;
1166     }
1167 
1168     /// Sets the maximum size of the connection window.
1169     ///
1170     /// The default value is MAX_CONNECTION_WINDOW (24MBytes).
set_max_connection_window(&mut self, v: u64)1171     pub fn set_max_connection_window(&mut self, v: u64) {
1172         self.max_connection_window = v;
1173     }
1174 
1175     /// Sets the maximum size of the stream window.
1176     ///
1177     /// The default value is MAX_STREAM_WINDOW (16MBytes).
set_max_stream_window(&mut self, v: u64)1178     pub fn set_max_stream_window(&mut self, v: u64) {
1179         self.max_stream_window = v;
1180     }
1181 
1182     /// Sets the initial stateless reset token.
1183     ///
1184     /// This value is only advertised by servers. Setting a stateless retry
1185     /// token as a client has no effect on the connection.
1186     ///
1187     /// The default value is `None`.
set_stateless_reset_token(&mut self, v: Option<u128>)1188     pub fn set_stateless_reset_token(&mut self, v: Option<u128>) {
1189         self.local_transport_params.stateless_reset_token = v;
1190     }
1191 
1192     /// Sets whether the QUIC connection should avoid reusing DCIDs over
1193     /// different paths.
1194     ///
1195     /// When set to `true`, it ensures that a destination Connection ID is never
1196     /// reused on different paths. Such behaviour may lead to connection stall
1197     /// if the peer performs a non-voluntary migration (e.g., NAT rebinding) and
1198     /// does not provide additional destination Connection IDs to handle such
1199     /// event.
1200     ///
1201     /// The default value is `false`.
set_disable_dcid_reuse(&mut self, v: bool)1202     pub fn set_disable_dcid_reuse(&mut self, v: bool) {
1203         self.disable_dcid_reuse = v;
1204     }
1205 }
1206 
1207 /// A QUIC connection.
1208 pub struct Connection {
1209     /// QUIC wire version used for the connection.
1210     version: u32,
1211 
1212     /// Connection Identifiers.
1213     ids: cid::ConnectionIdentifiers,
1214 
1215     /// Unique opaque ID for the connection that can be used for logging.
1216     trace_id: String,
1217 
1218     /// Packet number spaces.
1219     pkt_num_spaces: [packet::PktNumSpace; packet::Epoch::count()],
1220 
1221     /// Peer's transport parameters.
1222     peer_transport_params: TransportParams,
1223 
1224     /// Local transport parameters.
1225     local_transport_params: TransportParams,
1226 
1227     /// TLS handshake state.
1228     handshake: tls::Handshake,
1229 
1230     /// Serialized TLS session buffer.
1231     ///
1232     /// This field is populated when a new session ticket is processed on the
1233     /// client. On the server this is empty.
1234     session: Option<Vec<u8>>,
1235 
1236     /// The configuration for recovery.
1237     recovery_config: recovery::RecoveryConfig,
1238 
1239     /// The path manager.
1240     paths: path::PathMap,
1241 
1242     /// List of supported application protocols.
1243     application_protos: Vec<Vec<u8>>,
1244 
1245     /// Total number of received packets.
1246     recv_count: usize,
1247 
1248     /// Total number of sent packets.
1249     sent_count: usize,
1250 
1251     /// Total number of lost packets.
1252     lost_count: usize,
1253 
1254     /// Total number of packets sent with data retransmitted.
1255     retrans_count: usize,
1256 
1257     /// Total number of bytes received from the peer.
1258     rx_data: u64,
1259 
1260     /// Receiver flow controller.
1261     flow_control: flowcontrol::FlowControl,
1262 
1263     /// Whether we send MAX_DATA frame.
1264     almost_full: bool,
1265 
1266     /// Number of stream data bytes that can be buffered.
1267     tx_cap: usize,
1268 
1269     // Number of bytes buffered in the send buffer.
1270     tx_buffered: usize,
1271 
1272     /// Total number of bytes sent to the peer.
1273     tx_data: u64,
1274 
1275     /// Peer's flow control limit for the connection.
1276     max_tx_data: u64,
1277 
1278     /// Last tx_data before running a full send() loop.
1279     last_tx_data: u64,
1280 
1281     /// Total number of bytes retransmitted over the connection.
1282     /// This counts only STREAM and CRYPTO data.
1283     stream_retrans_bytes: u64,
1284 
1285     /// Total number of bytes sent over the connection.
1286     sent_bytes: u64,
1287 
1288     /// Total number of bytes received over the connection.
1289     recv_bytes: u64,
1290 
1291     /// Total number of bytes sent lost over the connection.
1292     lost_bytes: u64,
1293 
1294     /// Streams map, indexed by stream ID.
1295     streams: stream::StreamMap,
1296 
1297     /// Peer's original destination connection ID. Used by the client to
1298     /// validate the server's transport parameter.
1299     odcid: Option<ConnectionId<'static>>,
1300 
1301     /// Peer's retry source connection ID. Used by the client during stateless
1302     /// retry to validate the server's transport parameter.
1303     rscid: Option<ConnectionId<'static>>,
1304 
1305     /// Received address verification token.
1306     token: Option<Vec<u8>>,
1307 
1308     /// Error code and reason to be sent to the peer in a CONNECTION_CLOSE
1309     /// frame.
1310     local_error: Option<ConnectionError>,
1311 
1312     /// Error code and reason received from the peer in a CONNECTION_CLOSE
1313     /// frame.
1314     peer_error: Option<ConnectionError>,
1315 
1316     /// The connection-level limit at which send blocking occurred.
1317     blocked_limit: Option<u64>,
1318 
1319     /// Idle timeout expiration time.
1320     idle_timer: Option<time::Instant>,
1321 
1322     /// Draining timeout expiration time.
1323     draining_timer: Option<time::Instant>,
1324 
1325     /// List of raw packets that were received before they could be decrypted.
1326     undecryptable_pkts: VecDeque<(Vec<u8>, RecvInfo)>,
1327 
1328     /// The negotiated ALPN protocol.
1329     alpn: Vec<u8>,
1330 
1331     /// Whether this is a server-side connection.
1332     is_server: bool,
1333 
1334     /// Whether the initial secrets have been derived.
1335     derived_initial_secrets: bool,
1336 
1337     /// Whether a version negotiation packet has already been received. Only
1338     /// relevant for client connections.
1339     did_version_negotiation: bool,
1340 
1341     /// Whether stateless retry has been performed.
1342     did_retry: bool,
1343 
1344     /// Whether the peer already updated its connection ID.
1345     got_peer_conn_id: bool,
1346 
1347     /// Whether the peer verified our initial address.
1348     peer_verified_initial_address: bool,
1349 
1350     /// Whether the peer's transport parameters were parsed.
1351     parsed_peer_transport_params: bool,
1352 
1353     /// Whether the connection handshake has been completed.
1354     handshake_completed: bool,
1355 
1356     /// Whether the HANDSHAKE_DONE frame has been sent.
1357     handshake_done_sent: bool,
1358 
1359     /// Whether the HANDSHAKE_DONE frame has been acked.
1360     handshake_done_acked: bool,
1361 
1362     /// Whether the connection handshake has been confirmed.
1363     handshake_confirmed: bool,
1364 
1365     /// Key phase bit used for outgoing protected packets.
1366     key_phase: bool,
1367 
1368     /// Whether an ack-eliciting packet has been sent since last receiving a
1369     /// packet.
1370     ack_eliciting_sent: bool,
1371 
1372     /// Whether the connection is closed.
1373     closed: bool,
1374 
1375     // Whether the connection was timed out
1376     timed_out: bool,
1377 
1378     /// Whether to send GREASE.
1379     grease: bool,
1380 
1381     /// TLS keylog writer.
1382     keylog: Option<Box<dyn std::io::Write + Send + Sync>>,
1383 
1384     #[cfg(feature = "qlog")]
1385     qlog: QlogInfo,
1386 
1387     /// DATAGRAM queues.
1388     dgram_recv_queue: dgram::DatagramQueue,
1389     dgram_send_queue: dgram::DatagramQueue,
1390 
1391     /// Whether to emit DATAGRAM frames in the next packet.
1392     emit_dgram: bool,
1393 
1394     /// Whether the connection should prevent from reusing destination
1395     /// Connection IDs when the peer migrates.
1396     disable_dcid_reuse: bool,
1397 }
1398 
1399 /// Creates a new server-side connection.
1400 ///
1401 /// The `scid` parameter represents the server's source connection ID, while
1402 /// the optional `odcid` parameter represents the original destination ID the
1403 /// client sent before a stateless retry (this is only required when using
1404 /// the [`retry()`] function).
1405 ///
1406 /// [`retry()`]: fn.retry.html
1407 ///
1408 /// ## Examples:
1409 ///
1410 /// ```no_run
1411 /// # let mut config = quiche::Config::new(0xbabababa)?;
1412 /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
1413 /// # let local = "127.0.0.1:0".parse().unwrap();
1414 /// # let peer = "127.0.0.1:1234".parse().unwrap();
1415 /// let conn = quiche::accept(&scid, None, local, peer, &mut config)?;
1416 /// # Ok::<(), quiche::Error>(())
1417 /// ```
1418 #[inline]
accept( scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr, peer: SocketAddr, config: &mut Config, ) -> Result<Connection>1419 pub fn accept(
1420     scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1421     peer: SocketAddr, config: &mut Config,
1422 ) -> Result<Connection> {
1423     let conn = Connection::new(scid, odcid, local, peer, config, true)?;
1424 
1425     Ok(conn)
1426 }
1427 
1428 /// Creates a new client-side connection.
1429 ///
1430 /// The `scid` parameter is used as the connection's source connection ID,
1431 /// while the optional `server_name` parameter is used to verify the peer's
1432 /// certificate.
1433 ///
1434 /// ## Examples:
1435 ///
1436 /// ```no_run
1437 /// # let mut config = quiche::Config::new(0xbabababa)?;
1438 /// # let server_name = "quic.tech";
1439 /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
1440 /// # let local = "127.0.0.1:4321".parse().unwrap();
1441 /// # let peer = "127.0.0.1:1234".parse().unwrap();
1442 /// let conn =
1443 ///     quiche::connect(Some(&server_name), &scid, local, peer, &mut config)?;
1444 /// # Ok::<(), quiche::Error>(())
1445 /// ```
1446 #[inline]
connect( server_name: Option<&str>, scid: &ConnectionId, local: SocketAddr, peer: SocketAddr, config: &mut Config, ) -> Result<Connection>1447 pub fn connect(
1448     server_name: Option<&str>, scid: &ConnectionId, local: SocketAddr,
1449     peer: SocketAddr, config: &mut Config,
1450 ) -> Result<Connection> {
1451     let mut conn = Connection::new(scid, None, local, peer, config, false)?;
1452 
1453     if let Some(server_name) = server_name {
1454         conn.handshake.set_host_name(server_name)?;
1455     }
1456 
1457     Ok(conn)
1458 }
1459 
1460 /// Writes a version negotiation packet.
1461 ///
1462 /// The `scid` and `dcid` parameters are the source connection ID and the
1463 /// destination connection ID extracted from the received client's Initial
1464 /// packet that advertises an unsupported version.
1465 ///
1466 /// ## Examples:
1467 ///
1468 /// ```no_run
1469 /// # let mut buf = [0; 512];
1470 /// # let mut out = [0; 512];
1471 /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1472 /// let (len, src) = socket.recv_from(&mut buf).unwrap();
1473 ///
1474 /// let hdr =
1475 ///     quiche::Header::from_slice(&mut buf[..len], quiche::MAX_CONN_ID_LEN)?;
1476 ///
1477 /// if hdr.version != quiche::PROTOCOL_VERSION {
1478 ///     let len = quiche::negotiate_version(&hdr.scid, &hdr.dcid, &mut out)?;
1479 ///     socket.send_to(&out[..len], &src).unwrap();
1480 /// }
1481 /// # Ok::<(), quiche::Error>(())
1482 /// ```
1483 #[inline]
negotiate_version( scid: &ConnectionId, dcid: &ConnectionId, out: &mut [u8], ) -> Result<usize>1484 pub fn negotiate_version(
1485     scid: &ConnectionId, dcid: &ConnectionId, out: &mut [u8],
1486 ) -> Result<usize> {
1487     packet::negotiate_version(scid, dcid, out)
1488 }
1489 
1490 /// Writes a stateless retry packet.
1491 ///
1492 /// The `scid` and `dcid` parameters are the source connection ID and the
1493 /// destination connection ID extracted from the received client's Initial
1494 /// packet, while `new_scid` is the server's new source connection ID and
1495 /// `token` is the address validation token the client needs to echo back.
1496 ///
1497 /// The application is responsible for generating the address validation
1498 /// token to be sent to the client, and verifying tokens sent back by the
1499 /// client. The generated token should include the `dcid` parameter, such
1500 /// that it can be later extracted from the token and passed to the
1501 /// [`accept()`] function as its `odcid` parameter.
1502 ///
1503 /// [`accept()`]: fn.accept.html
1504 ///
1505 /// ## Examples:
1506 ///
1507 /// ```no_run
1508 /// # let mut config = quiche::Config::new(0xbabababa)?;
1509 /// # let mut buf = [0; 512];
1510 /// # let mut out = [0; 512];
1511 /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
1512 /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
1513 /// # let local = socket.local_addr().unwrap();
1514 /// # fn mint_token(hdr: &quiche::Header, src: &std::net::SocketAddr) -> Vec<u8> {
1515 /// #     vec![]
1516 /// # }
1517 /// # fn validate_token<'a>(src: &std::net::SocketAddr, token: &'a [u8]) -> Option<quiche::ConnectionId<'a>> {
1518 /// #     None
1519 /// # }
1520 /// let (len, peer) = socket.recv_from(&mut buf).unwrap();
1521 ///
1522 /// let hdr = quiche::Header::from_slice(&mut buf[..len], quiche::MAX_CONN_ID_LEN)?;
1523 ///
1524 /// let token = hdr.token.as_ref().unwrap();
1525 ///
1526 /// // No token sent by client, create a new one.
1527 /// if token.is_empty() {
1528 ///     let new_token = mint_token(&hdr, &peer);
1529 ///
1530 ///     let len = quiche::retry(
1531 ///         &hdr.scid, &hdr.dcid, &scid, &new_token, hdr.version, &mut out,
1532 ///     )?;
1533 ///
1534 ///     socket.send_to(&out[..len], &peer).unwrap();
1535 ///     return Ok(());
1536 /// }
1537 ///
1538 /// // Client sent token, validate it.
1539 /// let odcid = validate_token(&peer, token);
1540 ///
1541 /// if odcid.is_none() {
1542 ///     // Invalid address validation token.
1543 ///     return Ok(());
1544 /// }
1545 ///
1546 /// let conn = quiche::accept(&scid, odcid.as_ref(), local, peer, &mut config)?;
1547 /// # Ok::<(), quiche::Error>(())
1548 /// ```
1549 #[inline]
retry( scid: &ConnectionId, dcid: &ConnectionId, new_scid: &ConnectionId, token: &[u8], version: u32, out: &mut [u8], ) -> Result<usize>1550 pub fn retry(
1551     scid: &ConnectionId, dcid: &ConnectionId, new_scid: &ConnectionId,
1552     token: &[u8], version: u32, out: &mut [u8],
1553 ) -> Result<usize> {
1554     packet::retry(scid, dcid, new_scid, token, version, out)
1555 }
1556 
1557 /// Returns true if the given protocol version is supported.
1558 #[inline]
version_is_supported(version: u32) -> bool1559 pub fn version_is_supported(version: u32) -> bool {
1560     matches!(
1561         version,
1562         PROTOCOL_VERSION_V1 |
1563             PROTOCOL_VERSION_DRAFT27 |
1564             PROTOCOL_VERSION_DRAFT28 |
1565             PROTOCOL_VERSION_DRAFT29
1566     )
1567 }
1568 
1569 /// Pushes a frame to the output packet if there is enough space.
1570 ///
1571 /// Returns `true` on success, `false` otherwise. In case of failure it means
1572 /// there is no room to add the frame in the packet. You may retry to add the
1573 /// frame later.
1574 macro_rules! push_frame_to_pkt {
1575     ($out:expr, $frames:expr, $frame:expr, $left:expr) => {{
1576         if $frame.wire_len() <= $left {
1577             $left -= $frame.wire_len();
1578 
1579             $frame.to_bytes(&mut $out)?;
1580 
1581             $frames.push($frame);
1582 
1583             true
1584         } else {
1585             false
1586         }
1587     }};
1588 }
1589 
1590 /// Conditional qlog actions.
1591 ///
1592 /// Executes the provided body if the qlog feature is enabled and quiche
1593 /// has been configured with a log writer.
1594 macro_rules! qlog_with {
1595     ($qlog:expr, $qlog_streamer_ref:ident, $body:block) => {{
1596         #[cfg(feature = "qlog")]
1597         {
1598             if let Some($qlog_streamer_ref) = &mut $qlog.streamer {
1599                 $body
1600             }
1601         }
1602     }};
1603 }
1604 
1605 /// Executes the provided body if the qlog feature is enabled, quiche has been
1606 /// configured with a log writer, the event's importance is within the
1607 /// configured level.
1608 macro_rules! qlog_with_type {
1609     ($ty:expr, $qlog:expr, $qlog_streamer_ref:ident, $body:block) => {{
1610         #[cfg(feature = "qlog")]
1611         {
1612             if EventImportance::from($ty).is_contained_in(&$qlog.level) {
1613                 if let Some($qlog_streamer_ref) = &mut $qlog.streamer {
1614                     $body
1615                 }
1616             }
1617         }
1618     }};
1619 }
1620 
1621 #[cfg(feature = "qlog")]
1622 const QLOG_PARAMS_SET: EventType =
1623     EventType::TransportEventType(TransportEventType::ParametersSet);
1624 
1625 #[cfg(feature = "qlog")]
1626 const QLOG_PACKET_RX: EventType =
1627     EventType::TransportEventType(TransportEventType::PacketReceived);
1628 
1629 #[cfg(feature = "qlog")]
1630 const QLOG_PACKET_TX: EventType =
1631     EventType::TransportEventType(TransportEventType::PacketSent);
1632 
1633 #[cfg(feature = "qlog")]
1634 const QLOG_DATA_MV: EventType =
1635     EventType::TransportEventType(TransportEventType::DataMoved);
1636 
1637 #[cfg(feature = "qlog")]
1638 const QLOG_METRICS: EventType =
1639     EventType::RecoveryEventType(RecoveryEventType::MetricsUpdated);
1640 
1641 #[cfg(feature = "qlog")]
1642 struct QlogInfo {
1643     streamer: Option<qlog::streamer::QlogStreamer>,
1644     logged_peer_params: bool,
1645     level: EventImportance,
1646 }
1647 
1648 #[cfg(feature = "qlog")]
1649 impl Default for QlogInfo {
default() -> Self1650     fn default() -> Self {
1651         QlogInfo {
1652             streamer: None,
1653             logged_peer_params: false,
1654             level: EventImportance::Base,
1655         }
1656     }
1657 }
1658 
1659 impl Connection {
new( scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr, peer: SocketAddr, config: &mut Config, is_server: bool, ) -> Result<Connection>1660     fn new(
1661         scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1662         peer: SocketAddr, config: &mut Config, is_server: bool,
1663     ) -> Result<Connection> {
1664         let tls = config.tls_ctx.new_handshake()?;
1665         Connection::with_tls(scid, odcid, local, peer, config, tls, is_server)
1666     }
1667 
with_tls( scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr, peer: SocketAddr, config: &mut Config, tls: tls::Handshake, is_server: bool, ) -> Result<Connection>1668     fn with_tls(
1669         scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1670         peer: SocketAddr, config: &mut Config, tls: tls::Handshake,
1671         is_server: bool,
1672     ) -> Result<Connection> {
1673         let max_rx_data = config.local_transport_params.initial_max_data;
1674 
1675         let scid_as_hex: Vec<String> =
1676             scid.iter().map(|b| format!("{b:02x}")).collect();
1677 
1678         let reset_token = if is_server {
1679             config.local_transport_params.stateless_reset_token
1680         } else {
1681             None
1682         };
1683 
1684         let recovery_config = recovery::RecoveryConfig::from_config(config);
1685 
1686         let mut path = path::Path::new(local, peer, &recovery_config, true);
1687         // If we did stateless retry assume the peer's address is verified.
1688         path.verified_peer_address = odcid.is_some();
1689         // Assume clients validate the server's address implicitly.
1690         path.peer_verified_local_address = is_server;
1691 
1692         // Do not allocate more than the number of active CIDs.
1693         let paths = path::PathMap::new(
1694             path,
1695             config.local_transport_params.active_conn_id_limit as usize,
1696             is_server,
1697         );
1698 
1699         let active_path_id = paths.get_active_path_id()?;
1700 
1701         let ids = cid::ConnectionIdentifiers::new(
1702             config.local_transport_params.active_conn_id_limit as usize,
1703             scid,
1704             active_path_id,
1705             reset_token,
1706         );
1707 
1708         let mut conn = Connection {
1709             version: config.version,
1710 
1711             ids,
1712 
1713             trace_id: scid_as_hex.join(""),
1714 
1715             pkt_num_spaces: [
1716                 packet::PktNumSpace::new(),
1717                 packet::PktNumSpace::new(),
1718                 packet::PktNumSpace::new(),
1719             ],
1720 
1721             peer_transport_params: TransportParams::default(),
1722 
1723             local_transport_params: config.local_transport_params.clone(),
1724 
1725             handshake: tls,
1726 
1727             session: None,
1728 
1729             recovery_config,
1730 
1731             paths,
1732 
1733             application_protos: config.application_protos.clone(),
1734 
1735             recv_count: 0,
1736             sent_count: 0,
1737             lost_count: 0,
1738             retrans_count: 0,
1739             sent_bytes: 0,
1740             recv_bytes: 0,
1741             lost_bytes: 0,
1742 
1743             rx_data: 0,
1744             flow_control: flowcontrol::FlowControl::new(
1745                 max_rx_data,
1746                 cmp::min(max_rx_data / 2 * 3, DEFAULT_CONNECTION_WINDOW),
1747                 config.max_connection_window,
1748             ),
1749             almost_full: false,
1750 
1751             tx_cap: 0,
1752 
1753             tx_buffered: 0,
1754 
1755             tx_data: 0,
1756             max_tx_data: 0,
1757             last_tx_data: 0,
1758 
1759             stream_retrans_bytes: 0,
1760 
1761             streams: stream::StreamMap::new(
1762                 config.local_transport_params.initial_max_streams_bidi,
1763                 config.local_transport_params.initial_max_streams_uni,
1764                 config.max_stream_window,
1765             ),
1766 
1767             odcid: None,
1768 
1769             rscid: None,
1770 
1771             token: None,
1772 
1773             local_error: None,
1774 
1775             peer_error: None,
1776 
1777             blocked_limit: None,
1778 
1779             idle_timer: None,
1780 
1781             draining_timer: None,
1782 
1783             undecryptable_pkts: VecDeque::new(),
1784 
1785             alpn: Vec::new(),
1786 
1787             is_server,
1788 
1789             derived_initial_secrets: false,
1790 
1791             did_version_negotiation: false,
1792 
1793             did_retry: false,
1794 
1795             got_peer_conn_id: false,
1796 
1797             // Assume clients validate the server's address implicitly.
1798             peer_verified_initial_address: is_server,
1799 
1800             parsed_peer_transport_params: false,
1801 
1802             handshake_completed: false,
1803 
1804             handshake_done_sent: false,
1805             handshake_done_acked: false,
1806 
1807             handshake_confirmed: false,
1808 
1809             key_phase: false,
1810 
1811             ack_eliciting_sent: false,
1812 
1813             closed: false,
1814 
1815             timed_out: false,
1816 
1817             grease: config.grease,
1818 
1819             keylog: None,
1820 
1821             #[cfg(feature = "qlog")]
1822             qlog: Default::default(),
1823 
1824             dgram_recv_queue: dgram::DatagramQueue::new(
1825                 config.dgram_recv_max_queue_len,
1826             ),
1827 
1828             dgram_send_queue: dgram::DatagramQueue::new(
1829                 config.dgram_send_max_queue_len,
1830             ),
1831 
1832             emit_dgram: true,
1833 
1834             disable_dcid_reuse: config.disable_dcid_reuse,
1835         };
1836 
1837         if let Some(odcid) = odcid {
1838             conn.local_transport_params
1839                 .original_destination_connection_id = Some(odcid.to_vec().into());
1840 
1841             conn.local_transport_params.retry_source_connection_id =
1842                 Some(conn.ids.get_scid(0)?.cid.to_vec().into());
1843 
1844             conn.did_retry = true;
1845         }
1846 
1847         conn.local_transport_params.initial_source_connection_id =
1848             Some(conn.ids.get_scid(0)?.cid.to_vec().into());
1849 
1850         conn.handshake.init(is_server)?;
1851 
1852         conn.handshake
1853             .use_legacy_codepoint(config.version != PROTOCOL_VERSION_V1);
1854 
1855         conn.encode_transport_params()?;
1856 
1857         // Derive initial secrets for the client. We can do this here because
1858         // we already generated the random destination connection ID.
1859         if !is_server {
1860             let mut dcid = [0; 16];
1861             rand::rand_bytes(&mut dcid[..]);
1862 
1863             let (aead_open, aead_seal) = crypto::derive_initial_key_material(
1864                 &dcid,
1865                 conn.version,
1866                 conn.is_server,
1867             )?;
1868 
1869             let reset_token = conn.peer_transport_params.stateless_reset_token;
1870             conn.set_initial_dcid(
1871                 dcid.to_vec().into(),
1872                 reset_token,
1873                 active_path_id,
1874             )?;
1875 
1876             conn.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
1877                 Some(aead_open);
1878             conn.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
1879                 Some(aead_seal);
1880 
1881             conn.derived_initial_secrets = true;
1882         }
1883 
1884         conn.paths.get_mut(active_path_id)?.recovery.on_init();
1885 
1886         Ok(conn)
1887     }
1888 
1889     /// Sets keylog output to the designated [`Writer`].
1890     ///
1891     /// This needs to be called as soon as the connection is created, to avoid
1892     /// missing some early logs.
1893     ///
1894     /// [`Writer`]: https://doc.rust-lang.org/std/io/trait.Write.html
1895     #[inline]
set_keylog(&mut self, writer: Box<dyn std::io::Write + Send + Sync>)1896     pub fn set_keylog(&mut self, writer: Box<dyn std::io::Write + Send + Sync>) {
1897         self.keylog = Some(writer);
1898     }
1899 
1900     /// Sets qlog output to the designated [`Writer`].
1901     ///
1902     /// Only events included in `QlogLevel::Base` are written. The serialization
1903     /// format is JSON-SEQ.
1904     ///
1905     /// This needs to be called as soon as the connection is created, to avoid
1906     /// missing some early logs.
1907     ///
1908     /// [`Writer`]: https://doc.rust-lang.org/std/io/trait.Write.html
1909     #[cfg(feature = "qlog")]
1910     #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
set_qlog( &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String, description: String, )1911     pub fn set_qlog(
1912         &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String,
1913         description: String,
1914     ) {
1915         self.set_qlog_with_level(writer, title, description, QlogLevel::Base)
1916     }
1917 
1918     /// Sets qlog output to the designated [`Writer`].
1919     ///
1920     /// Only qlog events included in the specified `QlogLevel` are written. The
1921     /// serialization format is JSON-SEQ.
1922     ///
1923     /// This needs to be called as soon as the connection is created, to avoid
1924     /// missing some early logs.
1925     ///
1926     /// [`Writer`]: https://doc.rust-lang.org/std/io/trait.Write.html
1927     #[cfg(feature = "qlog")]
1928     #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
set_qlog_with_level( &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String, description: String, qlog_level: QlogLevel, )1929     pub fn set_qlog_with_level(
1930         &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String,
1931         description: String, qlog_level: QlogLevel,
1932     ) {
1933         let vp = if self.is_server {
1934             qlog::VantagePointType::Server
1935         } else {
1936             qlog::VantagePointType::Client
1937         };
1938 
1939         let level = match qlog_level {
1940             QlogLevel::Core => EventImportance::Core,
1941 
1942             QlogLevel::Base => EventImportance::Base,
1943 
1944             QlogLevel::Extra => EventImportance::Extra,
1945         };
1946 
1947         self.qlog.level = level;
1948 
1949         let trace = qlog::TraceSeq::new(
1950             qlog::VantagePoint {
1951                 name: None,
1952                 ty: vp,
1953                 flow: None,
1954             },
1955             Some(title.to_string()),
1956             Some(description.to_string()),
1957             Some(qlog::Configuration {
1958                 time_offset: Some(0.0),
1959                 original_uris: None,
1960             }),
1961             None,
1962         );
1963 
1964         let mut streamer = qlog::streamer::QlogStreamer::new(
1965             qlog::QLOG_VERSION.to_string(),
1966             Some(title),
1967             Some(description),
1968             None,
1969             time::Instant::now(),
1970             trace,
1971             self.qlog.level.clone(),
1972             writer,
1973         );
1974 
1975         streamer.start_log().ok();
1976 
1977         let ev_data = self
1978             .local_transport_params
1979             .to_qlog(TransportOwner::Local, self.handshake.cipher());
1980 
1981         // This event occurs very early, so just mark the relative time as 0.0.
1982         streamer.add_event(Event::with_time(0.0, ev_data)).ok();
1983 
1984         self.qlog.streamer = Some(streamer);
1985     }
1986 
1987     /// Configures the given session for resumption.
1988     ///
1989     /// On the client, this can be used to offer the given serialized session,
1990     /// as returned by [`session()`], for resumption.
1991     ///
1992     /// This must only be called immediately after creating a connection, that
1993     /// is, before any packet is sent or received.
1994     ///
1995     /// [`session()`]: struct.Connection.html#method.session
1996     #[inline]
set_session(&mut self, session: &[u8]) -> Result<()>1997     pub fn set_session(&mut self, session: &[u8]) -> Result<()> {
1998         let mut b = octets::Octets::with_slice(session);
1999 
2000         let session_len = b.get_u64()? as usize;
2001         let session_bytes = b.get_bytes(session_len)?;
2002 
2003         self.handshake.set_session(session_bytes.as_ref())?;
2004 
2005         let raw_params_len = b.get_u64()? as usize;
2006         let raw_params_bytes = b.get_bytes(raw_params_len)?;
2007 
2008         let peer_params =
2009             TransportParams::decode(raw_params_bytes.as_ref(), self.is_server)?;
2010 
2011         self.process_peer_transport_params(peer_params)?;
2012 
2013         Ok(())
2014     }
2015 
2016     /// Processes QUIC packets received from the peer.
2017     ///
2018     /// On success the number of bytes processed from the input buffer is
2019     /// returned. On error the connection will be closed by calling [`close()`]
2020     /// with the appropriate error code.
2021     ///
2022     /// Coalesced packets will be processed as necessary.
2023     ///
2024     /// Note that the contents of the input buffer `buf` might be modified by
2025     /// this function due to, for example, in-place decryption.
2026     ///
2027     /// [`close()`]: struct.Connection.html#method.close
2028     ///
2029     /// ## Examples:
2030     ///
2031     /// ```no_run
2032     /// # let mut buf = [0; 512];
2033     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
2034     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
2035     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
2036     /// # let peer = "127.0.0.1:1234".parse().unwrap();
2037     /// # let local = socket.local_addr().unwrap();
2038     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
2039     /// loop {
2040     ///     let (read, from) = socket.recv_from(&mut buf).unwrap();
2041     ///
2042     ///     let recv_info = quiche::RecvInfo {
2043     ///         from,
2044     ///         to: local,
2045     ///     };
2046     ///
2047     ///     let read = match conn.recv(&mut buf[..read], recv_info) {
2048     ///         Ok(v) => v,
2049     ///
2050     ///         Err(e) => {
2051     ///             // An error occurred, handle it.
2052     ///             break;
2053     ///         },
2054     ///     };
2055     /// }
2056     /// # Ok::<(), quiche::Error>(())
2057     /// ```
recv(&mut self, buf: &mut [u8], info: RecvInfo) -> Result<usize>2058     pub fn recv(&mut self, buf: &mut [u8], info: RecvInfo) -> Result<usize> {
2059         let len = buf.len();
2060 
2061         if len == 0 {
2062             return Err(Error::BufferTooShort);
2063         }
2064 
2065         let recv_pid = self.paths.path_id_from_addrs(&(info.to, info.from));
2066 
2067         if let Some(recv_pid) = recv_pid {
2068             let recv_path = self.paths.get_mut(recv_pid)?;
2069 
2070             // Keep track of how many bytes we received from the client, so we
2071             // can limit bytes sent back before address validation, to a
2072             // multiple of this. The limit needs to be increased early on, so
2073             // that if there is an error there is enough credit to send a
2074             // CONNECTION_CLOSE.
2075             //
2076             // It doesn't matter if the packets received were valid or not, we
2077             // only need to track the total amount of bytes received.
2078             //
2079             // Note that we also need to limit the number of bytes we sent on a
2080             // path if we are not the host that initiated its usage.
2081             if self.is_server && !recv_path.verified_peer_address {
2082                 recv_path.max_send_bytes += len * MAX_AMPLIFICATION_FACTOR;
2083             }
2084         } else if !self.is_server {
2085             // If a client receives packets from an unknown server address,
2086             // the client MUST discard these packets.
2087             trace!(
2088                 "{} client received packet from unknown address {:?}, dropping",
2089                 self.trace_id,
2090                 info,
2091             );
2092 
2093             return Ok(len);
2094         }
2095 
2096         let mut done = 0;
2097         let mut left = len;
2098 
2099         // Process coalesced packets.
2100         while left > 0 {
2101             let read = match self.recv_single(
2102                 &mut buf[len - left..len],
2103                 &info,
2104                 recv_pid,
2105             ) {
2106                 Ok(v) => v,
2107 
2108                 Err(Error::Done) => {
2109                     // If the packet can't be processed or decrypted, check if
2110                     // it's a stateless reset.
2111                     if self.is_stateless_reset(&buf[len - left..len]) {
2112                         trace!("{} packet is a stateless reset", self.trace_id);
2113 
2114                         self.closed = true;
2115                     }
2116 
2117                     left
2118                 },
2119 
2120                 Err(e) => {
2121                     // In case of error processing the incoming packet, close
2122                     // the connection.
2123                     self.close(false, e.to_wire(), b"").ok();
2124                     return Err(e);
2125                 },
2126             };
2127 
2128             done += read;
2129             left -= read;
2130         }
2131 
2132         // Even though the packet was previously "accepted", it
2133         // should be safe to forward the error, as it also comes
2134         // from the `recv()` method.
2135         self.process_undecrypted_0rtt_packets()?;
2136 
2137         Ok(done)
2138     }
2139 
process_undecrypted_0rtt_packets(&mut self) -> Result<()>2140     fn process_undecrypted_0rtt_packets(&mut self) -> Result<()> {
2141         // Process previously undecryptable 0-RTT packets if the decryption key
2142         // is now available.
2143         if self.pkt_num_spaces[packet::Epoch::Application]
2144             .crypto_0rtt_open
2145             .is_some()
2146         {
2147             while let Some((mut pkt, info)) = self.undecryptable_pkts.pop_front()
2148             {
2149                 if let Err(e) = self.recv(&mut pkt, info) {
2150                     self.undecryptable_pkts.clear();
2151 
2152                     return Err(e);
2153                 }
2154             }
2155         }
2156         Ok(())
2157     }
2158 
2159     /// Returns true if a QUIC packet is a stateless reset.
is_stateless_reset(&self, buf: &[u8]) -> bool2160     fn is_stateless_reset(&self, buf: &[u8]) -> bool {
2161         // If the packet is too small, then we just throw it away.
2162         let buf_len = buf.len();
2163         if buf_len < 21 {
2164             return false;
2165         }
2166 
2167         // TODO: we should iterate over all active destination connection IDs
2168         // and check against their reset token.
2169         match self.peer_transport_params.stateless_reset_token {
2170             Some(token) => {
2171                 let token_len = 16;
2172                 ring::constant_time::verify_slices_are_equal(
2173                     &token.to_be_bytes(),
2174                     &buf[buf_len - token_len..buf_len],
2175                 )
2176                 .is_ok()
2177             },
2178 
2179             None => false,
2180         }
2181     }
2182 
2183     /// Processes a single QUIC packet received from the peer.
2184     ///
2185     /// On success the number of bytes processed from the input buffer is
2186     /// returned. When the [`Done`] error is returned, processing of the
2187     /// remainder of the incoming UDP datagram should be interrupted.
2188     ///
2189     /// Note that a server might observe a new 4-tuple, preventing to
2190     /// know in advance to which path the incoming packet belongs to (`recv_pid`
2191     /// is `None`). As a client, packets from unknown 4-tuple are dropped
2192     /// beforehand (see `recv()`).
2193     ///
2194     /// On error, an error other than [`Done`] is returned.
2195     ///
2196     /// [`Done`]: enum.Error.html#variant.Done
recv_single( &mut self, buf: &mut [u8], info: &RecvInfo, recv_pid: Option<usize>, ) -> Result<usize>2197     fn recv_single(
2198         &mut self, buf: &mut [u8], info: &RecvInfo, recv_pid: Option<usize>,
2199     ) -> Result<usize> {
2200         let now = time::Instant::now();
2201 
2202         if buf.is_empty() {
2203             return Err(Error::Done);
2204         }
2205 
2206         if self.is_closed() || self.is_draining() {
2207             return Err(Error::Done);
2208         }
2209 
2210         let is_closing = self.local_error.is_some();
2211 
2212         if is_closing {
2213             return Err(Error::Done);
2214         }
2215 
2216         let buf_len = buf.len();
2217 
2218         let mut b = octets::OctetsMut::with_slice(buf);
2219 
2220         let mut hdr = Header::from_bytes(&mut b, self.source_id().len())
2221             .map_err(|e| {
2222                 drop_pkt_on_err(
2223                     e,
2224                     self.recv_count,
2225                     self.is_server,
2226                     &self.trace_id,
2227                 )
2228             })?;
2229 
2230         if hdr.ty == packet::Type::VersionNegotiation {
2231             // Version negotiation packets can only be sent by the server.
2232             if self.is_server {
2233                 return Err(Error::Done);
2234             }
2235 
2236             // Ignore duplicate version negotiation.
2237             if self.did_version_negotiation {
2238                 return Err(Error::Done);
2239             }
2240 
2241             // Ignore version negotiation if any other packet has already been
2242             // successfully processed.
2243             if self.recv_count > 0 {
2244                 return Err(Error::Done);
2245             }
2246 
2247             if hdr.dcid != self.source_id() {
2248                 return Err(Error::Done);
2249             }
2250 
2251             if hdr.scid != self.destination_id() {
2252                 return Err(Error::Done);
2253             }
2254 
2255             trace!("{} rx pkt {:?}", self.trace_id, hdr);
2256 
2257             let versions = hdr.versions.ok_or(Error::Done)?;
2258 
2259             // Ignore version negotiation if the version already selected is
2260             // listed.
2261             if versions.iter().any(|&v| v == self.version) {
2262                 return Err(Error::Done);
2263             }
2264 
2265             let supported_versions =
2266                 versions.iter().filter(|&&v| version_is_supported(v));
2267 
2268             let mut found_version = false;
2269 
2270             for &v in supported_versions {
2271                 found_version = true;
2272 
2273                 // The final version takes precedence over draft ones.
2274                 if v == PROTOCOL_VERSION_V1 {
2275                     self.version = v;
2276                     break;
2277                 }
2278 
2279                 self.version = cmp::max(self.version, v);
2280             }
2281 
2282             if !found_version {
2283                 // We don't support any of the versions offered.
2284                 //
2285                 // While a man-in-the-middle attacker might be able to
2286                 // inject a version negotiation packet that triggers this
2287                 // failure, the window of opportunity is very small and
2288                 // this error is quite useful for debugging, so don't just
2289                 // ignore the packet.
2290                 return Err(Error::UnknownVersion);
2291             }
2292 
2293             self.did_version_negotiation = true;
2294 
2295             // Derive Initial secrets based on the new version.
2296             let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2297                 &self.destination_id(),
2298                 self.version,
2299                 self.is_server,
2300             )?;
2301 
2302             // Reset connection state to force sending another Initial packet.
2303             self.drop_epoch_state(packet::Epoch::Initial, now);
2304             self.got_peer_conn_id = false;
2305             self.handshake.clear()?;
2306 
2307             self.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
2308                 Some(aead_open);
2309             self.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
2310                 Some(aead_seal);
2311 
2312             self.handshake
2313                 .use_legacy_codepoint(self.version != PROTOCOL_VERSION_V1);
2314 
2315             // Encode transport parameters again, as the new version might be
2316             // using a different format.
2317             self.encode_transport_params()?;
2318 
2319             return Err(Error::Done);
2320         }
2321 
2322         if hdr.ty == packet::Type::Retry {
2323             // Retry packets can only be sent by the server.
2324             if self.is_server {
2325                 return Err(Error::Done);
2326             }
2327 
2328             // Ignore duplicate retry.
2329             if self.did_retry {
2330                 return Err(Error::Done);
2331             }
2332 
2333             // Check if Retry packet is valid.
2334             if packet::verify_retry_integrity(
2335                 &b,
2336                 &self.destination_id(),
2337                 self.version,
2338             )
2339             .is_err()
2340             {
2341                 return Err(Error::Done);
2342             }
2343 
2344             trace!("{} rx pkt {:?}", self.trace_id, hdr);
2345 
2346             self.token = hdr.token;
2347             self.did_retry = true;
2348 
2349             // Remember peer's new connection ID.
2350             self.odcid = Some(self.destination_id().into_owned());
2351 
2352             self.set_initial_dcid(
2353                 hdr.scid.clone(),
2354                 None,
2355                 self.paths.get_active_path_id()?,
2356             )?;
2357 
2358             self.rscid = Some(self.destination_id().into_owned());
2359 
2360             // Derive Initial secrets using the new connection ID.
2361             let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2362                 &hdr.scid,
2363                 self.version,
2364                 self.is_server,
2365             )?;
2366 
2367             // Reset connection state to force sending another Initial packet.
2368             self.drop_epoch_state(packet::Epoch::Initial, now);
2369             self.got_peer_conn_id = false;
2370             self.handshake.clear()?;
2371 
2372             self.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
2373                 Some(aead_open);
2374             self.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
2375                 Some(aead_seal);
2376 
2377             return Err(Error::Done);
2378         }
2379 
2380         if self.is_server && !self.did_version_negotiation {
2381             if !version_is_supported(hdr.version) {
2382                 return Err(Error::UnknownVersion);
2383             }
2384 
2385             self.version = hdr.version;
2386             self.did_version_negotiation = true;
2387 
2388             self.handshake
2389                 .use_legacy_codepoint(self.version != PROTOCOL_VERSION_V1);
2390 
2391             // Encode transport parameters again, as the new version might be
2392             // using a different format.
2393             self.encode_transport_params()?;
2394         }
2395 
2396         if hdr.ty != packet::Type::Short && hdr.version != self.version {
2397             // At this point version negotiation was already performed, so
2398             // ignore packets that don't match the connection's version.
2399             return Err(Error::Done);
2400         }
2401 
2402         // Long header packets have an explicit payload length, but short
2403         // packets don't so just use the remaining capacity in the buffer.
2404         let payload_len = if hdr.ty == packet::Type::Short {
2405             b.cap()
2406         } else {
2407             b.get_varint().map_err(|e| {
2408                 drop_pkt_on_err(
2409                     e.into(),
2410                     self.recv_count,
2411                     self.is_server,
2412                     &self.trace_id,
2413                 )
2414             })? as usize
2415         };
2416 
2417         // Make sure the buffer is same or larger than an explicit
2418         // payload length.
2419         if payload_len > b.cap() {
2420             return Err(drop_pkt_on_err(
2421                 Error::InvalidPacket,
2422                 self.recv_count,
2423                 self.is_server,
2424                 &self.trace_id,
2425             ));
2426         }
2427 
2428         // Derive initial secrets on the server.
2429         if !self.derived_initial_secrets {
2430             let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2431                 &hdr.dcid,
2432                 self.version,
2433                 self.is_server,
2434             )?;
2435 
2436             self.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
2437                 Some(aead_open);
2438             self.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
2439                 Some(aead_seal);
2440 
2441             self.derived_initial_secrets = true;
2442         }
2443 
2444         // Select packet number space epoch based on the received packet's type.
2445         let epoch = hdr.ty.to_epoch()?;
2446 
2447         // Select AEAD context used to open incoming packet.
2448         let aead = if hdr.ty == packet::Type::ZeroRTT {
2449             // Only use 0-RTT key if incoming packet is 0-RTT.
2450             self.pkt_num_spaces[epoch].crypto_0rtt_open.as_ref()
2451         } else {
2452             // Otherwise use the packet number space's main key.
2453             self.pkt_num_spaces[epoch].crypto_open.as_ref()
2454         };
2455 
2456         // Finally, discard packet if no usable key is available.
2457         let mut aead = match aead {
2458             Some(v) => v,
2459 
2460             None => {
2461                 if hdr.ty == packet::Type::ZeroRTT &&
2462                     self.undecryptable_pkts.len() < MAX_UNDECRYPTABLE_PACKETS &&
2463                     !self.is_established()
2464                 {
2465                     // Buffer 0-RTT packets when the required read key is not
2466                     // available yet, and process them later.
2467                     //
2468                     // TODO: in the future we might want to buffer other types
2469                     // of undecryptable packets as well.
2470                     let pkt_len = b.off() + payload_len;
2471                     let pkt = (b.buf()[..pkt_len]).to_vec();
2472 
2473                     self.undecryptable_pkts.push_back((pkt, *info));
2474                     return Ok(pkt_len);
2475                 }
2476 
2477                 let e = drop_pkt_on_err(
2478                     Error::CryptoFail,
2479                     self.recv_count,
2480                     self.is_server,
2481                     &self.trace_id,
2482                 );
2483 
2484                 return Err(e);
2485             },
2486         };
2487 
2488         let aead_tag_len = aead.alg().tag_len();
2489 
2490         packet::decrypt_hdr(&mut b, &mut hdr, aead).map_err(|e| {
2491             drop_pkt_on_err(e, self.recv_count, self.is_server, &self.trace_id)
2492         })?;
2493 
2494         let pn = packet::decode_pkt_num(
2495             self.pkt_num_spaces[epoch].largest_rx_pkt_num,
2496             hdr.pkt_num,
2497             hdr.pkt_num_len,
2498         );
2499 
2500         let pn_len = hdr.pkt_num_len;
2501 
2502         trace!(
2503             "{} rx pkt {:?} len={} pn={} {}",
2504             self.trace_id,
2505             hdr,
2506             payload_len,
2507             pn,
2508             AddrTupleFmt(info.from, info.to)
2509         );
2510 
2511         #[cfg(feature = "qlog")]
2512         let mut qlog_frames = vec![];
2513 
2514         // Check for key update.
2515         let mut aead_next = None;
2516 
2517         if self.handshake_confirmed &&
2518             hdr.ty != Type::ZeroRTT &&
2519             hdr.key_phase != self.key_phase
2520         {
2521             // Check if this packet arrived before key update.
2522             if let Some(key_update) = self.pkt_num_spaces[epoch]
2523                 .key_update
2524                 .as_ref()
2525                 .and_then(|key_update| {
2526                     (pn < key_update.pn_on_update).then_some(key_update)
2527                 })
2528             {
2529                 aead = &key_update.crypto_open;
2530             } else {
2531                 trace!("{} peer-initiated key update", self.trace_id);
2532 
2533                 aead_next = Some((
2534                     self.pkt_num_spaces[epoch]
2535                         .crypto_open
2536                         .as_ref()
2537                         .unwrap()
2538                         .derive_next_packet_key()?,
2539                     self.pkt_num_spaces[epoch]
2540                         .crypto_seal
2541                         .as_ref()
2542                         .unwrap()
2543                         .derive_next_packet_key()?,
2544                 ));
2545 
2546                 // `aead_next` is always `Some()` at this point, so the `unwrap()`
2547                 // will never fail.
2548                 aead = &aead_next.as_ref().unwrap().0;
2549             }
2550         }
2551 
2552         let mut payload = packet::decrypt_pkt(
2553             &mut b,
2554             pn,
2555             pn_len,
2556             payload_len,
2557             aead,
2558         )
2559         .map_err(|e| {
2560             drop_pkt_on_err(e, self.recv_count, self.is_server, &self.trace_id)
2561         })?;
2562 
2563         if self.pkt_num_spaces[epoch].recv_pkt_num.contains(pn) {
2564             trace!("{} ignored duplicate packet {}", self.trace_id, pn);
2565             return Err(Error::Done);
2566         }
2567 
2568         // Packets with no frames are invalid.
2569         if payload.cap() == 0 {
2570             return Err(Error::InvalidPacket);
2571         }
2572 
2573         // Now that we decrypted the packet, let's see if we can map it to an
2574         // existing path.
2575         let recv_pid = if hdr.ty == packet::Type::Short && self.got_peer_conn_id {
2576             let pkt_dcid = ConnectionId::from_ref(&hdr.dcid);
2577             self.get_or_create_recv_path_id(recv_pid, &pkt_dcid, buf_len, info)?
2578         } else {
2579             // During handshake, we are on the initial path.
2580             self.paths.get_active_path_id()?
2581         };
2582 
2583         // The key update is verified once a packet is successfully decrypted
2584         // using the new keys.
2585         if let Some((open_next, seal_next)) = aead_next {
2586             if !self.pkt_num_spaces[epoch]
2587                 .key_update
2588                 .as_ref()
2589                 .map_or(true, |prev| prev.update_acked)
2590             {
2591                 // Peer has updated keys twice without awaiting confirmation.
2592                 return Err(Error::KeyUpdate);
2593             }
2594 
2595             trace!("{} key update verified", self.trace_id);
2596 
2597             let _ = self.pkt_num_spaces[epoch].crypto_seal.replace(seal_next);
2598 
2599             let open_prev = self.pkt_num_spaces[epoch]
2600                 .crypto_open
2601                 .replace(open_next)
2602                 .unwrap();
2603 
2604             let recv_path = self.paths.get_mut(recv_pid)?;
2605 
2606             self.pkt_num_spaces[epoch].key_update = Some(packet::KeyUpdate {
2607                 crypto_open: open_prev,
2608                 pn_on_update: pn,
2609                 update_acked: false,
2610                 timer: now + (recv_path.recovery.pto() * 3),
2611             });
2612 
2613             self.key_phase = !self.key_phase;
2614 
2615             qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
2616                 let trigger = Some(
2617                     qlog::events::security::KeyUpdateOrRetiredTrigger::RemoteUpdate,
2618                 );
2619 
2620                 let ev_data_client =
2621                     EventData::KeyUpdated(qlog::events::security::KeyUpdated {
2622                         key_type:
2623                             qlog::events::security::KeyType::Client1RttSecret,
2624                         old: None,
2625                         new: String::new(),
2626                         generation: None,
2627                         trigger: trigger.clone(),
2628                     });
2629 
2630                 q.add_event_data_with_instant(ev_data_client, now).ok();
2631 
2632                 let ev_data_server =
2633                     EventData::KeyUpdated(qlog::events::security::KeyUpdated {
2634                         key_type:
2635                             qlog::events::security::KeyType::Server1RttSecret,
2636                         old: None,
2637                         new: String::new(),
2638                         generation: None,
2639                         trigger,
2640                     });
2641 
2642                 q.add_event_data_with_instant(ev_data_server, now).ok();
2643             });
2644         }
2645 
2646         if !self.is_server && !self.got_peer_conn_id {
2647             if self.odcid.is_none() {
2648                 self.odcid = Some(self.destination_id().into_owned());
2649             }
2650 
2651             // Replace the randomly generated destination connection ID with
2652             // the one supplied by the server.
2653             self.set_initial_dcid(
2654                 hdr.scid.clone(),
2655                 self.peer_transport_params.stateless_reset_token,
2656                 recv_pid,
2657             )?;
2658 
2659             self.got_peer_conn_id = true;
2660         }
2661 
2662         if self.is_server && !self.got_peer_conn_id {
2663             self.set_initial_dcid(hdr.scid.clone(), None, recv_pid)?;
2664 
2665             if !self.did_retry &&
2666                 (self.version >= PROTOCOL_VERSION_DRAFT28 ||
2667                     self.version == PROTOCOL_VERSION_V1)
2668             {
2669                 self.local_transport_params
2670                     .original_destination_connection_id =
2671                     Some(hdr.dcid.to_vec().into());
2672 
2673                 self.encode_transport_params()?;
2674             }
2675 
2676             self.got_peer_conn_id = true;
2677         }
2678 
2679         // To avoid sending an ACK in response to an ACK-only packet, we need
2680         // to keep track of whether this packet contains any frame other than
2681         // ACK and PADDING.
2682         let mut ack_elicited = false;
2683 
2684         // Process packet payload. If a frame cannot be processed, store the
2685         // error and stop further packet processing.
2686         let mut frame_processing_err = None;
2687 
2688         // To know if the peer migrated the connection, we need to keep track
2689         // whether this is a non-probing packet.
2690         let mut probing = true;
2691 
2692         // Process packet payload.
2693         while payload.cap() > 0 {
2694             let frame = frame::Frame::from_bytes(&mut payload, hdr.ty)?;
2695 
2696             qlog_with_type!(QLOG_PACKET_RX, self.qlog, _q, {
2697                 qlog_frames.push(frame.to_qlog());
2698             });
2699 
2700             if frame.ack_eliciting() {
2701                 ack_elicited = true;
2702             }
2703 
2704             if !frame.probing() {
2705                 probing = false;
2706             }
2707 
2708             if let Err(e) = self.process_frame(frame, &hdr, recv_pid, epoch, now)
2709             {
2710                 frame_processing_err = Some(e);
2711                 break;
2712             }
2713         }
2714 
2715         qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
2716             let packet_size = b.len();
2717 
2718             let qlog_pkt_hdr = qlog::events::quic::PacketHeader::with_type(
2719                 hdr.ty.to_qlog(),
2720                 pn,
2721                 Some(hdr.version),
2722                 Some(&hdr.scid),
2723                 Some(&hdr.dcid),
2724             );
2725 
2726             let qlog_raw_info = RawInfo {
2727                 length: Some(packet_size as u64),
2728                 payload_length: Some(payload_len as u64),
2729                 data: None,
2730             };
2731 
2732             let ev_data =
2733                 EventData::PacketReceived(qlog::events::quic::PacketReceived {
2734                     header: qlog_pkt_hdr,
2735                     frames: Some(qlog_frames),
2736                     is_coalesced: None,
2737                     retry_token: None,
2738                     stateless_reset_token: None,
2739                     supported_versions: None,
2740                     raw: Some(qlog_raw_info),
2741                     datagram_id: None,
2742                     trigger: None,
2743                 });
2744 
2745             q.add_event_data_with_instant(ev_data, now).ok();
2746         });
2747 
2748         qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
2749             let recv_path = self.paths.get_mut(recv_pid)?;
2750             if let Some(ev_data) = recv_path.recovery.maybe_qlog() {
2751                 q.add_event_data_with_instant(ev_data, now).ok();
2752             }
2753         });
2754 
2755         if let Some(e) = frame_processing_err {
2756             // Any frame error is terminal, so now just return.
2757             return Err(e);
2758         }
2759 
2760         // Only log the remote transport parameters once the connection is
2761         // established (i.e. after frames have been fully parsed) and only
2762         // once per connection.
2763         if self.is_established() {
2764             qlog_with_type!(QLOG_PARAMS_SET, self.qlog, q, {
2765                 if !self.qlog.logged_peer_params {
2766                     let ev_data = self
2767                         .peer_transport_params
2768                         .to_qlog(TransportOwner::Remote, self.handshake.cipher());
2769 
2770                     q.add_event_data_with_instant(ev_data, now).ok();
2771 
2772                     self.qlog.logged_peer_params = true;
2773                 }
2774             });
2775         }
2776 
2777         // Process acked frames. Note that several packets from several paths
2778         // might have been acked by the received packet.
2779         for (_, p) in self.paths.iter_mut() {
2780             for acked in p.recovery.acked[epoch].drain(..) {
2781                 match acked {
2782                     frame::Frame::ACK { ranges, .. } => {
2783                         // Stop acknowledging packets less than or equal to the
2784                         // largest acknowledged in the sent ACK frame that, in
2785                         // turn, got acked.
2786                         if let Some(largest_acked) = ranges.last() {
2787                             self.pkt_num_spaces[epoch]
2788                                 .recv_pkt_need_ack
2789                                 .remove_until(largest_acked);
2790                         }
2791                     },
2792 
2793                     frame::Frame::CryptoHeader { offset, length } => {
2794                         self.pkt_num_spaces[epoch]
2795                             .crypto_stream
2796                             .send
2797                             .ack_and_drop(offset, length);
2798                     },
2799 
2800                     frame::Frame::StreamHeader {
2801                         stream_id,
2802                         offset,
2803                         length,
2804                         ..
2805                     } => {
2806                         let stream = match self.streams.get_mut(stream_id) {
2807                             Some(v) => v,
2808 
2809                             None => continue,
2810                         };
2811 
2812                         stream.send.ack_and_drop(offset, length);
2813 
2814                         self.tx_buffered =
2815                             self.tx_buffered.saturating_sub(length);
2816 
2817                         qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
2818                             let ev_data = EventData::DataMoved(
2819                                 qlog::events::quic::DataMoved {
2820                                     stream_id: Some(stream_id),
2821                                     offset: Some(offset),
2822                                     length: Some(length as u64),
2823                                     from: Some(DataRecipient::Transport),
2824                                     to: Some(DataRecipient::Dropped),
2825                                     raw: None,
2826                                 },
2827                             );
2828 
2829                             q.add_event_data_with_instant(ev_data, now).ok();
2830                         });
2831 
2832                         // Only collect the stream if it is complete and not
2833                         // readable. If it is readable, it will get collected when
2834                         // stream_recv() is used.
2835                         if stream.is_complete() && !stream.is_readable() {
2836                             let local = stream.local;
2837                             self.streams.collect(stream_id, local);
2838                         }
2839                     },
2840 
2841                     frame::Frame::HandshakeDone => {
2842                         // Explicitly set this to true, so that if the frame was
2843                         // already scheduled for retransmission, it is aborted.
2844                         self.handshake_done_sent = true;
2845 
2846                         self.handshake_done_acked = true;
2847                     },
2848 
2849                     frame::Frame::ResetStream { stream_id, .. } => {
2850                         let stream = match self.streams.get_mut(stream_id) {
2851                             Some(v) => v,
2852 
2853                             None => continue,
2854                         };
2855 
2856                         // Only collect the stream if it is complete and not
2857                         // readable. If it is readable, it will get collected when
2858                         // stream_recv() is used.
2859                         if stream.is_complete() && !stream.is_readable() {
2860                             let local = stream.local;
2861                             self.streams.collect(stream_id, local);
2862                         }
2863                     },
2864 
2865                     _ => (),
2866                 }
2867             }
2868         }
2869 
2870         // Now that we processed all the frames, if there is a path that has no
2871         // Destination CID, try to allocate one.
2872         let no_dcid = self
2873             .paths
2874             .iter_mut()
2875             .filter(|(_, p)| p.active_dcid_seq.is_none());
2876 
2877         for (pid, p) in no_dcid {
2878             if self.ids.zero_length_dcid() {
2879                 p.active_dcid_seq = Some(0);
2880                 continue;
2881             }
2882 
2883             let dcid_seq = match self.ids.lowest_available_dcid_seq() {
2884                 Some(seq) => seq,
2885                 None => break,
2886             };
2887 
2888             self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
2889 
2890             p.active_dcid_seq = Some(dcid_seq);
2891         }
2892 
2893         // We only record the time of arrival of the largest packet number
2894         // that still needs to be acked, to be used for ACK delay calculation.
2895         if self.pkt_num_spaces[epoch].recv_pkt_need_ack.last() < Some(pn) {
2896             self.pkt_num_spaces[epoch].largest_rx_pkt_time = now;
2897         }
2898 
2899         self.pkt_num_spaces[epoch].recv_pkt_num.insert(pn);
2900 
2901         self.pkt_num_spaces[epoch].recv_pkt_need_ack.push_item(pn);
2902 
2903         self.pkt_num_spaces[epoch].ack_elicited =
2904             cmp::max(self.pkt_num_spaces[epoch].ack_elicited, ack_elicited);
2905 
2906         self.pkt_num_spaces[epoch].largest_rx_pkt_num =
2907             cmp::max(self.pkt_num_spaces[epoch].largest_rx_pkt_num, pn);
2908 
2909         if !probing {
2910             self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num = cmp::max(
2911                 self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num,
2912                 pn,
2913             );
2914 
2915             // Did the peer migrated to another path?
2916             let active_path_id = self.paths.get_active_path_id()?;
2917 
2918             if self.is_server &&
2919                 recv_pid != active_path_id &&
2920                 self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num == pn
2921             {
2922                 self.paths
2923                     .on_peer_migrated(recv_pid, self.disable_dcid_reuse)?;
2924             }
2925         }
2926 
2927         if let Some(idle_timeout) = self.idle_timeout() {
2928             self.idle_timer = Some(now + idle_timeout);
2929         }
2930 
2931         // Update send capacity.
2932         self.update_tx_cap();
2933 
2934         self.recv_count += 1;
2935         self.paths.get_mut(recv_pid)?.recv_count += 1;
2936 
2937         let read = b.off() + aead_tag_len;
2938 
2939         self.recv_bytes += read as u64;
2940         self.paths.get_mut(recv_pid)?.recv_bytes += read as u64;
2941 
2942         // An Handshake packet has been received from the client and has been
2943         // successfully processed, so we can drop the initial state and consider
2944         // the client's address to be verified.
2945         if self.is_server && hdr.ty == packet::Type::Handshake {
2946             self.drop_epoch_state(packet::Epoch::Initial, now);
2947 
2948             self.paths.get_mut(recv_pid)?.verified_peer_address = true;
2949         }
2950 
2951         self.ack_eliciting_sent = false;
2952 
2953         // Reset pacer and start a new burst when a valid
2954         // packet is received.
2955         self.paths.get_mut(recv_pid)?.recovery.pacer.reset(now);
2956 
2957         Ok(read)
2958     }
2959 
2960     /// Writes a single QUIC packet to be sent to the peer.
2961     ///
2962     /// On success the number of bytes written to the output buffer is
2963     /// returned, or [`Done`] if there was nothing to write.
2964     ///
2965     /// The application should call `send()` multiple times until [`Done`] is
2966     /// returned, indicating that there are no more packets to send. It is
2967     /// recommended that `send()` be called in the following cases:
2968     ///
2969     ///  * When the application receives QUIC packets from the peer (that is,
2970     ///    any time [`recv()`] is also called).
2971     ///
2972     ///  * When the connection timer expires (that is, any time [`on_timeout()`]
2973     ///    is also called).
2974     ///
2975     ///  * When the application sends data to the peer (for example, any time
2976     ///    [`stream_send()`] or [`stream_shutdown()`] are called).
2977     ///
2978     ///  * When the application receives data from the peer (for example any
2979     ///    time [`stream_recv()`] is called).
2980     ///
2981     /// Once [`is_draining()`] returns `true`, it is no longer necessary to call
2982     /// `send()` and all calls will return [`Done`].
2983     ///
2984     /// [`Done`]: enum.Error.html#variant.Done
2985     /// [`recv()`]: struct.Connection.html#method.recv
2986     /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
2987     /// [`stream_send()`]: struct.Connection.html#method.stream_send
2988     /// [`stream_shutdown()`]: struct.Connection.html#method.stream_shutdown
2989     /// [`stream_recv()`]: struct.Connection.html#method.stream_recv
2990     /// [`is_draining()`]: struct.Connection.html#method.is_draining
2991     ///
2992     /// ## Examples:
2993     ///
2994     /// ```no_run
2995     /// # let mut out = [0; 512];
2996     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
2997     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
2998     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
2999     /// # let peer = "127.0.0.1:1234".parse().unwrap();
3000     /// # let local = socket.local_addr().unwrap();
3001     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
3002     /// loop {
3003     ///     let (write, send_info) = match conn.send(&mut out) {
3004     ///         Ok(v) => v,
3005     ///
3006     ///         Err(quiche::Error::Done) => {
3007     ///             // Done writing.
3008     ///             break;
3009     ///         },
3010     ///
3011     ///         Err(e) => {
3012     ///             // An error occurred, handle it.
3013     ///             break;
3014     ///         },
3015     ///     };
3016     ///
3017     ///     socket.send_to(&out[..write], &send_info.to).unwrap();
3018     /// }
3019     /// # Ok::<(), quiche::Error>(())
3020     /// ```
send(&mut self, out: &mut [u8]) -> Result<(usize, SendInfo)>3021     pub fn send(&mut self, out: &mut [u8]) -> Result<(usize, SendInfo)> {
3022         self.send_on_path(out, None, None)
3023     }
3024 
3025     /// Writes a single QUIC packet to be sent to the peer from the specified
3026     /// local address `from` to the destination address `to`.
3027     ///
3028     /// The behavior of this method differs depending on the value of the `from`
3029     /// and `to` parameters:
3030     ///
3031     ///  * If both are `Some`, then the method only consider the 4-tuple
3032     ///    (`from`, `to`). Application can monitor the 4-tuple availability,
3033     ///    either by monitoring [`path_event_next()`] events or by relying on
3034     ///    the [`paths_iter()`] method. If the provided 4-tuple does not exist
3035     ///    on the connection (anymore), it returns an [`InvalidState`].
3036     ///
3037     ///  * If `from` is `Some` and `to` is `None`, then the method only
3038     ///    considers sending packets on paths having `from` as local address.
3039     ///
3040     ///  * If `to` is `Some` and `from` is `None`, then the method only
3041     ///    considers sending packets on paths having `to` as peer address.
3042     ///
3043     ///  * If both are `None`, all available paths are considered.
3044     ///
3045     /// On success the number of bytes written to the output buffer is
3046     /// returned, or [`Done`] if there was nothing to write.
3047     ///
3048     /// The application should call `send_on_path()` multiple times until
3049     /// [`Done`] is returned, indicating that there are no more packets to
3050     /// send. It is recommended that `send_on_path()` be called in the
3051     /// following cases:
3052     ///
3053     ///  * When the application receives QUIC packets from the peer (that is,
3054     ///    any time [`recv()`] is also called).
3055     ///
3056     ///  * When the connection timer expires (that is, any time [`on_timeout()`]
3057     ///    is also called).
3058     ///
3059     ///  * When the application sends data to the peer (for examples, any time
3060     ///    [`stream_send()`] or [`stream_shutdown()`] are called).
3061     ///
3062     ///  * When the application receives data from the peer (for example any
3063     ///    time [`stream_recv()`] is called).
3064     ///
3065     /// Once [`is_draining()`] returns `true`, it is no longer necessary to call
3066     /// `send_on_path()` and all calls will return [`Done`].
3067     ///
3068     /// [`Done`]: enum.Error.html#variant.Done
3069     /// [`InvalidState`]: enum.Error.html#InvalidState
3070     /// [`recv()`]: struct.Connection.html#method.recv
3071     /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
3072     /// [`stream_send()`]: struct.Connection.html#method.stream_send
3073     /// [`stream_shutdown()`]: struct.Connection.html#method.stream_shutdown
3074     /// [`stream_recv()`]: struct.Connection.html#method.stream_recv
3075     /// [`path_event_next()`]: struct.Connection.html#method.path_event_next
3076     /// [`paths_iter()`]: struct.Connection.html#method.paths_iter
3077     /// [`is_draining()`]: struct.Connection.html#method.is_draining
3078     ///
3079     /// ## Examples:
3080     ///
3081     /// ```no_run
3082     /// # let mut out = [0; 512];
3083     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
3084     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
3085     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
3086     /// # let peer = "127.0.0.1:1234".parse().unwrap();
3087     /// # let local = socket.local_addr().unwrap();
3088     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
3089     /// loop {
3090     ///     let (write, send_info) = match conn.send_on_path(&mut out, Some(local), Some(peer)) {
3091     ///         Ok(v) => v,
3092     ///
3093     ///         Err(quiche::Error::Done) => {
3094     ///             // Done writing.
3095     ///             break;
3096     ///         },
3097     ///
3098     ///         Err(e) => {
3099     ///             // An error occurred, handle it.
3100     ///             break;
3101     ///         },
3102     ///     };
3103     ///
3104     ///     socket.send_to(&out[..write], &send_info.to).unwrap();
3105     /// }
3106     /// # Ok::<(), quiche::Error>(())
3107     /// ```
send_on_path( &mut self, out: &mut [u8], from: Option<SocketAddr>, to: Option<SocketAddr>, ) -> Result<(usize, SendInfo)>3108     pub fn send_on_path(
3109         &mut self, out: &mut [u8], from: Option<SocketAddr>,
3110         to: Option<SocketAddr>,
3111     ) -> Result<(usize, SendInfo)> {
3112         if out.is_empty() {
3113             return Err(Error::BufferTooShort);
3114         }
3115 
3116         if self.is_closed() || self.is_draining() {
3117             return Err(Error::Done);
3118         }
3119 
3120         if self.local_error.is_none() {
3121             self.do_handshake(time::Instant::now())?;
3122         }
3123 
3124         // Forwarding the error value here could confuse
3125         // applications, as they may not expect getting a `recv()`
3126         // error when calling `send()`.
3127         //
3128         // We simply fall-through to sending packets, which should
3129         // take care of terminating the connection as needed.
3130         let _ = self.process_undecrypted_0rtt_packets();
3131 
3132         // There's no point in trying to send a packet if the Initial secrets
3133         // have not been derived yet, so return early.
3134         if !self.derived_initial_secrets {
3135             return Err(Error::Done);
3136         }
3137 
3138         let mut has_initial = false;
3139 
3140         let mut done = 0;
3141 
3142         // Limit output packet size to respect the sender and receiver's
3143         // maximum UDP payload size limit.
3144         let mut left = cmp::min(out.len(), self.max_send_udp_payload_size());
3145 
3146         let send_pid = match (from, to) {
3147             (Some(f), Some(t)) => self
3148                 .paths
3149                 .path_id_from_addrs(&(f, t))
3150                 .ok_or(Error::InvalidState)?,
3151 
3152             _ => self.get_send_path_id(from, to)?,
3153         };
3154 
3155         let send_path = self.paths.get_mut(send_pid)?;
3156 
3157         // Limit data sent by the server based on the amount of data received
3158         // from the client before its address is validated.
3159         if !send_path.verified_peer_address && self.is_server {
3160             left = cmp::min(left, send_path.max_send_bytes);
3161         }
3162 
3163         // Generate coalesced packets.
3164         while left > 0 {
3165             let (ty, written) = match self.send_single(
3166                 &mut out[done..done + left],
3167                 send_pid,
3168                 has_initial,
3169             ) {
3170                 Ok(v) => v,
3171 
3172                 Err(Error::BufferTooShort) | Err(Error::Done) => break,
3173 
3174                 Err(e) => return Err(e),
3175             };
3176 
3177             done += written;
3178             left -= written;
3179 
3180             match ty {
3181                 packet::Type::Initial => has_initial = true,
3182 
3183                 // No more packets can be coalesced after a 1-RTT.
3184                 packet::Type::Short => break,
3185 
3186                 _ => (),
3187             };
3188 
3189             // When sending multiple PTO probes, don't coalesce them together,
3190             // so they are sent on separate UDP datagrams.
3191             if let Ok(epoch) = ty.to_epoch() {
3192                 if self.paths.get_mut(send_pid)?.recovery.loss_probes[epoch] > 0 {
3193                     break;
3194                 }
3195             }
3196 
3197             // Don't coalesce packets that must go on different paths.
3198             if !(from.is_some() && to.is_some()) &&
3199                 self.get_send_path_id(from, to)? != send_pid
3200             {
3201                 break;
3202             }
3203         }
3204 
3205         if done == 0 {
3206             self.last_tx_data = self.tx_data;
3207 
3208             return Err(Error::Done);
3209         }
3210 
3211         // Pad UDP datagram if it contains a QUIC Initial packet.
3212         if has_initial && left > 0 && done < MIN_CLIENT_INITIAL_LEN {
3213             let pad_len = cmp::min(left, MIN_CLIENT_INITIAL_LEN - done);
3214 
3215             // Fill padding area with null bytes, to avoid leaking information
3216             // in case the application reuses the packet buffer.
3217             out[done..done + pad_len].fill(0);
3218 
3219             done += pad_len;
3220         }
3221 
3222         let send_path = self.paths.get(send_pid)?;
3223 
3224         let info = SendInfo {
3225             from: send_path.local_addr(),
3226             to: send_path.peer_addr(),
3227 
3228             at: send_path.recovery.get_packet_send_time(),
3229         };
3230 
3231         Ok((done, info))
3232     }
3233 
send_single( &mut self, out: &mut [u8], send_pid: usize, has_initial: bool, ) -> Result<(packet::Type, usize)>3234     fn send_single(
3235         &mut self, out: &mut [u8], send_pid: usize, has_initial: bool,
3236     ) -> Result<(packet::Type, usize)> {
3237         let now = time::Instant::now();
3238 
3239         if out.is_empty() {
3240             return Err(Error::BufferTooShort);
3241         }
3242 
3243         if self.is_draining() {
3244             return Err(Error::Done);
3245         }
3246 
3247         let is_closing = self.local_error.is_some();
3248 
3249         let mut b = octets::OctetsMut::with_slice(out);
3250 
3251         let pkt_type = self.write_pkt_type(send_pid)?;
3252 
3253         let max_dgram_len = self.dgram_max_writable_len();
3254 
3255         let epoch = pkt_type.to_epoch()?;
3256         let pkt_space = &mut self.pkt_num_spaces[epoch];
3257 
3258         // Process lost frames. There might be several paths having lost frames.
3259         for (_, p) in self.paths.iter_mut() {
3260             for lost in p.recovery.lost[epoch].drain(..) {
3261                 match lost {
3262                     frame::Frame::CryptoHeader { offset, length } => {
3263                         pkt_space.crypto_stream.send.retransmit(offset, length);
3264 
3265                         self.stream_retrans_bytes += length as u64;
3266                         p.stream_retrans_bytes += length as u64;
3267 
3268                         self.retrans_count += 1;
3269                         p.retrans_count += 1;
3270                     },
3271 
3272                     frame::Frame::StreamHeader {
3273                         stream_id,
3274                         offset,
3275                         length,
3276                         fin,
3277                     } => {
3278                         let stream = match self.streams.get_mut(stream_id) {
3279                             Some(v) => v,
3280 
3281                             None => continue,
3282                         };
3283 
3284                         let was_flushable = stream.is_flushable();
3285 
3286                         let empty_fin = length == 0 && fin;
3287 
3288                         stream.send.retransmit(offset, length);
3289 
3290                         // If the stream is now flushable push it to the
3291                         // flushable queue, but only if it wasn't already
3292                         // queued.
3293                         //
3294                         // Consider the stream flushable also when we are
3295                         // sending a zero-length frame that has the fin flag
3296                         // set.
3297                         if (stream.is_flushable() || empty_fin) && !was_flushable
3298                         {
3299                             let urgency = stream.urgency;
3300                             let incremental = stream.incremental;
3301                             self.streams.push_flushable(
3302                                 stream_id,
3303                                 urgency,
3304                                 incremental,
3305                             );
3306                         }
3307 
3308                         self.stream_retrans_bytes += length as u64;
3309                         p.stream_retrans_bytes += length as u64;
3310 
3311                         self.retrans_count += 1;
3312                         p.retrans_count += 1;
3313                     },
3314 
3315                     frame::Frame::ACK { .. } => {
3316                         pkt_space.ack_elicited = true;
3317                     },
3318 
3319                     frame::Frame::ResetStream {
3320                         stream_id,
3321                         error_code,
3322                         final_size,
3323                     } =>
3324                         if self.streams.get(stream_id).is_some() {
3325                             self.streams.mark_reset(
3326                                 stream_id, true, error_code, final_size,
3327                             );
3328                         },
3329 
3330                     // Retransmit HANDSHAKE_DONE only if it hasn't been acked at
3331                     // least once already.
3332                     frame::Frame::HandshakeDone if !self.handshake_done_acked => {
3333                         self.handshake_done_sent = false;
3334                     },
3335 
3336                     frame::Frame::MaxStreamData { stream_id, .. } => {
3337                         if self.streams.get(stream_id).is_some() {
3338                             self.streams.mark_almost_full(stream_id, true);
3339                         }
3340                     },
3341 
3342                     frame::Frame::MaxData { .. } => {
3343                         self.almost_full = true;
3344                     },
3345 
3346                     frame::Frame::NewConnectionId { seq_num, .. } => {
3347                         self.ids.mark_advertise_new_scid_seq(seq_num, true);
3348                     },
3349 
3350                     frame::Frame::RetireConnectionId { seq_num } => {
3351                         self.ids.mark_retire_dcid_seq(seq_num, true);
3352                     },
3353 
3354                     _ => (),
3355                 }
3356             }
3357         }
3358 
3359         let is_app_limited = self.delivery_rate_check_if_app_limited();
3360         let n_paths = self.paths.len();
3361         let path = self.paths.get_mut(send_pid)?;
3362         let flow_control = &mut self.flow_control;
3363         let pkt_space = &mut self.pkt_num_spaces[epoch];
3364 
3365         let mut left = b.cap();
3366 
3367         let pn = pkt_space.next_pkt_num;
3368         let pn_len = packet::pkt_num_len(pn)?;
3369 
3370         // The AEAD overhead at the current encryption level.
3371         let crypto_overhead = pkt_space.crypto_overhead().ok_or(Error::Done)?;
3372 
3373         let dcid_seq = path.active_dcid_seq.ok_or(Error::OutOfIdentifiers)?;
3374 
3375         let dcid =
3376             ConnectionId::from_ref(self.ids.get_dcid(dcid_seq)?.cid.as_ref());
3377 
3378         let scid = if let Some(scid_seq) = path.active_scid_seq {
3379             ConnectionId::from_ref(self.ids.get_scid(scid_seq)?.cid.as_ref())
3380         } else if pkt_type == packet::Type::Short {
3381             ConnectionId::default()
3382         } else {
3383             return Err(Error::InvalidState);
3384         };
3385 
3386         let hdr = Header {
3387             ty: pkt_type,
3388 
3389             version: self.version,
3390 
3391             dcid,
3392             scid,
3393 
3394             pkt_num: 0,
3395             pkt_num_len: pn_len,
3396 
3397             // Only clone token for Initial packets, as other packets don't have
3398             // this field (Retry doesn't count, as it's not encoded as part of
3399             // this code path).
3400             token: if pkt_type == packet::Type::Initial {
3401                 self.token.clone()
3402             } else {
3403                 None
3404             },
3405 
3406             versions: None,
3407             key_phase: self.key_phase,
3408         };
3409 
3410         hdr.to_bytes(&mut b)?;
3411 
3412         let hdr_trace = if log::max_level() == log::LevelFilter::Trace {
3413             Some(format!("{hdr:?}"))
3414         } else {
3415             None
3416         };
3417 
3418         let hdr_ty = hdr.ty;
3419 
3420         #[cfg(feature = "qlog")]
3421         let qlog_pkt_hdr = self.qlog.streamer.as_ref().map(|_q| {
3422             qlog::events::quic::PacketHeader::with_type(
3423                 hdr.ty.to_qlog(),
3424                 pn,
3425                 Some(hdr.version),
3426                 Some(&hdr.scid),
3427                 Some(&hdr.dcid),
3428             )
3429         });
3430 
3431         // Calculate the space required for the packet, including the header
3432         // the payload length, the packet number and the AEAD overhead.
3433         let mut overhead = b.off() + pn_len + crypto_overhead;
3434 
3435         // We assume that the payload length, which is only present in long
3436         // header packets, can always be encoded with a 2-byte varint.
3437         if pkt_type != packet::Type::Short {
3438             overhead += PAYLOAD_LENGTH_LEN;
3439         }
3440 
3441         // Make sure we have enough space left for the packet overhead.
3442         match left.checked_sub(overhead) {
3443             Some(v) => left = v,
3444 
3445             None => {
3446                 // We can't send more because there isn't enough space available
3447                 // in the output buffer.
3448                 //
3449                 // This usually happens when we try to send a new packet but
3450                 // failed because cwnd is almost full. In such case app_limited
3451                 // is set to false here to make cwnd grow when ACK is received.
3452                 path.recovery.update_app_limited(false);
3453                 return Err(Error::Done);
3454             },
3455         }
3456 
3457         // Make sure there is enough space for the minimum payload length.
3458         if left < PAYLOAD_MIN_LEN {
3459             path.recovery.update_app_limited(false);
3460             return Err(Error::Done);
3461         }
3462 
3463         let mut frames: SmallVec<[frame::Frame; 1]> = SmallVec::new();
3464 
3465         let mut ack_eliciting = false;
3466         let mut in_flight = false;
3467         let mut has_data = false;
3468 
3469         // Whether or not we should explicitly elicit an ACK via PING frame if we
3470         // implicitly elicit one otherwise.
3471         let ack_elicit_required = path.recovery.should_elicit_ack(epoch);
3472 
3473         let header_offset = b.off();
3474 
3475         // Reserve space for payload length in advance. Since we don't yet know
3476         // what the final length will be, we reserve 2 bytes in all cases.
3477         //
3478         // Only long header packets have an explicit length field.
3479         if pkt_type != packet::Type::Short {
3480             b.skip(PAYLOAD_LENGTH_LEN)?;
3481         }
3482 
3483         packet::encode_pkt_num(pn, &mut b)?;
3484 
3485         let payload_offset = b.off();
3486 
3487         let cwnd_available =
3488             path.recovery.cwnd_available().saturating_sub(overhead);
3489 
3490         let left_before_packing_ack_frame = left;
3491 
3492         // Create ACK frame.
3493         //
3494         // When we need to explicitly elicit an ACK via PING later, go ahead and
3495         // generate an ACK (if there's anything to ACK) since we're going to
3496         // send a packet with PING anyways, even if we haven't received anything
3497         // ACK eliciting.
3498         if pkt_space.recv_pkt_need_ack.len() > 0 &&
3499             (pkt_space.ack_elicited || ack_elicit_required) &&
3500             (!is_closing ||
3501                 (pkt_type == Type::Handshake &&
3502                     self.local_error
3503                         .as_ref()
3504                         .map_or(false, |le| le.is_app))) &&
3505             path.active()
3506         {
3507             let ack_delay = pkt_space.largest_rx_pkt_time.elapsed();
3508 
3509             let ack_delay = ack_delay.as_micros() as u64 /
3510                 2_u64
3511                     .pow(self.local_transport_params.ack_delay_exponent as u32);
3512 
3513             let frame = frame::Frame::ACK {
3514                 ack_delay,
3515                 ranges: pkt_space.recv_pkt_need_ack.clone(),
3516                 ecn_counts: None, // sending ECN is not supported at this time
3517             };
3518 
3519             // When a PING frame needs to be sent, avoid sending the ACK if
3520             // there is not enough cwnd available for both (note that PING
3521             // frames are always 1 byte, so we just need to check that the
3522             // ACK's length is lower than cwnd).
3523             if pkt_space.ack_elicited || frame.wire_len() < cwnd_available {
3524                 // ACK-only packets are not congestion controlled so ACKs must
3525                 // be bundled considering the buffer capacity only, and not the
3526                 // available cwnd.
3527                 if push_frame_to_pkt!(b, frames, frame, left) {
3528                     pkt_space.ack_elicited = false;
3529                 }
3530             }
3531         }
3532 
3533         // Limit output packet size by congestion window size.
3534         left = cmp::min(
3535             left,
3536             // Bytes consumed by ACK frames.
3537             cwnd_available.saturating_sub(left_before_packing_ack_frame - left),
3538         );
3539 
3540         let mut challenge_data = None;
3541 
3542         if pkt_type == packet::Type::Short {
3543             // Create PATH_RESPONSE frame if needed.
3544             // We do not try to ensure that these are really sent.
3545             while let Some(challenge) = path.pop_received_challenge() {
3546                 let frame = frame::Frame::PathResponse { data: challenge };
3547 
3548                 if push_frame_to_pkt!(b, frames, frame, left) {
3549                     ack_eliciting = true;
3550                     in_flight = true;
3551                 } else {
3552                     // If there are other pending PATH_RESPONSE, don't lose them
3553                     // now.
3554                     break;
3555                 }
3556             }
3557 
3558             // Create PATH_CHALLENGE frame if needed.
3559             if path.validation_requested() {
3560                 // TODO: ensure that data is unique over paths.
3561                 let data = rand::rand_u64().to_be_bytes();
3562 
3563                 let frame = frame::Frame::PathChallenge { data };
3564 
3565                 if push_frame_to_pkt!(b, frames, frame, left) {
3566                     // Let's notify the path once we know the packet size.
3567                     challenge_data = Some(data);
3568 
3569                     ack_eliciting = true;
3570                     in_flight = true;
3571                 }
3572             }
3573 
3574             if let Some(key_update) = pkt_space.key_update.as_mut() {
3575                 key_update.update_acked = true;
3576             }
3577         }
3578 
3579         if pkt_type == packet::Type::Short && !is_closing {
3580             // Create NEW_CONNECTION_ID frames as needed.
3581             while let Some(seq_num) = self.ids.next_advertise_new_scid_seq() {
3582                 let frame = self.ids.get_new_connection_id_frame_for(seq_num)?;
3583 
3584                 if push_frame_to_pkt!(b, frames, frame, left) {
3585                     self.ids.mark_advertise_new_scid_seq(seq_num, false);
3586 
3587                     ack_eliciting = true;
3588                     in_flight = true;
3589                 } else {
3590                     break;
3591                 }
3592             }
3593         }
3594 
3595         if pkt_type == packet::Type::Short && !is_closing && path.active() {
3596             // Create HANDSHAKE_DONE frame.
3597             // self.should_send_handshake_done() but without the need to borrow
3598             if self.handshake_completed &&
3599                 !self.handshake_done_sent &&
3600                 self.is_server
3601             {
3602                 let frame = frame::Frame::HandshakeDone;
3603 
3604                 if push_frame_to_pkt!(b, frames, frame, left) {
3605                     self.handshake_done_sent = true;
3606 
3607                     ack_eliciting = true;
3608                     in_flight = true;
3609                 }
3610             }
3611 
3612             // Create MAX_STREAMS_BIDI frame.
3613             if self.streams.should_update_max_streams_bidi() {
3614                 let frame = frame::Frame::MaxStreamsBidi {
3615                     max: self.streams.max_streams_bidi_next(),
3616                 };
3617 
3618                 if push_frame_to_pkt!(b, frames, frame, left) {
3619                     self.streams.update_max_streams_bidi();
3620 
3621                     ack_eliciting = true;
3622                     in_flight = true;
3623                 }
3624             }
3625 
3626             // Create MAX_STREAMS_UNI frame.
3627             if self.streams.should_update_max_streams_uni() {
3628                 let frame = frame::Frame::MaxStreamsUni {
3629                     max: self.streams.max_streams_uni_next(),
3630                 };
3631 
3632                 if push_frame_to_pkt!(b, frames, frame, left) {
3633                     self.streams.update_max_streams_uni();
3634 
3635                     ack_eliciting = true;
3636                     in_flight = true;
3637                 }
3638             }
3639 
3640             // Create DATA_BLOCKED frame.
3641             if let Some(limit) = self.blocked_limit {
3642                 let frame = frame::Frame::DataBlocked { limit };
3643 
3644                 if push_frame_to_pkt!(b, frames, frame, left) {
3645                     self.blocked_limit = None;
3646 
3647                     ack_eliciting = true;
3648                     in_flight = true;
3649                 }
3650             }
3651 
3652             // Create MAX_STREAM_DATA frames as needed.
3653             for stream_id in self.streams.almost_full() {
3654                 let stream = match self.streams.get_mut(stream_id) {
3655                     Some(v) => v,
3656 
3657                     None => {
3658                         // The stream doesn't exist anymore, so remove it from
3659                         // the almost full set.
3660                         self.streams.mark_almost_full(stream_id, false);
3661                         continue;
3662                     },
3663                 };
3664 
3665                 // Autotune the stream window size.
3666                 stream.recv.autotune_window(now, path.recovery.rtt());
3667 
3668                 let frame = frame::Frame::MaxStreamData {
3669                     stream_id,
3670                     max: stream.recv.max_data_next(),
3671                 };
3672 
3673                 if push_frame_to_pkt!(b, frames, frame, left) {
3674                     let recv_win = stream.recv.window();
3675 
3676                     stream.recv.update_max_data(now);
3677 
3678                     self.streams.mark_almost_full(stream_id, false);
3679 
3680                     ack_eliciting = true;
3681                     in_flight = true;
3682 
3683                     // Make sure the connection window always has some
3684                     // room compared to the stream window.
3685                     flow_control.ensure_window_lower_bound(
3686                         (recv_win as f64 * CONNECTION_WINDOW_FACTOR) as u64,
3687                     );
3688 
3689                     // Also send MAX_DATA when MAX_STREAM_DATA is sent, to avoid a
3690                     // potential race condition.
3691                     self.almost_full = true;
3692                 }
3693             }
3694 
3695             // Create MAX_DATA frame as needed.
3696             if self.almost_full &&
3697                 flow_control.max_data() < flow_control.max_data_next()
3698             {
3699                 // Autotune the connection window size.
3700                 flow_control.autotune_window(now, path.recovery.rtt());
3701 
3702                 let frame = frame::Frame::MaxData {
3703                     max: flow_control.max_data_next(),
3704                 };
3705 
3706                 if push_frame_to_pkt!(b, frames, frame, left) {
3707                     self.almost_full = false;
3708 
3709                     // Commits the new max_rx_data limit.
3710                     flow_control.update_max_data(now);
3711 
3712                     ack_eliciting = true;
3713                     in_flight = true;
3714                 }
3715             }
3716 
3717             // Create STOP_SENDING frames as needed.
3718             for (stream_id, error_code) in self
3719                 .streams
3720                 .stopped()
3721                 .map(|(&k, &v)| (k, v))
3722                 .collect::<Vec<(u64, u64)>>()
3723             {
3724                 let frame = frame::Frame::StopSending {
3725                     stream_id,
3726                     error_code,
3727                 };
3728 
3729                 if push_frame_to_pkt!(b, frames, frame, left) {
3730                     self.streams.mark_stopped(stream_id, false, 0);
3731 
3732                     ack_eliciting = true;
3733                     in_flight = true;
3734                 }
3735             }
3736 
3737             // Create RESET_STREAM frames as needed.
3738             for (stream_id, (error_code, final_size)) in self
3739                 .streams
3740                 .reset()
3741                 .map(|(&k, &v)| (k, v))
3742                 .collect::<Vec<(u64, (u64, u64))>>()
3743             {
3744                 let frame = frame::Frame::ResetStream {
3745                     stream_id,
3746                     error_code,
3747                     final_size,
3748                 };
3749 
3750                 if push_frame_to_pkt!(b, frames, frame, left) {
3751                     self.streams.mark_reset(stream_id, false, 0, 0);
3752 
3753                     ack_eliciting = true;
3754                     in_flight = true;
3755                 }
3756             }
3757 
3758             // Create STREAM_DATA_BLOCKED frames as needed.
3759             for (stream_id, limit) in self
3760                 .streams
3761                 .blocked()
3762                 .map(|(&k, &v)| (k, v))
3763                 .collect::<Vec<(u64, u64)>>()
3764             {
3765                 let frame = frame::Frame::StreamDataBlocked { stream_id, limit };
3766 
3767                 if push_frame_to_pkt!(b, frames, frame, left) {
3768                     self.streams.mark_blocked(stream_id, false, 0);
3769 
3770                     ack_eliciting = true;
3771                     in_flight = true;
3772                 }
3773             }
3774 
3775             // Create RETIRE_CONNECTION_ID frames as needed.
3776             while let Some(seq_num) = self.ids.next_retire_dcid_seq() {
3777                 // The sequence number specified in a RETIRE_CONNECTION_ID frame
3778                 // MUST NOT refer to the Destination Connection ID field of the
3779                 // packet in which the frame is contained.
3780                 let dcid_seq = path.active_dcid_seq.ok_or(Error::InvalidState)?;
3781 
3782                 if seq_num == dcid_seq {
3783                     continue;
3784                 }
3785 
3786                 let frame = frame::Frame::RetireConnectionId { seq_num };
3787 
3788                 if push_frame_to_pkt!(b, frames, frame, left) {
3789                     self.ids.mark_retire_dcid_seq(seq_num, false);
3790 
3791                     ack_eliciting = true;
3792                     in_flight = true;
3793                 } else {
3794                     break;
3795                 }
3796             }
3797         }
3798 
3799         // Create CONNECTION_CLOSE frame. Try to send this only on the active
3800         // path, unless it is the last one available.
3801         if path.active() || n_paths == 1 {
3802             if let Some(conn_err) = self.local_error.as_ref() {
3803                 if conn_err.is_app {
3804                     // Create ApplicationClose frame.
3805                     if pkt_type == packet::Type::Short {
3806                         let frame = frame::Frame::ApplicationClose {
3807                             error_code: conn_err.error_code,
3808                             reason: conn_err.reason.clone(),
3809                         };
3810 
3811                         if push_frame_to_pkt!(b, frames, frame, left) {
3812                             let pto = path.recovery.pto();
3813                             self.draining_timer = Some(now + (pto * 3));
3814 
3815                             ack_eliciting = true;
3816                             in_flight = true;
3817                         }
3818                     }
3819                 } else {
3820                     // Create ConnectionClose frame.
3821                     let frame = frame::Frame::ConnectionClose {
3822                         error_code: conn_err.error_code,
3823                         frame_type: 0,
3824                         reason: conn_err.reason.clone(),
3825                     };
3826 
3827                     if push_frame_to_pkt!(b, frames, frame, left) {
3828                         let pto = path.recovery.pto();
3829                         self.draining_timer = Some(now + (pto * 3));
3830 
3831                         ack_eliciting = true;
3832                         in_flight = true;
3833                     }
3834                 }
3835             }
3836         }
3837 
3838         // Create CRYPTO frame.
3839         if pkt_space.crypto_stream.is_flushable() &&
3840             left > frame::MAX_CRYPTO_OVERHEAD &&
3841             !is_closing &&
3842             path.active()
3843         {
3844             let crypto_off = pkt_space.crypto_stream.send.off_front();
3845 
3846             // Encode the frame.
3847             //
3848             // Instead of creating a `frame::Frame` object, encode the frame
3849             // directly into the packet buffer.
3850             //
3851             // First we reserve some space in the output buffer for writing the
3852             // frame header (we assume the length field is always a 2-byte
3853             // varint as we don't know the value yet).
3854             //
3855             // Then we emit the data from the crypto stream's send buffer.
3856             //
3857             // Finally we go back and encode the frame header with the now
3858             // available information.
3859             let hdr_off = b.off();
3860             let hdr_len = 1 + // frame type
3861                 octets::varint_len(crypto_off) + // offset
3862                 2; // length, always encode as 2-byte varint
3863 
3864             if let Some(max_len) = left.checked_sub(hdr_len) {
3865                 let (mut crypto_hdr, mut crypto_payload) =
3866                     b.split_at(hdr_off + hdr_len)?;
3867 
3868                 // Write stream data into the packet buffer.
3869                 let (len, _) = pkt_space
3870                     .crypto_stream
3871                     .send
3872                     .emit(&mut crypto_payload.as_mut()[..max_len])?;
3873 
3874                 // Encode the frame's header.
3875                 //
3876                 // Due to how `OctetsMut::split_at()` works, `crypto_hdr` starts
3877                 // from the initial offset of `b` (rather than the current
3878                 // offset), so it needs to be advanced to the
3879                 // initial frame offset.
3880                 crypto_hdr.skip(hdr_off)?;
3881 
3882                 frame::encode_crypto_header(
3883                     crypto_off,
3884                     len as u64,
3885                     &mut crypto_hdr,
3886                 )?;
3887 
3888                 // Advance the packet buffer's offset.
3889                 b.skip(hdr_len + len)?;
3890 
3891                 let frame = frame::Frame::CryptoHeader {
3892                     offset: crypto_off,
3893                     length: len,
3894                 };
3895 
3896                 if push_frame_to_pkt!(b, frames, frame, left) {
3897                     ack_eliciting = true;
3898                     in_flight = true;
3899                     has_data = true;
3900                 }
3901             }
3902         }
3903 
3904         // The preference of data-bearing frame to include in a packet
3905         // is managed by `self.emit_dgram`. However, whether any frames
3906         // can be sent depends on the state of their buffers. In the case
3907         // where one type is preferred but its buffer is empty, fall back
3908         // to the other type in order not to waste this function call.
3909         let mut dgram_emitted = false;
3910         let dgrams_to_emit = max_dgram_len.is_some();
3911         let stream_to_emit = self.streams.has_flushable();
3912 
3913         let mut do_dgram = self.emit_dgram && dgrams_to_emit;
3914         let do_stream = !self.emit_dgram && stream_to_emit;
3915 
3916         if !do_stream && dgrams_to_emit {
3917             do_dgram = true;
3918         }
3919 
3920         // Create DATAGRAM frame.
3921         if (pkt_type == packet::Type::Short || pkt_type == packet::Type::ZeroRTT) &&
3922             left > frame::MAX_DGRAM_OVERHEAD &&
3923             !is_closing &&
3924             path.active() &&
3925             do_dgram
3926         {
3927             if let Some(max_dgram_payload) = max_dgram_len {
3928                 while let Some(len) = self.dgram_send_queue.peek_front_len() {
3929                     let hdr_off = b.off();
3930                     let hdr_len = 1 + // frame type
3931                         2; // length, always encode as 2-byte varint
3932 
3933                     if (hdr_len + len) <= left {
3934                         // Front of the queue fits this packet, send it.
3935                         match self.dgram_send_queue.pop() {
3936                             Some(data) => {
3937                                 // Encode the frame.
3938                                 //
3939                                 // Instead of creating a `frame::Frame` object,
3940                                 // encode the frame directly into the packet
3941                                 // buffer.
3942                                 //
3943                                 // First we reserve some space in the output
3944                                 // buffer for writing the frame header (we
3945                                 // assume the length field is always a 2-byte
3946                                 // varint as we don't know the value yet).
3947                                 //
3948                                 // Then we emit the data from the DATAGRAM's
3949                                 // buffer.
3950                                 //
3951                                 // Finally we go back and encode the frame
3952                                 // header with the now available information.
3953                                 let (mut dgram_hdr, mut dgram_payload) =
3954                                     b.split_at(hdr_off + hdr_len)?;
3955 
3956                                 dgram_payload.as_mut()[..len]
3957                                     .copy_from_slice(&data);
3958 
3959                                 // Encode the frame's header.
3960                                 //
3961                                 // Due to how `OctetsMut::split_at()` works,
3962                                 // `dgram_hdr` starts from the initial offset
3963                                 // of `b` (rather than the current offset), so
3964                                 // it needs to be advanced to the initial frame
3965                                 // offset.
3966                                 dgram_hdr.skip(hdr_off)?;
3967 
3968                                 frame::encode_dgram_header(
3969                                     len as u64,
3970                                     &mut dgram_hdr,
3971                                 )?;
3972 
3973                                 // Advance the packet buffer's offset.
3974                                 b.skip(hdr_len + len)?;
3975 
3976                                 let frame =
3977                                     frame::Frame::DatagramHeader { length: len };
3978 
3979                                 if push_frame_to_pkt!(b, frames, frame, left) {
3980                                     ack_eliciting = true;
3981                                     in_flight = true;
3982                                     dgram_emitted = true;
3983                                 }
3984                             },
3985 
3986                             None => continue,
3987                         };
3988                     } else if len > max_dgram_payload {
3989                         // This dgram frame will never fit. Let's purge it.
3990                         self.dgram_send_queue.pop();
3991                     } else {
3992                         break;
3993                     }
3994                 }
3995             }
3996         }
3997 
3998         // Create a single STREAM frame for the first stream that is flushable.
3999         if (pkt_type == packet::Type::Short || pkt_type == packet::Type::ZeroRTT) &&
4000             left > frame::MAX_STREAM_OVERHEAD &&
4001             !is_closing &&
4002             path.active() &&
4003             !dgram_emitted
4004         {
4005             while let Some(stream_id) = self.streams.peek_flushable() {
4006                 let stream = match self.streams.get_mut(stream_id) {
4007                     // Avoid sending frames for streams that were already stopped.
4008                     //
4009                     // This might happen if stream data was buffered but not yet
4010                     // flushed on the wire when a STOP_SENDING frame is received.
4011                     Some(v) if !v.send.is_stopped() => v,
4012                     _ => {
4013                         self.streams.remove_flushable();
4014                         continue;
4015                     },
4016                 };
4017 
4018                 let stream_off = stream.send.off_front();
4019 
4020                 // Encode the frame.
4021                 //
4022                 // Instead of creating a `frame::Frame` object, encode the frame
4023                 // directly into the packet buffer.
4024                 //
4025                 // First we reserve some space in the output buffer for writing
4026                 // the frame header (we assume the length field is always a
4027                 // 2-byte varint as we don't know the value yet).
4028                 //
4029                 // Then we emit the data from the stream's send buffer.
4030                 //
4031                 // Finally we go back and encode the frame header with the now
4032                 // available information.
4033                 let hdr_off = b.off();
4034                 let hdr_len = 1 + // frame type
4035                     octets::varint_len(stream_id) + // stream_id
4036                     octets::varint_len(stream_off) + // offset
4037                     2; // length, always encode as 2-byte varint
4038 
4039                 let max_len = match left.checked_sub(hdr_len) {
4040                     Some(v) => v,
4041                     None => {
4042                         self.streams.remove_flushable();
4043                         continue;
4044                     },
4045                 };
4046 
4047                 let (mut stream_hdr, mut stream_payload) =
4048                     b.split_at(hdr_off + hdr_len)?;
4049 
4050                 // Write stream data into the packet buffer.
4051                 let (len, fin) =
4052                     stream.send.emit(&mut stream_payload.as_mut()[..max_len])?;
4053 
4054                 // Encode the frame's header.
4055                 //
4056                 // Due to how `OctetsMut::split_at()` works, `stream_hdr` starts
4057                 // from the initial offset of `b` (rather than the current
4058                 // offset), so it needs to be advanced to the initial frame
4059                 // offset.
4060                 stream_hdr.skip(hdr_off)?;
4061 
4062                 frame::encode_stream_header(
4063                     stream_id,
4064                     stream_off,
4065                     len as u64,
4066                     fin,
4067                     &mut stream_hdr,
4068                 )?;
4069 
4070                 // Advance the packet buffer's offset.
4071                 b.skip(hdr_len + len)?;
4072 
4073                 let frame = frame::Frame::StreamHeader {
4074                     stream_id,
4075                     offset: stream_off,
4076                     length: len,
4077                     fin,
4078                 };
4079 
4080                 if push_frame_to_pkt!(b, frames, frame, left) {
4081                     ack_eliciting = true;
4082                     in_flight = true;
4083                     has_data = true;
4084                 }
4085 
4086                 // If the stream is no longer flushable, remove it from the queue
4087                 if !stream.is_flushable() {
4088                     self.streams.remove_flushable();
4089                 }
4090 
4091                 break;
4092             }
4093         }
4094 
4095         // Alternate trying to send DATAGRAMs next time.
4096         self.emit_dgram = !dgram_emitted;
4097 
4098         // If no other ack-eliciting frame is sent, include a PING frame
4099         // - if PTO probe needed; OR
4100         // - if we've sent too many non ack-eliciting packets without having
4101         // sent an ACK eliciting one; OR
4102         // - the application requested an ack-eliciting frame be sent.
4103         if (ack_elicit_required || path.needs_ack_eliciting) &&
4104             !ack_eliciting &&
4105             left >= 1 &&
4106             !is_closing
4107         {
4108             let frame = frame::Frame::Ping;
4109 
4110             if push_frame_to_pkt!(b, frames, frame, left) {
4111                 ack_eliciting = true;
4112                 in_flight = true;
4113             }
4114         }
4115 
4116         if ack_eliciting {
4117             path.needs_ack_eliciting = false;
4118             path.recovery.loss_probes[epoch] =
4119                 path.recovery.loss_probes[epoch].saturating_sub(1);
4120         }
4121 
4122         if frames.is_empty() {
4123             // When we reach this point we are not able to write more, so set
4124             // app_limited to false.
4125             path.recovery.update_app_limited(false);
4126             return Err(Error::Done);
4127         }
4128 
4129         // When coalescing a 1-RTT packet, we can't add padding in the UDP
4130         // datagram, so use PADDING frames instead.
4131         //
4132         // This is only needed if
4133         // 1) an Initial packet has already been written to the UDP datagram,
4134         // as Initial always requires padding.
4135         //
4136         // 2) this is a probing packet towards an unvalidated peer address.
4137         if (has_initial || !path.validated()) &&
4138             pkt_type == packet::Type::Short &&
4139             left >= 1
4140         {
4141             let frame = frame::Frame::Padding { len: left };
4142 
4143             if push_frame_to_pkt!(b, frames, frame, left) {
4144                 in_flight = true;
4145             }
4146         }
4147 
4148         // Pad payload so that it's always at least 4 bytes.
4149         if b.off() - payload_offset < PAYLOAD_MIN_LEN {
4150             let payload_len = b.off() - payload_offset;
4151 
4152             let frame = frame::Frame::Padding {
4153                 len: PAYLOAD_MIN_LEN - payload_len,
4154             };
4155 
4156             #[allow(unused_assignments)]
4157             if push_frame_to_pkt!(b, frames, frame, left) {
4158                 in_flight = true;
4159             }
4160         }
4161 
4162         let payload_len = b.off() - payload_offset;
4163 
4164         // Fill in payload length.
4165         if pkt_type != packet::Type::Short {
4166             let len = pn_len + payload_len + crypto_overhead;
4167 
4168             let (_, mut payload_with_len) = b.split_at(header_offset)?;
4169             payload_with_len
4170                 .put_varint_with_len(len as u64, PAYLOAD_LENGTH_LEN)?;
4171         }
4172 
4173         trace!(
4174             "{} tx pkt {} len={} pn={} {}",
4175             self.trace_id,
4176             hdr_trace.unwrap_or_default(),
4177             payload_len,
4178             pn,
4179             AddrTupleFmt(path.local_addr(), path.peer_addr())
4180         );
4181 
4182         #[cfg(feature = "qlog")]
4183         let mut qlog_frames: SmallVec<
4184             [qlog::events::quic::QuicFrame; 1],
4185         > = SmallVec::with_capacity(frames.len());
4186 
4187         for frame in &mut frames {
4188             trace!("{} tx frm {:?}", self.trace_id, frame);
4189 
4190             qlog_with_type!(QLOG_PACKET_TX, self.qlog, _q, {
4191                 qlog_frames.push(frame.to_qlog());
4192             });
4193         }
4194 
4195         qlog_with_type!(QLOG_PACKET_TX, self.qlog, q, {
4196             if let Some(header) = qlog_pkt_hdr {
4197                 // Qlog packet raw info described at
4198                 // https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-main-schema-00#section-5.1
4199                 //
4200                 // `length` includes packet headers and trailers (AEAD tag).
4201                 let length = payload_len + payload_offset + crypto_overhead;
4202                 let qlog_raw_info = RawInfo {
4203                     length: Some(length as u64),
4204                     payload_length: Some(payload_len as u64),
4205                     data: None,
4206                 };
4207 
4208                 let send_at_time =
4209                     now.duration_since(q.start_time()).as_secs_f32() * 1000.0;
4210 
4211                 let ev_data =
4212                     EventData::PacketSent(qlog::events::quic::PacketSent {
4213                         header,
4214                         frames: Some(qlog_frames),
4215                         is_coalesced: None,
4216                         retry_token: None,
4217                         stateless_reset_token: None,
4218                         supported_versions: None,
4219                         raw: Some(qlog_raw_info),
4220                         datagram_id: None,
4221                         send_at_time: Some(send_at_time),
4222                         trigger: None,
4223                     });
4224 
4225                 q.add_event_data_with_instant(ev_data, now).ok();
4226             }
4227         });
4228 
4229         let aead = match pkt_space.crypto_seal {
4230             Some(ref v) => v,
4231             None => return Err(Error::InvalidState),
4232         };
4233 
4234         let written = packet::encrypt_pkt(
4235             &mut b,
4236             pn,
4237             pn_len,
4238             payload_len,
4239             payload_offset,
4240             None,
4241             aead,
4242         )?;
4243 
4244         let sent_pkt = recovery::Sent {
4245             pkt_num: pn,
4246             frames,
4247             time_sent: now,
4248             time_acked: None,
4249             time_lost: None,
4250             size: if ack_eliciting { written } else { 0 },
4251             ack_eliciting,
4252             in_flight,
4253             delivered: 0,
4254             delivered_time: now,
4255             first_sent_time: now,
4256             is_app_limited: false,
4257             has_data,
4258         };
4259 
4260         if in_flight && is_app_limited {
4261             path.recovery.delivery_rate_update_app_limited(true);
4262         }
4263 
4264         pkt_space.next_pkt_num += 1;
4265 
4266         let handshake_status = recovery::HandshakeStatus {
4267             has_handshake_keys: self.pkt_num_spaces[packet::Epoch::Handshake]
4268                 .has_keys(),
4269             peer_verified_address: self.peer_verified_initial_address,
4270             completed: self.handshake_completed,
4271         };
4272 
4273         path.recovery.on_packet_sent(
4274             sent_pkt,
4275             epoch,
4276             handshake_status,
4277             now,
4278             &self.trace_id,
4279         );
4280 
4281         qlog_with_type!(QLOG_METRICS, self.qlog, q, {
4282             if let Some(ev_data) = path.recovery.maybe_qlog() {
4283                 q.add_event_data_with_instant(ev_data, now).ok();
4284             }
4285         });
4286 
4287         // Record sent packet size if we probe the path.
4288         if let Some(data) = challenge_data {
4289             path.add_challenge_sent(data, written, now);
4290         }
4291 
4292         self.sent_count += 1;
4293         self.sent_bytes += written as u64;
4294         path.sent_count += 1;
4295         path.sent_bytes += written as u64;
4296 
4297         if self.dgram_send_queue.byte_size() > path.recovery.cwnd_available() {
4298             path.recovery.update_app_limited(false);
4299         }
4300 
4301         path.max_send_bytes = path.max_send_bytes.saturating_sub(written);
4302 
4303         // On the client, drop initial state after sending an Handshake packet.
4304         if !self.is_server && hdr_ty == packet::Type::Handshake {
4305             self.drop_epoch_state(packet::Epoch::Initial, now);
4306         }
4307 
4308         // (Re)start the idle timer if we are sending the first ack-eliciting
4309         // packet since last receiving a packet.
4310         if ack_eliciting && !self.ack_eliciting_sent {
4311             if let Some(idle_timeout) = self.idle_timeout() {
4312                 self.idle_timer = Some(now + idle_timeout);
4313             }
4314         }
4315 
4316         if ack_eliciting {
4317             self.ack_eliciting_sent = true;
4318         }
4319 
4320         Ok((pkt_type, written))
4321     }
4322 
4323     /// Returns the size of the send quantum, in bytes.
4324     ///
4325     /// This represents the maximum size of a packet burst as determined by the
4326     /// congestion control algorithm in use.
4327     ///
4328     /// Applications can, for example, use it in conjunction with segmentation
4329     /// offloading mechanisms as the maximum limit for outgoing aggregates of
4330     /// multiple packets.
4331     #[inline]
send_quantum(&self) -> usize4332     pub fn send_quantum(&self) -> usize {
4333         match self.paths.get_active() {
4334             Ok(p) => p.recovery.send_quantum(),
4335             _ => 0,
4336         }
4337     }
4338 
4339     /// Returns the size of the send quantum over the given 4-tuple, in bytes.
4340     ///
4341     /// This represents the maximum size of a packet burst as determined by the
4342     /// congestion control algorithm in use.
4343     ///
4344     /// Applications can, for example, use it in conjunction with segmentation
4345     /// offloading mechanisms as the maximum limit for outgoing aggregates of
4346     /// multiple packets.
4347     ///
4348     /// If the (`local_addr`, peer_addr`) 4-tuple relates to a non-existing
4349     /// path, this method returns 0.
send_quantum_on_path( &self, local_addr: SocketAddr, peer_addr: SocketAddr, ) -> usize4350     pub fn send_quantum_on_path(
4351         &self, local_addr: SocketAddr, peer_addr: SocketAddr,
4352     ) -> usize {
4353         self.paths
4354             .path_id_from_addrs(&(local_addr, peer_addr))
4355             .and_then(|pid| self.paths.get(pid).ok())
4356             .map(|path| path.recovery.send_quantum())
4357             .unwrap_or(0)
4358     }
4359 
4360     /// Reads contiguous data from a stream into the provided slice.
4361     ///
4362     /// The slice must be sized by the caller and will be populated up to its
4363     /// capacity.
4364     ///
4365     /// On success the amount of bytes read and a flag indicating the fin state
4366     /// is returned as a tuple, or [`Done`] if there is no data to read.
4367     ///
4368     /// Reading data from a stream may trigger queueing of control messages
4369     /// (e.g. MAX_STREAM_DATA). [`send()`] should be called after reading.
4370     ///
4371     /// [`Done`]: enum.Error.html#variant.Done
4372     /// [`send()`]: struct.Connection.html#method.send
4373     ///
4374     /// ## Examples:
4375     ///
4376     /// ```no_run
4377     /// # let mut buf = [0; 512];
4378     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
4379     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
4380     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
4381     /// # let peer = "127.0.0.1:1234".parse().unwrap();
4382     /// # let local = socket.local_addr().unwrap();
4383     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
4384     /// # let stream_id = 0;
4385     /// while let Ok((read, fin)) = conn.stream_recv(stream_id, &mut buf) {
4386     ///     println!("Got {} bytes on stream {}", read, stream_id);
4387     /// }
4388     /// # Ok::<(), quiche::Error>(())
4389     /// ```
stream_recv( &mut self, stream_id: u64, out: &mut [u8], ) -> Result<(usize, bool)>4390     pub fn stream_recv(
4391         &mut self, stream_id: u64, out: &mut [u8],
4392     ) -> Result<(usize, bool)> {
4393         // We can't read on our own unidirectional streams.
4394         if !stream::is_bidi(stream_id) &&
4395             stream::is_local(stream_id, self.is_server)
4396         {
4397             return Err(Error::InvalidStreamState(stream_id));
4398         }
4399 
4400         let stream = self
4401             .streams
4402             .get_mut(stream_id)
4403             .ok_or(Error::InvalidStreamState(stream_id))?;
4404 
4405         if !stream.is_readable() {
4406             return Err(Error::Done);
4407         }
4408 
4409         let local = stream.local;
4410 
4411         #[cfg(feature = "qlog")]
4412         let offset = stream.recv.off_front();
4413 
4414         let (read, fin) = match stream.recv.emit(out) {
4415             Ok(v) => v,
4416 
4417             Err(e) => {
4418                 // Collect the stream if it is now complete. This can happen if
4419                 // we got a `StreamReset` error which will now be propagated to
4420                 // the application, so we don't need to keep the stream's state
4421                 // anymore.
4422                 if stream.is_complete() {
4423                     self.streams.collect(stream_id, local);
4424                 }
4425 
4426                 self.streams.mark_readable(stream_id, false);
4427                 return Err(e);
4428             },
4429         };
4430 
4431         self.flow_control.add_consumed(read as u64);
4432 
4433         let readable = stream.is_readable();
4434 
4435         let complete = stream.is_complete();
4436 
4437         if stream.recv.almost_full() {
4438             self.streams.mark_almost_full(stream_id, true);
4439         }
4440 
4441         if !readable {
4442             self.streams.mark_readable(stream_id, false);
4443         }
4444 
4445         if complete {
4446             self.streams.collect(stream_id, local);
4447         }
4448 
4449         qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
4450             let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved {
4451                 stream_id: Some(stream_id),
4452                 offset: Some(offset),
4453                 length: Some(read as u64),
4454                 from: Some(DataRecipient::Transport),
4455                 to: Some(DataRecipient::Application),
4456                 raw: None,
4457             });
4458 
4459             let now = time::Instant::now();
4460             q.add_event_data_with_instant(ev_data, now).ok();
4461         });
4462 
4463         if self.should_update_max_data() {
4464             self.almost_full = true;
4465         }
4466 
4467         Ok((read, fin))
4468     }
4469 
4470     /// Writes data to a stream.
4471     ///
4472     /// On success the number of bytes written is returned, or [`Done`] if no
4473     /// data was written (e.g. because the stream has no capacity).
4474     ///
4475     /// Applications can provide a 0-length buffer with the fin flag set to
4476     /// true. This will lead to a 0-length FIN STREAM frame being sent at the
4477     /// latest offset. The `Ok(0)` value is only returned when the application
4478     /// provided a 0-length buffer.
4479     ///
4480     /// In addition, if the peer has signalled that it doesn't want to receive
4481     /// any more data from this stream by sending the `STOP_SENDING` frame, the
4482     /// [`StreamStopped`] error will be returned instead of any data.
4483     ///
4484     /// Note that in order to avoid buffering an infinite amount of data in the
4485     /// stream's send buffer, streams are only allowed to buffer outgoing data
4486     /// up to the amount that the peer allows it to send (that is, up to the
4487     /// stream's outgoing flow control capacity).
4488     ///
4489     /// This means that the number of written bytes returned can be lower than
4490     /// the length of the input buffer when the stream doesn't have enough
4491     /// capacity for the operation to complete. The application should retry the
4492     /// operation once the stream is reported as writable again.
4493     ///
4494     /// Applications should call this method only after the handshake is
4495     /// completed (whenever [`is_established()`] returns `true`) or during
4496     /// early data if enabled (whenever [`is_in_early_data()`] returns `true`).
4497     ///
4498     /// [`Done`]: enum.Error.html#variant.Done
4499     /// [`StreamStopped`]: enum.Error.html#variant.StreamStopped
4500     /// [`is_established()`]: struct.Connection.html#method.is_established
4501     /// [`is_in_early_data()`]: struct.Connection.html#method.is_in_early_data
4502     ///
4503     /// ## Examples:
4504     ///
4505     /// ```no_run
4506     /// # let mut buf = [0; 512];
4507     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
4508     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
4509     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
4510     /// # let peer = "127.0.0.1:1234".parse().unwrap();
4511     /// # let local = "127.0.0.1:4321".parse().unwrap();
4512     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
4513     /// # let stream_id = 0;
4514     /// conn.stream_send(stream_id, b"hello", true)?;
4515     /// # Ok::<(), quiche::Error>(())
4516     /// ```
stream_send( &mut self, stream_id: u64, buf: &[u8], fin: bool, ) -> Result<usize>4517     pub fn stream_send(
4518         &mut self, stream_id: u64, buf: &[u8], fin: bool,
4519     ) -> Result<usize> {
4520         // We can't write on the peer's unidirectional streams.
4521         if !stream::is_bidi(stream_id) &&
4522             !stream::is_local(stream_id, self.is_server)
4523         {
4524             return Err(Error::InvalidStreamState(stream_id));
4525         }
4526 
4527         // Mark the connection as blocked if the connection-level flow control
4528         // limit doesn't let us buffer all the data.
4529         //
4530         // Note that this is separate from "send capacity" as that also takes
4531         // congestion control into consideration.
4532         if self.max_tx_data - self.tx_data < buf.len() as u64 {
4533             self.blocked_limit = Some(self.max_tx_data);
4534         }
4535 
4536         let cap = self.tx_cap;
4537 
4538         // Get existing stream or create a new one.
4539         let stream = self.get_or_create_stream(stream_id, true)?;
4540 
4541         #[cfg(feature = "qlog")]
4542         let offset = stream.send.off_back();
4543 
4544         let was_writable = stream.is_writable();
4545 
4546         let was_flushable = stream.is_flushable();
4547 
4548         // Truncate the input buffer based on the connection's send capacity if
4549         // necessary.
4550         //
4551         // When the cap is zero, the method returns Ok(0) *only* when the passed
4552         // buffer is empty. We return Error::Done otherwise.
4553         if cap == 0 && !buf.is_empty() {
4554             if was_writable {
4555                 // When `stream_writable_next()` returns a stream, the writable
4556                 // mark is removed, but because the stream is blocked by the
4557                 // connection-level send capacity it won't be marked as writable
4558                 // again once the capacity increases.
4559                 //
4560                 // Since the stream is writable already, mark it here instead.
4561                 self.streams.mark_writable(stream_id, true);
4562             }
4563 
4564             return Err(Error::Done);
4565         }
4566 
4567         let (buf, fin, blocked_by_cap) = if cap < buf.len() {
4568             (&buf[..cap], false, true)
4569         } else {
4570             (buf, fin, false)
4571         };
4572 
4573         let sent = match stream.send.write(buf, fin) {
4574             Ok(v) => v,
4575 
4576             Err(e) => {
4577                 self.streams.mark_writable(stream_id, false);
4578                 return Err(e);
4579             },
4580         };
4581 
4582         let urgency = stream.urgency;
4583         let incremental = stream.incremental;
4584 
4585         let flushable = stream.is_flushable();
4586 
4587         let writable = stream.is_writable();
4588 
4589         let empty_fin = buf.is_empty() && fin;
4590 
4591         if sent < buf.len() {
4592             let max_off = stream.send.max_off();
4593 
4594             if stream.send.blocked_at() != Some(max_off) {
4595                 stream.send.update_blocked_at(Some(max_off));
4596                 self.streams.mark_blocked(stream_id, true, max_off);
4597             }
4598         } else {
4599             stream.send.update_blocked_at(None);
4600             self.streams.mark_blocked(stream_id, false, 0);
4601         }
4602 
4603         // If the stream is now flushable push it to the flushable queue, but
4604         // only if it wasn't already queued.
4605         //
4606         // Consider the stream flushable also when we are sending a zero-length
4607         // frame that has the fin flag set.
4608         if (flushable || empty_fin) && !was_flushable {
4609             self.streams.push_flushable(stream_id, urgency, incremental);
4610         }
4611 
4612         if !writable {
4613             self.streams.mark_writable(stream_id, false);
4614         } else if was_writable && blocked_by_cap {
4615             // When `stream_writable_next()` returns a stream, the writable
4616             // mark is removed, but because the stream is blocked by the
4617             // connection-level send capacity it won't be marked as writable
4618             // again once the capacity increases.
4619             //
4620             // Since the stream is writable already, mark it here instead.
4621             self.streams.mark_writable(stream_id, true);
4622         }
4623 
4624         self.tx_cap -= sent;
4625 
4626         self.tx_data += sent as u64;
4627 
4628         self.tx_buffered += sent;
4629 
4630         qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
4631             let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved {
4632                 stream_id: Some(stream_id),
4633                 offset: Some(offset),
4634                 length: Some(sent as u64),
4635                 from: Some(DataRecipient::Application),
4636                 to: Some(DataRecipient::Transport),
4637                 raw: None,
4638             });
4639 
4640             let now = time::Instant::now();
4641             q.add_event_data_with_instant(ev_data, now).ok();
4642         });
4643 
4644         if sent == 0 && !buf.is_empty() {
4645             return Err(Error::Done);
4646         }
4647 
4648         Ok(sent)
4649     }
4650 
4651     /// Sets the priority for a stream.
4652     ///
4653     /// A stream's priority determines the order in which stream data is sent
4654     /// on the wire (streams with lower priority are sent first). Streams are
4655     /// created with a default priority of `127`.
4656     ///
4657     /// The target stream is created if it did not exist before calling this
4658     /// method.
stream_priority( &mut self, stream_id: u64, urgency: u8, incremental: bool, ) -> Result<()>4659     pub fn stream_priority(
4660         &mut self, stream_id: u64, urgency: u8, incremental: bool,
4661     ) -> Result<()> {
4662         // Get existing stream or create a new one, but if the stream
4663         // has already been closed and collected, ignore the prioritization.
4664         let stream = match self.get_or_create_stream(stream_id, true) {
4665             Ok(v) => v,
4666 
4667             Err(Error::Done) => return Ok(()),
4668 
4669             Err(e) => return Err(e),
4670         };
4671 
4672         if stream.urgency == urgency && stream.incremental == incremental {
4673             return Ok(());
4674         }
4675 
4676         stream.urgency = urgency;
4677         stream.incremental = incremental;
4678 
4679         // TODO: reprioritization
4680 
4681         Ok(())
4682     }
4683 
4684     /// Shuts down reading or writing from/to the specified stream.
4685     ///
4686     /// When the `direction` argument is set to [`Shutdown::Read`], outstanding
4687     /// data in the stream's receive buffer is dropped, and no additional data
4688     /// is added to it. Data received after calling this method is still
4689     /// validated and acked but not stored, and [`stream_recv()`] will not
4690     /// return it to the application. In addition, a `STOP_SENDING` frame will
4691     /// be sent to the peer to signal it to stop sending data.
4692     ///
4693     /// When the `direction` argument is set to [`Shutdown::Write`], outstanding
4694     /// data in the stream's send buffer is dropped, and no additional data is
4695     /// added to it. Data passed to [`stream_send()`] after calling this method
4696     /// will be ignored. In addition, a `RESET_STREAM` frame will be sent to the
4697     /// peer to signal the reset.
4698     ///
4699     /// Locally-initiated unidirectional streams can only be closed in the
4700     /// [`Shutdown::Write`] direction. Remotely-initiated unidirectional streams
4701     /// can only be closed in the [`Shutdown::Read`] direction. Using an
4702     /// incorrect direction will return [`InvalidStreamState`].
4703     ///
4704     /// [`Shutdown::Read`]: enum.Shutdown.html#variant.Read
4705     /// [`Shutdown::Write`]: enum.Shutdown.html#variant.Write
4706     /// [`stream_recv()`]: struct.Connection.html#method.stream_recv
4707     /// [`stream_send()`]: struct.Connection.html#method.stream_send
4708     /// [`InvalidStreamState`]: enum.Error.html#variant.InvalidStreamState
stream_shutdown( &mut self, stream_id: u64, direction: Shutdown, err: u64, ) -> Result<()>4709     pub fn stream_shutdown(
4710         &mut self, stream_id: u64, direction: Shutdown, err: u64,
4711     ) -> Result<()> {
4712         // Don't try to stop a local unidirectional stream.
4713         if direction == Shutdown::Read &&
4714             stream::is_local(stream_id, self.is_server) &&
4715             !stream::is_bidi(stream_id)
4716         {
4717             return Err(Error::InvalidStreamState(stream_id));
4718         }
4719 
4720         // Dont' try to reset a remote unidirectional stream.
4721         if direction == Shutdown::Write &&
4722             !stream::is_local(stream_id, self.is_server) &&
4723             !stream::is_bidi(stream_id)
4724         {
4725             return Err(Error::InvalidStreamState(stream_id));
4726         }
4727 
4728         // Get existing stream.
4729         let stream = self.streams.get_mut(stream_id).ok_or(Error::Done)?;
4730 
4731         match direction {
4732             Shutdown::Read => {
4733                 stream.recv.shutdown()?;
4734 
4735                 if !stream.recv.is_fin() {
4736                     self.streams.mark_stopped(stream_id, true, err);
4737                 }
4738 
4739                 // Once shutdown, the stream is guaranteed to be non-readable.
4740                 self.streams.mark_readable(stream_id, false);
4741             },
4742 
4743             Shutdown::Write => {
4744                 let (final_size, unsent) = stream.send.shutdown()?;
4745 
4746                 // Claw back some flow control allowance from data that was
4747                 // buffered but not actually sent before the stream was reset.
4748                 self.tx_data = self.tx_data.saturating_sub(unsent);
4749 
4750                 self.tx_buffered =
4751                     self.tx_buffered.saturating_sub(unsent as usize);
4752 
4753                 // Update send capacity.
4754                 self.update_tx_cap();
4755 
4756                 self.streams.mark_reset(stream_id, true, err, final_size);
4757 
4758                 // Once shutdown, the stream is guaranteed to be non-writable.
4759                 self.streams.mark_writable(stream_id, false);
4760             },
4761         }
4762 
4763         Ok(())
4764     }
4765 
4766     /// Returns the stream's send capacity in bytes.
4767     ///
4768     /// If the specified stream doesn't exist (including when it has already
4769     /// been completed and closed), the [`InvalidStreamState`] error will be
4770     /// returned.
4771     ///
4772     /// In addition, if the peer has signalled that it doesn't want to receive
4773     /// any more data from this stream by sending the `STOP_SENDING` frame, the
4774     /// [`StreamStopped`] error will be returned.
4775     ///
4776     /// [`InvalidStreamState`]: enum.Error.html#variant.InvalidStreamState
4777     /// [`StreamStopped`]: enum.Error.html#variant.StreamStopped
4778     #[inline]
stream_capacity(&self, stream_id: u64) -> Result<usize>4779     pub fn stream_capacity(&self, stream_id: u64) -> Result<usize> {
4780         if let Some(stream) = self.streams.get(stream_id) {
4781             let cap = cmp::min(self.tx_cap, stream.send.cap()?);
4782             return Ok(cap);
4783         };
4784 
4785         Err(Error::InvalidStreamState(stream_id))
4786     }
4787 
4788     /// Returns the next stream that has data to read.
4789     ///
4790     /// Note that once returned by this method, a stream ID will not be returned
4791     /// again until it is "re-armed".
4792     ///
4793     /// The application will need to read all of the pending data on the stream,
4794     /// and new data has to be received before the stream is reported again.
4795     ///
4796     /// This is unlike the [`readable()`] method, that returns the same list of
4797     /// readable streams when called multiple times in succession.
4798     ///
4799     /// [`readable()`]: struct.Connection.html#method.readable
stream_readable_next(&mut self) -> Option<u64>4800     pub fn stream_readable_next(&mut self) -> Option<u64> {
4801         let &stream_id = self.streams.readable.iter().next()?;
4802 
4803         self.streams.mark_readable(stream_id, false);
4804 
4805         Some(stream_id)
4806     }
4807 
4808     /// Returns true if the stream has data that can be read.
stream_readable(&self, stream_id: u64) -> bool4809     pub fn stream_readable(&self, stream_id: u64) -> bool {
4810         let stream = match self.streams.get(stream_id) {
4811             Some(v) => v,
4812 
4813             None => return false,
4814         };
4815 
4816         stream.is_readable()
4817     }
4818 
4819     /// Returns the next stream that can be written to.
4820     ///
4821     /// Note that once returned by this method, a stream ID will not be returned
4822     /// again until it is "re-armed".
4823     ///
4824     /// This is unlike the [`writable()`] method, that returns the same list of
4825     /// writable streams when called multiple times in succession. It is not
4826     /// advised to use both `stream_writable_next()` and [`writable()`] on the
4827     /// same connection, as it may lead to unexpected results.
4828     ///
4829     /// The [`stream_writable()`] method can also be used to fine-tune when a
4830     /// stream is reported as writable again.
4831     ///
4832     /// [`stream_writable()`]: struct.Connection.html#method.stream_writable
4833     /// [`writable()`]: struct.Connection.html#method.writable
stream_writable_next(&mut self) -> Option<u64>4834     pub fn stream_writable_next(&mut self) -> Option<u64> {
4835         // If there is not enough connection-level send capacity, none of the
4836         // streams are writable.
4837         if self.tx_cap == 0 {
4838             return None;
4839         }
4840 
4841         for &stream_id in &self.streams.writable {
4842             if let Some(stream) = self.streams.get(stream_id) {
4843                 let cap = match stream.send.cap() {
4844                     Ok(v) => v,
4845 
4846                     // Return the stream to the application immediately if it's
4847                     // stopped.
4848                     Err(_) =>
4849                         return {
4850                             self.streams.mark_writable(stream_id, false);
4851                             Some(stream_id)
4852                         },
4853                 };
4854 
4855                 if cmp::min(self.tx_cap, cap) >= stream.send_lowat {
4856                     self.streams.mark_writable(stream_id, false);
4857                     return Some(stream_id);
4858                 }
4859             }
4860         }
4861 
4862         None
4863     }
4864 
4865     /// Returns true if the stream has enough send capacity.
4866     ///
4867     /// When `len` more bytes can be buffered into the given stream's send
4868     /// buffer, `true` will be returned, `false` otherwise.
4869     ///
4870     /// In the latter case, if the additional data can't be buffered due to
4871     /// flow control limits, the peer will also be notified, and a "low send
4872     /// watermark" will be set for the stream, such that it is not going to be
4873     /// reported as writable again by [`stream_writable_next()`] until its send
4874     /// capacity reaches `len`.
4875     ///
4876     /// If the specified stream doesn't exist (including when it has already
4877     /// been completed and closed), the [`InvalidStreamState`] error will be
4878     /// returned.
4879     ///
4880     /// In addition, if the peer has signalled that it doesn't want to receive
4881     /// any more data from this stream by sending the `STOP_SENDING` frame, the
4882     /// [`StreamStopped`] error will be returned.
4883     ///
4884     /// [`stream_writable_next()`]: struct.Connection.html#method.stream_writable_next
4885     /// [`InvalidStreamState`]: enum.Error.html#variant.InvalidStreamState
4886     /// [`StreamStopped`]: enum.Error.html#variant.StreamStopped
4887     #[inline]
stream_writable( &mut self, stream_id: u64, len: usize, ) -> Result<bool>4888     pub fn stream_writable(
4889         &mut self, stream_id: u64, len: usize,
4890     ) -> Result<bool> {
4891         if self.stream_capacity(stream_id)? >= len {
4892             return Ok(true);
4893         }
4894 
4895         let stream = match self.streams.get_mut(stream_id) {
4896             Some(v) => v,
4897 
4898             None => return Err(Error::InvalidStreamState(stream_id)),
4899         };
4900 
4901         stream.send_lowat = cmp::max(1, len);
4902 
4903         let is_writable = stream.is_writable();
4904 
4905         if self.max_tx_data - self.tx_data < len as u64 {
4906             self.blocked_limit = Some(self.max_tx_data);
4907         }
4908 
4909         if stream.send.cap()? < len {
4910             let max_off = stream.send.max_off();
4911             if stream.send.blocked_at() != Some(max_off) {
4912                 stream.send.update_blocked_at(Some(max_off));
4913                 self.streams.mark_blocked(stream_id, true, max_off);
4914             }
4915         } else if is_writable {
4916             // When `stream_writable_next()` returns a stream, the writable
4917             // mark is removed, but because the stream is blocked by the
4918             // connection-level send capacity it won't be marked as writable
4919             // again once the capacity increases.
4920             //
4921             // Since the stream is writable already, mark it here instead.
4922             self.streams.mark_writable(stream_id, true);
4923         }
4924 
4925         Ok(false)
4926     }
4927 
4928     /// Returns true if all the data has been read from the specified stream.
4929     ///
4930     /// This instructs the application that all the data received from the
4931     /// peer on the stream has been read, and there won't be anymore in the
4932     /// future.
4933     ///
4934     /// Basically this returns true when the peer either set the `fin` flag
4935     /// for the stream, or sent `RESET_STREAM`.
4936     #[inline]
stream_finished(&self, stream_id: u64) -> bool4937     pub fn stream_finished(&self, stream_id: u64) -> bool {
4938         let stream = match self.streams.get(stream_id) {
4939             Some(v) => v,
4940 
4941             None => return true,
4942         };
4943 
4944         stream.recv.is_fin()
4945     }
4946 
4947     /// Returns the number of bidirectional streams that can be created
4948     /// before the peer's stream count limit is reached.
4949     ///
4950     /// This can be useful to know if it's possible to create a bidirectional
4951     /// stream without trying it first.
4952     #[inline]
peer_streams_left_bidi(&self) -> u644953     pub fn peer_streams_left_bidi(&self) -> u64 {
4954         self.streams.peer_streams_left_bidi()
4955     }
4956 
4957     /// Returns the number of unidirectional streams that can be created
4958     /// before the peer's stream count limit is reached.
4959     ///
4960     /// This can be useful to know if it's possible to create a unidirectional
4961     /// stream without trying it first.
4962     #[inline]
peer_streams_left_uni(&self) -> u644963     pub fn peer_streams_left_uni(&self) -> u64 {
4964         self.streams.peer_streams_left_uni()
4965     }
4966 
4967     /// Initializes the stream's application data.
4968     ///
4969     /// This can be used by applications to store per-stream information without
4970     /// having to maintain their own stream map.
4971     ///
4972     /// Stream data can only be initialized once. Additional calls to this
4973     /// method will return [`Done`].
4974     ///
4975     /// [`Done`]: enum.Error.html#variant.Done
stream_init_application_data<T>( &mut self, stream_id: u64, data: T, ) -> Result<()> where T: std::any::Any + Send + Sync,4976     pub fn stream_init_application_data<T>(
4977         &mut self, stream_id: u64, data: T,
4978     ) -> Result<()>
4979     where
4980         T: std::any::Any + Send + Sync,
4981     {
4982         // Get existing stream.
4983         let stream = self.streams.get_mut(stream_id).ok_or(Error::Done)?;
4984 
4985         if stream.data.is_some() {
4986             return Err(Error::Done);
4987         }
4988 
4989         stream.data = Some(Box::new(data));
4990 
4991         Ok(())
4992     }
4993 
4994     /// Returns the stream's application data, if any was initialized.
4995     ///
4996     /// This returns a reference to the application data that was initialized
4997     /// by calling [`stream_init_application_data()`].
4998     ///
4999     /// [`stream_init_application_data()`]:
5000     /// struct.Connection.html#method.stream_init_application_data
stream_application_data( &mut self, stream_id: u64, ) -> Option<&mut dyn std::any::Any>5001     pub fn stream_application_data(
5002         &mut self, stream_id: u64,
5003     ) -> Option<&mut dyn std::any::Any> {
5004         // Get existing stream.
5005         let stream = self.streams.get_mut(stream_id)?;
5006 
5007         if let Some(ref mut stream_data) = stream.data {
5008             return Some(stream_data.as_mut());
5009         }
5010 
5011         None
5012     }
5013 
5014     /// Returns an iterator over streams that have outstanding data to read.
5015     ///
5016     /// Note that the iterator will only include streams that were readable at
5017     /// the time the iterator itself was created (i.e. when `readable()` was
5018     /// called). To account for newly readable streams, the iterator needs to
5019     /// be created again.
5020     ///
5021     /// ## Examples:
5022     ///
5023     /// ```no_run
5024     /// # let mut buf = [0; 512];
5025     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5026     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5027     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5028     /// # let peer = "127.0.0.1:1234".parse().unwrap();
5029     /// # let local = socket.local_addr().unwrap();
5030     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5031     /// // Iterate over readable streams.
5032     /// for stream_id in conn.readable() {
5033     ///     // Stream is readable, read until there's no more data.
5034     ///     while let Ok((read, fin)) = conn.stream_recv(stream_id, &mut buf) {
5035     ///         println!("Got {} bytes on stream {}", read, stream_id);
5036     ///     }
5037     /// }
5038     /// # Ok::<(), quiche::Error>(())
5039     /// ```
5040     #[inline]
readable(&self) -> StreamIter5041     pub fn readable(&self) -> StreamIter {
5042         self.streams.readable()
5043     }
5044 
5045     /// Returns an iterator over streams that can be written to.
5046     ///
5047     /// A "writable" stream is a stream that has enough flow control capacity to
5048     /// send data to the peer. To avoid buffering an infinite amount of data,
5049     /// streams are only allowed to buffer outgoing data up to the amount that
5050     /// the peer allows to send.
5051     ///
5052     /// Note that the iterator will only include streams that were writable at
5053     /// the time the iterator itself was created (i.e. when `writable()` was
5054     /// called). To account for newly writable streams, the iterator needs to
5055     /// be created again.
5056     ///
5057     /// ## Examples:
5058     ///
5059     /// ```no_run
5060     /// # let mut buf = [0; 512];
5061     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5062     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5063     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5064     /// # let local = socket.local_addr().unwrap();
5065     /// # let peer = "127.0.0.1:1234".parse().unwrap();
5066     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5067     /// // Iterate over writable streams.
5068     /// for stream_id in conn.writable() {
5069     ///     // Stream is writable, write some data.
5070     ///     if let Ok(written) = conn.stream_send(stream_id, &buf, false) {
5071     ///         println!("Written {} bytes on stream {}", written, stream_id);
5072     ///     }
5073     /// }
5074     /// # Ok::<(), quiche::Error>(())
5075     /// ```
5076     #[inline]
writable(&self) -> StreamIter5077     pub fn writable(&self) -> StreamIter {
5078         // If there is not enough connection-level send capacity, none of the
5079         // streams are writable, so return an empty iterator.
5080         if self.tx_cap == 0 {
5081             return StreamIter::default();
5082         }
5083 
5084         self.streams.writable()
5085     }
5086 
5087     /// Returns the maximum possible size of egress UDP payloads.
5088     ///
5089     /// This is the maximum size of UDP payloads that can be sent, and depends
5090     /// on both the configured maximum send payload size of the local endpoint
5091     /// (as configured with [`set_max_send_udp_payload_size()`]), as well as
5092     /// the transport parameter advertised by the remote peer.
5093     ///
5094     /// Note that this value can change during the lifetime of the connection,
5095     /// but should remain stable across consecutive calls to [`send()`].
5096     ///
5097     /// [`set_max_send_udp_payload_size()`]:
5098     ///     struct.Config.html#method.set_max_send_udp_payload_size
5099     /// [`send()`]: struct.Connection.html#method.send
max_send_udp_payload_size(&self) -> usize5100     pub fn max_send_udp_payload_size(&self) -> usize {
5101         let max_datagram_size = self
5102             .paths
5103             .get_active()
5104             .ok()
5105             .map(|p| p.recovery.max_datagram_size());
5106 
5107         if let Some(max_datagram_size) = max_datagram_size {
5108             if self.is_established() {
5109                 // We cap the maximum packet size to 16KB or so, so that it can be
5110                 // always encoded with a 2-byte varint.
5111                 return cmp::min(16383, max_datagram_size);
5112             }
5113         }
5114 
5115         // Allow for 1200 bytes (minimum QUIC packet size) during the
5116         // handshake.
5117         MIN_CLIENT_INITIAL_LEN
5118     }
5119 
5120     /// Schedule an ack-eliciting packet on the active path.
5121     ///
5122     /// QUIC packets might not contain ack-eliciting frames during normal
5123     /// operating conditions. If the packet would already contain
5124     /// ack-eliciting frames, this method does not change any behavior.
5125     /// However, if the packet would not ordinarily contain ack-eliciting
5126     /// frames, this method ensures that a PING frame sent.
5127     ///
5128     /// Calling this method multiple times before [`send()`] has no effect.
5129     ///
5130     /// [`send()`]: struct.Connection.html#method.send
send_ack_eliciting(&mut self) -> Result<()>5131     pub fn send_ack_eliciting(&mut self) -> Result<()> {
5132         if self.is_closed() || self.is_draining() {
5133             return Ok(());
5134         }
5135         self.paths.get_active_mut()?.needs_ack_eliciting = true;
5136         Ok(())
5137     }
5138 
5139     /// Schedule an ack-eliciting packet on the specified path.
5140     ///
5141     /// See [`send_ack_eliciting()`] for more detail. [`InvalidState`] is
5142     /// returned if there is no record of the path.
5143     ///
5144     /// [`send_ack_eliciting()`]: struct.Connection.html#method.send_ack_eliciting
5145     /// [`InvalidState`]: enum.Error.html#variant.InvalidState
send_ack_eliciting_on_path( &mut self, local: SocketAddr, peer: SocketAddr, ) -> Result<()>5146     pub fn send_ack_eliciting_on_path(
5147         &mut self, local: SocketAddr, peer: SocketAddr,
5148     ) -> Result<()> {
5149         if self.is_closed() || self.is_draining() {
5150             return Ok(());
5151         }
5152         let path_id = self
5153             .paths
5154             .path_id_from_addrs(&(local, peer))
5155             .ok_or(Error::InvalidState)?;
5156         self.paths.get_mut(path_id)?.needs_ack_eliciting = true;
5157         Ok(())
5158     }
5159 
5160     /// Reads the first received DATAGRAM.
5161     ///
5162     /// On success the DATAGRAM's data is returned along with its size.
5163     ///
5164     /// [`Done`] is returned if there is no data to read.
5165     ///
5166     /// [`BufferTooShort`] is returned if the provided buffer is too small for
5167     /// the DATAGRAM.
5168     ///
5169     /// [`Done`]: enum.Error.html#variant.Done
5170     /// [`BufferTooShort`]: enum.Error.html#variant.BufferTooShort
5171     ///
5172     /// ## Examples:
5173     ///
5174     /// ```no_run
5175     /// # let mut buf = [0; 512];
5176     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5177     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5178     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5179     /// # let peer = "127.0.0.1:1234".parse().unwrap();
5180     /// # let local = socket.local_addr().unwrap();
5181     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5182     /// let mut dgram_buf = [0; 512];
5183     /// while let Ok((len)) = conn.dgram_recv(&mut dgram_buf) {
5184     ///     println!("Got {} bytes of DATAGRAM", len);
5185     /// }
5186     /// # Ok::<(), quiche::Error>(())
5187     /// ```
5188     #[inline]
dgram_recv(&mut self, buf: &mut [u8]) -> Result<usize>5189     pub fn dgram_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
5190         match self.dgram_recv_queue.pop() {
5191             Some(d) => {
5192                 if d.len() > buf.len() {
5193                     return Err(Error::BufferTooShort);
5194                 }
5195 
5196                 buf[..d.len()].copy_from_slice(&d);
5197                 Ok(d.len())
5198             },
5199 
5200             None => Err(Error::Done),
5201         }
5202     }
5203 
5204     /// Reads the first received DATAGRAM.
5205     ///
5206     /// This is the same as [`dgram_recv()`] but returns the DATAGRAM as a
5207     /// `Vec<u8>` instead of copying into the provided buffer.
5208     ///
5209     /// [`dgram_recv()`]: struct.Connection.html#method.dgram_recv
5210     #[inline]
dgram_recv_vec(&mut self) -> Result<Vec<u8>>5211     pub fn dgram_recv_vec(&mut self) -> Result<Vec<u8>> {
5212         match self.dgram_recv_queue.pop() {
5213             Some(d) => Ok(d),
5214 
5215             None => Err(Error::Done),
5216         }
5217     }
5218 
5219     /// Reads the first received DATAGRAM without removing it from the queue.
5220     ///
5221     /// On success the DATAGRAM's data is returned along with the actual number
5222     /// of bytes peeked. The requested length cannot exceed the DATAGRAM's
5223     /// actual length.
5224     ///
5225     /// [`Done`] is returned if there is no data to read.
5226     ///
5227     /// [`BufferTooShort`] is returned if the provided buffer is smaller the
5228     /// number of bytes to peek.
5229     ///
5230     /// [`Done`]: enum.Error.html#variant.Done
5231     /// [`BufferTooShort`]: enum.Error.html#variant.BufferTooShort
5232     #[inline]
dgram_recv_peek(&self, buf: &mut [u8], len: usize) -> Result<usize>5233     pub fn dgram_recv_peek(&self, buf: &mut [u8], len: usize) -> Result<usize> {
5234         self.dgram_recv_queue.peek_front_bytes(buf, len)
5235     }
5236 
5237     /// Returns the length of the first stored DATAGRAM.
5238     #[inline]
dgram_recv_front_len(&self) -> Option<usize>5239     pub fn dgram_recv_front_len(&self) -> Option<usize> {
5240         self.dgram_recv_queue.peek_front_len()
5241     }
5242 
5243     /// Returns the number of items in the DATAGRAM receive queue.
5244     #[inline]
dgram_recv_queue_len(&self) -> usize5245     pub fn dgram_recv_queue_len(&self) -> usize {
5246         self.dgram_recv_queue.len()
5247     }
5248 
5249     /// Returns the total size of all items in the DATAGRAM receive queue.
5250     #[inline]
dgram_recv_queue_byte_size(&self) -> usize5251     pub fn dgram_recv_queue_byte_size(&self) -> usize {
5252         self.dgram_recv_queue.byte_size()
5253     }
5254 
5255     /// Returns the number of items in the DATAGRAM send queue.
5256     #[inline]
dgram_send_queue_len(&self) -> usize5257     pub fn dgram_send_queue_len(&self) -> usize {
5258         self.dgram_send_queue.len()
5259     }
5260 
5261     /// Returns the total size of all items in the DATAGRAM send queue.
5262     #[inline]
dgram_send_queue_byte_size(&self) -> usize5263     pub fn dgram_send_queue_byte_size(&self) -> usize {
5264         self.dgram_send_queue.byte_size()
5265     }
5266 
5267     /// Returns whether or not the DATAGRAM send queue is full.
5268     #[inline]
is_dgram_send_queue_full(&self) -> bool5269     pub fn is_dgram_send_queue_full(&self) -> bool {
5270         self.dgram_send_queue.is_full()
5271     }
5272 
5273     /// Returns whether or not the DATAGRAM recv queue is full.
5274     #[inline]
is_dgram_recv_queue_full(&self) -> bool5275     pub fn is_dgram_recv_queue_full(&self) -> bool {
5276         self.dgram_recv_queue.is_full()
5277     }
5278 
5279     /// Sends data in a DATAGRAM frame.
5280     ///
5281     /// [`Done`] is returned if no data was written.
5282     /// [`InvalidState`] is returned if the peer does not support DATAGRAM.
5283     /// [`BufferTooShort`] is returned if the DATAGRAM frame length is larger
5284     /// than peer's supported DATAGRAM frame length. Use
5285     /// [`dgram_max_writable_len()`] to get the largest supported DATAGRAM
5286     /// frame length.
5287     ///
5288     /// Note that there is no flow control of DATAGRAM frames, so in order to
5289     /// avoid buffering an infinite amount of frames we apply an internal
5290     /// limit.
5291     ///
5292     /// [`Done`]: enum.Error.html#variant.Done
5293     /// [`InvalidState`]: enum.Error.html#variant.InvalidState
5294     /// [`BufferTooShort`]: enum.Error.html#variant.BufferTooShort
5295     /// [`dgram_max_writable_len()`]:
5296     /// struct.Connection.html#method.dgram_max_writable_len
5297     ///
5298     /// ## Examples:
5299     ///
5300     /// ```no_run
5301     /// # let mut buf = [0; 512];
5302     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5303     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5304     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5305     /// # let peer = "127.0.0.1:1234".parse().unwrap();
5306     /// # let local = socket.local_addr().unwrap();
5307     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5308     /// conn.dgram_send(b"hello")?;
5309     /// # Ok::<(), quiche::Error>(())
5310     /// ```
dgram_send(&mut self, buf: &[u8]) -> Result<()>5311     pub fn dgram_send(&mut self, buf: &[u8]) -> Result<()> {
5312         let max_payload_len = match self.dgram_max_writable_len() {
5313             Some(v) => v,
5314 
5315             None => return Err(Error::InvalidState),
5316         };
5317 
5318         if buf.len() > max_payload_len {
5319             return Err(Error::BufferTooShort);
5320         }
5321 
5322         self.dgram_send_queue.push(buf.to_vec())?;
5323 
5324         let active_path = self.paths.get_active_mut()?;
5325 
5326         if self.dgram_send_queue.byte_size() >
5327             active_path.recovery.cwnd_available()
5328         {
5329             active_path.recovery.update_app_limited(false);
5330         }
5331 
5332         Ok(())
5333     }
5334 
5335     /// Sends data in a DATAGRAM frame.
5336     ///
5337     /// This is the same as [`dgram_send()`] but takes a `Vec<u8>` instead of
5338     /// a slice.
5339     ///
5340     /// [`dgram_send()`]: struct.Connection.html#method.dgram_send
dgram_send_vec(&mut self, buf: Vec<u8>) -> Result<()>5341     pub fn dgram_send_vec(&mut self, buf: Vec<u8>) -> Result<()> {
5342         let max_payload_len = match self.dgram_max_writable_len() {
5343             Some(v) => v,
5344 
5345             None => return Err(Error::InvalidState),
5346         };
5347 
5348         if buf.len() > max_payload_len {
5349             return Err(Error::BufferTooShort);
5350         }
5351 
5352         self.dgram_send_queue.push(buf)?;
5353 
5354         let active_path = self.paths.get_active_mut()?;
5355 
5356         if self.dgram_send_queue.byte_size() >
5357             active_path.recovery.cwnd_available()
5358         {
5359             active_path.recovery.update_app_limited(false);
5360         }
5361 
5362         Ok(())
5363     }
5364 
5365     /// Purges queued outgoing DATAGRAMs matching the predicate.
5366     ///
5367     /// In other words, remove all elements `e` such that `f(&e)` returns true.
5368     ///
5369     /// ## Examples:
5370     /// ```no_run
5371     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5372     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5373     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5374     /// # let peer = "127.0.0.1:1234".parse().unwrap();
5375     /// # let local = socket.local_addr().unwrap();
5376     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5377     /// conn.dgram_send(b"hello")?;
5378     /// conn.dgram_purge_outgoing(&|d: &[u8]| -> bool { d[0] == 0 });
5379     /// # Ok::<(), quiche::Error>(())
5380     /// ```
5381     #[inline]
dgram_purge_outgoing<F: Fn(&[u8]) -> bool>(&mut self, f: F)5382     pub fn dgram_purge_outgoing<F: Fn(&[u8]) -> bool>(&mut self, f: F) {
5383         self.dgram_send_queue.purge(f);
5384     }
5385 
5386     /// Returns the maximum DATAGRAM payload that can be sent.
5387     ///
5388     /// [`None`] is returned if the peer hasn't advertised a maximum DATAGRAM
5389     /// frame size.
5390     ///
5391     /// ## Examples:
5392     ///
5393     /// ```no_run
5394     /// # let mut buf = [0; 512];
5395     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5396     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5397     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5398     /// # let peer = "127.0.0.1:1234".parse().unwrap();
5399     /// # let local = socket.local_addr().unwrap();
5400     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5401     /// if let Some(payload_size) = conn.dgram_max_writable_len() {
5402     ///     if payload_size > 5 {
5403     ///         conn.dgram_send(b"hello")?;
5404     ///     }
5405     /// }
5406     /// # Ok::<(), quiche::Error>(())
5407     /// ```
5408     #[inline]
dgram_max_writable_len(&self) -> Option<usize>5409     pub fn dgram_max_writable_len(&self) -> Option<usize> {
5410         match self.peer_transport_params.max_datagram_frame_size {
5411             None => None,
5412             Some(peer_frame_len) => {
5413                 let dcid = self.destination_id();
5414                 // Start from the maximum packet size...
5415                 let mut max_len = self.max_send_udp_payload_size();
5416                 // ...subtract the Short packet header overhead...
5417                 // (1 byte of pkt_len + len of dcid)
5418                 max_len = max_len.saturating_sub(1 + dcid.len());
5419                 // ...subtract the packet number (max len)...
5420                 max_len = max_len.saturating_sub(packet::MAX_PKT_NUM_LEN);
5421                 // ...subtract the crypto overhead...
5422                 max_len = max_len.saturating_sub(
5423                     self.pkt_num_spaces[packet::Epoch::Application]
5424                         .crypto_overhead()?,
5425                 );
5426                 // ...clamp to what peer can support...
5427                 max_len = cmp::min(peer_frame_len as usize, max_len);
5428                 // ...subtract frame overhead, checked for underflow.
5429                 // (1 byte of frame type + len of length )
5430                 max_len.checked_sub(1 + frame::MAX_DGRAM_OVERHEAD)
5431             },
5432         }
5433     }
5434 
dgram_enabled(&self) -> bool5435     fn dgram_enabled(&self) -> bool {
5436         self.local_transport_params
5437             .max_datagram_frame_size
5438             .is_some()
5439     }
5440 
5441     /// Returns when the next timeout event will occur.
5442     ///
5443     /// Once the timeout Instant has been reached, the [`on_timeout()`] method
5444     /// should be called. A timeout of `None` means that the timer should be
5445     /// disarmed.
5446     ///
5447     /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
timeout_instant(&self) -> Option<time::Instant>5448     pub fn timeout_instant(&self) -> Option<time::Instant> {
5449         if self.is_closed() {
5450             return None;
5451         }
5452 
5453         if self.is_draining() {
5454             // Draining timer takes precedence over all other timers. If it is
5455             // set it means the connection is closing so there's no point in
5456             // processing the other timers.
5457             self.draining_timer
5458         } else {
5459             // Use the lowest timer value (i.e. "sooner") among idle and loss
5460             // detection timers. If they are both unset (i.e. `None`) then the
5461             // result is `None`, but if at least one of them is set then a
5462             // `Some(...)` value is returned.
5463             let path_timer = self
5464                 .paths
5465                 .iter()
5466                 .filter_map(|(_, p)| p.recovery.loss_detection_timer())
5467                 .min();
5468 
5469             let key_update_timer = self.pkt_num_spaces
5470                 [packet::Epoch::Application]
5471                 .key_update
5472                 .as_ref()
5473                 .map(|key_update| key_update.timer);
5474 
5475             let timers = [self.idle_timer, path_timer, key_update_timer];
5476 
5477             timers.iter().filter_map(|&x| x).min()
5478         }
5479     }
5480 
5481     /// Returns the amount of time until the next timeout event.
5482     ///
5483     /// Once the given duration has elapsed, the [`on_timeout()`] method should
5484     /// be called. A timeout of `None` means that the timer should be disarmed.
5485     ///
5486     /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
timeout(&self) -> Option<time::Duration>5487     pub fn timeout(&self) -> Option<time::Duration> {
5488         self.timeout_instant().map(|timeout| {
5489             let now = time::Instant::now();
5490 
5491             if timeout <= now {
5492                 time::Duration::ZERO
5493             } else {
5494                 timeout.duration_since(now)
5495             }
5496         })
5497     }
5498 
5499     /// Processes a timeout event.
5500     ///
5501     /// If no timeout has occurred it does nothing.
on_timeout(&mut self)5502     pub fn on_timeout(&mut self) {
5503         let now = time::Instant::now();
5504 
5505         if let Some(draining_timer) = self.draining_timer {
5506             if draining_timer <= now {
5507                 trace!("{} draining timeout expired", self.trace_id);
5508 
5509                 qlog_with!(self.qlog, q, {
5510                     q.finish_log().ok();
5511                 });
5512 
5513                 self.closed = true;
5514             }
5515 
5516             // Draining timer takes precedence over all other timers. If it is
5517             // set it means the connection is closing so there's no point in
5518             // processing the other timers.
5519             return;
5520         }
5521 
5522         if let Some(timer) = self.idle_timer {
5523             if timer <= now {
5524                 trace!("{} idle timeout expired", self.trace_id);
5525 
5526                 qlog_with!(self.qlog, q, {
5527                     q.finish_log().ok();
5528                 });
5529 
5530                 self.closed = true;
5531                 self.timed_out = true;
5532                 return;
5533             }
5534         }
5535 
5536         if let Some(timer) = self.pkt_num_spaces[packet::Epoch::Application]
5537             .key_update
5538             .as_ref()
5539             .map(|key_update| key_update.timer)
5540         {
5541             if timer <= now {
5542                 // Discard previous key once key update timer expired.
5543                 let _ = self.pkt_num_spaces[packet::Epoch::Application]
5544                     .key_update
5545                     .take();
5546             }
5547         }
5548 
5549         let handshake_status = self.handshake_status();
5550 
5551         for (_, p) in self.paths.iter_mut() {
5552             if let Some(timer) = p.recovery.loss_detection_timer() {
5553                 if timer <= now {
5554                     trace!("{} loss detection timeout expired", self.trace_id);
5555 
5556                     let (lost_packets, lost_bytes) = p.on_loss_detection_timeout(
5557                         handshake_status,
5558                         now,
5559                         self.is_server,
5560                         &self.trace_id,
5561                     );
5562 
5563                     self.lost_count += lost_packets;
5564                     self.lost_bytes += lost_bytes as u64;
5565 
5566                     qlog_with_type!(QLOG_METRICS, self.qlog, q, {
5567                         if let Some(ev_data) = p.recovery.maybe_qlog() {
5568                             q.add_event_data_with_instant(ev_data, now).ok();
5569                         }
5570                     });
5571                 }
5572             }
5573         }
5574 
5575         // Notify timeout events to the application.
5576         self.paths.notify_failed_validations();
5577 
5578         // If the active path failed, try to find a new candidate.
5579         if self.paths.get_active_path_id().is_err() {
5580             match self.paths.find_candidate_path() {
5581                 Some(pid) =>
5582                     if self.paths.set_active_path(pid).is_err() {
5583                         // The connection cannot continue.
5584                         self.closed = true;
5585                     },
5586 
5587                 // The connection cannot continue.
5588                 None => self.closed = true,
5589             }
5590         }
5591     }
5592 
5593     /// Requests the stack to perform path validation of the proposed 4-tuple.
5594     ///
5595     /// Probing new paths requires spare Connection IDs at both the host and the
5596     /// peer sides. If it is not the case, it raises an [`OutOfIdentifiers`].
5597     ///
5598     /// The probing of new addresses can only be done by the client. The server
5599     /// can only probe network paths that were previously advertised by
5600     /// [`NewPath`]. If the server tries to probe such an unseen network path,
5601     /// this call raises an [`InvalidState`].
5602     ///
5603     /// The caller might also want to probe an existing path. In such case, it
5604     /// triggers a PATH_CHALLENGE frame, but it does not require spare CIDs.
5605     ///
5606     /// A server always probes a new path it observes. Calling this method is
5607     /// hence not required to validate a new path. However, a server can still
5608     /// request an additional path validation of the proposed 4-tuple.
5609     ///
5610     /// Calling this method several times before calling [`send()`] or
5611     /// [`send_on_path()`] results in a single probe being generated. An
5612     /// application wanting to send multiple in-flight probes must call this
5613     /// method again after having sent packets.
5614     ///
5615     /// Returns the Destination Connection ID sequence number associated to that
5616     /// path.
5617     ///
5618     /// [`NewPath`]: enum.QuicEvent.html#NewPath
5619     /// [`OutOfIdentifiers`]: enum.Error.html#OutOfIdentifiers
5620     /// [`InvalidState`]: enum.Error.html#InvalidState
5621     /// [`send()`]: struct.Connection.html#method.send
5622     /// [`send_on_path()`]: struct.Connection.html#method.send_on_path
probe_path( &mut self, local_addr: SocketAddr, peer_addr: SocketAddr, ) -> Result<u64>5623     pub fn probe_path(
5624         &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
5625     ) -> Result<u64> {
5626         // We may want to probe an existing path.
5627         let pid = match self.paths.path_id_from_addrs(&(local_addr, peer_addr)) {
5628             Some(pid) => pid,
5629             None => self.create_path_on_client(local_addr, peer_addr)?,
5630         };
5631 
5632         let path = self.paths.get_mut(pid)?;
5633         path.request_validation();
5634 
5635         path.active_dcid_seq.ok_or(Error::InvalidState)
5636     }
5637 
5638     /// Migrates the connection to a new local address `local_addr`.
5639     ///
5640     /// The behavior is similar to [`migrate()`], with the nuance that the
5641     /// connection only changes the local address, but not the peer one.
5642     ///
5643     /// See [`migrate()`] for the full specification of this method.
5644     ///
5645     /// [`migrate()`]: struct.Connection.html#method.migrate
migrate_source(&mut self, local_addr: SocketAddr) -> Result<u64>5646     pub fn migrate_source(&mut self, local_addr: SocketAddr) -> Result<u64> {
5647         let peer_addr = self.paths.get_active()?.peer_addr();
5648         self.migrate(local_addr, peer_addr)
5649     }
5650 
5651     /// Migrates the connection over the given network path between `local_addr`
5652     /// and `peer_addr`.
5653     ///
5654     /// Connection migration can only be initiated by the client. Calling this
5655     /// method as a server returns [`InvalidState`].
5656     ///
5657     /// To initiate voluntary migration, there should be enough Connection IDs
5658     /// at both sides. If this requirement is not satisfied, this call returns
5659     /// [`OutOfIdentifiers`].
5660     ///
5661     /// Returns the Destination Connection ID associated to that migrated path.
5662     ///
5663     /// [`OutOfIdentifiers`]: enum.Error.html#OutOfIdentifiers
5664     /// [`InvalidState`]: enum.Error.html#InvalidState
migrate( &mut self, local_addr: SocketAddr, peer_addr: SocketAddr, ) -> Result<u64>5665     pub fn migrate(
5666         &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
5667     ) -> Result<u64> {
5668         if self.is_server {
5669             return Err(Error::InvalidState);
5670         }
5671 
5672         // If the path already exists, mark it as the active one.
5673         let (pid, dcid_seq) = if let Some(pid) =
5674             self.paths.path_id_from_addrs(&(local_addr, peer_addr))
5675         {
5676             let path = self.paths.get_mut(pid)?;
5677 
5678             // If it is already active, do nothing.
5679             if path.active() {
5680                 return path.active_dcid_seq.ok_or(Error::OutOfIdentifiers);
5681             }
5682 
5683             // Ensures that a Source Connection ID has been dedicated to this
5684             // path, or a free one is available. This is only required if the
5685             // host uses non-zero length Source Connection IDs.
5686             if !self.ids.zero_length_scid() &&
5687                 path.active_scid_seq.is_none() &&
5688                 self.ids.available_scids() == 0
5689             {
5690                 return Err(Error::OutOfIdentifiers);
5691             }
5692 
5693             // Ensures that the migrated path has a Destination Connection ID.
5694             let dcid_seq = if let Some(dcid_seq) = path.active_dcid_seq {
5695                 dcid_seq
5696             } else {
5697                 let dcid_seq = self
5698                     .ids
5699                     .lowest_available_dcid_seq()
5700                     .ok_or(Error::OutOfIdentifiers)?;
5701 
5702                 self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
5703                 path.active_dcid_seq = Some(dcid_seq);
5704 
5705                 dcid_seq
5706             };
5707 
5708             (pid, dcid_seq)
5709         } else {
5710             let pid = self.create_path_on_client(local_addr, peer_addr)?;
5711 
5712             let dcid_seq = self
5713                 .paths
5714                 .get(pid)?
5715                 .active_dcid_seq
5716                 .ok_or(Error::InvalidState)?;
5717 
5718             (pid, dcid_seq)
5719         };
5720 
5721         // Change the active path.
5722         self.paths.set_active_path(pid)?;
5723 
5724         Ok(dcid_seq)
5725     }
5726 
5727     /// Provides additional source Connection IDs that the peer can use to reach
5728     /// this host.
5729     ///
5730     /// This triggers sending NEW_CONNECTION_ID frames if the provided Source
5731     /// Connection ID is not already present. In the case the caller tries to
5732     /// reuse a Connection ID with a different reset token, this raises an
5733     /// `InvalidState`.
5734     ///
5735     /// At any time, the peer cannot have more Destination Connection IDs than
5736     /// the maximum number of active Connection IDs it negotiated. In such case
5737     /// (i.e., when [`source_cids_left()`] returns 0), if the host agrees to
5738     /// request the removal of previous connection IDs, it sets the
5739     /// `retire_if_needed` parameter. Otherwise, an [`IdLimit`] is returned.
5740     ///
5741     /// Note that setting `retire_if_needed` does not prevent this function from
5742     /// returning an [`IdLimit`] in the case the caller wants to retire still
5743     /// unannounced Connection IDs.
5744     ///
5745     /// The caller is responsible from ensuring that the provided `scid` is not
5746     /// repeated several times over the connection. quiche ensures that as long
5747     /// as the provided Connection ID is still in use (i.e., not retired), it
5748     /// does not assign a different sequence number.
5749     ///
5750     /// Note that if the host uses zero-length Source Connection IDs, it cannot
5751     /// advertise Source Connection IDs and calling this method returns an
5752     /// [`InvalidState`].
5753     ///
5754     /// Returns the sequence number associated to the provided Connection ID.
5755     ///
5756     /// [`source_cids_left()`]: struct.Connection.html#method.source_cids_left
5757     /// [`IdLimit`]: enum.Error.html#IdLimit
5758     /// [`InvalidState`]: enum.Error.html#InvalidState
new_source_cid( &mut self, scid: &ConnectionId, reset_token: u128, retire_if_needed: bool, ) -> Result<u64>5759     pub fn new_source_cid(
5760         &mut self, scid: &ConnectionId, reset_token: u128, retire_if_needed: bool,
5761     ) -> Result<u64> {
5762         self.ids.new_scid(
5763             scid.to_vec().into(),
5764             Some(reset_token),
5765             true,
5766             None,
5767             retire_if_needed,
5768         )
5769     }
5770 
5771     /// Returns the number of source Connection IDs that are active. This is
5772     /// only meaningful if the host uses non-zero length Source Connection IDs.
active_source_cids(&self) -> usize5773     pub fn active_source_cids(&self) -> usize {
5774         self.ids.active_source_cids()
5775     }
5776 
5777     /// Returns the maximum number of concurrently active source Connection IDs
5778     /// that can be provided to the peer.
max_active_source_cids(&self) -> usize5779     pub fn max_active_source_cids(&self) -> usize {
5780         self.peer_transport_params.active_conn_id_limit as usize
5781     }
5782 
5783     /// Returns the number of source Connection IDs that can still be provided
5784     /// to the peer without exceeding the limit it advertised.
5785     ///
5786     /// The application should not issue the maximum number of permitted source
5787     /// Connection IDs, but instead treat this as an untrusted upper bound.
5788     /// Applications should limit how many outstanding source ConnectionIDs
5789     /// are simultaneously issued to prevent issuing more than they can handle.
5790     #[inline]
source_cids_left(&self) -> usize5791     pub fn source_cids_left(&self) -> usize {
5792         self.max_active_source_cids() - self.active_source_cids()
5793     }
5794 
5795     /// Requests the retirement of the destination Connection ID used by the
5796     /// host to reach its peer.
5797     ///
5798     /// This triggers sending RETIRE_CONNECTION_ID frames.
5799     ///
5800     /// If the application tries to retire a non-existing Destination Connection
5801     /// ID sequence number, or if it uses zero-length Destination Connection ID,
5802     /// this method returns an [`InvalidState`].
5803     ///
5804     /// At any time, the host must have at least one Destination ID. If the
5805     /// application tries to retire the last one, or if the caller tries to
5806     /// retire the destination Connection ID used by the current active path
5807     /// while having neither spare Destination Connection IDs nor validated
5808     /// network paths, this method returns an [`OutOfIdentifiers`]. This
5809     /// behavior prevents the caller from stalling the connection due to the
5810     /// lack of validated path to send non-probing packets.
5811     ///
5812     /// [`InvalidState`]: enum.Error.html#InvalidState
5813     /// [`OutOfIdentifiers`]: enum.Error.html#OutOfIdentifiers
retire_destination_cid(&mut self, dcid_seq: u64) -> Result<()>5814     pub fn retire_destination_cid(&mut self, dcid_seq: u64) -> Result<()> {
5815         if self.ids.zero_length_dcid() {
5816             return Err(Error::InvalidState);
5817         }
5818 
5819         let active_path_dcid_seq = self
5820             .paths
5821             .get_active()?
5822             .active_dcid_seq
5823             .ok_or(Error::InvalidState)?;
5824 
5825         let active_path_id = self.paths.get_active_path_id()?;
5826 
5827         if active_path_dcid_seq == dcid_seq &&
5828             self.ids.lowest_available_dcid_seq().is_none() &&
5829             !self
5830                 .paths
5831                 .iter()
5832                 .any(|(pid, p)| pid != active_path_id && p.usable())
5833         {
5834             return Err(Error::OutOfIdentifiers);
5835         }
5836 
5837         if let Some(pid) = self.ids.retire_dcid(dcid_seq)? {
5838             // The retired Destination CID was associated to a given path. Let's
5839             // find an available DCID to associate to that path.
5840             let path = self.paths.get_mut(pid)?;
5841             let dcid_seq = self.ids.lowest_available_dcid_seq();
5842 
5843             if let Some(dcid_seq) = dcid_seq {
5844                 self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
5845             }
5846 
5847             path.active_dcid_seq = dcid_seq;
5848         }
5849 
5850         Ok(())
5851     }
5852 
5853     /// Processes path-specific events.
5854     ///
5855     /// On success it returns a [`PathEvent`], or `None` when there are no
5856     /// events to report. Please refer to [`PathEvent`] for the exhaustive event
5857     /// list.
5858     ///
5859     /// Note that all events are edge-triggered, meaning that once reported they
5860     /// will not be reported again by calling this method again, until the event
5861     /// is re-armed.
5862     ///
5863     /// [`PathEvent`]: enum.PathEvent.html
path_event_next(&mut self) -> Option<PathEvent>5864     pub fn path_event_next(&mut self) -> Option<PathEvent> {
5865         self.paths.pop_event()
5866     }
5867 
5868     /// Returns a source `ConnectionId` that has been retired.
5869     ///
5870     /// On success it returns a [`ConnectionId`], or `None` when there are no
5871     /// more retired connection IDs.
5872     ///
5873     /// [`ConnectionId`]: struct.ConnectionId.html
retired_scid_next(&mut self) -> Option<ConnectionId<'static>>5874     pub fn retired_scid_next(&mut self) -> Option<ConnectionId<'static>> {
5875         self.ids.pop_retired_scid()
5876     }
5877 
5878     /// Returns the number of spare Destination Connection IDs, i.e.,
5879     /// Destination Connection IDs that are still unused.
5880     ///
5881     /// Note that this function returns 0 if the host uses zero length
5882     /// Destination Connection IDs.
available_dcids(&self) -> usize5883     pub fn available_dcids(&self) -> usize {
5884         self.ids.available_dcids()
5885     }
5886 
5887     /// Returns an iterator over destination `SockAddr`s whose association
5888     /// with `from` forms a known QUIC path on which packets can be sent to.
5889     ///
5890     /// This function is typically used in combination with [`send_on_path()`].
5891     ///
5892     /// Note that the iterator includes all the possible combination of
5893     /// destination `SockAddr`s, even those whose sending is not required now.
5894     /// In other words, this is another way for the application to recall from
5895     /// past [`NewPath`] events.
5896     ///
5897     /// [`NewPath`]: enum.QuicEvent.html#NewPath
5898     /// [`send_on_path()`]: struct.Connection.html#method.send_on_path
5899     ///
5900     /// ## Examples:
5901     ///
5902     /// ```no_run
5903     /// # let mut out = [0; 512];
5904     /// # let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
5905     /// # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
5906     /// # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
5907     /// # let local = socket.local_addr().unwrap();
5908     /// # let peer = "127.0.0.1:1234".parse().unwrap();
5909     /// # let mut conn = quiche::accept(&scid, None, local, peer, &mut config)?;
5910     /// // Iterate over possible destinations for the given local `SockAddr`.
5911     /// for dest in conn.paths_iter(local) {
5912     ///     loop {
5913     ///         let (write, send_info) =
5914     ///             match conn.send_on_path(&mut out, Some(local), Some(dest)) {
5915     ///                 Ok(v) => v,
5916     ///
5917     ///                 Err(quiche::Error::Done) => {
5918     ///                     // Done writing for this destination.
5919     ///                     break;
5920     ///                 },
5921     ///
5922     ///                 Err(e) => {
5923     ///                     // An error occurred, handle it.
5924     ///                     break;
5925     ///                 },
5926     ///             };
5927     ///
5928     ///         socket.send_to(&out[..write], &send_info.to).unwrap();
5929     ///     }
5930     /// }
5931     /// # Ok::<(), quiche::Error>(())
5932     /// ```
5933     #[inline]
paths_iter(&self, from: SocketAddr) -> SocketAddrIter5934     pub fn paths_iter(&self, from: SocketAddr) -> SocketAddrIter {
5935         // Instead of trying to identify whether packets will be sent on the
5936         // given 4-tuple, simply filter paths that cannot be used.
5937         SocketAddrIter {
5938             sockaddrs: self
5939                 .paths
5940                 .iter()
5941                 .filter(|(_, p)| p.usable() || p.probing_required())
5942                 .filter(|(_, p)| p.local_addr() == from)
5943                 .map(|(_, p)| p.peer_addr())
5944                 .collect(),
5945         }
5946     }
5947 
5948     /// Closes the connection with the given error and reason.
5949     ///
5950     /// The `app` parameter specifies whether an application close should be
5951     /// sent to the peer. Otherwise a normal connection close is sent.
5952     ///
5953     /// If `app` is true but the connection is not in a state that is safe to
5954     /// send an application error (not established nor in early data), in
5955     /// accordance with [RFC
5956     /// 9000](https://www.rfc-editor.org/rfc/rfc9000.html#section-10.2.3-3), the
5957     /// error code is changed to APPLICATION_ERROR and the reason phrase is
5958     /// cleared.
5959     ///
5960     /// Returns [`Done`] if the connection had already been closed.
5961     ///
5962     /// Note that the connection will not be closed immediately. An application
5963     /// should continue calling the [`recv()`], [`send()`], [`timeout()`] and
5964     /// [`on_timeout()`] methods as normal, until the [`is_closed()`] method
5965     /// returns `true`.
5966     ///
5967     /// [`Done`]: enum.Error.html#variant.Done
5968     /// [`recv()`]: struct.Connection.html#method.recv
5969     /// [`send()`]: struct.Connection.html#method.send
5970     /// [`timeout()`]: struct.Connection.html#method.timeout
5971     /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
5972     /// [`is_closed()`]: struct.Connection.html#method.is_closed
close(&mut self, app: bool, err: u64, reason: &[u8]) -> Result<()>5973     pub fn close(&mut self, app: bool, err: u64, reason: &[u8]) -> Result<()> {
5974         if self.is_closed() || self.is_draining() {
5975             return Err(Error::Done);
5976         }
5977 
5978         if self.local_error.is_some() {
5979             return Err(Error::Done);
5980         }
5981 
5982         let is_safe_to_send_app_data =
5983             self.is_established() || self.is_in_early_data();
5984 
5985         if app && !is_safe_to_send_app_data {
5986             // Clear error information.
5987             self.local_error = Some(ConnectionError {
5988                 is_app: false,
5989                 error_code: 0x0c,
5990                 reason: vec![],
5991             });
5992         } else {
5993             self.local_error = Some(ConnectionError {
5994                 is_app: app,
5995                 error_code: err,
5996                 reason: reason.to_vec(),
5997             });
5998         }
5999 
6000         // When no packet was successfully processed close connection immediately.
6001         if self.recv_count == 0 {
6002             self.closed = true;
6003         }
6004 
6005         Ok(())
6006     }
6007 
6008     /// Returns a string uniquely representing the connection.
6009     ///
6010     /// This can be used for logging purposes to differentiate between multiple
6011     /// connections.
6012     #[inline]
trace_id(&self) -> &str6013     pub fn trace_id(&self) -> &str {
6014         &self.trace_id
6015     }
6016 
6017     /// Returns the negotiated ALPN protocol.
6018     ///
6019     /// If no protocol has been negotiated, the returned value is empty.
6020     #[inline]
application_proto(&self) -> &[u8]6021     pub fn application_proto(&self) -> &[u8] {
6022         self.alpn.as_ref()
6023     }
6024 
6025     /// Returns the server name requested by the client.
6026     #[inline]
server_name(&self) -> Option<&str>6027     pub fn server_name(&self) -> Option<&str> {
6028         self.handshake.server_name()
6029     }
6030 
6031     /// Returns the peer's leaf certificate (if any) as a DER-encoded buffer.
6032     #[inline]
peer_cert(&self) -> Option<&[u8]>6033     pub fn peer_cert(&self) -> Option<&[u8]> {
6034         self.handshake.peer_cert()
6035     }
6036 
6037     /// Returns the peer's certificate chain (if any) as a vector of DER-encoded
6038     /// buffers.
6039     ///
6040     /// The certificate at index 0 is the peer's leaf certificate, the other
6041     /// certificates (if any) are the chain certificate authorities used to
6042     /// sign the leaf certificate.
6043     #[inline]
peer_cert_chain(&self) -> Option<Vec<&[u8]>>6044     pub fn peer_cert_chain(&self) -> Option<Vec<&[u8]>> {
6045         self.handshake.peer_cert_chain()
6046     }
6047 
6048     /// Returns the serialized cryptographic session for the connection.
6049     ///
6050     /// This can be used by a client to cache a connection's session, and resume
6051     /// it later using the [`set_session()`] method.
6052     ///
6053     /// [`set_session()`]: struct.Connection.html#method.set_session
6054     #[inline]
session(&self) -> Option<&[u8]>6055     pub fn session(&self) -> Option<&[u8]> {
6056         self.session.as_deref()
6057     }
6058 
6059     /// Returns the source connection ID.
6060     ///
6061     /// Note that the value returned can change throughout the connection's
6062     /// lifetime.
6063     #[inline]
source_id(&self) -> ConnectionId6064     pub fn source_id(&self) -> ConnectionId {
6065         if let Ok(path) = self.paths.get_active() {
6066             if let Some(active_scid_seq) = path.active_scid_seq {
6067                 if let Ok(e) = self.ids.get_scid(active_scid_seq) {
6068                     return ConnectionId::from_ref(e.cid.as_ref());
6069                 }
6070             }
6071         }
6072 
6073         let e = self.ids.oldest_scid();
6074         ConnectionId::from_ref(e.cid.as_ref())
6075     }
6076 
6077     /// Returns the destination connection ID.
6078     ///
6079     /// Note that the value returned can change throughout the connection's
6080     /// lifetime.
6081     #[inline]
destination_id(&self) -> ConnectionId6082     pub fn destination_id(&self) -> ConnectionId {
6083         if let Ok(path) = self.paths.get_active() {
6084             if let Some(active_dcid_seq) = path.active_dcid_seq {
6085                 if let Ok(e) = self.ids.get_dcid(active_dcid_seq) {
6086                     return ConnectionId::from_ref(e.cid.as_ref());
6087                 }
6088             }
6089         }
6090 
6091         let e = self.ids.oldest_dcid();
6092         ConnectionId::from_ref(e.cid.as_ref())
6093     }
6094 
6095     /// Returns true if the connection handshake is complete.
6096     #[inline]
is_established(&self) -> bool6097     pub fn is_established(&self) -> bool {
6098         self.handshake_completed
6099     }
6100 
6101     /// Returns true if the connection is resumed.
6102     #[inline]
is_resumed(&self) -> bool6103     pub fn is_resumed(&self) -> bool {
6104         self.handshake.is_resumed()
6105     }
6106 
6107     /// Returns true if the connection has a pending handshake that has
6108     /// progressed enough to send or receive early data.
6109     #[inline]
is_in_early_data(&self) -> bool6110     pub fn is_in_early_data(&self) -> bool {
6111         self.handshake.is_in_early_data()
6112     }
6113 
6114     /// Returns whether there is stream or DATAGRAM data available to read.
6115     #[inline]
is_readable(&self) -> bool6116     pub fn is_readable(&self) -> bool {
6117         self.streams.has_readable() || self.dgram_recv_front_len().is_some()
6118     }
6119 
6120     /// Returns whether the network path with local address `from` and remote
6121     /// address `peer` has been validated.
6122     ///
6123     /// If the 4-tuple does not exist over the connection, returns an
6124     /// [`InvalidState`].
6125     ///
6126     /// [`InvalidState`]: enum.Error.html#variant.InvalidState
is_path_validated( &self, from: SocketAddr, to: SocketAddr, ) -> Result<bool>6127     pub fn is_path_validated(
6128         &self, from: SocketAddr, to: SocketAddr,
6129     ) -> Result<bool> {
6130         let pid = self
6131             .paths
6132             .path_id_from_addrs(&(from, to))
6133             .ok_or(Error::InvalidState)?;
6134 
6135         Ok(self.paths.get(pid)?.validated())
6136     }
6137 
6138     /// Returns true if the connection is draining.
6139     ///
6140     /// If this returns `true`, the connection object cannot yet be dropped, but
6141     /// no new application data can be sent or received. An application should
6142     /// continue calling the [`recv()`], [`timeout()`], and [`on_timeout()`]
6143     /// methods as normal, until the [`is_closed()`] method returns `true`.
6144     ///
6145     /// In contrast, once `is_draining()` returns `true`, calling [`send()`]
6146     /// is not required because no new outgoing packets will be generated.
6147     ///
6148     /// [`recv()`]: struct.Connection.html#method.recv
6149     /// [`send()`]: struct.Connection.html#method.send
6150     /// [`timeout()`]: struct.Connection.html#method.timeout
6151     /// [`on_timeout()`]: struct.Connection.html#method.on_timeout
6152     /// [`is_closed()`]: struct.Connection.html#method.is_closed
6153     #[inline]
is_draining(&self) -> bool6154     pub fn is_draining(&self) -> bool {
6155         self.draining_timer.is_some()
6156     }
6157 
6158     /// Returns true if the connection is closed.
6159     ///
6160     /// If this returns true, the connection object can be dropped.
6161     #[inline]
is_closed(&self) -> bool6162     pub fn is_closed(&self) -> bool {
6163         self.closed
6164     }
6165 
6166     /// Returns true if the connection was closed due to the idle timeout.
6167     #[inline]
is_timed_out(&self) -> bool6168     pub fn is_timed_out(&self) -> bool {
6169         self.timed_out
6170     }
6171 
6172     /// Returns the error received from the peer, if any.
6173     ///
6174     /// Note that a `Some` return value does not necessarily imply
6175     /// [`is_closed()`] or any other connection state.
6176     ///
6177     /// [`is_closed()`]: struct.Connection.html#method.is_closed
6178     #[inline]
peer_error(&self) -> Option<&ConnectionError>6179     pub fn peer_error(&self) -> Option<&ConnectionError> {
6180         self.peer_error.as_ref()
6181     }
6182 
6183     /// Returns the error [`close()`] was called with, or internally
6184     /// created quiche errors, if any.
6185     ///
6186     /// Note that a `Some` return value does not necessarily imply
6187     /// [`is_closed()`] or any other connection state.
6188     /// `Some` also does not guarantee that the error has been sent to
6189     /// or received by the peer.
6190     ///
6191     /// [`close()`]: struct.Connection.html#method.close
6192     /// [`is_closed()`]: struct.Connection.html#method.is_closed
6193     #[inline]
local_error(&self) -> Option<&ConnectionError>6194     pub fn local_error(&self) -> Option<&ConnectionError> {
6195         self.local_error.as_ref()
6196     }
6197 
6198     /// Collects and returns statistics about the connection.
6199     #[inline]
stats(&self) -> Stats6200     pub fn stats(&self) -> Stats {
6201         Stats {
6202             recv: self.recv_count,
6203             sent: self.sent_count,
6204             lost: self.lost_count,
6205             retrans: self.retrans_count,
6206             sent_bytes: self.sent_bytes,
6207             recv_bytes: self.recv_bytes,
6208             lost_bytes: self.lost_bytes,
6209             stream_retrans_bytes: self.stream_retrans_bytes,
6210             paths_count: self.paths.len(),
6211             peer_max_idle_timeout: self.peer_transport_params.max_idle_timeout,
6212             peer_max_udp_payload_size: self
6213                 .peer_transport_params
6214                 .max_udp_payload_size,
6215             peer_initial_max_data: self.peer_transport_params.initial_max_data,
6216             peer_initial_max_stream_data_bidi_local: self
6217                 .peer_transport_params
6218                 .initial_max_stream_data_bidi_local,
6219             peer_initial_max_stream_data_bidi_remote: self
6220                 .peer_transport_params
6221                 .initial_max_stream_data_bidi_remote,
6222             peer_initial_max_stream_data_uni: self
6223                 .peer_transport_params
6224                 .initial_max_stream_data_uni,
6225             peer_initial_max_streams_bidi: self
6226                 .peer_transport_params
6227                 .initial_max_streams_bidi,
6228             peer_initial_max_streams_uni: self
6229                 .peer_transport_params
6230                 .initial_max_streams_uni,
6231             peer_ack_delay_exponent: self
6232                 .peer_transport_params
6233                 .ack_delay_exponent,
6234             peer_max_ack_delay: self.peer_transport_params.max_ack_delay,
6235             peer_disable_active_migration: self
6236                 .peer_transport_params
6237                 .disable_active_migration,
6238             peer_active_conn_id_limit: self
6239                 .peer_transport_params
6240                 .active_conn_id_limit,
6241             peer_max_datagram_frame_size: self
6242                 .peer_transport_params
6243                 .max_datagram_frame_size,
6244         }
6245     }
6246 
6247     /// Collects and returns statistics about each known path for the
6248     /// connection.
path_stats(&self) -> impl Iterator<Item = PathStats> + '_6249     pub fn path_stats(&self) -> impl Iterator<Item = PathStats> + '_ {
6250         self.paths.iter().map(|(_, p)| p.stats())
6251     }
6252 
encode_transport_params(&mut self) -> Result<()>6253     fn encode_transport_params(&mut self) -> Result<()> {
6254         let mut raw_params = [0; 128];
6255 
6256         let raw_params = TransportParams::encode(
6257             &self.local_transport_params,
6258             self.is_server,
6259             &mut raw_params,
6260         )?;
6261 
6262         self.handshake.set_quic_transport_params(raw_params)?;
6263 
6264         Ok(())
6265     }
6266 
parse_peer_transport_params( &mut self, peer_params: TransportParams, ) -> Result<()>6267     fn parse_peer_transport_params(
6268         &mut self, peer_params: TransportParams,
6269     ) -> Result<()> {
6270         if self.version >= PROTOCOL_VERSION_DRAFT28 ||
6271             self.version == PROTOCOL_VERSION_V1
6272         {
6273             // Validate initial_source_connection_id.
6274             match &peer_params.initial_source_connection_id {
6275                 Some(v) if v != &self.destination_id() =>
6276                     return Err(Error::InvalidTransportParam),
6277 
6278                 Some(_) => (),
6279 
6280                 // initial_source_connection_id must be sent by
6281                 // both endpoints.
6282                 None => return Err(Error::InvalidTransportParam),
6283             }
6284 
6285             // Validate original_destination_connection_id.
6286             if let Some(odcid) = &self.odcid {
6287                 match &peer_params.original_destination_connection_id {
6288                     Some(v) if v != odcid =>
6289                         return Err(Error::InvalidTransportParam),
6290 
6291                     Some(_) => (),
6292 
6293                     // original_destination_connection_id must be
6294                     // sent by the server.
6295                     None if !self.is_server =>
6296                         return Err(Error::InvalidTransportParam),
6297 
6298                     None => (),
6299                 }
6300             }
6301 
6302             // Validate retry_source_connection_id.
6303             if let Some(rscid) = &self.rscid {
6304                 match &peer_params.retry_source_connection_id {
6305                     Some(v) if v != rscid =>
6306                         return Err(Error::InvalidTransportParam),
6307 
6308                     Some(_) => (),
6309 
6310                     // retry_source_connection_id must be sent by
6311                     // the server.
6312                     None => return Err(Error::InvalidTransportParam),
6313                 }
6314             }
6315         } else {
6316             // Legacy validation of the original connection ID when
6317             // stateless retry is performed, for drafts < 28.
6318             if self.did_retry &&
6319                 peer_params.original_destination_connection_id != self.odcid
6320             {
6321                 return Err(Error::InvalidTransportParam);
6322             }
6323         }
6324 
6325         self.process_peer_transport_params(peer_params)?;
6326 
6327         self.parsed_peer_transport_params = true;
6328 
6329         Ok(())
6330     }
6331 
process_peer_transport_params( &mut self, peer_params: TransportParams, ) -> Result<()>6332     fn process_peer_transport_params(
6333         &mut self, peer_params: TransportParams,
6334     ) -> Result<()> {
6335         self.max_tx_data = peer_params.initial_max_data;
6336 
6337         // Update send capacity.
6338         self.update_tx_cap();
6339 
6340         self.streams
6341             .update_peer_max_streams_bidi(peer_params.initial_max_streams_bidi);
6342         self.streams
6343             .update_peer_max_streams_uni(peer_params.initial_max_streams_uni);
6344 
6345         let max_ack_delay =
6346             time::Duration::from_millis(peer_params.max_ack_delay);
6347 
6348         self.recovery_config.max_ack_delay = max_ack_delay;
6349 
6350         let active_path = self.paths.get_active_mut()?;
6351 
6352         active_path.recovery.max_ack_delay = max_ack_delay;
6353 
6354         active_path
6355             .recovery
6356             .update_max_datagram_size(peer_params.max_udp_payload_size as usize);
6357 
6358         // Record the max_active_conn_id parameter advertised by the peer.
6359         self.ids
6360             .set_source_conn_id_limit(peer_params.active_conn_id_limit);
6361 
6362         self.peer_transport_params = peer_params;
6363 
6364         Ok(())
6365     }
6366 
6367     /// Continues the handshake.
6368     ///
6369     /// If the connection is already established, it does nothing.
do_handshake(&mut self, now: time::Instant) -> Result<()>6370     fn do_handshake(&mut self, now: time::Instant) -> Result<()> {
6371         let mut ex_data = tls::ExData {
6372             application_protos: &self.application_protos,
6373 
6374             pkt_num_spaces: &mut self.pkt_num_spaces,
6375 
6376             session: &mut self.session,
6377 
6378             local_error: &mut self.local_error,
6379 
6380             keylog: self.keylog.as_mut(),
6381 
6382             trace_id: &self.trace_id,
6383 
6384             is_server: self.is_server,
6385         };
6386 
6387         if self.handshake_completed {
6388             return self.handshake.process_post_handshake(&mut ex_data);
6389         }
6390 
6391         match self.handshake.do_handshake(&mut ex_data) {
6392             Ok(_) => (),
6393 
6394             Err(Error::Done) => {
6395                 // Try to parse transport parameters as soon as the first flight
6396                 // of handshake data is processed.
6397                 //
6398                 // This is potentially dangerous as the handshake hasn't been
6399                 // completed yet, though it's required to be able to send data
6400                 // in 0.5 RTT.
6401                 let raw_params = self.handshake.quic_transport_params();
6402 
6403                 if !self.parsed_peer_transport_params && !raw_params.is_empty() {
6404                     let peer_params =
6405                         TransportParams::decode(raw_params, self.is_server)?;
6406 
6407                     self.parse_peer_transport_params(peer_params)?;
6408                 }
6409 
6410                 return Ok(());
6411             },
6412 
6413             Err(e) => return Err(e),
6414         };
6415 
6416         self.handshake_completed = self.handshake.is_completed();
6417 
6418         self.alpn = self.handshake.alpn_protocol().to_vec();
6419 
6420         let raw_params = self.handshake.quic_transport_params();
6421 
6422         if !self.parsed_peer_transport_params && !raw_params.is_empty() {
6423             let peer_params =
6424                 TransportParams::decode(raw_params, self.is_server)?;
6425 
6426             self.parse_peer_transport_params(peer_params)?;
6427         }
6428 
6429         if self.handshake_completed {
6430             // The handshake is considered confirmed at the server when the
6431             // handshake completes, at which point we can also drop the
6432             // handshake epoch.
6433             if self.is_server {
6434                 self.handshake_confirmed = true;
6435 
6436                 self.drop_epoch_state(packet::Epoch::Handshake, now);
6437             }
6438 
6439             // Once the handshake is completed there's no point in processing
6440             // 0-RTT packets anymore, so clear the buffer now.
6441             self.undecryptable_pkts.clear();
6442 
6443             trace!("{} connection established: proto={:?} cipher={:?} curve={:?} sigalg={:?} resumed={} {:?}",
6444                    &self.trace_id,
6445                    std::str::from_utf8(self.application_proto()),
6446                    self.handshake.cipher(),
6447                    self.handshake.curve(),
6448                    self.handshake.sigalg(),
6449                    self.handshake.is_resumed(),
6450                    self.peer_transport_params);
6451         }
6452 
6453         Ok(())
6454     }
6455 
6456     /// Selects the packet type for the next outgoing packet.
write_pkt_type(&self, send_pid: usize) -> Result<packet::Type>6457     fn write_pkt_type(&self, send_pid: usize) -> Result<packet::Type> {
6458         // On error send packet in the latest epoch available, but only send
6459         // 1-RTT ones when the handshake is completed.
6460         if self
6461             .local_error
6462             .as_ref()
6463             .map_or(false, |conn_err| !conn_err.is_app)
6464         {
6465             let epoch = match self.handshake.write_level() {
6466                 crypto::Level::Initial => packet::Epoch::Initial,
6467                 crypto::Level::ZeroRTT => unreachable!(),
6468                 crypto::Level::Handshake => packet::Epoch::Handshake,
6469                 crypto::Level::OneRTT => packet::Epoch::Application,
6470             };
6471 
6472             if !self.is_established() {
6473                 match epoch {
6474                     // Downgrade the epoch to Handshake as the handshake is not
6475                     // completed yet.
6476                     packet::Epoch::Application =>
6477                         return Ok(packet::Type::Handshake),
6478 
6479                     // Downgrade the epoch to Initial as the remote peer might
6480                     // not be able to decrypt handshake packets yet.
6481                     packet::Epoch::Handshake
6482                         if self.pkt_num_spaces[packet::Epoch::Initial]
6483                             .has_keys() =>
6484                         return Ok(packet::Type::Initial),
6485 
6486                     _ => (),
6487                 };
6488             }
6489 
6490             return Ok(packet::Type::from_epoch(epoch));
6491         }
6492 
6493         for &epoch in packet::Epoch::epochs(
6494             packet::Epoch::Initial..=packet::Epoch::Application,
6495         ) {
6496             // Only send packets in a space when we have the send keys for it.
6497             if self.pkt_num_spaces[epoch].crypto_seal.is_none() {
6498                 continue;
6499             }
6500 
6501             // We are ready to send data for this packet number space.
6502             if self.pkt_num_spaces[epoch].ready() {
6503                 return Ok(packet::Type::from_epoch(epoch));
6504             }
6505 
6506             // There are lost frames in this packet number space.
6507             for (_, p) in self.paths.iter() {
6508                 if !p.recovery.lost[epoch].is_empty() {
6509                     return Ok(packet::Type::from_epoch(epoch));
6510                 }
6511 
6512                 // We need to send PTO probe packets.
6513                 if p.recovery.loss_probes[epoch] > 0 {
6514                     return Ok(packet::Type::from_epoch(epoch));
6515                 }
6516             }
6517         }
6518 
6519         // If there are flushable, almost full or blocked streams, use the
6520         // Application epoch.
6521         let send_path = self.paths.get(send_pid)?;
6522         if (self.is_established() || self.is_in_early_data()) &&
6523             (self.should_send_handshake_done() ||
6524                 self.almost_full ||
6525                 self.blocked_limit.is_some() ||
6526                 self.dgram_send_queue.has_pending() ||
6527                 self.local_error
6528                     .as_ref()
6529                     .map_or(false, |conn_err| conn_err.is_app) ||
6530                 self.streams.should_update_max_streams_bidi() ||
6531                 self.streams.should_update_max_streams_uni() ||
6532                 self.streams.has_flushable() ||
6533                 self.streams.has_almost_full() ||
6534                 self.streams.has_blocked() ||
6535                 self.streams.has_reset() ||
6536                 self.streams.has_stopped() ||
6537                 self.ids.has_new_scids() ||
6538                 self.ids.has_retire_dcids() ||
6539                 send_path.needs_ack_eliciting ||
6540                 send_path.probing_required())
6541         {
6542             // Only clients can send 0-RTT packets.
6543             if !self.is_server && self.is_in_early_data() {
6544                 return Ok(packet::Type::ZeroRTT);
6545             }
6546 
6547             return Ok(packet::Type::Short);
6548         }
6549 
6550         Err(Error::Done)
6551     }
6552 
6553     /// Returns the mutable stream with the given ID if it exists, or creates
6554     /// a new one otherwise.
get_or_create_stream( &mut self, id: u64, local: bool, ) -> Result<&mut stream::Stream>6555     fn get_or_create_stream(
6556         &mut self, id: u64, local: bool,
6557     ) -> Result<&mut stream::Stream> {
6558         self.streams.get_or_create(
6559             id,
6560             &self.local_transport_params,
6561             &self.peer_transport_params,
6562             local,
6563             self.is_server,
6564         )
6565     }
6566 
6567     /// Processes an incoming frame.
process_frame( &mut self, frame: frame::Frame, hdr: &packet::Header, recv_path_id: usize, epoch: packet::Epoch, now: time::Instant, ) -> Result<()>6568     fn process_frame(
6569         &mut self, frame: frame::Frame, hdr: &packet::Header,
6570         recv_path_id: usize, epoch: packet::Epoch, now: time::Instant,
6571     ) -> Result<()> {
6572         trace!("{} rx frm {:?}", self.trace_id, frame);
6573 
6574         match frame {
6575             frame::Frame::Padding { .. } => (),
6576 
6577             frame::Frame::Ping => (),
6578 
6579             frame::Frame::ACK {
6580                 ranges, ack_delay, ..
6581             } => {
6582                 let ack_delay = ack_delay
6583                     .checked_mul(2_u64.pow(
6584                         self.peer_transport_params.ack_delay_exponent as u32,
6585                     ))
6586                     .ok_or(Error::InvalidFrame)?;
6587 
6588                 if epoch == packet::Epoch::Handshake ||
6589                     (epoch == packet::Epoch::Application &&
6590                         self.is_established())
6591                 {
6592                     self.peer_verified_initial_address = true;
6593                 }
6594 
6595                 let handshake_status = self.handshake_status();
6596 
6597                 let is_app_limited = self.delivery_rate_check_if_app_limited();
6598 
6599                 for (_, p) in self.paths.iter_mut() {
6600                     if is_app_limited {
6601                         p.recovery.delivery_rate_update_app_limited(true);
6602                     }
6603 
6604                     let (lost_packets, lost_bytes) = p.recovery.on_ack_received(
6605                         &ranges,
6606                         ack_delay,
6607                         epoch,
6608                         handshake_status,
6609                         now,
6610                         &self.trace_id,
6611                     )?;
6612 
6613                     self.lost_count += lost_packets;
6614                     self.lost_bytes += lost_bytes as u64;
6615                 }
6616             },
6617 
6618             frame::Frame::ResetStream {
6619                 stream_id,
6620                 error_code,
6621                 final_size,
6622             } => {
6623                 // Peer can't send on our unidirectional streams.
6624                 if !stream::is_bidi(stream_id) &&
6625                     stream::is_local(stream_id, self.is_server)
6626                 {
6627                     return Err(Error::InvalidStreamState(stream_id));
6628                 }
6629 
6630                 let max_rx_data_left = self.max_rx_data() - self.rx_data;
6631 
6632                 // Get existing stream or create a new one, but if the stream
6633                 // has already been closed and collected, ignore the frame.
6634                 //
6635                 // This can happen if e.g. an ACK frame is lost, and the peer
6636                 // retransmits another frame before it realizes that the stream
6637                 // is gone.
6638                 //
6639                 // Note that it makes it impossible to check if the frame is
6640                 // illegal, since we have no state, but since we ignore the
6641                 // frame, it should be fine.
6642                 let stream = match self.get_or_create_stream(stream_id, false) {
6643                     Ok(v) => v,
6644 
6645                     Err(Error::Done) => return Ok(()),
6646 
6647                     Err(e) => return Err(e),
6648                 };
6649 
6650                 let was_readable = stream.is_readable();
6651 
6652                 let max_off_delta =
6653                     stream.recv.reset(error_code, final_size)? as u64;
6654 
6655                 if max_off_delta > max_rx_data_left {
6656                     return Err(Error::FlowControl);
6657                 }
6658 
6659                 if !was_readable && stream.is_readable() {
6660                     self.streams.mark_readable(stream_id, true);
6661                 }
6662 
6663                 self.rx_data += max_off_delta;
6664             },
6665 
6666             frame::Frame::StopSending {
6667                 stream_id,
6668                 error_code,
6669             } => {
6670                 // STOP_SENDING on a receive-only stream is a fatal error.
6671                 if !stream::is_local(stream_id, self.is_server) &&
6672                     !stream::is_bidi(stream_id)
6673                 {
6674                     return Err(Error::InvalidStreamState(stream_id));
6675                 }
6676 
6677                 // Get existing stream or create a new one, but if the stream
6678                 // has already been closed and collected, ignore the frame.
6679                 //
6680                 // This can happen if e.g. an ACK frame is lost, and the peer
6681                 // retransmits another frame before it realizes that the stream
6682                 // is gone.
6683                 //
6684                 // Note that it makes it impossible to check if the frame is
6685                 // illegal, since we have no state, but since we ignore the
6686                 // frame, it should be fine.
6687                 let stream = match self.get_or_create_stream(stream_id, false) {
6688                     Ok(v) => v,
6689 
6690                     Err(Error::Done) => return Ok(()),
6691 
6692                     Err(e) => return Err(e),
6693                 };
6694 
6695                 let was_writable = stream.is_writable();
6696 
6697                 // Try stopping the stream.
6698                 if let Ok((final_size, unsent)) = stream.send.stop(error_code) {
6699                     // Claw back some flow control allowance from data that was
6700                     // buffered but not actually sent before the stream was
6701                     // reset.
6702                     //
6703                     // Note that `tx_cap` will be updated later on, so no need
6704                     // to touch it here.
6705                     self.tx_data = self.tx_data.saturating_sub(unsent);
6706 
6707                     self.tx_buffered =
6708                         self.tx_buffered.saturating_sub(unsent as usize);
6709 
6710                     self.streams
6711                         .mark_reset(stream_id, true, error_code, final_size);
6712 
6713                     if !was_writable {
6714                         self.streams.mark_writable(stream_id, true);
6715                     }
6716                 }
6717             },
6718 
6719             frame::Frame::Crypto { data } => {
6720                 // Push the data to the stream so it can be re-ordered.
6721                 self.pkt_num_spaces[epoch].crypto_stream.recv.write(data)?;
6722 
6723                 // Feed crypto data to the TLS state, if there's data
6724                 // available at the expected offset.
6725                 let mut crypto_buf = [0; 512];
6726 
6727                 let level = crypto::Level::from_epoch(epoch);
6728 
6729                 let stream = &mut self.pkt_num_spaces[epoch].crypto_stream;
6730 
6731                 while let Ok((read, _)) = stream.recv.emit(&mut crypto_buf) {
6732                     let recv_buf = &crypto_buf[..read];
6733                     self.handshake.provide_data(level, recv_buf)?;
6734                 }
6735 
6736                 self.do_handshake(now)?;
6737             },
6738 
6739             frame::Frame::CryptoHeader { .. } => unreachable!(),
6740 
6741             // TODO: implement stateless retry
6742             frame::Frame::NewToken { .. } => (),
6743 
6744             frame::Frame::Stream { stream_id, data } => {
6745                 // Peer can't send on our unidirectional streams.
6746                 if !stream::is_bidi(stream_id) &&
6747                     stream::is_local(stream_id, self.is_server)
6748                 {
6749                     return Err(Error::InvalidStreamState(stream_id));
6750                 }
6751 
6752                 let max_rx_data_left = self.max_rx_data() - self.rx_data;
6753 
6754                 // Get existing stream or create a new one, but if the stream
6755                 // has already been closed and collected, ignore the frame.
6756                 //
6757                 // This can happen if e.g. an ACK frame is lost, and the peer
6758                 // retransmits another frame before it realizes that the stream
6759                 // is gone.
6760                 //
6761                 // Note that it makes it impossible to check if the frame is
6762                 // illegal, since we have no state, but since we ignore the
6763                 // frame, it should be fine.
6764                 let stream = match self.get_or_create_stream(stream_id, false) {
6765                     Ok(v) => v,
6766 
6767                     Err(Error::Done) => return Ok(()),
6768 
6769                     Err(e) => return Err(e),
6770                 };
6771 
6772                 // Check for the connection-level flow control limit.
6773                 let max_off_delta =
6774                     data.max_off().saturating_sub(stream.recv.max_off());
6775 
6776                 if max_off_delta > max_rx_data_left {
6777                     return Err(Error::FlowControl);
6778                 }
6779 
6780                 let was_readable = stream.is_readable();
6781 
6782                 let was_draining = stream.is_draining();
6783 
6784                 stream.recv.write(data)?;
6785 
6786                 if !was_readable && stream.is_readable() {
6787                     self.streams.mark_readable(stream_id, true);
6788                 }
6789 
6790                 self.rx_data += max_off_delta;
6791 
6792                 if was_draining {
6793                     // When a stream is in draining state it will not queue
6794                     // incoming data for the application to read, so consider
6795                     // the received data as consumed, which might trigger a flow
6796                     // control update.
6797                     self.flow_control.add_consumed(max_off_delta);
6798 
6799                     if self.should_update_max_data() {
6800                         self.almost_full = true;
6801                     }
6802                 }
6803             },
6804 
6805             frame::Frame::StreamHeader { .. } => unreachable!(),
6806 
6807             frame::Frame::MaxData { max } => {
6808                 self.max_tx_data = cmp::max(self.max_tx_data, max);
6809             },
6810 
6811             frame::Frame::MaxStreamData { stream_id, max } => {
6812                 // Peer can't receive on its own unidirectional streams.
6813                 if !stream::is_bidi(stream_id) &&
6814                     !stream::is_local(stream_id, self.is_server)
6815                 {
6816                     return Err(Error::InvalidStreamState(stream_id));
6817                 }
6818 
6819                 // Get existing stream or create a new one, but if the stream
6820                 // has already been closed and collected, ignore the frame.
6821                 //
6822                 // This can happen if e.g. an ACK frame is lost, and the peer
6823                 // retransmits another frame before it realizes that the stream
6824                 // is gone.
6825                 //
6826                 // Note that it makes it impossible to check if the frame is
6827                 // illegal, since we have no state, but since we ignore the
6828                 // frame, it should be fine.
6829                 let stream = match self.get_or_create_stream(stream_id, false) {
6830                     Ok(v) => v,
6831 
6832                     Err(Error::Done) => return Ok(()),
6833 
6834                     Err(e) => return Err(e),
6835                 };
6836 
6837                 let was_flushable = stream.is_flushable();
6838 
6839                 stream.send.update_max_data(max);
6840 
6841                 let writable = stream.is_writable();
6842 
6843                 // If the stream is now flushable push it to the flushable queue,
6844                 // but only if it wasn't already queued.
6845                 if stream.is_flushable() && !was_flushable {
6846                     let urgency = stream.urgency;
6847                     let incremental = stream.incremental;
6848                     self.streams.push_flushable(stream_id, urgency, incremental);
6849                 }
6850 
6851                 if writable {
6852                     self.streams.mark_writable(stream_id, true);
6853                 }
6854             },
6855 
6856             frame::Frame::MaxStreamsBidi { max } => {
6857                 if max > MAX_STREAM_ID {
6858                     return Err(Error::InvalidFrame);
6859                 }
6860 
6861                 self.streams.update_peer_max_streams_bidi(max);
6862             },
6863 
6864             frame::Frame::MaxStreamsUni { max } => {
6865                 if max > MAX_STREAM_ID {
6866                     return Err(Error::InvalidFrame);
6867                 }
6868 
6869                 self.streams.update_peer_max_streams_uni(max);
6870             },
6871 
6872             frame::Frame::DataBlocked { .. } => (),
6873 
6874             frame::Frame::StreamDataBlocked { .. } => (),
6875 
6876             frame::Frame::StreamsBlockedBidi { limit } =>
6877                 if limit > MAX_STREAM_ID {
6878                     return Err(Error::InvalidFrame);
6879                 },
6880 
6881             frame::Frame::StreamsBlockedUni { limit } =>
6882                 if limit > MAX_STREAM_ID {
6883                     return Err(Error::InvalidFrame);
6884                 },
6885 
6886             frame::Frame::NewConnectionId {
6887                 seq_num,
6888                 retire_prior_to,
6889                 conn_id,
6890                 reset_token,
6891             } => {
6892                 if self.ids.zero_length_dcid() {
6893                     return Err(Error::InvalidState);
6894                 }
6895 
6896                 let retired_path_ids = self.ids.new_dcid(
6897                     conn_id.into(),
6898                     seq_num,
6899                     u128::from_be_bytes(reset_token),
6900                     retire_prior_to,
6901                 )?;
6902 
6903                 for (dcid_seq, pid) in retired_path_ids {
6904                     let path = self.paths.get_mut(pid)?;
6905 
6906                     // Maybe the path already switched to another DCID.
6907                     if path.active_dcid_seq != Some(dcid_seq) {
6908                         continue;
6909                     }
6910 
6911                     if let Some(new_dcid_seq) =
6912                         self.ids.lowest_available_dcid_seq()
6913                     {
6914                         path.active_dcid_seq = Some(new_dcid_seq);
6915 
6916                         self.ids.link_dcid_to_path_id(new_dcid_seq, pid)?;
6917 
6918                         trace!(
6919                             "{} path ID {} changed DCID: old seq num {} new seq num {}",
6920                             self.trace_id, pid, dcid_seq, new_dcid_seq,
6921                         );
6922                     } else {
6923                         // We cannot use this path anymore for now.
6924                         path.active_dcid_seq = None;
6925 
6926                         trace!(
6927                             "{} path ID {} cannot be used; DCID seq num {} has been retired",
6928                             self.trace_id, pid, dcid_seq,
6929                         );
6930                     }
6931                 }
6932             },
6933 
6934             frame::Frame::RetireConnectionId { seq_num } => {
6935                 if self.ids.zero_length_scid() {
6936                     return Err(Error::InvalidState);
6937                 }
6938 
6939                 if let Some(pid) = self.ids.retire_scid(seq_num, &hdr.dcid)? {
6940                     let path = self.paths.get_mut(pid)?;
6941 
6942                     // Maybe we already linked a new SCID to that path.
6943                     if path.active_scid_seq == Some(seq_num) {
6944                         // XXX: We do not remove unused paths now, we instead
6945                         // wait until we need to maintain more paths than the
6946                         // host is willing to.
6947                         path.active_scid_seq = None;
6948                     }
6949                 }
6950             },
6951 
6952             frame::Frame::PathChallenge { data } => {
6953                 self.paths
6954                     .get_mut(recv_path_id)?
6955                     .on_challenge_received(data);
6956             },
6957 
6958             frame::Frame::PathResponse { data } => {
6959                 self.paths.on_response_received(data)?;
6960             },
6961 
6962             frame::Frame::ConnectionClose {
6963                 error_code, reason, ..
6964             } => {
6965                 self.peer_error = Some(ConnectionError {
6966                     is_app: false,
6967                     error_code,
6968                     reason,
6969                 });
6970 
6971                 let path = self.paths.get_active()?;
6972                 self.draining_timer = Some(now + (path.recovery.pto() * 3));
6973             },
6974 
6975             frame::Frame::ApplicationClose { error_code, reason } => {
6976                 self.peer_error = Some(ConnectionError {
6977                     is_app: true,
6978                     error_code,
6979                     reason,
6980                 });
6981 
6982                 let path = self.paths.get_active()?;
6983                 self.draining_timer = Some(now + (path.recovery.pto() * 3));
6984             },
6985 
6986             frame::Frame::HandshakeDone => {
6987                 if self.is_server {
6988                     return Err(Error::InvalidPacket);
6989                 }
6990 
6991                 self.peer_verified_initial_address = true;
6992 
6993                 self.handshake_confirmed = true;
6994 
6995                 // Once the handshake is confirmed, we can drop Handshake keys.
6996                 self.drop_epoch_state(packet::Epoch::Handshake, now);
6997             },
6998 
6999             frame::Frame::Datagram { data } => {
7000                 // Close the connection if DATAGRAMs are not enabled.
7001                 // quiche always advertises support for 64K sized DATAGRAM
7002                 // frames, as recommended by the standard, so we don't need a
7003                 // size check.
7004                 if !self.dgram_enabled() {
7005                     return Err(Error::InvalidState);
7006                 }
7007 
7008                 // If recv queue is full, discard oldest
7009                 if self.dgram_recv_queue.is_full() {
7010                     self.dgram_recv_queue.pop();
7011                 }
7012 
7013                 self.dgram_recv_queue.push(data)?;
7014             },
7015 
7016             frame::Frame::DatagramHeader { .. } => unreachable!(),
7017         }
7018 
7019         Ok(())
7020     }
7021 
7022     /// Drops the keys and recovery state for the given epoch.
drop_epoch_state(&mut self, epoch: packet::Epoch, now: time::Instant)7023     fn drop_epoch_state(&mut self, epoch: packet::Epoch, now: time::Instant) {
7024         if self.pkt_num_spaces[epoch].crypto_open.is_none() {
7025             return;
7026         }
7027 
7028         self.pkt_num_spaces[epoch].crypto_open = None;
7029         self.pkt_num_spaces[epoch].crypto_seal = None;
7030         self.pkt_num_spaces[epoch].clear();
7031 
7032         let handshake_status = self.handshake_status();
7033         for (_, p) in self.paths.iter_mut() {
7034             p.recovery
7035                 .on_pkt_num_space_discarded(epoch, handshake_status, now);
7036         }
7037 
7038         trace!("{} dropped epoch {} state", self.trace_id, epoch);
7039     }
7040 
7041     /// Returns true if the connection-level flow control needs to be updated.
7042     ///
7043     /// This happens when the new max data limit is at least double the amount
7044     /// of data that can be received before blocking.
should_update_max_data(&self) -> bool7045     fn should_update_max_data(&self) -> bool {
7046         self.flow_control.should_update_max_data()
7047     }
7048 
7049     /// Returns the connection level flow control limit.
max_rx_data(&self) -> u647050     fn max_rx_data(&self) -> u64 {
7051         self.flow_control.max_data()
7052     }
7053 
7054     /// Returns true if the HANDSHAKE_DONE frame needs to be sent.
should_send_handshake_done(&self) -> bool7055     fn should_send_handshake_done(&self) -> bool {
7056         self.is_established() && !self.handshake_done_sent && self.is_server
7057     }
7058 
7059     /// Returns the idle timeout value.
7060     ///
7061     /// `None` is returned if both end-points disabled the idle timeout.
idle_timeout(&mut self) -> Option<time::Duration>7062     fn idle_timeout(&mut self) -> Option<time::Duration> {
7063         // If the transport parameter is set to 0, then the respective endpoint
7064         // decided to disable the idle timeout. If both are disabled we should
7065         // not set any timeout.
7066         if self.local_transport_params.max_idle_timeout == 0 &&
7067             self.peer_transport_params.max_idle_timeout == 0
7068         {
7069             return None;
7070         }
7071 
7072         // If the local endpoint or the peer disabled the idle timeout, use the
7073         // other peer's value, otherwise use the minimum of the two values.
7074         let idle_timeout = if self.local_transport_params.max_idle_timeout == 0 {
7075             self.peer_transport_params.max_idle_timeout
7076         } else if self.peer_transport_params.max_idle_timeout == 0 {
7077             self.local_transport_params.max_idle_timeout
7078         } else {
7079             cmp::min(
7080                 self.local_transport_params.max_idle_timeout,
7081                 self.peer_transport_params.max_idle_timeout,
7082             )
7083         };
7084 
7085         let path_pto = match self.paths.get_active() {
7086             Ok(p) => p.recovery.pto(),
7087             Err(_) => time::Duration::ZERO,
7088         };
7089 
7090         let idle_timeout = time::Duration::from_millis(idle_timeout);
7091         let idle_timeout = cmp::max(idle_timeout, 3 * path_pto);
7092 
7093         Some(idle_timeout)
7094     }
7095 
7096     /// Returns the connection's handshake status for use in loss recovery.
handshake_status(&self) -> recovery::HandshakeStatus7097     fn handshake_status(&self) -> recovery::HandshakeStatus {
7098         recovery::HandshakeStatus {
7099             has_handshake_keys: self.pkt_num_spaces[packet::Epoch::Handshake]
7100                 .has_keys(),
7101 
7102             peer_verified_address: self.peer_verified_initial_address,
7103 
7104             completed: self.is_established(),
7105         }
7106     }
7107 
7108     /// Updates send capacity.
update_tx_cap(&mut self)7109     fn update_tx_cap(&mut self) {
7110         let cwin_available = match self.paths.get_active() {
7111             Ok(p) => p.recovery.cwnd_available() as u64,
7112             Err(_) => 0,
7113         };
7114 
7115         self.tx_cap =
7116             cmp::min(cwin_available, self.max_tx_data - self.tx_data) as usize;
7117     }
7118 
delivery_rate_check_if_app_limited(&self) -> bool7119     fn delivery_rate_check_if_app_limited(&self) -> bool {
7120         // Enter the app-limited phase of delivery rate when these conditions
7121         // are met:
7122         //
7123         // - The remaining capacity is higher than available bytes in cwnd (there
7124         //   is more room to send).
7125         // - New data since the last send() is smaller than available bytes in
7126         //   cwnd (we queued less than what we can send).
7127         // - There is room to send more data in cwnd.
7128         //
7129         // In application-limited phases the transmission rate is limited by the
7130         // application rather than the congestion control algorithm.
7131         //
7132         // Note that this is equivalent to CheckIfApplicationLimited() from the
7133         // delivery rate draft. This is also separate from `recovery.app_limited`
7134         // and only applies to delivery rate calculation.
7135         let cwin_available = self
7136             .paths
7137             .iter()
7138             .filter_map(|(_, p)| p.active().then(|| p.recovery.cwnd_available()))
7139             .sum();
7140 
7141         ((self.tx_buffered + self.dgram_send_queue_len()) < cwin_available) &&
7142             (self.tx_data.saturating_sub(self.last_tx_data)) <
7143                 cwin_available as u64 &&
7144             cwin_available > 0
7145     }
7146 
set_initial_dcid( &mut self, cid: ConnectionId<'static>, reset_token: Option<u128>, path_id: usize, ) -> Result<()>7147     fn set_initial_dcid(
7148         &mut self, cid: ConnectionId<'static>, reset_token: Option<u128>,
7149         path_id: usize,
7150     ) -> Result<()> {
7151         self.ids.set_initial_dcid(cid, reset_token, Some(path_id));
7152         self.paths.get_mut(path_id)?.active_dcid_seq = Some(0);
7153 
7154         Ok(())
7155     }
7156 
7157     /// Selects the path that the incoming packet belongs to, or creates a new
7158     /// one if no existing path matches.
get_or_create_recv_path_id( &mut self, recv_pid: Option<usize>, dcid: &ConnectionId, buf_len: usize, info: &RecvInfo, ) -> Result<usize>7159     fn get_or_create_recv_path_id(
7160         &mut self, recv_pid: Option<usize>, dcid: &ConnectionId, buf_len: usize,
7161         info: &RecvInfo,
7162     ) -> Result<usize> {
7163         let ids = &mut self.ids;
7164 
7165         let (in_scid_seq, mut in_scid_pid) =
7166             ids.find_scid_seq(dcid).ok_or(Error::InvalidState)?;
7167 
7168         if let Some(recv_pid) = recv_pid {
7169             // If the path observes a change of SCID used, note it.
7170             let recv_path = self.paths.get_mut(recv_pid)?;
7171 
7172             let cid_entry =
7173                 recv_path.active_scid_seq.and_then(|v| ids.get_scid(v).ok());
7174 
7175             if cid_entry.map(|e| &e.cid) != Some(dcid) {
7176                 let incoming_cid_entry = ids.get_scid(in_scid_seq)?;
7177 
7178                 let prev_recv_pid =
7179                     incoming_cid_entry.path_id.unwrap_or(recv_pid);
7180 
7181                 if prev_recv_pid != recv_pid {
7182                     trace!(
7183                         "{} peer reused CID {:?} from path {} on path {}",
7184                         self.trace_id,
7185                         dcid,
7186                         prev_recv_pid,
7187                         recv_pid
7188                     );
7189 
7190                     // TODO: reset congestion control.
7191                 }
7192 
7193                 trace!(
7194                     "{} path ID {} now see SCID with seq num {}",
7195                     self.trace_id,
7196                     recv_pid,
7197                     in_scid_seq
7198                 );
7199 
7200                 recv_path.active_scid_seq = Some(in_scid_seq);
7201                 ids.link_scid_to_path_id(in_scid_seq, recv_pid)?;
7202             }
7203 
7204             return Ok(recv_pid);
7205         }
7206 
7207         // This is a new 4-tuple. See if the CID has not been assigned on
7208         // another path.
7209 
7210         // Ignore this step if are using zero-length SCID.
7211         if ids.zero_length_scid() {
7212             in_scid_pid = None;
7213         }
7214 
7215         if let Some(in_scid_pid) = in_scid_pid {
7216             // This CID has been used by another path. If we have the
7217             // room to do so, create a new `Path` structure holding this
7218             // new 4-tuple. Otherwise, drop the packet.
7219             let old_path = self.paths.get_mut(in_scid_pid)?;
7220             let old_local_addr = old_path.local_addr();
7221             let old_peer_addr = old_path.peer_addr();
7222 
7223             trace!(
7224                 "{} reused CID seq {} of ({},{}) (path {}) on ({},{})",
7225                 self.trace_id,
7226                 in_scid_seq,
7227                 old_local_addr,
7228                 old_peer_addr,
7229                 in_scid_pid,
7230                 info.to,
7231                 info.from
7232             );
7233 
7234             // Notify the application.
7235             self.paths
7236                 .notify_event(path::PathEvent::ReusedSourceConnectionId(
7237                     in_scid_seq,
7238                     (old_local_addr, old_peer_addr),
7239                     (info.to, info.from),
7240                 ));
7241         }
7242 
7243         // This is a new path using an unassigned CID; create it!
7244         let mut path =
7245             path::Path::new(info.to, info.from, &self.recovery_config, false);
7246 
7247         path.max_send_bytes = buf_len * MAX_AMPLIFICATION_FACTOR;
7248         path.active_scid_seq = Some(in_scid_seq);
7249 
7250         // Automatically probes the new path.
7251         path.request_validation();
7252 
7253         let pid = self.paths.insert_path(path, self.is_server)?;
7254 
7255         // Do not record path reuse.
7256         if in_scid_pid.is_none() {
7257             ids.link_scid_to_path_id(in_scid_seq, pid)?;
7258         }
7259 
7260         Ok(pid)
7261     }
7262 
7263     /// Selects the path on which the next packet must be sent.
get_send_path_id( &self, from: Option<SocketAddr>, to: Option<SocketAddr>, ) -> Result<usize>7264     fn get_send_path_id(
7265         &self, from: Option<SocketAddr>, to: Option<SocketAddr>,
7266     ) -> Result<usize> {
7267         // A probing packet must be sent, but only if the connection is fully
7268         // established.
7269         if self.is_established() {
7270             let mut probing = self
7271                 .paths
7272                 .iter()
7273                 .filter(|(_, p)| from.is_none() || Some(p.local_addr()) == from)
7274                 .filter(|(_, p)| to.is_none() || Some(p.peer_addr()) == to)
7275                 .filter(|(_, p)| p.active_dcid_seq.is_some())
7276                 .filter(|(_, p)| p.probing_required())
7277                 .map(|(pid, _)| pid);
7278 
7279             if let Some(pid) = probing.next() {
7280                 return Ok(pid);
7281             }
7282         }
7283 
7284         if let Some((pid, p)) = self.paths.get_active_with_pid() {
7285             if from.is_some() && Some(p.local_addr()) != from {
7286                 return Err(Error::Done);
7287             }
7288 
7289             if to.is_some() && Some(p.peer_addr()) != to {
7290                 return Err(Error::Done);
7291             }
7292 
7293             return Ok(pid);
7294         };
7295 
7296         Err(Error::InvalidState)
7297     }
7298 
7299     /// Creates a new client-side path.
create_path_on_client( &mut self, local_addr: SocketAddr, peer_addr: SocketAddr, ) -> Result<usize>7300     fn create_path_on_client(
7301         &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
7302     ) -> Result<usize> {
7303         if self.is_server {
7304             return Err(Error::InvalidState);
7305         }
7306 
7307         // If we use zero-length SCID and go over our local active CID limit,
7308         // the `insert_path()` call will raise an error.
7309         if !self.ids.zero_length_scid() && self.ids.available_scids() == 0 {
7310             return Err(Error::OutOfIdentifiers);
7311         }
7312 
7313         // Do we have a spare DCID? If we are using zero-length DCID, just use
7314         // the default having sequence 0 (note that if we exceed our local CID
7315         // limit, the `insert_path()` call will raise an error.
7316         let dcid_seq = if self.ids.zero_length_dcid() {
7317             0
7318         } else {
7319             self.ids
7320                 .lowest_available_dcid_seq()
7321                 .ok_or(Error::OutOfIdentifiers)?
7322         };
7323 
7324         let mut path =
7325             path::Path::new(local_addr, peer_addr, &self.recovery_config, false);
7326         path.active_dcid_seq = Some(dcid_seq);
7327 
7328         let pid = self
7329             .paths
7330             .insert_path(path, false)
7331             .map_err(|_| Error::OutOfIdentifiers)?;
7332         self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
7333 
7334         Ok(pid)
7335     }
7336 }
7337 
7338 /// Maps an `Error` to `Error::Done`, or itself.
7339 ///
7340 /// When a received packet that hasn't yet been authenticated triggers a failure
7341 /// it should, in most cases, be ignored, instead of raising a connection error,
7342 /// to avoid potential man-in-the-middle and man-on-the-side attacks.
7343 ///
7344 /// However, if no other packet was previously received, the connection should
7345 /// indeed be closed as the received packet might just be network background
7346 /// noise, and it shouldn't keep resources occupied indefinitely.
7347 ///
7348 /// This function maps an error to `Error::Done` to ignore a packet failure
7349 /// without aborting the connection, except when no other packet was previously
7350 /// received, in which case the error itself is returned, but only on the
7351 /// server-side as the client will already have armed the idle timer.
7352 ///
7353 /// This must only be used for errors preceding packet authentication. Failures
7354 /// happening after a packet has been authenticated should still cause the
7355 /// connection to be aborted.
drop_pkt_on_err( e: Error, recv_count: usize, is_server: bool, trace_id: &str, ) -> Error7356 fn drop_pkt_on_err(
7357     e: Error, recv_count: usize, is_server: bool, trace_id: &str,
7358 ) -> Error {
7359     // On the server, if no other packet has been successfully processed, abort
7360     // the connection to avoid keeping the connection open when only junk is
7361     // received.
7362     if is_server && recv_count == 0 {
7363         return e;
7364     }
7365 
7366     trace!("{} dropped invalid packet", trace_id);
7367 
7368     // Ignore other invalid packets that haven't been authenticated to prevent
7369     // man-in-the-middle and man-on-the-side attacks.
7370     Error::Done
7371 }
7372 
7373 struct AddrTupleFmt(SocketAddr, SocketAddr);
7374 
7375 impl std::fmt::Display for AddrTupleFmt {
fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result7376     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
7377         let AddrTupleFmt(src, dst) = &self;
7378 
7379         if src.ip().is_unspecified() || dst.ip().is_unspecified() {
7380             return Ok(());
7381         }
7382 
7383         f.write_fmt(format_args!("src:{src} dst:{dst}"))
7384     }
7385 }
7386 
7387 /// Statistics about the connection.
7388 ///
7389 /// A connection's statistics can be collected using the [`stats()`] method.
7390 ///
7391 /// [`stats()`]: struct.Connection.html#method.stats
7392 #[derive(Clone, Default)]
7393 pub struct Stats {
7394     /// The number of QUIC packets received.
7395     pub recv: usize,
7396 
7397     /// The number of QUIC packets sent.
7398     pub sent: usize,
7399 
7400     /// The number of QUIC packets that were lost.
7401     pub lost: usize,
7402 
7403     /// The number of sent QUIC packets with retransmitted data.
7404     pub retrans: usize,
7405 
7406     /// The number of sent bytes.
7407     pub sent_bytes: u64,
7408 
7409     /// The number of received bytes.
7410     pub recv_bytes: u64,
7411 
7412     /// The number of bytes sent lost.
7413     pub lost_bytes: u64,
7414 
7415     /// The number of stream bytes retransmitted.
7416     pub stream_retrans_bytes: u64,
7417 
7418     /// The number of known paths for the connection.
7419     pub paths_count: usize,
7420 
7421     /// The maximum idle timeout.
7422     pub peer_max_idle_timeout: u64,
7423 
7424     /// The maximum UDP payload size.
7425     pub peer_max_udp_payload_size: u64,
7426 
7427     /// The initial flow control maximum data for the connection.
7428     pub peer_initial_max_data: u64,
7429 
7430     /// The initial flow control maximum data for local bidirectional streams.
7431     pub peer_initial_max_stream_data_bidi_local: u64,
7432 
7433     /// The initial flow control maximum data for remote bidirectional streams.
7434     pub peer_initial_max_stream_data_bidi_remote: u64,
7435 
7436     /// The initial flow control maximum data for unidirectional streams.
7437     pub peer_initial_max_stream_data_uni: u64,
7438 
7439     /// The initial maximum bidirectional streams.
7440     pub peer_initial_max_streams_bidi: u64,
7441 
7442     /// The initial maximum unidirectional streams.
7443     pub peer_initial_max_streams_uni: u64,
7444 
7445     /// The ACK delay exponent.
7446     pub peer_ack_delay_exponent: u64,
7447 
7448     /// The max ACK delay.
7449     pub peer_max_ack_delay: u64,
7450 
7451     /// Whether active migration is disabled.
7452     pub peer_disable_active_migration: bool,
7453 
7454     /// The active connection ID limit.
7455     pub peer_active_conn_id_limit: u64,
7456 
7457     /// DATAGRAM frame extension parameter, if any.
7458     pub peer_max_datagram_frame_size: Option<u64>,
7459 }
7460 
7461 impl std::fmt::Debug for Stats {
7462     #[inline]
fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result7463     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
7464         write!(
7465             f,
7466             "recv={} sent={} lost={} retrans={}",
7467             self.recv, self.sent, self.lost, self.retrans,
7468         )?;
7469 
7470         write!(
7471             f,
7472             " sent_bytes={} recv_bytes={} lost_bytes={}",
7473             self.sent_bytes, self.recv_bytes, self.lost_bytes,
7474         )?;
7475 
7476         write!(f, " peer_tps={{")?;
7477 
7478         write!(f, " max_idle_timeout={},", self.peer_max_idle_timeout)?;
7479 
7480         write!(
7481             f,
7482             " max_udp_payload_size={},",
7483             self.peer_max_udp_payload_size,
7484         )?;
7485 
7486         write!(f, " initial_max_data={},", self.peer_initial_max_data)?;
7487 
7488         write!(
7489             f,
7490             " initial_max_stream_data_bidi_local={},",
7491             self.peer_initial_max_stream_data_bidi_local,
7492         )?;
7493 
7494         write!(
7495             f,
7496             " initial_max_stream_data_bidi_remote={},",
7497             self.peer_initial_max_stream_data_bidi_remote,
7498         )?;
7499 
7500         write!(
7501             f,
7502             " initial_max_stream_data_uni={},",
7503             self.peer_initial_max_stream_data_uni,
7504         )?;
7505 
7506         write!(
7507             f,
7508             " initial_max_streams_bidi={},",
7509             self.peer_initial_max_streams_bidi,
7510         )?;
7511 
7512         write!(
7513             f,
7514             " initial_max_streams_uni={},",
7515             self.peer_initial_max_streams_uni,
7516         )?;
7517 
7518         write!(f, " ack_delay_exponent={},", self.peer_ack_delay_exponent)?;
7519 
7520         write!(f, " max_ack_delay={},", self.peer_max_ack_delay)?;
7521 
7522         write!(
7523             f,
7524             " disable_active_migration={},",
7525             self.peer_disable_active_migration,
7526         )?;
7527 
7528         write!(
7529             f,
7530             " active_conn_id_limit={},",
7531             self.peer_active_conn_id_limit,
7532         )?;
7533 
7534         write!(
7535             f,
7536             " max_datagram_frame_size={:?}",
7537             self.peer_max_datagram_frame_size,
7538         )?;
7539 
7540         write!(f, "}}")
7541     }
7542 }
7543 
7544 #[derive(Clone, Debug, PartialEq)]
7545 struct TransportParams {
7546     pub original_destination_connection_id: Option<ConnectionId<'static>>,
7547     pub max_idle_timeout: u64,
7548     pub stateless_reset_token: Option<u128>,
7549     pub max_udp_payload_size: u64,
7550     pub initial_max_data: u64,
7551     pub initial_max_stream_data_bidi_local: u64,
7552     pub initial_max_stream_data_bidi_remote: u64,
7553     pub initial_max_stream_data_uni: u64,
7554     pub initial_max_streams_bidi: u64,
7555     pub initial_max_streams_uni: u64,
7556     pub ack_delay_exponent: u64,
7557     pub max_ack_delay: u64,
7558     pub disable_active_migration: bool,
7559     // pub preferred_address: ...,
7560     pub active_conn_id_limit: u64,
7561     pub initial_source_connection_id: Option<ConnectionId<'static>>,
7562     pub retry_source_connection_id: Option<ConnectionId<'static>>,
7563     pub max_datagram_frame_size: Option<u64>,
7564 }
7565 
7566 impl Default for TransportParams {
default() -> TransportParams7567     fn default() -> TransportParams {
7568         TransportParams {
7569             original_destination_connection_id: None,
7570             max_idle_timeout: 0,
7571             stateless_reset_token: None,
7572             max_udp_payload_size: 65527,
7573             initial_max_data: 0,
7574             initial_max_stream_data_bidi_local: 0,
7575             initial_max_stream_data_bidi_remote: 0,
7576             initial_max_stream_data_uni: 0,
7577             initial_max_streams_bidi: 0,
7578             initial_max_streams_uni: 0,
7579             ack_delay_exponent: 3,
7580             max_ack_delay: 25,
7581             disable_active_migration: false,
7582             active_conn_id_limit: 2,
7583             initial_source_connection_id: None,
7584             retry_source_connection_id: None,
7585             max_datagram_frame_size: None,
7586         }
7587     }
7588 }
7589 
7590 impl TransportParams {
decode(buf: &[u8], is_server: bool) -> Result<TransportParams>7591     fn decode(buf: &[u8], is_server: bool) -> Result<TransportParams> {
7592         let mut params = octets::Octets::with_slice(buf);
7593         let mut seen_params = HashSet::new();
7594 
7595         let mut tp = TransportParams::default();
7596 
7597         while params.cap() > 0 {
7598             let id = params.get_varint()?;
7599 
7600             if seen_params.contains(&id) {
7601                 return Err(Error::InvalidTransportParam);
7602             }
7603             seen_params.insert(id);
7604 
7605             let mut val = params.get_bytes_with_varint_length()?;
7606 
7607             match id {
7608                 0x0000 => {
7609                     if is_server {
7610                         return Err(Error::InvalidTransportParam);
7611                     }
7612 
7613                     tp.original_destination_connection_id =
7614                         Some(val.to_vec().into());
7615                 },
7616 
7617                 0x0001 => {
7618                     tp.max_idle_timeout = val.get_varint()?;
7619                 },
7620 
7621                 0x0002 => {
7622                     if is_server {
7623                         return Err(Error::InvalidTransportParam);
7624                     }
7625 
7626                     tp.stateless_reset_token = Some(u128::from_be_bytes(
7627                         val.get_bytes(16)?
7628                             .to_vec()
7629                             .try_into()
7630                             .map_err(|_| Error::BufferTooShort)?,
7631                     ));
7632                 },
7633 
7634                 0x0003 => {
7635                     tp.max_udp_payload_size = val.get_varint()?;
7636 
7637                     if tp.max_udp_payload_size < 1200 {
7638                         return Err(Error::InvalidTransportParam);
7639                     }
7640                 },
7641 
7642                 0x0004 => {
7643                     tp.initial_max_data = val.get_varint()?;
7644                 },
7645 
7646                 0x0005 => {
7647                     tp.initial_max_stream_data_bidi_local = val.get_varint()?;
7648                 },
7649 
7650                 0x0006 => {
7651                     tp.initial_max_stream_data_bidi_remote = val.get_varint()?;
7652                 },
7653 
7654                 0x0007 => {
7655                     tp.initial_max_stream_data_uni = val.get_varint()?;
7656                 },
7657 
7658                 0x0008 => {
7659                     let max = val.get_varint()?;
7660 
7661                     if max > MAX_STREAM_ID {
7662                         return Err(Error::InvalidTransportParam);
7663                     }
7664 
7665                     tp.initial_max_streams_bidi = max;
7666                 },
7667 
7668                 0x0009 => {
7669                     let max = val.get_varint()?;
7670 
7671                     if max > MAX_STREAM_ID {
7672                         return Err(Error::InvalidTransportParam);
7673                     }
7674 
7675                     tp.initial_max_streams_uni = max;
7676                 },
7677 
7678                 0x000a => {
7679                     let ack_delay_exponent = val.get_varint()?;
7680 
7681                     if ack_delay_exponent > 20 {
7682                         return Err(Error::InvalidTransportParam);
7683                     }
7684 
7685                     tp.ack_delay_exponent = ack_delay_exponent;
7686                 },
7687 
7688                 0x000b => {
7689                     let max_ack_delay = val.get_varint()?;
7690 
7691                     if max_ack_delay >= 2_u64.pow(14) {
7692                         return Err(Error::InvalidTransportParam);
7693                     }
7694 
7695                     tp.max_ack_delay = max_ack_delay;
7696                 },
7697 
7698                 0x000c => {
7699                     tp.disable_active_migration = true;
7700                 },
7701 
7702                 0x000d => {
7703                     if is_server {
7704                         return Err(Error::InvalidTransportParam);
7705                     }
7706 
7707                     // TODO: decode preferred_address
7708                 },
7709 
7710                 0x000e => {
7711                     let limit = val.get_varint()?;
7712 
7713                     if limit < 2 {
7714                         return Err(Error::InvalidTransportParam);
7715                     }
7716 
7717                     tp.active_conn_id_limit = limit;
7718                 },
7719 
7720                 0x000f => {
7721                     tp.initial_source_connection_id = Some(val.to_vec().into());
7722                 },
7723 
7724                 0x00010 => {
7725                     if is_server {
7726                         return Err(Error::InvalidTransportParam);
7727                     }
7728 
7729                     tp.retry_source_connection_id = Some(val.to_vec().into());
7730                 },
7731 
7732                 0x0020 => {
7733                     tp.max_datagram_frame_size = Some(val.get_varint()?);
7734                 },
7735 
7736                 // Ignore unknown parameters.
7737                 _ => (),
7738             }
7739         }
7740 
7741         Ok(tp)
7742     }
7743 
encode_param( b: &mut octets::OctetsMut, ty: u64, len: usize, ) -> Result<()>7744     fn encode_param(
7745         b: &mut octets::OctetsMut, ty: u64, len: usize,
7746     ) -> Result<()> {
7747         b.put_varint(ty)?;
7748         b.put_varint(len as u64)?;
7749 
7750         Ok(())
7751     }
7752 
encode<'a>( tp: &TransportParams, is_server: bool, out: &'a mut [u8], ) -> Result<&'a mut [u8]>7753     fn encode<'a>(
7754         tp: &TransportParams, is_server: bool, out: &'a mut [u8],
7755     ) -> Result<&'a mut [u8]> {
7756         let mut b = octets::OctetsMut::with_slice(out);
7757 
7758         if is_server {
7759             if let Some(ref odcid) = tp.original_destination_connection_id {
7760                 TransportParams::encode_param(&mut b, 0x0000, odcid.len())?;
7761                 b.put_bytes(odcid)?;
7762             }
7763         };
7764 
7765         if tp.max_idle_timeout != 0 {
7766             TransportParams::encode_param(
7767                 &mut b,
7768                 0x0001,
7769                 octets::varint_len(tp.max_idle_timeout),
7770             )?;
7771             b.put_varint(tp.max_idle_timeout)?;
7772         }
7773 
7774         if is_server {
7775             if let Some(ref token) = tp.stateless_reset_token {
7776                 TransportParams::encode_param(&mut b, 0x0002, 16)?;
7777                 b.put_bytes(&token.to_be_bytes())?;
7778             }
7779         }
7780 
7781         if tp.max_udp_payload_size != 0 {
7782             TransportParams::encode_param(
7783                 &mut b,
7784                 0x0003,
7785                 octets::varint_len(tp.max_udp_payload_size),
7786             )?;
7787             b.put_varint(tp.max_udp_payload_size)?;
7788         }
7789 
7790         if tp.initial_max_data != 0 {
7791             TransportParams::encode_param(
7792                 &mut b,
7793                 0x0004,
7794                 octets::varint_len(tp.initial_max_data),
7795             )?;
7796             b.put_varint(tp.initial_max_data)?;
7797         }
7798 
7799         if tp.initial_max_stream_data_bidi_local != 0 {
7800             TransportParams::encode_param(
7801                 &mut b,
7802                 0x0005,
7803                 octets::varint_len(tp.initial_max_stream_data_bidi_local),
7804             )?;
7805             b.put_varint(tp.initial_max_stream_data_bidi_local)?;
7806         }
7807 
7808         if tp.initial_max_stream_data_bidi_remote != 0 {
7809             TransportParams::encode_param(
7810                 &mut b,
7811                 0x0006,
7812                 octets::varint_len(tp.initial_max_stream_data_bidi_remote),
7813             )?;
7814             b.put_varint(tp.initial_max_stream_data_bidi_remote)?;
7815         }
7816 
7817         if tp.initial_max_stream_data_uni != 0 {
7818             TransportParams::encode_param(
7819                 &mut b,
7820                 0x0007,
7821                 octets::varint_len(tp.initial_max_stream_data_uni),
7822             )?;
7823             b.put_varint(tp.initial_max_stream_data_uni)?;
7824         }
7825 
7826         if tp.initial_max_streams_bidi != 0 {
7827             TransportParams::encode_param(
7828                 &mut b,
7829                 0x0008,
7830                 octets::varint_len(tp.initial_max_streams_bidi),
7831             )?;
7832             b.put_varint(tp.initial_max_streams_bidi)?;
7833         }
7834 
7835         if tp.initial_max_streams_uni != 0 {
7836             TransportParams::encode_param(
7837                 &mut b,
7838                 0x0009,
7839                 octets::varint_len(tp.initial_max_streams_uni),
7840             )?;
7841             b.put_varint(tp.initial_max_streams_uni)?;
7842         }
7843 
7844         if tp.ack_delay_exponent != 0 {
7845             TransportParams::encode_param(
7846                 &mut b,
7847                 0x000a,
7848                 octets::varint_len(tp.ack_delay_exponent),
7849             )?;
7850             b.put_varint(tp.ack_delay_exponent)?;
7851         }
7852 
7853         if tp.max_ack_delay != 0 {
7854             TransportParams::encode_param(
7855                 &mut b,
7856                 0x000b,
7857                 octets::varint_len(tp.max_ack_delay),
7858             )?;
7859             b.put_varint(tp.max_ack_delay)?;
7860         }
7861 
7862         if tp.disable_active_migration {
7863             TransportParams::encode_param(&mut b, 0x000c, 0)?;
7864         }
7865 
7866         // TODO: encode preferred_address
7867 
7868         if tp.active_conn_id_limit != 2 {
7869             TransportParams::encode_param(
7870                 &mut b,
7871                 0x000e,
7872                 octets::varint_len(tp.active_conn_id_limit),
7873             )?;
7874             b.put_varint(tp.active_conn_id_limit)?;
7875         }
7876 
7877         if let Some(scid) = &tp.initial_source_connection_id {
7878             TransportParams::encode_param(&mut b, 0x000f, scid.len())?;
7879             b.put_bytes(scid)?;
7880         }
7881 
7882         if is_server {
7883             if let Some(scid) = &tp.retry_source_connection_id {
7884                 TransportParams::encode_param(&mut b, 0x0010, scid.len())?;
7885                 b.put_bytes(scid)?;
7886             }
7887         }
7888 
7889         if let Some(max_datagram_frame_size) = tp.max_datagram_frame_size {
7890             TransportParams::encode_param(
7891                 &mut b,
7892                 0x0020,
7893                 octets::varint_len(max_datagram_frame_size),
7894             )?;
7895             b.put_varint(max_datagram_frame_size)?;
7896         }
7897 
7898         let out_len = b.off();
7899 
7900         Ok(&mut out[..out_len])
7901     }
7902 
7903     /// Creates a qlog event for connection transport parameters and TLS fields
7904     #[cfg(feature = "qlog")]
to_qlog( &self, owner: TransportOwner, cipher: Option<crypto::Algorithm>, ) -> EventData7905     pub fn to_qlog(
7906         &self, owner: TransportOwner, cipher: Option<crypto::Algorithm>,
7907     ) -> EventData {
7908         let original_destination_connection_id = qlog::HexSlice::maybe_string(
7909             self.original_destination_connection_id.as_ref(),
7910         );
7911 
7912         let stateless_reset_token = qlog::HexSlice::maybe_string(
7913             self.stateless_reset_token.map(|s| s.to_be_bytes()).as_ref(),
7914         );
7915 
7916         EventData::TransportParametersSet(
7917             qlog::events::quic::TransportParametersSet {
7918                 owner: Some(owner),
7919                 resumption_allowed: None,
7920                 early_data_enabled: None,
7921                 tls_cipher: Some(format!("{cipher:?}")),
7922                 aead_tag_length: None,
7923                 original_destination_connection_id,
7924                 initial_source_connection_id: None,
7925                 retry_source_connection_id: None,
7926                 stateless_reset_token,
7927                 disable_active_migration: Some(self.disable_active_migration),
7928                 max_idle_timeout: Some(self.max_idle_timeout),
7929                 max_udp_payload_size: Some(self.max_udp_payload_size as u32),
7930                 ack_delay_exponent: Some(self.ack_delay_exponent as u16),
7931                 max_ack_delay: Some(self.max_ack_delay as u16),
7932                 active_connection_id_limit: Some(
7933                     self.active_conn_id_limit as u32,
7934                 ),
7935 
7936                 initial_max_data: Some(self.initial_max_data),
7937                 initial_max_stream_data_bidi_local: Some(
7938                     self.initial_max_stream_data_bidi_local,
7939                 ),
7940                 initial_max_stream_data_bidi_remote: Some(
7941                     self.initial_max_stream_data_bidi_remote,
7942                 ),
7943                 initial_max_stream_data_uni: Some(
7944                     self.initial_max_stream_data_uni,
7945                 ),
7946                 initial_max_streams_bidi: Some(self.initial_max_streams_bidi),
7947                 initial_max_streams_uni: Some(self.initial_max_streams_uni),
7948 
7949                 preferred_address: None,
7950             },
7951         )
7952     }
7953 }
7954 
7955 #[doc(hidden)]
7956 pub mod testing {
7957     use super::*;
7958 
7959     pub struct Pipe {
7960         pub client: Connection,
7961         pub server: Connection,
7962     }
7963 
7964     impl Pipe {
new() -> Result<Pipe>7965         pub fn new() -> Result<Pipe> {
7966             let mut config = Config::new(crate::PROTOCOL_VERSION)?;
7967             config.load_cert_chain_from_pem_file("examples/cert.crt")?;
7968             config.load_priv_key_from_pem_file("examples/cert.key")?;
7969             config.set_application_protos(&[b"proto1", b"proto2"])?;
7970             config.set_initial_max_data(30);
7971             config.set_initial_max_stream_data_bidi_local(15);
7972             config.set_initial_max_stream_data_bidi_remote(15);
7973             config.set_initial_max_stream_data_uni(10);
7974             config.set_initial_max_streams_bidi(3);
7975             config.set_initial_max_streams_uni(3);
7976             config.set_max_idle_timeout(180_000);
7977             config.verify_peer(false);
7978             config.set_ack_delay_exponent(8);
7979 
7980             Pipe::with_config(&mut config)
7981         }
7982 
client_addr() -> SocketAddr7983         pub fn client_addr() -> SocketAddr {
7984             "127.0.0.1:1234".parse().unwrap()
7985         }
7986 
server_addr() -> SocketAddr7987         pub fn server_addr() -> SocketAddr {
7988             "127.0.0.1:4321".parse().unwrap()
7989         }
7990 
with_config(config: &mut Config) -> Result<Pipe>7991         pub fn with_config(config: &mut Config) -> Result<Pipe> {
7992             let mut client_scid = [0; 16];
7993             rand::rand_bytes(&mut client_scid[..]);
7994             let client_scid = ConnectionId::from_ref(&client_scid);
7995             let client_addr = Pipe::client_addr();
7996 
7997             let mut server_scid = [0; 16];
7998             rand::rand_bytes(&mut server_scid[..]);
7999             let server_scid = ConnectionId::from_ref(&server_scid);
8000             let server_addr = Pipe::server_addr();
8001 
8002             Ok(Pipe {
8003                 client: connect(
8004                     Some("quic.tech"),
8005                     &client_scid,
8006                     client_addr,
8007                     server_addr,
8008                     config,
8009                 )?,
8010                 server: accept(
8011                     &server_scid,
8012                     None,
8013                     server_addr,
8014                     client_addr,
8015                     config,
8016                 )?,
8017             })
8018         }
8019 
with_config_and_scid_lengths( config: &mut Config, client_scid_len: usize, server_scid_len: usize, ) -> Result<Pipe>8020         pub fn with_config_and_scid_lengths(
8021             config: &mut Config, client_scid_len: usize, server_scid_len: usize,
8022         ) -> Result<Pipe> {
8023             let mut client_scid = vec![0; client_scid_len];
8024             rand::rand_bytes(&mut client_scid[..]);
8025             let client_scid = ConnectionId::from_ref(&client_scid);
8026             let client_addr = Pipe::client_addr();
8027 
8028             let mut server_scid = vec![0; server_scid_len];
8029             rand::rand_bytes(&mut server_scid[..]);
8030             let server_scid = ConnectionId::from_ref(&server_scid);
8031             let server_addr = Pipe::server_addr();
8032 
8033             Ok(Pipe {
8034                 client: connect(
8035                     Some("quic.tech"),
8036                     &client_scid,
8037                     client_addr,
8038                     server_addr,
8039                     config,
8040                 )?,
8041                 server: accept(
8042                     &server_scid,
8043                     None,
8044                     server_addr,
8045                     client_addr,
8046                     config,
8047                 )?,
8048             })
8049         }
8050 
with_client_config(client_config: &mut Config) -> Result<Pipe>8051         pub fn with_client_config(client_config: &mut Config) -> Result<Pipe> {
8052             let mut client_scid = [0; 16];
8053             rand::rand_bytes(&mut client_scid[..]);
8054             let client_scid = ConnectionId::from_ref(&client_scid);
8055             let client_addr = Pipe::client_addr();
8056 
8057             let mut server_scid = [0; 16];
8058             rand::rand_bytes(&mut server_scid[..]);
8059             let server_scid = ConnectionId::from_ref(&server_scid);
8060             let server_addr = Pipe::server_addr();
8061 
8062             let mut config = Config::new(crate::PROTOCOL_VERSION)?;
8063             config.load_cert_chain_from_pem_file("examples/cert.crt")?;
8064             config.load_priv_key_from_pem_file("examples/cert.key")?;
8065             config.set_application_protos(&[b"proto1", b"proto2"])?;
8066             config.set_initial_max_data(30);
8067             config.set_initial_max_stream_data_bidi_local(15);
8068             config.set_initial_max_stream_data_bidi_remote(15);
8069             config.set_initial_max_streams_bidi(3);
8070             config.set_initial_max_streams_uni(3);
8071             config.set_ack_delay_exponent(8);
8072 
8073             Ok(Pipe {
8074                 client: connect(
8075                     Some("quic.tech"),
8076                     &client_scid,
8077                     client_addr,
8078                     server_addr,
8079                     client_config,
8080                 )?,
8081                 server: accept(
8082                     &server_scid,
8083                     None,
8084                     server_addr,
8085                     client_addr,
8086                     &mut config,
8087                 )?,
8088             })
8089         }
8090 
with_server_config(server_config: &mut Config) -> Result<Pipe>8091         pub fn with_server_config(server_config: &mut Config) -> Result<Pipe> {
8092             let mut client_scid = [0; 16];
8093             rand::rand_bytes(&mut client_scid[..]);
8094             let client_scid = ConnectionId::from_ref(&client_scid);
8095             let client_addr = Pipe::client_addr();
8096 
8097             let mut server_scid = [0; 16];
8098             rand::rand_bytes(&mut server_scid[..]);
8099             let server_scid = ConnectionId::from_ref(&server_scid);
8100             let server_addr = Pipe::server_addr();
8101 
8102             let mut config = Config::new(crate::PROTOCOL_VERSION)?;
8103             config.set_application_protos(&[b"proto1", b"proto2"])?;
8104             config.set_initial_max_data(30);
8105             config.set_initial_max_stream_data_bidi_local(15);
8106             config.set_initial_max_stream_data_bidi_remote(15);
8107             config.set_initial_max_streams_bidi(3);
8108             config.set_initial_max_streams_uni(3);
8109             config.set_ack_delay_exponent(8);
8110 
8111             Ok(Pipe {
8112                 client: connect(
8113                     Some("quic.tech"),
8114                     &client_scid,
8115                     client_addr,
8116                     server_addr,
8117                     &mut config,
8118                 )?,
8119                 server: accept(
8120                     &server_scid,
8121                     None,
8122                     server_addr,
8123                     client_addr,
8124                     server_config,
8125                 )?,
8126             })
8127         }
8128 
handshake(&mut self) -> Result<()>8129         pub fn handshake(&mut self) -> Result<()> {
8130             while !self.client.is_established() || !self.server.is_established() {
8131                 let flight = emit_flight(&mut self.client)?;
8132                 process_flight(&mut self.server, flight)?;
8133 
8134                 let flight = emit_flight(&mut self.server)?;
8135                 process_flight(&mut self.client, flight)?;
8136             }
8137 
8138             Ok(())
8139         }
8140 
advance(&mut self) -> Result<()>8141         pub fn advance(&mut self) -> Result<()> {
8142             let mut client_done = false;
8143             let mut server_done = false;
8144 
8145             while !client_done || !server_done {
8146                 match emit_flight(&mut self.client) {
8147                     Ok(flight) => process_flight(&mut self.server, flight)?,
8148 
8149                     Err(Error::Done) => client_done = true,
8150 
8151                     Err(e) => return Err(e),
8152                 };
8153 
8154                 match emit_flight(&mut self.server) {
8155                     Ok(flight) => process_flight(&mut self.client, flight)?,
8156 
8157                     Err(Error::Done) => server_done = true,
8158 
8159                     Err(e) => return Err(e),
8160                 };
8161             }
8162 
8163             Ok(())
8164         }
8165 
client_recv(&mut self, buf: &mut [u8]) -> Result<usize>8166         pub fn client_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
8167             let server_path = &self.server.paths.get_active().unwrap();
8168             let info = RecvInfo {
8169                 to: server_path.peer_addr(),
8170                 from: server_path.local_addr(),
8171             };
8172 
8173             self.client.recv(buf, info)
8174         }
8175 
server_recv(&mut self, buf: &mut [u8]) -> Result<usize>8176         pub fn server_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
8177             let client_path = &self.client.paths.get_active().unwrap();
8178             let info = RecvInfo {
8179                 to: client_path.peer_addr(),
8180                 from: client_path.local_addr(),
8181             };
8182 
8183             self.server.recv(buf, info)
8184         }
8185 
send_pkt_to_server( &mut self, pkt_type: packet::Type, frames: &[frame::Frame], buf: &mut [u8], ) -> Result<usize>8186         pub fn send_pkt_to_server(
8187             &mut self, pkt_type: packet::Type, frames: &[frame::Frame],
8188             buf: &mut [u8],
8189         ) -> Result<usize> {
8190             let written = encode_pkt(&mut self.client, pkt_type, frames, buf)?;
8191             recv_send(&mut self.server, buf, written)
8192         }
8193 
client_update_key(&mut self) -> Result<()>8194         pub fn client_update_key(&mut self) -> Result<()> {
8195             let space =
8196                 &mut self.client.pkt_num_spaces[packet::Epoch::Application];
8197 
8198             let open_next = space
8199                 .crypto_open
8200                 .as_ref()
8201                 .unwrap()
8202                 .derive_next_packet_key()
8203                 .unwrap();
8204 
8205             let seal_next = space
8206                 .crypto_seal
8207                 .as_ref()
8208                 .unwrap()
8209                 .derive_next_packet_key()?;
8210 
8211             let open_prev = space.crypto_open.replace(open_next);
8212             space.crypto_seal.replace(seal_next);
8213 
8214             space.key_update = Some(packet::KeyUpdate {
8215                 crypto_open: open_prev.unwrap(),
8216                 pn_on_update: space.next_pkt_num,
8217                 update_acked: true,
8218                 timer: time::Instant::now(),
8219             });
8220 
8221             self.client.key_phase = !self.client.key_phase;
8222 
8223             Ok(())
8224         }
8225     }
8226 
recv_send( conn: &mut Connection, buf: &mut [u8], len: usize, ) -> Result<usize>8227     pub fn recv_send(
8228         conn: &mut Connection, buf: &mut [u8], len: usize,
8229     ) -> Result<usize> {
8230         let active_path = conn.paths.get_active()?;
8231         let info = RecvInfo {
8232             to: active_path.local_addr(),
8233             from: active_path.peer_addr(),
8234         };
8235 
8236         conn.recv(&mut buf[..len], info)?;
8237 
8238         let mut off = 0;
8239 
8240         match conn.send(&mut buf[off..]) {
8241             Ok((write, _)) => off += write,
8242 
8243             Err(Error::Done) => (),
8244 
8245             Err(e) => return Err(e),
8246         }
8247 
8248         Ok(off)
8249     }
8250 
process_flight( conn: &mut Connection, flight: Vec<(Vec<u8>, SendInfo)>, ) -> Result<()>8251     pub fn process_flight(
8252         conn: &mut Connection, flight: Vec<(Vec<u8>, SendInfo)>,
8253     ) -> Result<()> {
8254         for (mut pkt, si) in flight {
8255             let info = RecvInfo {
8256                 to: si.to,
8257                 from: si.from,
8258             };
8259 
8260             conn.recv(&mut pkt, info)?;
8261         }
8262 
8263         Ok(())
8264     }
8265 
emit_flight_with_max_buffer( conn: &mut Connection, out_size: usize, ) -> Result<Vec<(Vec<u8>, SendInfo)>>8266     pub fn emit_flight_with_max_buffer(
8267         conn: &mut Connection, out_size: usize,
8268     ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
8269         let mut flight = Vec::new();
8270 
8271         loop {
8272             let mut out = vec![0u8; out_size];
8273 
8274             let info = match conn.send(&mut out) {
8275                 Ok((written, info)) => {
8276                     out.truncate(written);
8277                     info
8278                 },
8279 
8280                 Err(Error::Done) => break,
8281 
8282                 Err(e) => return Err(e),
8283             };
8284 
8285             flight.push((out, info));
8286         }
8287 
8288         if flight.is_empty() {
8289             return Err(Error::Done);
8290         }
8291 
8292         Ok(flight)
8293     }
8294 
emit_flight( conn: &mut Connection, ) -> Result<Vec<(Vec<u8>, SendInfo)>>8295     pub fn emit_flight(
8296         conn: &mut Connection,
8297     ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
8298         emit_flight_with_max_buffer(conn, 65535)
8299     }
8300 
encode_pkt( conn: &mut Connection, pkt_type: packet::Type, frames: &[frame::Frame], buf: &mut [u8], ) -> Result<usize>8301     pub fn encode_pkt(
8302         conn: &mut Connection, pkt_type: packet::Type, frames: &[frame::Frame],
8303         buf: &mut [u8],
8304     ) -> Result<usize> {
8305         let mut b = octets::OctetsMut::with_slice(buf);
8306 
8307         let epoch = pkt_type.to_epoch()?;
8308 
8309         let space = &mut conn.pkt_num_spaces[epoch];
8310 
8311         let pn = space.next_pkt_num;
8312         let pn_len = 4;
8313 
8314         let send_path = conn.paths.get_active()?;
8315         let active_dcid_seq = send_path
8316             .active_dcid_seq
8317             .as_ref()
8318             .ok_or(Error::InvalidState)?;
8319         let active_scid_seq = send_path
8320             .active_scid_seq
8321             .as_ref()
8322             .ok_or(Error::InvalidState)?;
8323 
8324         let hdr = Header {
8325             ty: pkt_type,
8326             version: conn.version,
8327             dcid: ConnectionId::from_ref(
8328                 conn.ids.get_dcid(*active_dcid_seq)?.cid.as_ref(),
8329             ),
8330             scid: ConnectionId::from_ref(
8331                 conn.ids.get_scid(*active_scid_seq)?.cid.as_ref(),
8332             ),
8333             pkt_num: 0,
8334             pkt_num_len: pn_len,
8335             token: conn.token.clone(),
8336             versions: None,
8337             key_phase: conn.key_phase,
8338         };
8339 
8340         hdr.to_bytes(&mut b)?;
8341 
8342         let payload_len = frames.iter().fold(0, |acc, x| acc + x.wire_len());
8343 
8344         if pkt_type != packet::Type::Short {
8345             let len = pn_len + payload_len + space.crypto_overhead().unwrap();
8346             b.put_varint(len as u64)?;
8347         }
8348 
8349         // Always encode packet number in 4 bytes, to allow encoding packets
8350         // with empty payloads.
8351         b.put_u32(pn as u32)?;
8352 
8353         let payload_offset = b.off();
8354 
8355         for frame in frames {
8356             frame.to_bytes(&mut b)?;
8357         }
8358 
8359         let aead = match space.crypto_seal {
8360             Some(ref v) => v,
8361             None => return Err(Error::InvalidState),
8362         };
8363 
8364         let written = packet::encrypt_pkt(
8365             &mut b,
8366             pn,
8367             pn_len,
8368             payload_len,
8369             payload_offset,
8370             None,
8371             aead,
8372         )?;
8373 
8374         space.next_pkt_num += 1;
8375 
8376         Ok(written)
8377     }
8378 
decode_pkt( conn: &mut Connection, buf: &mut [u8], len: usize, ) -> Result<Vec<frame::Frame>>8379     pub fn decode_pkt(
8380         conn: &mut Connection, buf: &mut [u8], len: usize,
8381     ) -> Result<Vec<frame::Frame>> {
8382         let mut b = octets::OctetsMut::with_slice(&mut buf[..len]);
8383 
8384         let mut hdr = Header::from_bytes(&mut b, conn.source_id().len()).unwrap();
8385 
8386         let epoch = hdr.ty.to_epoch()?;
8387 
8388         let aead = conn.pkt_num_spaces[epoch].crypto_open.as_ref().unwrap();
8389 
8390         let payload_len = b.cap();
8391 
8392         packet::decrypt_hdr(&mut b, &mut hdr, aead).unwrap();
8393 
8394         let pn = packet::decode_pkt_num(
8395             conn.pkt_num_spaces[epoch].largest_rx_pkt_num,
8396             hdr.pkt_num,
8397             hdr.pkt_num_len,
8398         );
8399 
8400         let mut payload =
8401             packet::decrypt_pkt(&mut b, pn, hdr.pkt_num_len, payload_len, aead)
8402                 .unwrap();
8403 
8404         let mut frames = Vec::new();
8405 
8406         while payload.cap() > 0 {
8407             let frame = frame::Frame::from_bytes(&mut payload, hdr.ty)?;
8408             frames.push(frame);
8409         }
8410 
8411         Ok(frames)
8412     }
8413 
create_cid_and_reset_token( cid_len: usize, ) -> (ConnectionId<'static>, u128)8414     pub fn create_cid_and_reset_token(
8415         cid_len: usize,
8416     ) -> (ConnectionId<'static>, u128) {
8417         let mut cid = vec![0; cid_len];
8418         rand::rand_bytes(&mut cid[..]);
8419         let cid = ConnectionId::from_ref(&cid).into_owned();
8420 
8421         let mut reset_token = [0; 16];
8422         rand::rand_bytes(&mut reset_token);
8423         let reset_token = u128::from_be_bytes(reset_token);
8424 
8425         (cid, reset_token)
8426     }
8427 }
8428 
8429 #[cfg(test)]
8430 mod tests {
8431     use super::*;
8432 
8433     #[test]
transport_params()8434     fn transport_params() {
8435         // Server encodes, client decodes.
8436         let tp = TransportParams {
8437             original_destination_connection_id: None,
8438             max_idle_timeout: 30,
8439             stateless_reset_token: Some(u128::from_be_bytes([0xba; 16])),
8440             max_udp_payload_size: 23_421,
8441             initial_max_data: 424_645_563,
8442             initial_max_stream_data_bidi_local: 154_323_123,
8443             initial_max_stream_data_bidi_remote: 6_587_456,
8444             initial_max_stream_data_uni: 2_461_234,
8445             initial_max_streams_bidi: 12_231,
8446             initial_max_streams_uni: 18_473,
8447             ack_delay_exponent: 20,
8448             max_ack_delay: 2_u64.pow(14) - 1,
8449             disable_active_migration: true,
8450             active_conn_id_limit: 8,
8451             initial_source_connection_id: Some(b"woot woot".to_vec().into()),
8452             retry_source_connection_id: Some(b"retry".to_vec().into()),
8453             max_datagram_frame_size: Some(32),
8454         };
8455 
8456         let mut raw_params = [42; 256];
8457         let raw_params =
8458             TransportParams::encode(&tp, true, &mut raw_params).unwrap();
8459         assert_eq!(raw_params.len(), 94);
8460 
8461         let new_tp = TransportParams::decode(raw_params, false).unwrap();
8462 
8463         assert_eq!(new_tp, tp);
8464 
8465         // Client encodes, server decodes.
8466         let tp = TransportParams {
8467             original_destination_connection_id: None,
8468             max_idle_timeout: 30,
8469             stateless_reset_token: None,
8470             max_udp_payload_size: 23_421,
8471             initial_max_data: 424_645_563,
8472             initial_max_stream_data_bidi_local: 154_323_123,
8473             initial_max_stream_data_bidi_remote: 6_587_456,
8474             initial_max_stream_data_uni: 2_461_234,
8475             initial_max_streams_bidi: 12_231,
8476             initial_max_streams_uni: 18_473,
8477             ack_delay_exponent: 20,
8478             max_ack_delay: 2_u64.pow(14) - 1,
8479             disable_active_migration: true,
8480             active_conn_id_limit: 8,
8481             initial_source_connection_id: Some(b"woot woot".to_vec().into()),
8482             retry_source_connection_id: None,
8483             max_datagram_frame_size: Some(32),
8484         };
8485 
8486         let mut raw_params = [42; 256];
8487         let raw_params =
8488             TransportParams::encode(&tp, false, &mut raw_params).unwrap();
8489         assert_eq!(raw_params.len(), 69);
8490 
8491         let new_tp = TransportParams::decode(raw_params, true).unwrap();
8492 
8493         assert_eq!(new_tp, tp);
8494     }
8495 
8496     #[test]
transport_params_forbid_duplicates()8497     fn transport_params_forbid_duplicates() {
8498         // Given an encoded param.
8499         let initial_source_connection_id = b"id";
8500         let initial_source_connection_id_raw = [
8501             15,
8502             initial_source_connection_id.len() as u8,
8503             initial_source_connection_id[0],
8504             initial_source_connection_id[1],
8505         ];
8506 
8507         // No error when decoding the param.
8508         let tp = TransportParams::decode(
8509             initial_source_connection_id_raw.as_slice(),
8510             true,
8511         )
8512         .unwrap();
8513 
8514         assert_eq!(
8515             tp.initial_source_connection_id,
8516             Some(initial_source_connection_id.to_vec().into())
8517         );
8518 
8519         // Duplicate the param.
8520         let mut raw_params = Vec::new();
8521         raw_params.append(&mut initial_source_connection_id_raw.to_vec());
8522         raw_params.append(&mut initial_source_connection_id_raw.to_vec());
8523 
8524         // Decoding fails.
8525         assert_eq!(
8526             TransportParams::decode(raw_params.as_slice(), true),
8527             Err(Error::InvalidTransportParam)
8528         );
8529     }
8530 
8531     #[test]
unknown_version()8532     fn unknown_version() {
8533         let mut config = Config::new(0xbabababa).unwrap();
8534         config
8535             .set_application_protos(&[b"proto1", b"proto2"])
8536             .unwrap();
8537         config.verify_peer(false);
8538 
8539         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
8540         assert_eq!(pipe.handshake(), Err(Error::UnknownVersion));
8541     }
8542 
8543     #[test]
config_version_reserved()8544     fn config_version_reserved() {
8545         Config::new(0xbabababa).unwrap();
8546         Config::new(0x1a2a3a4a).unwrap();
8547     }
8548 
8549     #[test]
config_version_invalid()8550     fn config_version_invalid() {
8551         assert_eq!(
8552             Config::new(0xb1bababa).err().unwrap(),
8553             Error::UnknownVersion
8554         );
8555     }
8556 
8557     #[test]
version_negotiation()8558     fn version_negotiation() {
8559         let mut buf = [0; 65535];
8560 
8561         let mut config = Config::new(0xbabababa).unwrap();
8562         config
8563             .set_application_protos(&[b"proto1", b"proto2"])
8564             .unwrap();
8565         config.verify_peer(false);
8566 
8567         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
8568 
8569         let (mut len, _) = pipe.client.send(&mut buf).unwrap();
8570 
8571         let hdr = packet::Header::from_slice(&mut buf[..len], 0).unwrap();
8572         len = crate::negotiate_version(&hdr.scid, &hdr.dcid, &mut buf).unwrap();
8573 
8574         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
8575 
8576         assert_eq!(pipe.handshake(), Ok(()));
8577 
8578         assert_eq!(pipe.client.version, PROTOCOL_VERSION);
8579         assert_eq!(pipe.server.version, PROTOCOL_VERSION);
8580     }
8581 
8582     #[test]
verify_custom_root()8583     fn verify_custom_root() {
8584         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
8585         config.verify_peer(true);
8586         config
8587             .load_verify_locations_from_file("examples/rootca.crt")
8588             .unwrap();
8589         config
8590             .set_application_protos(&[b"proto1", b"proto2"])
8591             .unwrap();
8592 
8593         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
8594         assert_eq!(pipe.handshake(), Ok(()));
8595     }
8596 
8597     #[test]
missing_initial_source_connection_id()8598     fn missing_initial_source_connection_id() {
8599         let mut buf = [0; 65535];
8600 
8601         let mut pipe = testing::Pipe::new().unwrap();
8602 
8603         // Reset initial_source_connection_id.
8604         pipe.client
8605             .local_transport_params
8606             .initial_source_connection_id = None;
8607         assert_eq!(pipe.client.encode_transport_params(), Ok(()));
8608 
8609         // Client sends initial flight.
8610         let (len, _) = pipe.client.send(&mut buf).unwrap();
8611 
8612         // Server rejects transport parameters.
8613         assert_eq!(
8614             pipe.server_recv(&mut buf[..len]),
8615             Err(Error::InvalidTransportParam)
8616         );
8617     }
8618 
8619     #[test]
invalid_initial_source_connection_id()8620     fn invalid_initial_source_connection_id() {
8621         let mut buf = [0; 65535];
8622 
8623         let mut pipe = testing::Pipe::new().unwrap();
8624 
8625         // Scramble initial_source_connection_id.
8626         pipe.client
8627             .local_transport_params
8628             .initial_source_connection_id = Some(b"bogus value".to_vec().into());
8629         assert_eq!(pipe.client.encode_transport_params(), Ok(()));
8630 
8631         // Client sends initial flight.
8632         let (len, _) = pipe.client.send(&mut buf).unwrap();
8633 
8634         // Server rejects transport parameters.
8635         assert_eq!(
8636             pipe.server_recv(&mut buf[..len]),
8637             Err(Error::InvalidTransportParam)
8638         );
8639     }
8640 
8641     #[test]
handshake()8642     fn handshake() {
8643         let mut pipe = testing::Pipe::new().unwrap();
8644         assert_eq!(pipe.handshake(), Ok(()));
8645 
8646         assert_eq!(
8647             pipe.client.application_proto(),
8648             pipe.server.application_proto()
8649         );
8650 
8651         assert_eq!(pipe.server.server_name(), Some("quic.tech"));
8652     }
8653 
8654     #[test]
handshake_done()8655     fn handshake_done() {
8656         let mut pipe = testing::Pipe::new().unwrap();
8657 
8658         // Disable session tickets on the server (SSL_OP_NO_TICKET) to avoid
8659         // triggering 1-RTT packet send with a CRYPTO frame.
8660         pipe.server.handshake.set_options(0x0000_4000);
8661 
8662         assert_eq!(pipe.handshake(), Ok(()));
8663 
8664         assert!(pipe.server.handshake_done_sent);
8665     }
8666 
8667     #[test]
handshake_confirmation()8668     fn handshake_confirmation() {
8669         let mut pipe = testing::Pipe::new().unwrap();
8670 
8671         // Client sends initial flight.
8672         let flight = testing::emit_flight(&mut pipe.client).unwrap();
8673         testing::process_flight(&mut pipe.server, flight).unwrap();
8674 
8675         // Server sends initial flight.
8676         let flight = testing::emit_flight(&mut pipe.server).unwrap();
8677 
8678         assert!(!pipe.client.is_established());
8679         assert!(!pipe.client.handshake_confirmed);
8680 
8681         assert!(!pipe.server.is_established());
8682         assert!(!pipe.server.handshake_confirmed);
8683 
8684         testing::process_flight(&mut pipe.client, flight).unwrap();
8685 
8686         // Client sends Handshake packet and completes handshake.
8687         let flight = testing::emit_flight(&mut pipe.client).unwrap();
8688 
8689         assert!(pipe.client.is_established());
8690         assert!(!pipe.client.handshake_confirmed);
8691 
8692         assert!(!pipe.server.is_established());
8693         assert!(!pipe.server.handshake_confirmed);
8694 
8695         testing::process_flight(&mut pipe.server, flight).unwrap();
8696 
8697         // Server completes and confirms handshake, and sends HANDSHAKE_DONE.
8698         let flight = testing::emit_flight(&mut pipe.server).unwrap();
8699 
8700         assert!(pipe.client.is_established());
8701         assert!(!pipe.client.handshake_confirmed);
8702 
8703         assert!(pipe.server.is_established());
8704         assert!(pipe.server.handshake_confirmed);
8705 
8706         testing::process_flight(&mut pipe.client, flight).unwrap();
8707 
8708         // Client acks 1-RTT packet, and confirms handshake.
8709         let flight = testing::emit_flight(&mut pipe.client).unwrap();
8710 
8711         assert!(pipe.client.is_established());
8712         assert!(pipe.client.handshake_confirmed);
8713 
8714         assert!(pipe.server.is_established());
8715         assert!(pipe.server.handshake_confirmed);
8716 
8717         testing::process_flight(&mut pipe.server, flight).unwrap();
8718 
8719         assert!(pipe.client.is_established());
8720         assert!(pipe.client.handshake_confirmed);
8721 
8722         assert!(pipe.server.is_established());
8723         assert!(pipe.server.handshake_confirmed);
8724     }
8725 
8726     #[test]
handshake_resumption()8727     fn handshake_resumption() {
8728         const SESSION_TICKET_KEY: [u8; 48] = [0xa; 48];
8729 
8730         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
8731         config
8732             .load_cert_chain_from_pem_file("examples/cert.crt")
8733             .unwrap();
8734         config
8735             .load_priv_key_from_pem_file("examples/cert.key")
8736             .unwrap();
8737         config
8738             .set_application_protos(&[b"proto1", b"proto2"])
8739             .unwrap();
8740         config.set_initial_max_data(30);
8741         config.set_initial_max_stream_data_bidi_local(15);
8742         config.set_initial_max_stream_data_bidi_remote(15);
8743         config.set_initial_max_streams_bidi(3);
8744         config.set_ticket_key(&SESSION_TICKET_KEY).unwrap();
8745 
8746         // Perform initial handshake.
8747         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
8748         assert_eq!(pipe.handshake(), Ok(()));
8749 
8750         assert_eq!(pipe.client.is_established(), true);
8751         assert_eq!(pipe.server.is_established(), true);
8752 
8753         assert_eq!(pipe.client.is_resumed(), false);
8754         assert_eq!(pipe.server.is_resumed(), false);
8755 
8756         // Extract session,
8757         let session = pipe.client.session().unwrap();
8758 
8759         // Configure session on new connection and perform handshake.
8760         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
8761         config
8762             .load_cert_chain_from_pem_file("examples/cert.crt")
8763             .unwrap();
8764         config
8765             .load_priv_key_from_pem_file("examples/cert.key")
8766             .unwrap();
8767         config
8768             .set_application_protos(&[b"proto1", b"proto2"])
8769             .unwrap();
8770         config.set_initial_max_data(30);
8771         config.set_initial_max_stream_data_bidi_local(15);
8772         config.set_initial_max_stream_data_bidi_remote(15);
8773         config.set_initial_max_streams_bidi(3);
8774         config.set_ticket_key(&SESSION_TICKET_KEY).unwrap();
8775 
8776         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
8777 
8778         assert_eq!(pipe.client.set_session(session), Ok(()));
8779         assert_eq!(pipe.handshake(), Ok(()));
8780 
8781         assert_eq!(pipe.client.is_established(), true);
8782         assert_eq!(pipe.server.is_established(), true);
8783 
8784         assert_eq!(pipe.client.is_resumed(), true);
8785         assert_eq!(pipe.server.is_resumed(), true);
8786     }
8787 
8788     #[test]
handshake_alpn_mismatch()8789     fn handshake_alpn_mismatch() {
8790         let mut buf = [0; 65535];
8791 
8792         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
8793         config
8794             .set_application_protos(&[b"proto3\x06proto4"])
8795             .unwrap();
8796         config.verify_peer(false);
8797 
8798         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
8799         assert_eq!(pipe.handshake(), Err(Error::TlsFail));
8800 
8801         assert_eq!(pipe.client.application_proto(), b"");
8802         assert_eq!(pipe.server.application_proto(), b"");
8803 
8804         // Server should only send one packet in response to ALPN mismatch.
8805         let (len, _) = pipe.server.send(&mut buf).unwrap();
8806         assert_eq!(len, 1200);
8807 
8808         assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
8809         assert_eq!(pipe.server.sent_count, 1);
8810     }
8811 
8812     #[test]
handshake_0rtt()8813     fn handshake_0rtt() {
8814         let mut buf = [0; 65535];
8815 
8816         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
8817         config
8818             .load_cert_chain_from_pem_file("examples/cert.crt")
8819             .unwrap();
8820         config
8821             .load_priv_key_from_pem_file("examples/cert.key")
8822             .unwrap();
8823         config
8824             .set_application_protos(&[b"proto1", b"proto2"])
8825             .unwrap();
8826         config.set_initial_max_data(30);
8827         config.set_initial_max_stream_data_bidi_local(15);
8828         config.set_initial_max_stream_data_bidi_remote(15);
8829         config.set_initial_max_streams_bidi(3);
8830         config.enable_early_data();
8831         config.verify_peer(false);
8832 
8833         // Perform initial handshake.
8834         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
8835         assert_eq!(pipe.handshake(), Ok(()));
8836 
8837         // Extract session,
8838         let session = pipe.client.session().unwrap();
8839 
8840         // Configure session on new connection.
8841         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
8842         assert_eq!(pipe.client.set_session(session), Ok(()));
8843 
8844         // Client sends initial flight.
8845         let (len, _) = pipe.client.send(&mut buf).unwrap();
8846         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
8847 
8848         // Client sends 0-RTT packet.
8849         let pkt_type = packet::Type::ZeroRTT;
8850 
8851         let frames = [frame::Frame::Stream {
8852             stream_id: 4,
8853             data: stream::RangeBuf::from(b"aaaaa", 0, true),
8854         }];
8855 
8856         assert_eq!(
8857             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
8858             Ok(1200)
8859         );
8860 
8861         assert_eq!(pipe.server.undecryptable_pkts.len(), 0);
8862 
8863         // 0-RTT stream data is readable.
8864         let mut r = pipe.server.readable();
8865         assert_eq!(r.next(), Some(4));
8866         assert_eq!(r.next(), None);
8867 
8868         let mut b = [0; 15];
8869         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
8870         assert_eq!(&b[..5], b"aaaaa");
8871     }
8872 
8873     #[test]
handshake_0rtt_reordered()8874     fn handshake_0rtt_reordered() {
8875         let mut buf = [0; 65535];
8876 
8877         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
8878         config
8879             .load_cert_chain_from_pem_file("examples/cert.crt")
8880             .unwrap();
8881         config
8882             .load_priv_key_from_pem_file("examples/cert.key")
8883             .unwrap();
8884         config
8885             .set_application_protos(&[b"proto1", b"proto2"])
8886             .unwrap();
8887         config.set_initial_max_data(30);
8888         config.set_initial_max_stream_data_bidi_local(15);
8889         config.set_initial_max_stream_data_bidi_remote(15);
8890         config.set_initial_max_streams_bidi(3);
8891         config.enable_early_data();
8892         config.verify_peer(false);
8893 
8894         // Perform initial handshake.
8895         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
8896         assert_eq!(pipe.handshake(), Ok(()));
8897 
8898         // Extract session,
8899         let session = pipe.client.session().unwrap();
8900 
8901         // Configure session on new connection.
8902         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
8903         assert_eq!(pipe.client.set_session(session), Ok(()));
8904 
8905         // Client sends initial flight.
8906         let (len, _) = pipe.client.send(&mut buf).unwrap();
8907         let mut initial = buf[..len].to_vec();
8908 
8909         // Client sends 0-RTT packet.
8910         let pkt_type = packet::Type::ZeroRTT;
8911 
8912         let frames = [frame::Frame::Stream {
8913             stream_id: 4,
8914             data: stream::RangeBuf::from(b"aaaaa", 0, true),
8915         }];
8916 
8917         let len =
8918             testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
8919                 .unwrap();
8920         let mut zrtt = buf[..len].to_vec();
8921 
8922         // 0-RTT packet is received before the Initial one.
8923         assert_eq!(pipe.server_recv(&mut zrtt), Ok(zrtt.len()));
8924 
8925         assert_eq!(pipe.server.undecryptable_pkts.len(), 1);
8926         assert_eq!(pipe.server.undecryptable_pkts[0].0.len(), zrtt.len());
8927 
8928         let mut r = pipe.server.readable();
8929         assert_eq!(r.next(), None);
8930 
8931         // Initial packet is also received.
8932         assert_eq!(pipe.server_recv(&mut initial), Ok(initial.len()));
8933 
8934         // 0-RTT stream data is readable.
8935         let mut r = pipe.server.readable();
8936         assert_eq!(r.next(), Some(4));
8937         assert_eq!(r.next(), None);
8938 
8939         let mut b = [0; 15];
8940         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
8941         assert_eq!(&b[..5], b"aaaaa");
8942     }
8943 
8944     #[test]
handshake_0rtt_truncated()8945     fn handshake_0rtt_truncated() {
8946         let mut buf = [0; 65535];
8947 
8948         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
8949         config
8950             .load_cert_chain_from_pem_file("examples/cert.crt")
8951             .unwrap();
8952         config
8953             .load_priv_key_from_pem_file("examples/cert.key")
8954             .unwrap();
8955         config
8956             .set_application_protos(&[b"proto1", b"proto2"])
8957             .unwrap();
8958         config.set_initial_max_data(30);
8959         config.set_initial_max_stream_data_bidi_local(15);
8960         config.set_initial_max_stream_data_bidi_remote(15);
8961         config.set_initial_max_streams_bidi(3);
8962         config.enable_early_data();
8963         config.verify_peer(false);
8964 
8965         // Perform initial handshake.
8966         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
8967         assert_eq!(pipe.handshake(), Ok(()));
8968 
8969         // Extract session,
8970         let session = pipe.client.session().unwrap();
8971 
8972         // Configure session on new connection.
8973         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
8974         assert_eq!(pipe.client.set_session(session), Ok(()));
8975 
8976         // Client sends initial flight.
8977         pipe.client.send(&mut buf).unwrap();
8978 
8979         // Client sends 0-RTT packet.
8980         let pkt_type = packet::Type::ZeroRTT;
8981 
8982         let frames = [frame::Frame::Stream {
8983             stream_id: 4,
8984             data: stream::RangeBuf::from(b"aaaaa", 0, true),
8985         }];
8986 
8987         let len =
8988             testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
8989                 .unwrap();
8990 
8991         // Simulate a truncated packet by sending one byte less.
8992         let mut zrtt = buf[..len - 1].to_vec();
8993 
8994         // 0-RTT packet is received before the Initial one.
8995         assert_eq!(pipe.server_recv(&mut zrtt), Err(Error::InvalidPacket));
8996 
8997         assert_eq!(pipe.server.undecryptable_pkts.len(), 0);
8998 
8999         assert!(pipe.server.is_closed());
9000     }
9001 
9002     #[test]
9003     /// Tests that a pre-v1 client can connect to a v1-enabled server, by making
9004     /// the server downgrade to the pre-v1 version.
handshake_downgrade_v1()9005     fn handshake_downgrade_v1() {
9006         let mut config = Config::new(PROTOCOL_VERSION_DRAFT29).unwrap();
9007         config
9008             .set_application_protos(&[b"proto1", b"proto2"])
9009             .unwrap();
9010         config.verify_peer(false);
9011 
9012         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
9013         assert_eq!(pipe.handshake(), Ok(()));
9014 
9015         assert_eq!(pipe.client.version, PROTOCOL_VERSION_DRAFT29);
9016         assert_eq!(pipe.server.version, PROTOCOL_VERSION_DRAFT29);
9017     }
9018 
9019     #[test]
limit_handshake_data()9020     fn limit_handshake_data() {
9021         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
9022         config
9023             .load_cert_chain_from_pem_file("examples/cert-big.crt")
9024             .unwrap();
9025         config
9026             .load_priv_key_from_pem_file("examples/cert.key")
9027             .unwrap();
9028         config
9029             .set_application_protos(&[b"proto1", b"proto2"])
9030             .unwrap();
9031 
9032         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
9033 
9034         let flight = testing::emit_flight(&mut pipe.client).unwrap();
9035         let client_sent = flight.iter().fold(0, |out, p| out + p.0.len());
9036         testing::process_flight(&mut pipe.server, flight).unwrap();
9037 
9038         let flight = testing::emit_flight(&mut pipe.server).unwrap();
9039         let server_sent = flight.iter().fold(0, |out, p| out + p.0.len());
9040 
9041         assert_eq!(server_sent, client_sent * MAX_AMPLIFICATION_FACTOR);
9042     }
9043 
9044     #[test]
stream()9045     fn stream() {
9046         let mut pipe = testing::Pipe::new().unwrap();
9047         assert_eq!(pipe.handshake(), Ok(()));
9048 
9049         assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
9050         assert_eq!(pipe.advance(), Ok(()));
9051 
9052         assert!(!pipe.server.stream_finished(4));
9053 
9054         let mut r = pipe.server.readable();
9055         assert_eq!(r.next(), Some(4));
9056         assert_eq!(r.next(), None);
9057 
9058         let mut b = [0; 15];
9059         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((12, true)));
9060         assert_eq!(&b[..12], b"hello, world");
9061 
9062         assert!(pipe.server.stream_finished(4));
9063     }
9064 
9065     #[test]
zero_rtt()9066     fn zero_rtt() {
9067         let mut buf = [0; 65535];
9068 
9069         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9070         config
9071             .load_cert_chain_from_pem_file("examples/cert.crt")
9072             .unwrap();
9073         config
9074             .load_priv_key_from_pem_file("examples/cert.key")
9075             .unwrap();
9076         config
9077             .set_application_protos(&[b"proto1", b"proto2"])
9078             .unwrap();
9079         config.set_initial_max_data(30);
9080         config.set_initial_max_stream_data_bidi_local(15);
9081         config.set_initial_max_stream_data_bidi_remote(15);
9082         config.set_initial_max_streams_bidi(3);
9083         config.enable_early_data();
9084         config.verify_peer(false);
9085 
9086         // Perform initial handshake.
9087         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
9088         assert_eq!(pipe.handshake(), Ok(()));
9089 
9090         // Extract session,
9091         let session = pipe.client.session().unwrap();
9092 
9093         // Configure session on new connection.
9094         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
9095         assert_eq!(pipe.client.set_session(session), Ok(()));
9096 
9097         // Client sends initial flight.
9098         let (len, _) = pipe.client.send(&mut buf).unwrap();
9099         let mut initial = buf[..len].to_vec();
9100 
9101         assert_eq!(pipe.client.is_in_early_data(), true);
9102 
9103         // Client sends 0-RTT data.
9104         assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
9105 
9106         let (len, _) = pipe.client.send(&mut buf).unwrap();
9107         let mut zrtt = buf[..len].to_vec();
9108 
9109         // Server receives packets.
9110         assert_eq!(pipe.server_recv(&mut initial), Ok(initial.len()));
9111         assert_eq!(pipe.server.is_in_early_data(), true);
9112 
9113         assert_eq!(pipe.server_recv(&mut zrtt), Ok(zrtt.len()));
9114 
9115         // 0-RTT stream data is readable.
9116         let mut r = pipe.server.readable();
9117         assert_eq!(r.next(), Some(4));
9118         assert_eq!(r.next(), None);
9119 
9120         let mut b = [0; 15];
9121         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((12, true)));
9122         assert_eq!(&b[..12], b"hello, world");
9123     }
9124 
9125     #[test]
stream_send_on_32bit_arch()9126     fn stream_send_on_32bit_arch() {
9127         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9128         config
9129             .load_cert_chain_from_pem_file("examples/cert.crt")
9130             .unwrap();
9131         config
9132             .load_priv_key_from_pem_file("examples/cert.key")
9133             .unwrap();
9134         config
9135             .set_application_protos(&[b"proto1", b"proto2"])
9136             .unwrap();
9137         config.set_initial_max_data(2_u64.pow(32) + 5);
9138         config.set_initial_max_stream_data_bidi_local(15);
9139         config.set_initial_max_stream_data_bidi_remote(15);
9140         config.set_initial_max_stream_data_uni(10);
9141         config.set_initial_max_streams_bidi(3);
9142         config.set_initial_max_streams_uni(0);
9143         config.verify_peer(false);
9144 
9145         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
9146         assert_eq!(pipe.handshake(), Ok(()));
9147 
9148         // In 32bit arch, send_capacity() should be min(2^32+5, cwnd),
9149         // not min(5, cwnd)
9150         assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
9151 
9152         assert_eq!(pipe.advance(), Ok(()));
9153 
9154         assert!(!pipe.server.stream_finished(4));
9155     }
9156 
9157     #[test]
empty_stream_frame()9158     fn empty_stream_frame() {
9159         let mut buf = [0; 65535];
9160 
9161         let mut pipe = testing::Pipe::new().unwrap();
9162         assert_eq!(pipe.handshake(), Ok(()));
9163 
9164         let frames = [frame::Frame::Stream {
9165             stream_id: 4,
9166             data: stream::RangeBuf::from(b"aaaaa", 0, false),
9167         }];
9168 
9169         let pkt_type = packet::Type::Short;
9170         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
9171 
9172         let mut readable = pipe.server.readable();
9173         assert_eq!(readable.next(), Some(4));
9174 
9175         assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((5, false)));
9176 
9177         let frames = [frame::Frame::Stream {
9178             stream_id: 4,
9179             data: stream::RangeBuf::from(b"", 5, true),
9180         }];
9181 
9182         let pkt_type = packet::Type::Short;
9183         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
9184 
9185         let mut readable = pipe.server.readable();
9186         assert_eq!(readable.next(), Some(4));
9187 
9188         assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((0, true)));
9189 
9190         let frames = [frame::Frame::Stream {
9191             stream_id: 4,
9192             data: stream::RangeBuf::from(b"", 15, true),
9193         }];
9194 
9195         let pkt_type = packet::Type::Short;
9196         assert_eq!(
9197             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9198             Err(Error::FinalSize)
9199         );
9200     }
9201 
9202     #[test]
update_key_request()9203     fn update_key_request() {
9204         let mut b = [0; 15];
9205 
9206         let mut pipe = testing::Pipe::new().unwrap();
9207         assert_eq!(pipe.handshake(), Ok(()));
9208         assert_eq!(pipe.advance(), Ok(()));
9209 
9210         // Client sends message with key update request.
9211         assert_eq!(pipe.client_update_key(), Ok(()));
9212         assert_eq!(pipe.client.stream_send(4, b"hello", false), Ok(5));
9213         assert_eq!(pipe.advance(), Ok(()));
9214 
9215         // Ensure server updates key and it correctly decrypts the message.
9216         let mut r = pipe.server.readable();
9217         assert_eq!(r.next(), Some(4));
9218         assert_eq!(r.next(), None);
9219         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, false)));
9220         assert_eq!(&b[..5], b"hello");
9221 
9222         // Ensure ACK for key update.
9223         assert!(
9224             pipe.server.pkt_num_spaces[packet::Epoch::Application]
9225                 .key_update
9226                 .as_ref()
9227                 .unwrap()
9228                 .update_acked
9229         );
9230 
9231         // Server sends message with the new key.
9232         assert_eq!(pipe.server.stream_send(4, b"world", true), Ok(5));
9233         assert_eq!(pipe.advance(), Ok(()));
9234 
9235         // Ensure update key is completed and client can decrypt packet.
9236         let mut r = pipe.client.readable();
9237         assert_eq!(r.next(), Some(4));
9238         assert_eq!(r.next(), None);
9239         assert_eq!(pipe.client.stream_recv(4, &mut b), Ok((5, true)));
9240         assert_eq!(&b[..5], b"world");
9241     }
9242 
9243     #[test]
update_key_request_twice_error()9244     fn update_key_request_twice_error() {
9245         let mut buf = [0; 65535];
9246 
9247         let mut pipe = testing::Pipe::new().unwrap();
9248         assert_eq!(pipe.handshake(), Ok(()));
9249         assert_eq!(pipe.advance(), Ok(()));
9250 
9251         let frames = [frame::Frame::Stream {
9252             stream_id: 4,
9253             data: stream::RangeBuf::from(b"hello", 0, false),
9254         }];
9255 
9256         // Client sends stream frame with key update request.
9257         assert_eq!(pipe.client_update_key(), Ok(()));
9258         let written = testing::encode_pkt(
9259             &mut pipe.client,
9260             packet::Type::Short,
9261             &frames,
9262             &mut buf,
9263         )
9264         .unwrap();
9265 
9266         // Server correctly decode with new key.
9267         assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
9268 
9269         // Client sends stream frame with another key update request before server
9270         // ACK.
9271         assert_eq!(pipe.client_update_key(), Ok(()));
9272         let written = testing::encode_pkt(
9273             &mut pipe.client,
9274             packet::Type::Short,
9275             &frames,
9276             &mut buf,
9277         )
9278         .unwrap();
9279 
9280         // Check server correctly closes the connection with a key update error
9281         // for the peer.
9282         assert_eq!(pipe.server_recv(&mut buf[..written]), Err(Error::KeyUpdate));
9283     }
9284 
9285     #[test]
9286     /// Tests that receiving a MAX_STREAM_DATA frame for a receive-only
9287     /// unidirectional stream is forbidden.
max_stream_data_receive_uni()9288     fn max_stream_data_receive_uni() {
9289         let mut buf = [0; 65535];
9290 
9291         let mut pipe = testing::Pipe::new().unwrap();
9292         assert_eq!(pipe.handshake(), Ok(()));
9293 
9294         // Client opens unidirectional stream.
9295         assert_eq!(pipe.client.stream_send(2, b"hello", false), Ok(5));
9296         assert_eq!(pipe.advance(), Ok(()));
9297 
9298         // Client sends MAX_STREAM_DATA on local unidirectional stream.
9299         let frames = [frame::Frame::MaxStreamData {
9300             stream_id: 2,
9301             max: 1024,
9302         }];
9303 
9304         let pkt_type = packet::Type::Short;
9305         assert_eq!(
9306             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9307             Err(Error::InvalidStreamState(2)),
9308         );
9309     }
9310 
9311     #[test]
empty_payload()9312     fn empty_payload() {
9313         let mut buf = [0; 65535];
9314 
9315         let mut pipe = testing::Pipe::new().unwrap();
9316         assert_eq!(pipe.handshake(), Ok(()));
9317 
9318         // Send a packet with no frames.
9319         let pkt_type = packet::Type::Short;
9320         assert_eq!(
9321             pipe.send_pkt_to_server(pkt_type, &[], &mut buf),
9322             Err(Error::InvalidPacket)
9323         );
9324     }
9325 
9326     #[test]
min_payload()9327     fn min_payload() {
9328         let mut buf = [0; 65535];
9329 
9330         let mut pipe = testing::Pipe::new().unwrap();
9331 
9332         // Send a non-ack-eliciting packet.
9333         let frames = [frame::Frame::Padding { len: 4 }];
9334 
9335         let pkt_type = packet::Type::Initial;
9336         let written =
9337             testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
9338                 .unwrap();
9339         assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
9340 
9341         let initial_path = pipe
9342             .server
9343             .paths
9344             .get_active()
9345             .expect("initial path not found");
9346 
9347         assert_eq!(initial_path.max_send_bytes, 195);
9348 
9349         // Force server to send a single PING frame.
9350         pipe.server
9351             .paths
9352             .get_active_mut()
9353             .expect("no active path")
9354             .recovery
9355             .loss_probes[packet::Epoch::Initial] = 1;
9356 
9357         let initial_path = pipe
9358             .server
9359             .paths
9360             .get_active_mut()
9361             .expect("initial path not found");
9362 
9363         // Artificially limit the amount of bytes the server can send.
9364         initial_path.max_send_bytes = 60;
9365 
9366         assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
9367     }
9368 
9369     #[test]
flow_control_limit()9370     fn flow_control_limit() {
9371         let mut buf = [0; 65535];
9372 
9373         let mut pipe = testing::Pipe::new().unwrap();
9374         assert_eq!(pipe.handshake(), Ok(()));
9375 
9376         let frames = [
9377             frame::Frame::Stream {
9378                 stream_id: 0,
9379                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
9380             },
9381             frame::Frame::Stream {
9382                 stream_id: 4,
9383                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
9384             },
9385             frame::Frame::Stream {
9386                 stream_id: 8,
9387                 data: stream::RangeBuf::from(b"a", 0, false),
9388             },
9389         ];
9390 
9391         let pkt_type = packet::Type::Short;
9392         assert_eq!(
9393             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9394             Err(Error::FlowControl),
9395         );
9396     }
9397 
9398     #[test]
flow_control_limit_dup()9399     fn flow_control_limit_dup() {
9400         let mut buf = [0; 65535];
9401 
9402         let mut pipe = testing::Pipe::new().unwrap();
9403         assert_eq!(pipe.handshake(), Ok(()));
9404 
9405         let frames = [
9406             // One byte less than stream limit.
9407             frame::Frame::Stream {
9408                 stream_id: 0,
9409                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaa", 0, false),
9410             },
9411             // Same stream, but one byte more.
9412             frame::Frame::Stream {
9413                 stream_id: 0,
9414                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
9415             },
9416             frame::Frame::Stream {
9417                 stream_id: 8,
9418                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
9419             },
9420         ];
9421 
9422         let pkt_type = packet::Type::Short;
9423         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9424     }
9425 
9426     #[test]
flow_control_update()9427     fn flow_control_update() {
9428         let mut buf = [0; 65535];
9429 
9430         let mut pipe = testing::Pipe::new().unwrap();
9431         assert_eq!(pipe.handshake(), Ok(()));
9432 
9433         let frames = [
9434             frame::Frame::Stream {
9435                 stream_id: 0,
9436                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
9437             },
9438             frame::Frame::Stream {
9439                 stream_id: 4,
9440                 data: stream::RangeBuf::from(b"a", 0, false),
9441             },
9442         ];
9443 
9444         let pkt_type = packet::Type::Short;
9445 
9446         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9447 
9448         pipe.server.stream_recv(0, &mut buf).unwrap();
9449         pipe.server.stream_recv(4, &mut buf).unwrap();
9450 
9451         let frames = [frame::Frame::Stream {
9452             stream_id: 4,
9453             data: stream::RangeBuf::from(b"a", 1, false),
9454         }];
9455 
9456         let len = pipe
9457             .send_pkt_to_server(pkt_type, &frames, &mut buf)
9458             .unwrap();
9459 
9460         assert!(len > 0);
9461 
9462         let frames =
9463             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
9464         let mut iter = frames.iter();
9465 
9466         // Ignore ACK.
9467         iter.next().unwrap();
9468 
9469         assert_eq!(
9470             iter.next(),
9471             Some(&frame::Frame::MaxStreamData {
9472                 stream_id: 0,
9473                 max: 30
9474             })
9475         );
9476         assert_eq!(iter.next(), Some(&frame::Frame::MaxData { max: 61 }));
9477     }
9478 
9479     #[test]
9480     /// Tests that flow control is properly updated even when a stream is shut
9481     /// down.
flow_control_drain()9482     fn flow_control_drain() {
9483         let mut pipe = testing::Pipe::new().unwrap();
9484         assert_eq!(pipe.handshake(), Ok(()));
9485 
9486         // Client opens a stream and sends some data.
9487         assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
9488         assert_eq!(pipe.advance(), Ok(()));
9489 
9490         // Server receives data, without reading it.
9491         let mut r = pipe.server.readable();
9492         assert_eq!(r.next(), Some(4));
9493         assert_eq!(r.next(), None);
9494 
9495         // In the meantime, client sends more data.
9496         assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
9497         assert_eq!(pipe.client.stream_send(4, b"aaaaa", true), Ok(5));
9498 
9499         assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
9500         assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
9501         assert_eq!(pipe.client.stream_send(8, b"aaaaa", true), Ok(5));
9502 
9503         // Server shuts down one stream.
9504         assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 42), Ok(()));
9505 
9506         let mut r = pipe.server.readable();
9507         assert_eq!(r.next(), None);
9508 
9509         // Flush connection.
9510         assert_eq!(pipe.advance(), Ok(()));
9511     }
9512 
9513     #[test]
stream_flow_control_limit_bidi()9514     fn stream_flow_control_limit_bidi() {
9515         let mut buf = [0; 65535];
9516 
9517         let mut pipe = testing::Pipe::new().unwrap();
9518         assert_eq!(pipe.handshake(), Ok(()));
9519 
9520         let frames = [frame::Frame::Stream {
9521             stream_id: 4,
9522             data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaaa", 0, true),
9523         }];
9524 
9525         let pkt_type = packet::Type::Short;
9526         assert_eq!(
9527             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9528             Err(Error::FlowControl),
9529         );
9530     }
9531 
9532     #[test]
stream_flow_control_limit_uni()9533     fn stream_flow_control_limit_uni() {
9534         let mut buf = [0; 65535];
9535 
9536         let mut pipe = testing::Pipe::new().unwrap();
9537         assert_eq!(pipe.handshake(), Ok(()));
9538 
9539         let frames = [frame::Frame::Stream {
9540             stream_id: 2,
9541             data: stream::RangeBuf::from(b"aaaaaaaaaaa", 0, true),
9542         }];
9543 
9544         let pkt_type = packet::Type::Short;
9545         assert_eq!(
9546             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9547             Err(Error::FlowControl),
9548         );
9549     }
9550 
9551     #[test]
stream_flow_control_update()9552     fn stream_flow_control_update() {
9553         let mut buf = [0; 65535];
9554 
9555         let mut pipe = testing::Pipe::new().unwrap();
9556         assert_eq!(pipe.handshake(), Ok(()));
9557 
9558         let frames = [frame::Frame::Stream {
9559             stream_id: 4,
9560             data: stream::RangeBuf::from(b"aaaaaaaaa", 0, false),
9561         }];
9562 
9563         let pkt_type = packet::Type::Short;
9564 
9565         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9566 
9567         pipe.server.stream_recv(4, &mut buf).unwrap();
9568 
9569         let frames = [frame::Frame::Stream {
9570             stream_id: 4,
9571             data: stream::RangeBuf::from(b"a", 9, false),
9572         }];
9573 
9574         let len = pipe
9575             .send_pkt_to_server(pkt_type, &frames, &mut buf)
9576             .unwrap();
9577 
9578         assert!(len > 0);
9579 
9580         let frames =
9581             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
9582         let mut iter = frames.iter();
9583 
9584         // Ignore ACK.
9585         iter.next().unwrap();
9586 
9587         assert_eq!(
9588             iter.next(),
9589             Some(&frame::Frame::MaxStreamData {
9590                 stream_id: 4,
9591                 max: 24,
9592             })
9593         );
9594     }
9595 
9596     #[test]
stream_left_bidi()9597     fn stream_left_bidi() {
9598         let mut buf = [0; 65535];
9599 
9600         let mut pipe = testing::Pipe::new().unwrap();
9601         assert_eq!(pipe.handshake(), Ok(()));
9602 
9603         assert_eq!(3, pipe.client.peer_streams_left_bidi());
9604         assert_eq!(3, pipe.server.peer_streams_left_bidi());
9605 
9606         pipe.server.stream_send(1, b"a", false).ok();
9607         assert_eq!(2, pipe.server.peer_streams_left_bidi());
9608         pipe.server.stream_send(5, b"a", false).ok();
9609         assert_eq!(1, pipe.server.peer_streams_left_bidi());
9610 
9611         pipe.server.stream_send(9, b"a", false).ok();
9612         assert_eq!(0, pipe.server.peer_streams_left_bidi());
9613 
9614         let frames = [frame::Frame::MaxStreamsBidi { max: MAX_STREAM_ID }];
9615 
9616         let pkt_type = packet::Type::Short;
9617         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9618 
9619         assert_eq!(MAX_STREAM_ID - 3, pipe.server.peer_streams_left_bidi());
9620     }
9621 
9622     #[test]
stream_left_uni()9623     fn stream_left_uni() {
9624         let mut buf = [0; 65535];
9625 
9626         let mut pipe = testing::Pipe::new().unwrap();
9627         assert_eq!(pipe.handshake(), Ok(()));
9628 
9629         assert_eq!(3, pipe.client.peer_streams_left_uni());
9630         assert_eq!(3, pipe.server.peer_streams_left_uni());
9631 
9632         pipe.server.stream_send(3, b"a", false).ok();
9633         assert_eq!(2, pipe.server.peer_streams_left_uni());
9634         pipe.server.stream_send(7, b"a", false).ok();
9635         assert_eq!(1, pipe.server.peer_streams_left_uni());
9636 
9637         pipe.server.stream_send(11, b"a", false).ok();
9638         assert_eq!(0, pipe.server.peer_streams_left_uni());
9639 
9640         let frames = [frame::Frame::MaxStreamsUni { max: MAX_STREAM_ID }];
9641 
9642         let pkt_type = packet::Type::Short;
9643         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9644 
9645         assert_eq!(MAX_STREAM_ID - 3, pipe.server.peer_streams_left_uni());
9646     }
9647 
9648     #[test]
stream_limit_bidi()9649     fn stream_limit_bidi() {
9650         let mut buf = [0; 65535];
9651 
9652         let mut pipe = testing::Pipe::new().unwrap();
9653         assert_eq!(pipe.handshake(), Ok(()));
9654 
9655         let frames = [
9656             frame::Frame::Stream {
9657                 stream_id: 4,
9658                 data: stream::RangeBuf::from(b"a", 0, false),
9659             },
9660             frame::Frame::Stream {
9661                 stream_id: 8,
9662                 data: stream::RangeBuf::from(b"a", 0, false),
9663             },
9664             frame::Frame::Stream {
9665                 stream_id: 12,
9666                 data: stream::RangeBuf::from(b"a", 0, false),
9667             },
9668             frame::Frame::Stream {
9669                 stream_id: 16,
9670                 data: stream::RangeBuf::from(b"a", 0, false),
9671             },
9672             frame::Frame::Stream {
9673                 stream_id: 20,
9674                 data: stream::RangeBuf::from(b"a", 0, false),
9675             },
9676             frame::Frame::Stream {
9677                 stream_id: 24,
9678                 data: stream::RangeBuf::from(b"a", 0, false),
9679             },
9680             frame::Frame::Stream {
9681                 stream_id: 28,
9682                 data: stream::RangeBuf::from(b"a", 0, false),
9683             },
9684         ];
9685 
9686         let pkt_type = packet::Type::Short;
9687         assert_eq!(
9688             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9689             Err(Error::StreamLimit),
9690         );
9691     }
9692 
9693     #[test]
stream_limit_max_bidi()9694     fn stream_limit_max_bidi() {
9695         let mut buf = [0; 65535];
9696 
9697         let mut pipe = testing::Pipe::new().unwrap();
9698         assert_eq!(pipe.handshake(), Ok(()));
9699 
9700         let frames = [frame::Frame::MaxStreamsBidi { max: MAX_STREAM_ID }];
9701 
9702         let pkt_type = packet::Type::Short;
9703         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9704 
9705         let frames = [frame::Frame::MaxStreamsBidi {
9706             max: MAX_STREAM_ID + 1,
9707         }];
9708 
9709         let pkt_type = packet::Type::Short;
9710         assert_eq!(
9711             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9712             Err(Error::InvalidFrame),
9713         );
9714     }
9715 
9716     #[test]
stream_limit_uni()9717     fn stream_limit_uni() {
9718         let mut buf = [0; 65535];
9719 
9720         let mut pipe = testing::Pipe::new().unwrap();
9721         assert_eq!(pipe.handshake(), Ok(()));
9722 
9723         let frames = [
9724             frame::Frame::Stream {
9725                 stream_id: 2,
9726                 data: stream::RangeBuf::from(b"a", 0, false),
9727             },
9728             frame::Frame::Stream {
9729                 stream_id: 6,
9730                 data: stream::RangeBuf::from(b"a", 0, false),
9731             },
9732             frame::Frame::Stream {
9733                 stream_id: 10,
9734                 data: stream::RangeBuf::from(b"a", 0, false),
9735             },
9736             frame::Frame::Stream {
9737                 stream_id: 14,
9738                 data: stream::RangeBuf::from(b"a", 0, false),
9739             },
9740             frame::Frame::Stream {
9741                 stream_id: 18,
9742                 data: stream::RangeBuf::from(b"a", 0, false),
9743             },
9744             frame::Frame::Stream {
9745                 stream_id: 22,
9746                 data: stream::RangeBuf::from(b"a", 0, false),
9747             },
9748             frame::Frame::Stream {
9749                 stream_id: 26,
9750                 data: stream::RangeBuf::from(b"a", 0, false),
9751             },
9752         ];
9753 
9754         let pkt_type = packet::Type::Short;
9755         assert_eq!(
9756             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9757             Err(Error::StreamLimit),
9758         );
9759     }
9760 
9761     #[test]
stream_limit_max_uni()9762     fn stream_limit_max_uni() {
9763         let mut buf = [0; 65535];
9764 
9765         let mut pipe = testing::Pipe::new().unwrap();
9766         assert_eq!(pipe.handshake(), Ok(()));
9767 
9768         let frames = [frame::Frame::MaxStreamsUni { max: MAX_STREAM_ID }];
9769 
9770         let pkt_type = packet::Type::Short;
9771         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9772 
9773         let frames = [frame::Frame::MaxStreamsUni {
9774             max: MAX_STREAM_ID + 1,
9775         }];
9776 
9777         let pkt_type = packet::Type::Short;
9778         assert_eq!(
9779             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9780             Err(Error::InvalidFrame),
9781         );
9782     }
9783 
9784     #[test]
streams_blocked_max_bidi()9785     fn streams_blocked_max_bidi() {
9786         let mut buf = [0; 65535];
9787 
9788         let mut pipe = testing::Pipe::new().unwrap();
9789         assert_eq!(pipe.handshake(), Ok(()));
9790 
9791         let frames = [frame::Frame::StreamsBlockedBidi {
9792             limit: MAX_STREAM_ID,
9793         }];
9794 
9795         let pkt_type = packet::Type::Short;
9796         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9797 
9798         let frames = [frame::Frame::StreamsBlockedBidi {
9799             limit: MAX_STREAM_ID + 1,
9800         }];
9801 
9802         let pkt_type = packet::Type::Short;
9803         assert_eq!(
9804             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9805             Err(Error::InvalidFrame),
9806         );
9807     }
9808 
9809     #[test]
streams_blocked_max_uni()9810     fn streams_blocked_max_uni() {
9811         let mut buf = [0; 65535];
9812 
9813         let mut pipe = testing::Pipe::new().unwrap();
9814         assert_eq!(pipe.handshake(), Ok(()));
9815 
9816         let frames = [frame::Frame::StreamsBlockedUni {
9817             limit: MAX_STREAM_ID,
9818         }];
9819 
9820         let pkt_type = packet::Type::Short;
9821         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9822 
9823         let frames = [frame::Frame::StreamsBlockedUni {
9824             limit: MAX_STREAM_ID + 1,
9825         }];
9826 
9827         let pkt_type = packet::Type::Short;
9828         assert_eq!(
9829             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9830             Err(Error::InvalidFrame),
9831         );
9832     }
9833 
9834     #[test]
stream_data_overlap()9835     fn stream_data_overlap() {
9836         let mut buf = [0; 65535];
9837 
9838         let mut pipe = testing::Pipe::new().unwrap();
9839         assert_eq!(pipe.handshake(), Ok(()));
9840 
9841         let frames = [
9842             frame::Frame::Stream {
9843                 stream_id: 0,
9844                 data: stream::RangeBuf::from(b"aaaaa", 0, false),
9845             },
9846             frame::Frame::Stream {
9847                 stream_id: 0,
9848                 data: stream::RangeBuf::from(b"bbbbb", 3, false),
9849             },
9850             frame::Frame::Stream {
9851                 stream_id: 0,
9852                 data: stream::RangeBuf::from(b"ccccc", 6, false),
9853             },
9854         ];
9855 
9856         let pkt_type = packet::Type::Short;
9857         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9858 
9859         let mut b = [0; 15];
9860         assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((11, false)));
9861         assert_eq!(&b[..11], b"aaaaabbbccc");
9862     }
9863 
9864     #[test]
stream_data_overlap_with_reordering()9865     fn stream_data_overlap_with_reordering() {
9866         let mut buf = [0; 65535];
9867 
9868         let mut pipe = testing::Pipe::new().unwrap();
9869         assert_eq!(pipe.handshake(), Ok(()));
9870 
9871         let frames = [
9872             frame::Frame::Stream {
9873                 stream_id: 0,
9874                 data: stream::RangeBuf::from(b"aaaaa", 0, false),
9875             },
9876             frame::Frame::Stream {
9877                 stream_id: 0,
9878                 data: stream::RangeBuf::from(b"ccccc", 6, false),
9879             },
9880             frame::Frame::Stream {
9881                 stream_id: 0,
9882                 data: stream::RangeBuf::from(b"bbbbb", 3, false),
9883             },
9884         ];
9885 
9886         let pkt_type = packet::Type::Short;
9887         assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
9888 
9889         let mut b = [0; 15];
9890         assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((11, false)));
9891         assert_eq!(&b[..11], b"aaaaabccccc");
9892     }
9893 
9894     #[test]
9895     /// Tests that receiving a valid RESET_STREAM frame when all data has
9896     /// already been read, notifies the application.
reset_stream_data_recvd()9897     fn reset_stream_data_recvd() {
9898         let mut b = [0; 15];
9899         let mut buf = [0; 65535];
9900 
9901         let mut pipe = testing::Pipe::new().unwrap();
9902         assert_eq!(pipe.handshake(), Ok(()));
9903 
9904         // Client sends some data.
9905         assert_eq!(pipe.client.stream_send(0, b"hello", false), Ok(5));
9906         assert_eq!(pipe.advance(), Ok(()));
9907 
9908         // Server gets data and sends data back, closing stream.
9909         let mut r = pipe.server.readable();
9910         assert_eq!(r.next(), Some(0));
9911         assert_eq!(r.next(), None);
9912 
9913         assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, false)));
9914         assert!(!pipe.server.stream_finished(0));
9915 
9916         let mut r = pipe.server.readable();
9917         assert_eq!(r.next(), None);
9918 
9919         assert_eq!(pipe.server.stream_send(0, b"", true), Ok(0));
9920         assert_eq!(pipe.advance(), Ok(()));
9921 
9922         let mut r = pipe.client.readable();
9923         assert_eq!(r.next(), Some(0));
9924         assert_eq!(r.next(), None);
9925 
9926         assert_eq!(pipe.client.stream_recv(0, &mut b), Ok((0, true)));
9927         assert!(pipe.client.stream_finished(0));
9928 
9929         // Client sends RESET_STREAM, closing stream.
9930         let frames = [frame::Frame::ResetStream {
9931             stream_id: 0,
9932             error_code: 42,
9933             final_size: 5,
9934         }];
9935 
9936         let pkt_type = packet::Type::Short;
9937         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
9938 
9939         // Server is notified of stream readability, due to reset.
9940         let mut r = pipe.server.readable();
9941         assert_eq!(r.next(), Some(0));
9942         assert_eq!(r.next(), None);
9943 
9944         assert_eq!(
9945             pipe.server.stream_recv(0, &mut b),
9946             Err(Error::StreamReset(42))
9947         );
9948 
9949         assert!(pipe.server.stream_finished(0));
9950 
9951         // Sending RESET_STREAM again shouldn't make stream readable again.
9952         pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
9953             .unwrap();
9954 
9955         let mut r = pipe.server.readable();
9956         assert_eq!(r.next(), None);
9957     }
9958 
9959     #[test]
9960     /// Tests that receiving a valid RESET_STREAM frame when all data has _not_
9961     /// been read, discards all buffered data and notifies the application.
reset_stream_data_not_recvd()9962     fn reset_stream_data_not_recvd() {
9963         let mut b = [0; 15];
9964         let mut buf = [0; 65535];
9965 
9966         let mut pipe = testing::Pipe::new().unwrap();
9967         assert_eq!(pipe.handshake(), Ok(()));
9968 
9969         // Client sends some data.
9970         assert_eq!(pipe.client.stream_send(0, b"h", false), Ok(1));
9971         assert_eq!(pipe.advance(), Ok(()));
9972 
9973         // Server gets data and sends data back, closing stream.
9974         let mut r = pipe.server.readable();
9975         assert_eq!(r.next(), Some(0));
9976         assert_eq!(r.next(), None);
9977 
9978         assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((1, false)));
9979         assert!(!pipe.server.stream_finished(0));
9980 
9981         let mut r = pipe.server.readable();
9982         assert_eq!(r.next(), None);
9983 
9984         assert_eq!(pipe.server.stream_send(0, b"", true), Ok(0));
9985         assert_eq!(pipe.advance(), Ok(()));
9986 
9987         let mut r = pipe.client.readable();
9988         assert_eq!(r.next(), Some(0));
9989         assert_eq!(r.next(), None);
9990 
9991         assert_eq!(pipe.client.stream_recv(0, &mut b), Ok((0, true)));
9992         assert!(pipe.client.stream_finished(0));
9993 
9994         // Client sends RESET_STREAM, closing stream.
9995         let frames = [frame::Frame::ResetStream {
9996             stream_id: 0,
9997             error_code: 42,
9998             final_size: 5,
9999         }];
10000 
10001         let pkt_type = packet::Type::Short;
10002         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
10003 
10004         // Server is notified of stream readability, due to reset.
10005         let mut r = pipe.server.readable();
10006         assert_eq!(r.next(), Some(0));
10007         assert_eq!(r.next(), None);
10008 
10009         assert_eq!(
10010             pipe.server.stream_recv(0, &mut b),
10011             Err(Error::StreamReset(42))
10012         );
10013 
10014         assert!(pipe.server.stream_finished(0));
10015 
10016         // Sending RESET_STREAM again shouldn't make stream readable again.
10017         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
10018 
10019         let mut r = pipe.server.readable();
10020         assert_eq!(r.next(), None);
10021     }
10022 
10023     #[test]
10024     /// Tests that RESET_STREAM frames exceeding the connection-level flow
10025     /// control limit cause an error.
reset_stream_flow_control()10026     fn reset_stream_flow_control() {
10027         let mut buf = [0; 65535];
10028 
10029         let mut pipe = testing::Pipe::new().unwrap();
10030         assert_eq!(pipe.handshake(), Ok(()));
10031 
10032         let frames = [
10033             frame::Frame::Stream {
10034                 stream_id: 0,
10035                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
10036             },
10037             frame::Frame::Stream {
10038                 stream_id: 4,
10039                 data: stream::RangeBuf::from(b"a", 0, false),
10040             },
10041             frame::Frame::ResetStream {
10042                 stream_id: 4,
10043                 error_code: 0,
10044                 final_size: 15,
10045             },
10046             frame::Frame::Stream {
10047                 stream_id: 8,
10048                 data: stream::RangeBuf::from(b"a", 0, false),
10049             },
10050         ];
10051 
10052         let pkt_type = packet::Type::Short;
10053         assert_eq!(
10054             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10055             Err(Error::FlowControl),
10056         );
10057     }
10058 
10059     #[test]
10060     /// Tests that RESET_STREAM frames exceeding the stream-level flow control
10061     /// limit cause an error.
reset_stream_flow_control_stream()10062     fn reset_stream_flow_control_stream() {
10063         let mut buf = [0; 65535];
10064 
10065         let mut pipe = testing::Pipe::new().unwrap();
10066         assert_eq!(pipe.handshake(), Ok(()));
10067 
10068         let frames = [
10069             frame::Frame::Stream {
10070                 stream_id: 4,
10071                 data: stream::RangeBuf::from(b"a", 0, false),
10072             },
10073             frame::Frame::ResetStream {
10074                 stream_id: 4,
10075                 error_code: 0,
10076                 final_size: 16, // Past stream's flow control limit.
10077             },
10078         ];
10079 
10080         let pkt_type = packet::Type::Short;
10081         assert_eq!(
10082             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10083             Err(Error::FlowControl),
10084         );
10085     }
10086 
10087     #[test]
path_challenge()10088     fn path_challenge() {
10089         let mut buf = [0; 65535];
10090 
10091         let mut pipe = testing::Pipe::new().unwrap();
10092         assert_eq!(pipe.handshake(), Ok(()));
10093 
10094         let frames = [frame::Frame::PathChallenge { data: [0xba; 8] }];
10095 
10096         let pkt_type = packet::Type::Short;
10097 
10098         let len = pipe
10099             .send_pkt_to_server(pkt_type, &frames, &mut buf)
10100             .unwrap();
10101 
10102         assert!(len > 0);
10103 
10104         let frames =
10105             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
10106         let mut iter = frames.iter();
10107 
10108         // Ignore ACK.
10109         iter.next().unwrap();
10110 
10111         assert_eq!(
10112             iter.next(),
10113             Some(&frame::Frame::PathResponse { data: [0xba; 8] })
10114         );
10115     }
10116 
10117     #[test]
10118     /// Simulates reception of an early 1-RTT packet on the server, by
10119     /// delaying the client's Handshake packet that completes the handshake.
early_1rtt_packet()10120     fn early_1rtt_packet() {
10121         let mut buf = [0; 65535];
10122 
10123         let mut pipe = testing::Pipe::new().unwrap();
10124 
10125         // Client sends initial flight
10126         let flight = testing::emit_flight(&mut pipe.client).unwrap();
10127         testing::process_flight(&mut pipe.server, flight).unwrap();
10128 
10129         // Server sends initial flight.
10130         let flight = testing::emit_flight(&mut pipe.server).unwrap();
10131         testing::process_flight(&mut pipe.client, flight).unwrap();
10132 
10133         // Client sends Handshake packet.
10134         let flight = testing::emit_flight(&mut pipe.client).unwrap();
10135 
10136         // Emulate handshake packet delay by not making server process client
10137         // packet.
10138         let delayed = flight;
10139 
10140         testing::emit_flight(&mut pipe.server).ok();
10141 
10142         assert!(pipe.client.is_established());
10143 
10144         // Send 1-RTT packet #0.
10145         let frames = [frame::Frame::Stream {
10146             stream_id: 0,
10147             data: stream::RangeBuf::from(b"hello, world", 0, true),
10148         }];
10149 
10150         let pkt_type = packet::Type::Short;
10151         let written =
10152             testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
10153                 .unwrap();
10154 
10155         assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
10156 
10157         // Send 1-RTT packet #1.
10158         let frames = [frame::Frame::Stream {
10159             stream_id: 4,
10160             data: stream::RangeBuf::from(b"hello, world", 0, true),
10161         }];
10162 
10163         let written =
10164             testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
10165                 .unwrap();
10166 
10167         assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
10168 
10169         assert!(!pipe.server.is_established());
10170 
10171         // Client sent 1-RTT packets 0 and 1, but server hasn't received them.
10172         //
10173         // Note that `largest_rx_pkt_num` is initialized to 0, so we need to
10174         // send another 1-RTT packet to make this check meaningful.
10175         assert_eq!(
10176             pipe.server.pkt_num_spaces[packet::Epoch::Application]
10177                 .largest_rx_pkt_num,
10178             0
10179         );
10180 
10181         // Process delayed packet.
10182         testing::process_flight(&mut pipe.server, delayed).unwrap();
10183 
10184         assert!(pipe.server.is_established());
10185 
10186         assert_eq!(
10187             pipe.server.pkt_num_spaces[packet::Epoch::Application]
10188                 .largest_rx_pkt_num,
10189             0
10190         );
10191     }
10192 
10193     #[test]
stop_sending()10194     fn stop_sending() {
10195         let mut b = [0; 15];
10196 
10197         let mut buf = [0; 65535];
10198 
10199         let mut pipe = testing::Pipe::new().unwrap();
10200         assert_eq!(pipe.handshake(), Ok(()));
10201 
10202         // Client sends some data, and closes stream.
10203         assert_eq!(pipe.client.stream_send(0, b"hello", true), Ok(5));
10204         assert_eq!(pipe.advance(), Ok(()));
10205 
10206         // Server gets data.
10207         let mut r = pipe.server.readable();
10208         assert_eq!(r.next(), Some(0));
10209         assert_eq!(r.next(), None);
10210 
10211         assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, true)));
10212         assert!(pipe.server.stream_finished(0));
10213 
10214         let mut r = pipe.server.readable();
10215         assert_eq!(r.next(), None);
10216 
10217         // Server sends data, until blocked.
10218         let mut r = pipe.server.writable();
10219         assert_eq!(r.next(), Some(0));
10220         assert_eq!(r.next(), None);
10221 
10222         loop {
10223             if pipe.server.stream_send(0, b"world", false) == Err(Error::Done) {
10224                 break;
10225             }
10226 
10227             assert_eq!(pipe.advance(), Ok(()));
10228         }
10229 
10230         let mut r = pipe.server.writable();
10231         assert_eq!(r.next(), None);
10232 
10233         // Client sends STOP_SENDING.
10234         let frames = [frame::Frame::StopSending {
10235             stream_id: 0,
10236             error_code: 42,
10237         }];
10238 
10239         let pkt_type = packet::Type::Short;
10240         let len = pipe
10241             .send_pkt_to_server(pkt_type, &frames, &mut buf)
10242             .unwrap();
10243 
10244         // Server sent a RESET_STREAM frame in response.
10245         let frames =
10246             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
10247 
10248         let mut iter = frames.iter();
10249 
10250         // Skip ACK frame.
10251         iter.next();
10252 
10253         assert_eq!(
10254             iter.next(),
10255             Some(&frame::Frame::ResetStream {
10256                 stream_id: 0,
10257                 error_code: 42,
10258                 final_size: 15,
10259             })
10260         );
10261 
10262         // Stream is writable, but writing returns an error.
10263         let mut r = pipe.server.writable();
10264         assert_eq!(r.next(), Some(0));
10265         assert_eq!(r.next(), None);
10266 
10267         assert_eq!(
10268             pipe.server.stream_send(0, b"world", true),
10269             Err(Error::StreamStopped(42)),
10270         );
10271 
10272         assert_eq!(pipe.server.streams.len(), 1);
10273 
10274         // Client acks RESET_STREAM frame.
10275         let mut ranges = ranges::RangeSet::default();
10276         ranges.insert(0..6);
10277 
10278         let frames = [frame::Frame::ACK {
10279             ack_delay: 15,
10280             ranges,
10281             ecn_counts: None,
10282         }];
10283 
10284         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(0));
10285 
10286         // Stream is collected on the server after RESET_STREAM is acked.
10287         assert_eq!(pipe.server.streams.len(), 0);
10288 
10289         // Sending STOP_SENDING again shouldn't trigger RESET_STREAM again.
10290         let frames = [frame::Frame::StopSending {
10291             stream_id: 0,
10292             error_code: 42,
10293         }];
10294 
10295         let len = pipe
10296             .send_pkt_to_server(pkt_type, &frames, &mut buf)
10297             .unwrap();
10298 
10299         let frames =
10300             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
10301 
10302         assert_eq!(frames.len(), 1);
10303 
10304         match frames.first() {
10305             Some(frame::Frame::ACK { .. }) => (),
10306 
10307             f => panic!("expected ACK frame, got {:?}", f),
10308         };
10309 
10310         let mut r = pipe.server.writable();
10311         assert_eq!(r.next(), None);
10312     }
10313 
10314     #[test]
stop_sending_fin()10315     fn stop_sending_fin() {
10316         let mut b = [0; 15];
10317 
10318         let mut buf = [0; 65535];
10319 
10320         let mut pipe = testing::Pipe::new().unwrap();
10321         assert_eq!(pipe.handshake(), Ok(()));
10322 
10323         // Client sends some data, and closes stream.
10324         assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
10325         assert_eq!(pipe.advance(), Ok(()));
10326 
10327         // Server gets data.
10328         let mut r = pipe.server.readable();
10329         assert_eq!(r.next(), Some(4));
10330         assert_eq!(r.next(), None);
10331 
10332         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
10333         assert!(pipe.server.stream_finished(4));
10334 
10335         let mut r = pipe.server.readable();
10336         assert_eq!(r.next(), None);
10337 
10338         // Server sends data...
10339         let mut r = pipe.server.writable();
10340         assert_eq!(r.next(), Some(4));
10341         assert_eq!(r.next(), None);
10342 
10343         assert_eq!(pipe.server.stream_send(4, b"world", false), Ok(5));
10344         assert_eq!(pipe.advance(), Ok(()));
10345 
10346         // ...and buffers more, and closes stream.
10347         assert_eq!(pipe.server.stream_send(4, b"world", true), Ok(5));
10348 
10349         // Client sends STOP_SENDING before server flushes stream.
10350         let frames = [frame::Frame::StopSending {
10351             stream_id: 4,
10352             error_code: 42,
10353         }];
10354 
10355         let pkt_type = packet::Type::Short;
10356         let len = pipe
10357             .send_pkt_to_server(pkt_type, &frames, &mut buf)
10358             .unwrap();
10359 
10360         // Server sent a RESET_STREAM frame in response.
10361         let frames =
10362             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
10363 
10364         let mut iter = frames.iter();
10365 
10366         // Skip ACK frame.
10367         iter.next();
10368 
10369         assert_eq!(
10370             iter.next(),
10371             Some(&frame::Frame::ResetStream {
10372                 stream_id: 4,
10373                 error_code: 42,
10374                 final_size: 5,
10375             })
10376         );
10377 
10378         // No more frames are sent by the server.
10379         assert_eq!(iter.next(), None);
10380     }
10381 
10382     #[test]
10383     /// Tests that resetting a stream restores flow control for unsent data.
stop_sending_unsent_tx_cap()10384     fn stop_sending_unsent_tx_cap() {
10385         let mut buf = [0; 65535];
10386 
10387         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10388         config
10389             .load_cert_chain_from_pem_file("examples/cert.crt")
10390             .unwrap();
10391         config
10392             .load_priv_key_from_pem_file("examples/cert.key")
10393             .unwrap();
10394         config
10395             .set_application_protos(&[b"proto1", b"proto2"])
10396             .unwrap();
10397         config.set_initial_max_data(15);
10398         config.set_initial_max_stream_data_bidi_local(30);
10399         config.set_initial_max_stream_data_bidi_remote(30);
10400         config.set_initial_max_stream_data_uni(30);
10401         config.set_initial_max_streams_bidi(3);
10402         config.set_initial_max_streams_uni(0);
10403         config.verify_peer(false);
10404 
10405         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10406         assert_eq!(pipe.handshake(), Ok(()));
10407 
10408         // Client sends some data.
10409         assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
10410         assert_eq!(pipe.advance(), Ok(()));
10411 
10412         let mut r = pipe.server.readable();
10413         assert_eq!(r.next(), Some(4));
10414         assert_eq!(r.next(), None);
10415 
10416         let mut b = [0; 15];
10417         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
10418 
10419         // Server sends some data.
10420         assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
10421         assert_eq!(pipe.advance(), Ok(()));
10422 
10423         // Server buffers some data, until send capacity limit reached.
10424         assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
10425         assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
10426         assert_eq!(
10427             pipe.server.stream_send(4, b"hello", false),
10428             Err(Error::Done)
10429         );
10430 
10431         // Client sends STOP_SENDING.
10432         let frames = [frame::Frame::StopSending {
10433             stream_id: 4,
10434             error_code: 42,
10435         }];
10436 
10437         let pkt_type = packet::Type::Short;
10438         pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
10439             .unwrap();
10440 
10441         // Server can now send more data (on a different stream).
10442         assert_eq!(pipe.client.stream_send(8, b"hello", true), Ok(5));
10443         assert_eq!(pipe.advance(), Ok(()));
10444 
10445         assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
10446         assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
10447         assert_eq!(
10448             pipe.server.stream_send(8, b"hello", false),
10449             Err(Error::Done)
10450         );
10451         assert_eq!(pipe.advance(), Ok(()));
10452     }
10453 
10454     #[test]
stream_shutdown_read()10455     fn stream_shutdown_read() {
10456         let mut buf = [0; 65535];
10457 
10458         let mut pipe = testing::Pipe::new().unwrap();
10459         assert_eq!(pipe.handshake(), Ok(()));
10460 
10461         // Client sends some data.
10462         assert_eq!(pipe.client.stream_send(4, b"hello, world", false), Ok(12));
10463         assert_eq!(pipe.advance(), Ok(()));
10464 
10465         let mut r = pipe.server.readable();
10466         assert_eq!(r.next(), Some(4));
10467         assert_eq!(r.next(), None);
10468 
10469         assert_eq!(pipe.client.streams.len(), 1);
10470         assert_eq!(pipe.server.streams.len(), 1);
10471 
10472         // Server shuts down stream.
10473         assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 42), Ok(()));
10474 
10475         let mut r = pipe.server.readable();
10476         assert_eq!(r.next(), None);
10477 
10478         let (len, _) = pipe.server.send(&mut buf).unwrap();
10479 
10480         let mut dummy = buf[..len].to_vec();
10481 
10482         let frames =
10483             testing::decode_pkt(&mut pipe.client, &mut dummy, len).unwrap();
10484         let mut iter = frames.iter();
10485 
10486         assert_eq!(
10487             iter.next(),
10488             Some(&frame::Frame::StopSending {
10489                 stream_id: 4,
10490                 error_code: 42,
10491             })
10492         );
10493 
10494         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
10495 
10496         assert_eq!(pipe.advance(), Ok(()));
10497 
10498         // Sending more data is forbidden.
10499         let mut r = pipe.client.writable();
10500         assert_eq!(r.next(), Some(4));
10501         assert_eq!(r.next(), None);
10502 
10503         assert_eq!(
10504             pipe.client.stream_send(4, b"bye", false),
10505             Err(Error::StreamStopped(42))
10506         );
10507 
10508         // Server sends some data, without reading the incoming data, and closes
10509         // the stream.
10510         assert_eq!(pipe.server.stream_send(4, b"hello, world", true), Ok(12));
10511         assert_eq!(pipe.advance(), Ok(()));
10512 
10513         // Client reads the data.
10514         let mut r = pipe.client.readable();
10515         assert_eq!(r.next(), Some(4));
10516         assert_eq!(r.next(), None);
10517 
10518         assert_eq!(pipe.client.stream_recv(4, &mut buf), Ok((12, true)));
10519 
10520         // Stream is collected on both sides.
10521         assert_eq!(pipe.client.streams.len(), 0);
10522         assert_eq!(pipe.server.streams.len(), 0);
10523 
10524         assert_eq!(
10525             pipe.server.stream_shutdown(4, Shutdown::Read, 0),
10526             Err(Error::Done)
10527         );
10528     }
10529 
10530     #[test]
stream_shutdown_read_after_fin()10531     fn stream_shutdown_read_after_fin() {
10532         let mut buf = [0; 65535];
10533 
10534         let mut pipe = testing::Pipe::new().unwrap();
10535         assert_eq!(pipe.handshake(), Ok(()));
10536 
10537         // Client sends some data.
10538         assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
10539         assert_eq!(pipe.advance(), Ok(()));
10540 
10541         let mut r = pipe.server.readable();
10542         assert_eq!(r.next(), Some(4));
10543         assert_eq!(r.next(), None);
10544 
10545         assert_eq!(pipe.client.streams.len(), 1);
10546         assert_eq!(pipe.server.streams.len(), 1);
10547 
10548         // Server shuts down stream.
10549         assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 42), Ok(()));
10550 
10551         let mut r = pipe.server.readable();
10552         assert_eq!(r.next(), None);
10553 
10554         // Server has nothing to send.
10555         assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
10556 
10557         assert_eq!(pipe.advance(), Ok(()));
10558 
10559         // Server sends some data, without reading the incoming data, and closes
10560         // the stream.
10561         assert_eq!(pipe.server.stream_send(4, b"hello, world", true), Ok(12));
10562         assert_eq!(pipe.advance(), Ok(()));
10563 
10564         // Client reads the data.
10565         let mut r = pipe.client.readable();
10566         assert_eq!(r.next(), Some(4));
10567         assert_eq!(r.next(), None);
10568 
10569         assert_eq!(pipe.client.stream_recv(4, &mut buf), Ok((12, true)));
10570 
10571         // Stream is collected on both sides.
10572         assert_eq!(pipe.client.streams.len(), 0);
10573         assert_eq!(pipe.server.streams.len(), 0);
10574 
10575         assert_eq!(
10576             pipe.server.stream_shutdown(4, Shutdown::Read, 0),
10577             Err(Error::Done)
10578         );
10579     }
10580 
10581     #[test]
stream_shutdown_read_update_max_data()10582     fn stream_shutdown_read_update_max_data() {
10583         let mut buf = [0; 65535];
10584 
10585         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10586         config
10587             .load_cert_chain_from_pem_file("examples/cert.crt")
10588             .unwrap();
10589         config
10590             .load_priv_key_from_pem_file("examples/cert.key")
10591             .unwrap();
10592         config
10593             .set_application_protos(&[b"proto1", b"proto2"])
10594             .unwrap();
10595         config.set_initial_max_data(30);
10596         config.set_initial_max_stream_data_bidi_local(10000);
10597         config.set_initial_max_stream_data_bidi_remote(10000);
10598         config.set_initial_max_streams_bidi(10);
10599         config.verify_peer(false);
10600 
10601         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10602         assert_eq!(pipe.handshake(), Ok(()));
10603 
10604         assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
10605         assert_eq!(pipe.advance(), Ok(()));
10606 
10607         assert_eq!(pipe.server.stream_recv(0, &mut buf), Ok((1, false)));
10608         assert_eq!(pipe.server.stream_shutdown(0, Shutdown::Read, 123), Ok(()));
10609 
10610         assert_eq!(pipe.server.rx_data, 1);
10611         assert_eq!(pipe.client.tx_data, 1);
10612         assert_eq!(pipe.client.max_tx_data, 30);
10613 
10614         assert_eq!(
10615             pipe.client
10616                 .stream_send(0, &buf[..pipe.client.tx_cap], false),
10617             Ok(29)
10618         );
10619         assert_eq!(pipe.advance(), Ok(()));
10620 
10621         assert_eq!(pipe.server.stream_readable(0), false); // nothing can be consumed
10622 
10623         // The client has increased its tx_data, and server has received it, so
10624         // it increases flow control accordingly.
10625         assert_eq!(pipe.client.tx_data, 30);
10626         assert_eq!(pipe.server.rx_data, 30);
10627         assert_eq!(pipe.client.tx_cap, 45);
10628     }
10629 
10630     #[test]
stream_shutdown_uni()10631     fn stream_shutdown_uni() {
10632         let mut pipe = testing::Pipe::new().unwrap();
10633         assert_eq!(pipe.handshake(), Ok(()));
10634 
10635         // Exchange some data on uni streams.
10636         assert_eq!(pipe.client.stream_send(2, b"hello, world", false), Ok(10));
10637         assert_eq!(pipe.server.stream_send(3, b"hello, world", false), Ok(10));
10638         assert_eq!(pipe.advance(), Ok(()));
10639 
10640         // Test local and remote shutdown.
10641         assert_eq!(pipe.client.stream_shutdown(2, Shutdown::Write, 42), Ok(()));
10642         assert_eq!(
10643             pipe.client.stream_shutdown(2, Shutdown::Read, 42),
10644             Err(Error::InvalidStreamState(2))
10645         );
10646 
10647         assert_eq!(
10648             pipe.client.stream_shutdown(3, Shutdown::Write, 42),
10649             Err(Error::InvalidStreamState(3))
10650         );
10651         assert_eq!(pipe.client.stream_shutdown(3, Shutdown::Read, 42), Ok(()));
10652     }
10653 
10654     #[test]
stream_shutdown_write()10655     fn stream_shutdown_write() {
10656         let mut buf = [0; 65535];
10657 
10658         let mut pipe = testing::Pipe::new().unwrap();
10659         assert_eq!(pipe.handshake(), Ok(()));
10660 
10661         // Client sends some data.
10662         assert_eq!(pipe.client.stream_send(4, b"hello, world", false), Ok(12));
10663         assert_eq!(pipe.advance(), Ok(()));
10664 
10665         let mut r = pipe.server.readable();
10666         assert_eq!(r.next(), Some(4));
10667         assert_eq!(r.next(), None);
10668 
10669         let mut r = pipe.server.writable();
10670         assert_eq!(r.next(), Some(4));
10671         assert_eq!(r.next(), None);
10672 
10673         assert_eq!(pipe.client.streams.len(), 1);
10674         assert_eq!(pipe.server.streams.len(), 1);
10675 
10676         // Server sends some data.
10677         assert_eq!(pipe.server.stream_send(4, b"goodbye, world", false), Ok(14));
10678         assert_eq!(pipe.advance(), Ok(()));
10679 
10680         // Server shuts down stream.
10681         assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Write, 42), Ok(()));
10682 
10683         let mut r = pipe.server.writable();
10684         assert_eq!(r.next(), None);
10685 
10686         let (len, _) = pipe.server.send(&mut buf).unwrap();
10687 
10688         let mut dummy = buf[..len].to_vec();
10689 
10690         let frames =
10691             testing::decode_pkt(&mut pipe.client, &mut dummy, len).unwrap();
10692         let mut iter = frames.iter();
10693 
10694         assert_eq!(
10695             iter.next(),
10696             Some(&frame::Frame::ResetStream {
10697                 stream_id: 4,
10698                 error_code: 42,
10699                 final_size: 14,
10700             })
10701         );
10702 
10703         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
10704 
10705         assert_eq!(pipe.advance(), Ok(()));
10706 
10707         // Sending more data is forbidden.
10708         assert_eq!(
10709             pipe.server.stream_send(4, b"bye", false),
10710             Err(Error::FinalSize)
10711         );
10712 
10713         // Client sends some data and closes the stream.
10714         assert_eq!(pipe.client.stream_send(4, b"bye", true), Ok(3));
10715         assert_eq!(pipe.advance(), Ok(()));
10716 
10717         // Server reads the data.
10718         let mut r = pipe.server.readable();
10719         assert_eq!(r.next(), Some(4));
10720         assert_eq!(r.next(), None);
10721 
10722         assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((15, true)));
10723 
10724         // Client processes readable streams.
10725         let mut r = pipe.client.readable();
10726         assert_eq!(r.next(), Some(4));
10727         assert_eq!(r.next(), None);
10728 
10729         assert_eq!(
10730             pipe.client.stream_recv(4, &mut buf),
10731             Err(Error::StreamReset(42))
10732         );
10733 
10734         // Stream is collected on both sides.
10735         assert_eq!(pipe.client.streams.len(), 0);
10736         assert_eq!(pipe.server.streams.len(), 0);
10737 
10738         assert_eq!(
10739             pipe.server.stream_shutdown(4, Shutdown::Write, 0),
10740             Err(Error::Done)
10741         );
10742     }
10743 
10744     #[test]
10745     /// Tests that shutting down a stream restores flow control for unsent data.
stream_shutdown_write_unsent_tx_cap()10746     fn stream_shutdown_write_unsent_tx_cap() {
10747         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10748         config
10749             .load_cert_chain_from_pem_file("examples/cert.crt")
10750             .unwrap();
10751         config
10752             .load_priv_key_from_pem_file("examples/cert.key")
10753             .unwrap();
10754         config
10755             .set_application_protos(&[b"proto1", b"proto2"])
10756             .unwrap();
10757         config.set_initial_max_data(15);
10758         config.set_initial_max_stream_data_bidi_local(30);
10759         config.set_initial_max_stream_data_bidi_remote(30);
10760         config.set_initial_max_stream_data_uni(30);
10761         config.set_initial_max_streams_bidi(3);
10762         config.set_initial_max_streams_uni(0);
10763         config.verify_peer(false);
10764 
10765         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10766         assert_eq!(pipe.handshake(), Ok(()));
10767 
10768         // Client sends some data.
10769         assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
10770         assert_eq!(pipe.advance(), Ok(()));
10771 
10772         let mut r = pipe.server.readable();
10773         assert_eq!(r.next(), Some(4));
10774         assert_eq!(r.next(), None);
10775 
10776         let mut b = [0; 15];
10777         assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
10778 
10779         // Server sends some data.
10780         assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
10781         assert_eq!(pipe.advance(), Ok(()));
10782 
10783         // Server buffers some data, until send capacity limit reached.
10784         assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
10785         assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
10786         assert_eq!(
10787             pipe.server.stream_send(4, b"hello", false),
10788             Err(Error::Done)
10789         );
10790 
10791         // Client shouldn't update flow control.
10792         assert_eq!(pipe.client.should_update_max_data(), false);
10793 
10794         // Server shuts down stream.
10795         assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Write, 42), Ok(()));
10796         assert_eq!(pipe.advance(), Ok(()));
10797 
10798         // Server can now send more data (on a different stream).
10799         assert_eq!(pipe.client.stream_send(8, b"hello", true), Ok(5));
10800         assert_eq!(pipe.advance(), Ok(()));
10801 
10802         assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
10803         assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
10804         assert_eq!(
10805             pipe.server.stream_send(8, b"hello", false),
10806             Err(Error::Done)
10807         );
10808         assert_eq!(pipe.advance(), Ok(()));
10809     }
10810 
10811     #[test]
10812     /// Tests that the order of flushable streams scheduled on the wire is the
10813     /// same as the order of `stream_send()` calls done by the application.
stream_round_robin()10814     fn stream_round_robin() {
10815         let mut buf = [0; 65535];
10816 
10817         let mut pipe = testing::Pipe::new().unwrap();
10818         assert_eq!(pipe.handshake(), Ok(()));
10819 
10820         assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
10821         assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
10822         assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
10823 
10824         let (len, _) = pipe.client.send(&mut buf).unwrap();
10825 
10826         let frames =
10827             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
10828 
10829         let mut iter = frames.iter();
10830 
10831         // Skip ACK frame.
10832         iter.next();
10833 
10834         assert_eq!(
10835             iter.next(),
10836             Some(&frame::Frame::Stream {
10837                 stream_id: 8,
10838                 data: stream::RangeBuf::from(b"aaaaa", 0, false),
10839             })
10840         );
10841 
10842         let (len, _) = pipe.client.send(&mut buf).unwrap();
10843 
10844         let frames =
10845             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
10846 
10847         assert_eq!(
10848             frames.first(),
10849             Some(&frame::Frame::Stream {
10850                 stream_id: 0,
10851                 data: stream::RangeBuf::from(b"aaaaa", 0, false),
10852             })
10853         );
10854 
10855         let (len, _) = pipe.client.send(&mut buf).unwrap();
10856 
10857         let frames =
10858             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
10859 
10860         assert_eq!(
10861             frames.first(),
10862             Some(&frame::Frame::Stream {
10863                 stream_id: 4,
10864                 data: stream::RangeBuf::from(b"aaaaa", 0, false),
10865             })
10866         );
10867     }
10868 
10869     #[test]
10870     /// Tests the readable iterator.
stream_readable()10871     fn stream_readable() {
10872         let mut pipe = testing::Pipe::new().unwrap();
10873         assert_eq!(pipe.handshake(), Ok(()));
10874 
10875         // No readable streams.
10876         let mut r = pipe.client.readable();
10877         assert_eq!(r.next(), None);
10878 
10879         assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
10880 
10881         let mut r = pipe.client.readable();
10882         assert_eq!(r.next(), None);
10883 
10884         let mut r = pipe.server.readable();
10885         assert_eq!(r.next(), None);
10886 
10887         assert_eq!(pipe.advance(), Ok(()));
10888 
10889         // Server received stream.
10890         let mut r = pipe.server.readable();
10891         assert_eq!(r.next(), Some(0));
10892         assert_eq!(r.next(), None);
10893 
10894         assert_eq!(
10895             pipe.server.stream_send(0, b"aaaaaaaaaaaaaaa", false),
10896             Ok(15)
10897         );
10898         assert_eq!(pipe.advance(), Ok(()));
10899 
10900         let mut r = pipe.client.readable();
10901         assert_eq!(r.next(), Some(0));
10902         assert_eq!(r.next(), None);
10903 
10904         // Client drains stream.
10905         let mut b = [0; 15];
10906         pipe.client.stream_recv(0, &mut b).unwrap();
10907         assert_eq!(pipe.advance(), Ok(()));
10908 
10909         let mut r = pipe.client.readable();
10910         assert_eq!(r.next(), None);
10911 
10912         // Server shuts down stream.
10913         let mut r = pipe.server.readable();
10914         assert_eq!(r.next(), Some(0));
10915         assert_eq!(r.next(), None);
10916 
10917         assert_eq!(pipe.server.stream_shutdown(0, Shutdown::Read, 0), Ok(()));
10918 
10919         let mut r = pipe.server.readable();
10920         assert_eq!(r.next(), None);
10921 
10922         // Client creates multiple streams.
10923         assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
10924         assert_eq!(pipe.advance(), Ok(()));
10925 
10926         assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
10927         assert_eq!(pipe.advance(), Ok(()));
10928 
10929         let mut r = pipe.server.readable();
10930         assert_eq!(r.len(), 2);
10931 
10932         assert!(r.next().is_some());
10933         assert!(r.next().is_some());
10934         assert!(r.next().is_none());
10935 
10936         assert_eq!(r.len(), 0);
10937     }
10938 
10939     #[test]
10940     /// Tests the writable iterator.
stream_writable()10941     fn stream_writable() {
10942         let mut pipe = testing::Pipe::new().unwrap();
10943         assert_eq!(pipe.handshake(), Ok(()));
10944 
10945         // No writable streams.
10946         let mut w = pipe.client.writable();
10947         assert_eq!(w.next(), None);
10948 
10949         assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
10950 
10951         // Client created stream.
10952         let mut w = pipe.client.writable();
10953         assert_eq!(w.next(), Some(0));
10954         assert_eq!(w.next(), None);
10955 
10956         assert_eq!(pipe.advance(), Ok(()));
10957 
10958         // Server created stream.
10959         let mut w = pipe.server.writable();
10960         assert_eq!(w.next(), Some(0));
10961         assert_eq!(w.next(), None);
10962 
10963         assert_eq!(
10964             pipe.server.stream_send(0, b"aaaaaaaaaaaaaaa", false),
10965             Ok(15)
10966         );
10967 
10968         // Server stream is full.
10969         let mut w = pipe.server.writable();
10970         assert_eq!(w.next(), None);
10971 
10972         assert_eq!(pipe.advance(), Ok(()));
10973 
10974         // Client drains stream.
10975         let mut b = [0; 15];
10976         pipe.client.stream_recv(0, &mut b).unwrap();
10977         assert_eq!(pipe.advance(), Ok(()));
10978 
10979         // Server stream is writable again.
10980         let mut w = pipe.server.writable();
10981         assert_eq!(w.next(), Some(0));
10982         assert_eq!(w.next(), None);
10983 
10984         // Server shuts down stream.
10985         assert_eq!(pipe.server.stream_shutdown(0, Shutdown::Write, 0), Ok(()));
10986 
10987         let mut w = pipe.server.writable();
10988         assert_eq!(w.next(), None);
10989 
10990         // Client creates multiple streams.
10991         assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
10992         assert_eq!(pipe.advance(), Ok(()));
10993 
10994         assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
10995         assert_eq!(pipe.advance(), Ok(()));
10996 
10997         let mut w = pipe.server.writable();
10998         assert_eq!(w.len(), 2);
10999 
11000         assert!(w.next().is_some());
11001         assert!(w.next().is_some());
11002         assert!(w.next().is_none());
11003 
11004         assert_eq!(w.len(), 0);
11005 
11006         // Server finishes stream.
11007         assert_eq!(pipe.server.stream_send(8, b"aaaaa", true), Ok(5));
11008 
11009         let mut w = pipe.server.writable();
11010         assert_eq!(w.next(), Some(4));
11011         assert_eq!(w.next(), None);
11012     }
11013 
11014     #[test]
stream_writable_blocked()11015     fn stream_writable_blocked() {
11016         let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
11017         config
11018             .load_cert_chain_from_pem_file("examples/cert.crt")
11019             .unwrap();
11020         config
11021             .load_priv_key_from_pem_file("examples/cert.key")
11022             .unwrap();
11023         config.set_application_protos(&[b"h3"]).unwrap();
11024         config.set_initial_max_data(70);
11025         config.set_initial_max_stream_data_bidi_local(150000);
11026         config.set_initial_max_stream_data_bidi_remote(150000);
11027         config.set_initial_max_stream_data_uni(150000);
11028         config.set_initial_max_streams_bidi(100);
11029         config.set_initial_max_streams_uni(5);
11030         config.verify_peer(false);
11031 
11032         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
11033         assert_eq!(pipe.handshake(), Ok(()));
11034 
11035         // Client creates stream and sends some data.
11036         let send_buf = [0; 35];
11037         assert_eq!(pipe.client.stream_send(0, &send_buf, false), Ok(35));
11038 
11039         // Stream is still writable as it still has capacity.
11040         assert_eq!(pipe.client.stream_writable_next(), Some(0));
11041         assert_eq!(pipe.client.stream_writable_next(), None);
11042 
11043         // Client fills stream, which becomes unwritable due to connection
11044         // capacity.
11045         let send_buf = [0; 36];
11046         assert_eq!(pipe.client.stream_send(0, &send_buf, false), Ok(35));
11047 
11048         assert_eq!(pipe.client.stream_writable_next(), None);
11049 
11050         assert_eq!(pipe.client.tx_cap, 0);
11051 
11052         assert_eq!(pipe.advance(), Ok(()));
11053 
11054         let mut b = [0; 70];
11055         pipe.server.stream_recv(0, &mut b).unwrap();
11056 
11057         assert_eq!(pipe.advance(), Ok(()));
11058 
11059         // The connection capacity has increased and the stream is now writable
11060         // again.
11061         assert_ne!(pipe.client.tx_cap, 0);
11062 
11063         assert_eq!(pipe.client.stream_writable_next(), Some(0));
11064         assert_eq!(pipe.client.stream_writable_next(), None);
11065     }
11066 
11067     #[test]
11068     /// Tests that we don't exceed the per-connection flow control limit set by
11069     /// the peer.
flow_control_limit_send()11070     fn flow_control_limit_send() {
11071         let mut pipe = testing::Pipe::new().unwrap();
11072         assert_eq!(pipe.handshake(), Ok(()));
11073 
11074         assert_eq!(
11075             pipe.client.stream_send(0, b"aaaaaaaaaaaaaaa", false),
11076             Ok(15)
11077         );
11078         assert_eq!(pipe.advance(), Ok(()));
11079         assert_eq!(
11080             pipe.client.stream_send(4, b"aaaaaaaaaaaaaaa", false),
11081             Ok(15)
11082         );
11083         assert_eq!(pipe.advance(), Ok(()));
11084         assert_eq!(pipe.client.stream_send(8, b"a", false), Err(Error::Done));
11085         assert_eq!(pipe.advance(), Ok(()));
11086 
11087         let mut r = pipe.server.readable();
11088         assert!(r.next().is_some());
11089         assert!(r.next().is_some());
11090         assert!(r.next().is_none());
11091     }
11092 
11093     #[test]
11094     /// Tests that invalid packets received before any other valid ones cause
11095     /// the server to close the connection immediately.
invalid_initial_server()11096     fn invalid_initial_server() {
11097         let mut buf = [0; 65535];
11098         let mut pipe = testing::Pipe::new().unwrap();
11099 
11100         let frames = [frame::Frame::Padding { len: 10 }];
11101 
11102         let written = testing::encode_pkt(
11103             &mut pipe.client,
11104             packet::Type::Initial,
11105             &frames,
11106             &mut buf,
11107         )
11108         .unwrap();
11109 
11110         // Corrupt the packets's last byte to make decryption fail (the last
11111         // byte is part of the AEAD tag, so changing it means that the packet
11112         // cannot be authenticated during decryption).
11113         buf[written - 1] = !buf[written - 1];
11114 
11115         assert_eq!(pipe.server.timeout(), None);
11116 
11117         assert_eq!(
11118             pipe.server_recv(&mut buf[..written]),
11119             Err(Error::CryptoFail)
11120         );
11121 
11122         assert!(pipe.server.is_closed());
11123     }
11124 
11125     #[test]
11126     /// Tests that invalid Initial packets received to cause
11127     /// the client to close the connection immediately.
invalid_initial_client()11128     fn invalid_initial_client() {
11129         let mut buf = [0; 65535];
11130         let mut pipe = testing::Pipe::new().unwrap();
11131 
11132         // Client sends initial flight.
11133         let (len, _) = pipe.client.send(&mut buf).unwrap();
11134 
11135         // Server sends initial flight.
11136         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(1200));
11137 
11138         let frames = [frame::Frame::Padding { len: 10 }];
11139 
11140         let written = testing::encode_pkt(
11141             &mut pipe.server,
11142             packet::Type::Initial,
11143             &frames,
11144             &mut buf,
11145         )
11146         .unwrap();
11147 
11148         // Corrupt the packets's last byte to make decryption fail (the last
11149         // byte is part of the AEAD tag, so changing it means that the packet
11150         // cannot be authenticated during decryption).
11151         buf[written - 1] = !buf[written - 1];
11152 
11153         // Client will ignore invalid packet.
11154         assert_eq!(pipe.client_recv(&mut buf[..written]), Ok(71));
11155 
11156         // The connection should be alive...
11157         assert_eq!(pipe.client.is_closed(), false);
11158 
11159         // ...and the idle timeout should be armed.
11160         assert!(pipe.client.idle_timer.is_some());
11161     }
11162 
11163     #[test]
11164     /// Tests that packets with invalid payload length received before any other
11165     /// valid packet cause the server to close the connection immediately.
invalid_initial_payload()11166     fn invalid_initial_payload() {
11167         let mut buf = [0; 65535];
11168         let mut pipe = testing::Pipe::new().unwrap();
11169 
11170         let mut b = octets::OctetsMut::with_slice(&mut buf);
11171 
11172         let epoch = packet::Type::Initial.to_epoch().unwrap();
11173 
11174         let pn = 0;
11175         let pn_len = packet::pkt_num_len(pn).unwrap();
11176 
11177         let dcid = pipe.client.destination_id();
11178         let scid = pipe.client.source_id();
11179 
11180         let hdr = Header {
11181             ty: packet::Type::Initial,
11182             version: pipe.client.version,
11183             dcid: ConnectionId::from_ref(&dcid),
11184             scid: ConnectionId::from_ref(&scid),
11185             pkt_num: 0,
11186             pkt_num_len: pn_len,
11187             token: pipe.client.token.clone(),
11188             versions: None,
11189             key_phase: false,
11190         };
11191 
11192         hdr.to_bytes(&mut b).unwrap();
11193 
11194         // Payload length is invalid!!!
11195         let payload_len = 4096;
11196 
11197         let len = pn_len + payload_len;
11198         b.put_varint(len as u64).unwrap();
11199 
11200         packet::encode_pkt_num(pn, &mut b).unwrap();
11201 
11202         let payload_offset = b.off();
11203 
11204         let frames = [frame::Frame::Padding { len: 10 }];
11205 
11206         for frame in &frames {
11207             frame.to_bytes(&mut b).unwrap();
11208         }
11209 
11210         let space = &mut pipe.client.pkt_num_spaces[epoch];
11211 
11212         // Use correct payload length when encrypting the packet.
11213         let payload_len = frames.iter().fold(0, |acc, x| acc + x.wire_len());
11214 
11215         let aead = space.crypto_seal.as_ref().unwrap();
11216 
11217         let written = packet::encrypt_pkt(
11218             &mut b,
11219             pn,
11220             pn_len,
11221             payload_len,
11222             payload_offset,
11223             None,
11224             aead,
11225         )
11226         .unwrap();
11227 
11228         assert_eq!(pipe.server.timeout(), None);
11229 
11230         assert_eq!(
11231             pipe.server_recv(&mut buf[..written]),
11232             Err(Error::InvalidPacket)
11233         );
11234 
11235         assert!(pipe.server.is_closed());
11236     }
11237 
11238     #[test]
11239     /// Tests that invalid packets don't cause the connection to be closed.
invalid_packet()11240     fn invalid_packet() {
11241         let mut buf = [0; 65535];
11242 
11243         let mut pipe = testing::Pipe::new().unwrap();
11244         assert_eq!(pipe.handshake(), Ok(()));
11245 
11246         let frames = [frame::Frame::Padding { len: 10 }];
11247 
11248         let written = testing::encode_pkt(
11249             &mut pipe.client,
11250             packet::Type::Short,
11251             &frames,
11252             &mut buf,
11253         )
11254         .unwrap();
11255 
11256         // Corrupt the packets's last byte to make decryption fail (the last
11257         // byte is part of the AEAD tag, so changing it means that the packet
11258         // cannot be authenticated during decryption).
11259         buf[written - 1] = !buf[written - 1];
11260 
11261         assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
11262 
11263         // Corrupt the packets's first byte to make the header fail decoding.
11264         buf[0] = 255;
11265 
11266         assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
11267     }
11268 
11269     #[test]
recv_empty_buffer()11270     fn recv_empty_buffer() {
11271         let mut buf = [0; 65535];
11272 
11273         let mut pipe = testing::Pipe::new().unwrap();
11274         assert_eq!(pipe.handshake(), Ok(()));
11275 
11276         assert_eq!(pipe.server_recv(&mut buf[..0]), Err(Error::BufferTooShort));
11277     }
11278 
11279     #[test]
11280     /// Tests that the MAX_STREAMS frame is sent for bidirectional streams.
stream_limit_update_bidi()11281     fn stream_limit_update_bidi() {
11282         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
11283         config
11284             .load_cert_chain_from_pem_file("examples/cert.crt")
11285             .unwrap();
11286         config
11287             .load_priv_key_from_pem_file("examples/cert.key")
11288             .unwrap();
11289         config
11290             .set_application_protos(&[b"proto1", b"proto2"])
11291             .unwrap();
11292         config.set_initial_max_data(30);
11293         config.set_initial_max_stream_data_bidi_local(15);
11294         config.set_initial_max_stream_data_bidi_remote(15);
11295         config.set_initial_max_stream_data_uni(10);
11296         config.set_initial_max_streams_bidi(3);
11297         config.set_initial_max_streams_uni(0);
11298         config.verify_peer(false);
11299 
11300         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
11301         assert_eq!(pipe.handshake(), Ok(()));
11302 
11303         // Client sends stream data.
11304         assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
11305         assert_eq!(pipe.advance(), Ok(()));
11306 
11307         assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
11308         assert_eq!(pipe.advance(), Ok(()));
11309 
11310         assert_eq!(pipe.client.stream_send(4, b"b", true), Ok(1));
11311         assert_eq!(pipe.advance(), Ok(()));
11312 
11313         assert_eq!(pipe.client.stream_send(0, b"b", true), Ok(1));
11314         assert_eq!(pipe.advance(), Ok(()));
11315 
11316         // Server reads stream data.
11317         let mut b = [0; 15];
11318         pipe.server.stream_recv(0, &mut b).unwrap();
11319         pipe.server.stream_recv(4, &mut b).unwrap();
11320         assert_eq!(pipe.advance(), Ok(()));
11321 
11322         // Server sends stream data, with fin.
11323         assert_eq!(pipe.server.stream_send(0, b"a", false), Ok(1));
11324         assert_eq!(pipe.advance(), Ok(()));
11325 
11326         assert_eq!(pipe.server.stream_send(4, b"a", false), Ok(1));
11327         assert_eq!(pipe.advance(), Ok(()));
11328 
11329         assert_eq!(pipe.server.stream_send(4, b"b", true), Ok(1));
11330         assert_eq!(pipe.advance(), Ok(()));
11331 
11332         assert_eq!(pipe.server.stream_send(0, b"b", true), Ok(1));
11333 
11334         // Server sends MAX_STREAMS.
11335         assert_eq!(pipe.advance(), Ok(()));
11336 
11337         // Client tries to create new streams.
11338         assert_eq!(pipe.client.stream_send(8, b"a", false), Ok(1));
11339         assert_eq!(pipe.advance(), Ok(()));
11340 
11341         assert_eq!(pipe.client.stream_send(12, b"a", false), Ok(1));
11342         assert_eq!(pipe.advance(), Ok(()));
11343 
11344         assert_eq!(pipe.client.stream_send(16, b"a", false), Ok(1));
11345         assert_eq!(pipe.advance(), Ok(()));
11346 
11347         assert_eq!(
11348             pipe.client.stream_send(20, b"a", false),
11349             Err(Error::StreamLimit)
11350         );
11351 
11352         assert_eq!(pipe.server.readable().len(), 3);
11353     }
11354 
11355     #[test]
11356     /// Tests that the MAX_STREAMS frame is sent for unidirectional streams.
stream_limit_update_uni()11357     fn stream_limit_update_uni() {
11358         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
11359         config
11360             .load_cert_chain_from_pem_file("examples/cert.crt")
11361             .unwrap();
11362         config
11363             .load_priv_key_from_pem_file("examples/cert.key")
11364             .unwrap();
11365         config
11366             .set_application_protos(&[b"proto1", b"proto2"])
11367             .unwrap();
11368         config.set_initial_max_data(30);
11369         config.set_initial_max_stream_data_bidi_local(15);
11370         config.set_initial_max_stream_data_bidi_remote(15);
11371         config.set_initial_max_stream_data_uni(10);
11372         config.set_initial_max_streams_bidi(0);
11373         config.set_initial_max_streams_uni(3);
11374         config.verify_peer(false);
11375 
11376         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
11377         assert_eq!(pipe.handshake(), Ok(()));
11378 
11379         // Client sends stream data.
11380         assert_eq!(pipe.client.stream_send(2, b"a", false), Ok(1));
11381         assert_eq!(pipe.advance(), Ok(()));
11382 
11383         assert_eq!(pipe.client.stream_send(6, b"a", false), Ok(1));
11384         assert_eq!(pipe.advance(), Ok(()));
11385 
11386         assert_eq!(pipe.client.stream_send(6, b"b", true), Ok(1));
11387         assert_eq!(pipe.advance(), Ok(()));
11388 
11389         assert_eq!(pipe.client.stream_send(2, b"b", true), Ok(1));
11390         assert_eq!(pipe.advance(), Ok(()));
11391 
11392         // Server reads stream data.
11393         let mut b = [0; 15];
11394         pipe.server.stream_recv(2, &mut b).unwrap();
11395         pipe.server.stream_recv(6, &mut b).unwrap();
11396 
11397         // Server sends MAX_STREAMS.
11398         assert_eq!(pipe.advance(), Ok(()));
11399 
11400         // Client tries to create new streams.
11401         assert_eq!(pipe.client.stream_send(10, b"a", false), Ok(1));
11402         assert_eq!(pipe.advance(), Ok(()));
11403 
11404         assert_eq!(pipe.client.stream_send(14, b"a", false), Ok(1));
11405         assert_eq!(pipe.advance(), Ok(()));
11406 
11407         assert_eq!(pipe.client.stream_send(18, b"a", false), Ok(1));
11408         assert_eq!(pipe.advance(), Ok(()));
11409 
11410         assert_eq!(
11411             pipe.client.stream_send(22, b"a", false),
11412             Err(Error::StreamLimit)
11413         );
11414 
11415         assert_eq!(pipe.server.readable().len(), 3);
11416     }
11417 
11418     #[test]
11419     /// Tests that the stream's fin flag is properly flushed even if there's no
11420     /// data in the buffer, and that the buffer becomes readable on the other
11421     /// side.
stream_zero_length_fin()11422     fn stream_zero_length_fin() {
11423         let mut pipe = testing::Pipe::new().unwrap();
11424         assert_eq!(pipe.handshake(), Ok(()));
11425 
11426         assert_eq!(
11427             pipe.client.stream_send(0, b"aaaaaaaaaaaaaaa", false),
11428             Ok(15)
11429         );
11430         assert_eq!(pipe.advance(), Ok(()));
11431 
11432         let mut r = pipe.server.readable();
11433         assert_eq!(r.next(), Some(0));
11434         assert!(r.next().is_none());
11435 
11436         let mut b = [0; 15];
11437         pipe.server.stream_recv(0, &mut b).unwrap();
11438         assert_eq!(pipe.advance(), Ok(()));
11439 
11440         // Client sends zero-length frame.
11441         assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
11442         assert_eq!(pipe.advance(), Ok(()));
11443 
11444         // Stream should be readable on the server after receiving empty fin.
11445         let mut r = pipe.server.readable();
11446         assert_eq!(r.next(), Some(0));
11447         assert!(r.next().is_none());
11448 
11449         let mut b = [0; 15];
11450         pipe.server.stream_recv(0, &mut b).unwrap();
11451         assert_eq!(pipe.advance(), Ok(()));
11452 
11453         // Client sends zero-length frame (again).
11454         assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
11455         assert_eq!(pipe.advance(), Ok(()));
11456 
11457         // Stream should _not_ be readable on the server after receiving empty
11458         // fin, because it was already finished.
11459         let mut r = pipe.server.readable();
11460         assert_eq!(r.next(), None);
11461     }
11462 
11463     #[test]
11464     /// Tests that the stream's fin flag is properly flushed even if there's no
11465     /// data in the buffer, that the buffer becomes readable on the other
11466     /// side and stays readable even if the stream is fin'd locally.
stream_zero_length_fin_deferred_collection()11467     fn stream_zero_length_fin_deferred_collection() {
11468         let mut pipe = testing::Pipe::new().unwrap();
11469         assert_eq!(pipe.handshake(), Ok(()));
11470 
11471         assert_eq!(
11472             pipe.client.stream_send(0, b"aaaaaaaaaaaaaaa", false),
11473             Ok(15)
11474         );
11475         assert_eq!(pipe.advance(), Ok(()));
11476 
11477         let mut r = pipe.server.readable();
11478         assert_eq!(r.next(), Some(0));
11479         assert!(r.next().is_none());
11480 
11481         let mut b = [0; 15];
11482         pipe.server.stream_recv(0, &mut b).unwrap();
11483         assert_eq!(pipe.advance(), Ok(()));
11484 
11485         // Client sends zero-length frame.
11486         assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
11487         assert_eq!(pipe.advance(), Ok(()));
11488 
11489         // Server sends zero-length frame.
11490         assert_eq!(pipe.server.stream_send(0, b"", true), Ok(0));
11491         assert_eq!(pipe.advance(), Ok(()));
11492 
11493         // Stream should be readable on the server after receiving empty fin.
11494         let mut r = pipe.server.readable();
11495         assert_eq!(r.next(), Some(0));
11496         assert!(r.next().is_none());
11497 
11498         let mut b = [0; 15];
11499         pipe.server.stream_recv(0, &mut b).unwrap();
11500         assert_eq!(pipe.advance(), Ok(()));
11501 
11502         // Client sends zero-length frame (again).
11503         assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
11504         assert_eq!(pipe.advance(), Ok(()));
11505 
11506         // Stream should _not_ be readable on the server after receiving empty
11507         // fin, because it was already finished.
11508         let mut r = pipe.server.readable();
11509         assert_eq!(r.next(), None);
11510 
11511         // Stream _is_readable on the client side.
11512         let mut r = pipe.client.readable();
11513         assert_eq!(r.next(), Some(0));
11514 
11515         pipe.client.stream_recv(0, &mut b).unwrap();
11516         assert_eq!(pipe.advance(), Ok(()));
11517 
11518         // Stream is completed and _is not_ readable.
11519         let mut r = pipe.client.readable();
11520         assert_eq!(r.next(), None);
11521     }
11522 
11523     #[test]
11524     /// Tests that the stream gets created with stream_send() even if there's
11525     /// no data in the buffer and the fin flag is not set.
stream_zero_length_non_fin()11526     fn stream_zero_length_non_fin() {
11527         let mut pipe = testing::Pipe::new().unwrap();
11528         assert_eq!(pipe.handshake(), Ok(()));
11529 
11530         assert_eq!(pipe.client.stream_send(0, b"", false), Ok(0));
11531 
11532         // The stream now should have been created.
11533         assert_eq!(pipe.client.streams.len(), 1);
11534         assert_eq!(pipe.advance(), Ok(()));
11535 
11536         // Sending an empty non-fin should not change any stream state on the
11537         // other side.
11538         let mut r = pipe.server.readable();
11539         assert!(r.next().is_none());
11540     }
11541 
11542     #[test]
11543     /// Tests that completed streams are garbage collected.
collect_streams()11544     fn collect_streams() {
11545         let mut buf = [0; 65535];
11546 
11547         let mut pipe = testing::Pipe::new().unwrap();
11548         assert_eq!(pipe.handshake(), Ok(()));
11549 
11550         assert_eq!(pipe.client.streams.len(), 0);
11551         assert_eq!(pipe.server.streams.len(), 0);
11552 
11553         assert_eq!(pipe.client.stream_send(0, b"aaaaa", true), Ok(5));
11554         assert_eq!(pipe.advance(), Ok(()));
11555 
11556         assert!(!pipe.client.stream_finished(0));
11557         assert!(!pipe.server.stream_finished(0));
11558 
11559         assert_eq!(pipe.client.streams.len(), 1);
11560         assert_eq!(pipe.server.streams.len(), 1);
11561 
11562         let mut b = [0; 5];
11563         pipe.server.stream_recv(0, &mut b).unwrap();
11564         assert_eq!(pipe.advance(), Ok(()));
11565 
11566         assert_eq!(pipe.server.stream_send(0, b"aaaaa", true), Ok(5));
11567         assert_eq!(pipe.advance(), Ok(()));
11568 
11569         assert!(!pipe.client.stream_finished(0));
11570         assert!(pipe.server.stream_finished(0));
11571 
11572         assert_eq!(pipe.client.streams.len(), 1);
11573         assert_eq!(pipe.server.streams.len(), 0);
11574 
11575         let mut b = [0; 5];
11576         pipe.client.stream_recv(0, &mut b).unwrap();
11577         assert_eq!(pipe.advance(), Ok(()));
11578 
11579         assert_eq!(pipe.client.streams.len(), 0);
11580         assert_eq!(pipe.server.streams.len(), 0);
11581 
11582         assert!(pipe.client.stream_finished(0));
11583         assert!(pipe.server.stream_finished(0));
11584 
11585         assert_eq!(pipe.client.stream_send(0, b"", true), Err(Error::Done));
11586 
11587         let frames = [frame::Frame::Stream {
11588             stream_id: 0,
11589             data: stream::RangeBuf::from(b"aa", 0, false),
11590         }];
11591 
11592         let pkt_type = packet::Type::Short;
11593         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
11594     }
11595 
11596     #[test]
config_set_cc_algorithm_name()11597     fn config_set_cc_algorithm_name() {
11598         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
11599 
11600         assert_eq!(config.set_cc_algorithm_name("reno"), Ok(()));
11601 
11602         // Unknown name.
11603         assert_eq!(
11604             config.set_cc_algorithm_name("???"),
11605             Err(Error::CongestionControl)
11606         );
11607     }
11608 
11609     #[test]
peer_cert()11610     fn peer_cert() {
11611         let mut pipe = testing::Pipe::new().unwrap();
11612         assert_eq!(pipe.handshake(), Ok(()));
11613 
11614         match pipe.client.peer_cert() {
11615             Some(c) => assert_eq!(c.len(), 753),
11616 
11617             None => panic!("missing server certificate"),
11618         }
11619     }
11620 
11621     #[test]
peer_cert_chain()11622     fn peer_cert_chain() {
11623         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
11624         config
11625             .load_cert_chain_from_pem_file("examples/cert-big.crt")
11626             .unwrap();
11627         config
11628             .load_priv_key_from_pem_file("examples/cert.key")
11629             .unwrap();
11630         config
11631             .set_application_protos(&[b"proto1", b"proto2"])
11632             .unwrap();
11633 
11634         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
11635         assert_eq!(pipe.handshake(), Ok(()));
11636 
11637         match pipe.client.peer_cert_chain() {
11638             Some(c) => assert_eq!(c.len(), 5),
11639 
11640             None => panic!("missing server certificate chain"),
11641         }
11642     }
11643 
11644     #[test]
retry()11645     fn retry() {
11646         let mut buf = [0; 65535];
11647 
11648         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
11649         config
11650             .load_cert_chain_from_pem_file("examples/cert.crt")
11651             .unwrap();
11652         config
11653             .load_priv_key_from_pem_file("examples/cert.key")
11654             .unwrap();
11655         config
11656             .set_application_protos(&[b"proto1", b"proto2"])
11657             .unwrap();
11658 
11659         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
11660 
11661         // Client sends initial flight.
11662         let (mut len, _) = pipe.client.send(&mut buf).unwrap();
11663 
11664         // Server sends Retry packet.
11665         let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
11666 
11667         let odcid = hdr.dcid.clone();
11668 
11669         let mut scid = [0; MAX_CONN_ID_LEN];
11670         rand::rand_bytes(&mut scid[..]);
11671         let scid = ConnectionId::from_ref(&scid);
11672 
11673         let token = b"quiche test retry token";
11674 
11675         len = packet::retry(
11676             &hdr.scid,
11677             &hdr.dcid,
11678             &scid,
11679             token,
11680             hdr.version,
11681             &mut buf,
11682         )
11683         .unwrap();
11684 
11685         // Client receives Retry and sends new Initial.
11686         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
11687 
11688         let (len, _) = pipe.client.send(&mut buf).unwrap();
11689 
11690         let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
11691         assert_eq!(&hdr.token.unwrap(), token);
11692 
11693         // Server accepts connection.
11694         let from = "127.0.0.1:1234".parse().unwrap();
11695         pipe.server = accept(
11696             &scid,
11697             Some(&odcid),
11698             testing::Pipe::server_addr(),
11699             from,
11700             &mut config,
11701         )
11702         .unwrap();
11703         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
11704 
11705         assert_eq!(pipe.advance(), Ok(()));
11706 
11707         assert!(pipe.client.is_established());
11708         assert!(pipe.server.is_established());
11709     }
11710 
11711     #[test]
missing_retry_source_connection_id()11712     fn missing_retry_source_connection_id() {
11713         let mut buf = [0; 65535];
11714 
11715         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
11716         config
11717             .load_cert_chain_from_pem_file("examples/cert.crt")
11718             .unwrap();
11719         config
11720             .load_priv_key_from_pem_file("examples/cert.key")
11721             .unwrap();
11722         config
11723             .set_application_protos(&[b"proto1", b"proto2"])
11724             .unwrap();
11725 
11726         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
11727 
11728         // Client sends initial flight.
11729         let (mut len, _) = pipe.client.send(&mut buf).unwrap();
11730 
11731         // Server sends Retry packet.
11732         let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
11733 
11734         let mut scid = [0; MAX_CONN_ID_LEN];
11735         rand::rand_bytes(&mut scid[..]);
11736         let scid = ConnectionId::from_ref(&scid);
11737 
11738         let token = b"quiche test retry token";
11739 
11740         len = packet::retry(
11741             &hdr.scid,
11742             &hdr.dcid,
11743             &scid,
11744             token,
11745             hdr.version,
11746             &mut buf,
11747         )
11748         .unwrap();
11749 
11750         // Client receives Retry and sends new Initial.
11751         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
11752 
11753         let (len, _) = pipe.client.send(&mut buf).unwrap();
11754 
11755         // Server accepts connection and send first flight. But original
11756         // destination connection ID is ignored.
11757         let from = "127.0.0.1:1234".parse().unwrap();
11758         pipe.server =
11759             accept(&scid, None, testing::Pipe::server_addr(), from, &mut config)
11760                 .unwrap();
11761         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
11762 
11763         let flight = testing::emit_flight(&mut pipe.server).unwrap();
11764 
11765         assert_eq!(
11766             testing::process_flight(&mut pipe.client, flight),
11767             Err(Error::InvalidTransportParam)
11768         );
11769     }
11770 
11771     #[test]
invalid_retry_source_connection_id()11772     fn invalid_retry_source_connection_id() {
11773         let mut buf = [0; 65535];
11774 
11775         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
11776         config
11777             .load_cert_chain_from_pem_file("examples/cert.crt")
11778             .unwrap();
11779         config
11780             .load_priv_key_from_pem_file("examples/cert.key")
11781             .unwrap();
11782         config
11783             .set_application_protos(&[b"proto1", b"proto2"])
11784             .unwrap();
11785 
11786         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
11787 
11788         // Client sends initial flight.
11789         let (mut len, _) = pipe.client.send(&mut buf).unwrap();
11790 
11791         // Server sends Retry packet.
11792         let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
11793 
11794         let mut scid = [0; MAX_CONN_ID_LEN];
11795         rand::rand_bytes(&mut scid[..]);
11796         let scid = ConnectionId::from_ref(&scid);
11797 
11798         let token = b"quiche test retry token";
11799 
11800         len = packet::retry(
11801             &hdr.scid,
11802             &hdr.dcid,
11803             &scid,
11804             token,
11805             hdr.version,
11806             &mut buf,
11807         )
11808         .unwrap();
11809 
11810         // Client receives Retry and sends new Initial.
11811         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
11812 
11813         let (len, _) = pipe.client.send(&mut buf).unwrap();
11814 
11815         // Server accepts connection and send first flight. But original
11816         // destination connection ID is invalid.
11817         let from = "127.0.0.1:1234".parse().unwrap();
11818         let odcid = ConnectionId::from_ref(b"bogus value");
11819         pipe.server = accept(
11820             &scid,
11821             Some(&odcid),
11822             testing::Pipe::server_addr(),
11823             from,
11824             &mut config,
11825         )
11826         .unwrap();
11827         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
11828 
11829         let flight = testing::emit_flight(&mut pipe.server).unwrap();
11830 
11831         assert_eq!(
11832             testing::process_flight(&mut pipe.client, flight),
11833             Err(Error::InvalidTransportParam)
11834         );
11835     }
11836 
check_send(_: &mut impl Send)11837     fn check_send(_: &mut impl Send) {}
11838 
11839     #[test]
config_must_be_send()11840     fn config_must_be_send() {
11841         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
11842         check_send(&mut config);
11843     }
11844 
11845     #[test]
connection_must_be_send()11846     fn connection_must_be_send() {
11847         let mut pipe = testing::Pipe::new().unwrap();
11848         check_send(&mut pipe.client);
11849     }
11850 
check_sync(_: &mut impl Sync)11851     fn check_sync(_: &mut impl Sync) {}
11852 
11853     #[test]
config_must_be_sync()11854     fn config_must_be_sync() {
11855         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
11856         check_sync(&mut config);
11857     }
11858 
11859     #[test]
connection_must_be_sync()11860     fn connection_must_be_sync() {
11861         let mut pipe = testing::Pipe::new().unwrap();
11862         check_sync(&mut pipe.client);
11863     }
11864 
11865     #[test]
data_blocked()11866     fn data_blocked() {
11867         let mut buf = [0; 65535];
11868 
11869         let mut pipe = testing::Pipe::new().unwrap();
11870         assert_eq!(pipe.handshake(), Ok(()));
11871 
11872         assert_eq!(pipe.client.stream_send(0, b"aaaaaaaaaa", false), Ok(10));
11873         assert_eq!(pipe.client.blocked_limit, None);
11874         assert_eq!(pipe.advance(), Ok(()));
11875 
11876         assert_eq!(pipe.client.stream_send(4, b"aaaaaaaaaa", false), Ok(10));
11877         assert_eq!(pipe.client.blocked_limit, None);
11878         assert_eq!(pipe.advance(), Ok(()));
11879 
11880         assert_eq!(pipe.client.stream_send(8, b"aaaaaaaaaaa", false), Ok(10));
11881         assert_eq!(pipe.client.blocked_limit, Some(30));
11882 
11883         let (len, _) = pipe.client.send(&mut buf).unwrap();
11884         assert_eq!(pipe.client.blocked_limit, None);
11885 
11886         let frames =
11887             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
11888 
11889         let mut iter = frames.iter();
11890 
11891         assert_eq!(iter.next(), Some(&frame::Frame::DataBlocked { limit: 30 }));
11892 
11893         assert_eq!(
11894             iter.next(),
11895             Some(&frame::Frame::Stream {
11896                 stream_id: 8,
11897                 data: stream::RangeBuf::from(b"aaaaaaaaaa", 0, false),
11898             })
11899         );
11900 
11901         assert_eq!(iter.next(), None);
11902     }
11903 
11904     #[test]
stream_data_blocked()11905     fn stream_data_blocked() {
11906         let mut buf = [0; 65535];
11907 
11908         let mut pipe = testing::Pipe::new().unwrap();
11909         assert_eq!(pipe.handshake(), Ok(()));
11910 
11911         assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
11912         assert_eq!(pipe.client.streams.blocked().len(), 0);
11913 
11914         assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
11915         assert_eq!(pipe.client.streams.blocked().len(), 0);
11916 
11917         assert_eq!(pipe.client.stream_send(0, b"aaaaaa", false), Ok(5));
11918         assert_eq!(pipe.client.streams.blocked().len(), 1);
11919 
11920         let (len, _) = pipe.client.send(&mut buf).unwrap();
11921         assert_eq!(pipe.client.streams.blocked().len(), 0);
11922 
11923         let frames =
11924             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
11925 
11926         let mut iter = frames.iter();
11927 
11928         // Skip ACK frame.
11929         iter.next();
11930 
11931         assert_eq!(
11932             iter.next(),
11933             Some(&frame::Frame::StreamDataBlocked {
11934                 stream_id: 0,
11935                 limit: 15,
11936             })
11937         );
11938 
11939         assert_eq!(
11940             iter.next(),
11941             Some(&frame::Frame::Stream {
11942                 stream_id: 0,
11943                 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
11944             })
11945         );
11946 
11947         assert_eq!(iter.next(), None);
11948 
11949         // Send from another stream, make sure we don't send STREAM_DATA_BLOCKED
11950         // again.
11951         assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
11952 
11953         let (len, _) = pipe.client.send(&mut buf).unwrap();
11954         assert_eq!(pipe.client.streams.blocked().len(), 0);
11955 
11956         let frames =
11957             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
11958 
11959         let mut iter = frames.iter();
11960 
11961         assert_eq!(
11962             iter.next(),
11963             Some(&frame::Frame::Stream {
11964                 stream_id: 4,
11965                 data: stream::RangeBuf::from(b"a", 0, false),
11966             })
11967         );
11968 
11969         assert_eq!(iter.next(), None);
11970 
11971         // Send again from blocked stream and make sure it is not marked as
11972         // blocked again.
11973         assert_eq!(
11974             pipe.client.stream_send(0, b"aaaaaa", false),
11975             Err(Error::Done)
11976         );
11977         assert_eq!(pipe.client.streams.blocked().len(), 0);
11978         assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
11979     }
11980 
11981     #[test]
stream_data_blocked_unblocked_flow_control()11982     fn stream_data_blocked_unblocked_flow_control() {
11983         let mut buf = [0; 65535];
11984         let mut pipe = testing::Pipe::new().unwrap();
11985         assert_eq!(pipe.handshake(), Ok(()));
11986 
11987         assert_eq!(
11988             pipe.client.stream_send(0, b"aaaaaaaaaaaaaaah", false),
11989             Ok(15)
11990         );
11991         assert_eq!(pipe.client.streams.blocked().len(), 1);
11992         assert_eq!(pipe.advance(), Ok(()));
11993         assert_eq!(pipe.client.streams.blocked().len(), 0);
11994 
11995         // Send again on blocked stream. It's blocked at the same offset as
11996         // previously, so it should not be marked as blocked again.
11997         assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
11998         assert_eq!(pipe.client.streams.blocked().len(), 0);
11999 
12000         // No matter how many times we try to write stream data tried, no
12001         // packets containing STREAM_BLOCKED should be emitted.
12002         assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
12003         assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
12004 
12005         assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
12006         assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
12007 
12008         assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
12009         assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
12010 
12011         // Now read some data at the server to release flow control.
12012         let mut r = pipe.server.readable();
12013         assert_eq!(r.next(), Some(0));
12014         assert_eq!(r.next(), None);
12015 
12016         let mut b = [0; 10];
12017         assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((10, false)));
12018         assert_eq!(&b[..10], b"aaaaaaaaaa");
12019         assert_eq!(pipe.advance(), Ok(()));
12020 
12021         assert_eq!(pipe.client.stream_send(0, b"hhhhhhhhhh!", false), Ok(10));
12022         assert_eq!(pipe.client.streams.blocked().len(), 1);
12023 
12024         let (len, _) = pipe.client.send(&mut buf).unwrap();
12025         assert_eq!(pipe.client.streams.blocked().len(), 0);
12026 
12027         let frames =
12028             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
12029 
12030         let mut iter = frames.iter();
12031 
12032         assert_eq!(
12033             iter.next(),
12034             Some(&frame::Frame::StreamDataBlocked {
12035                 stream_id: 0,
12036                 limit: 25,
12037             })
12038         );
12039 
12040         // don't care about remaining received frames
12041 
12042         assert_eq!(pipe.client.stream_send(0, b"!", false), Err(Error::Done));
12043         assert_eq!(pipe.client.streams.blocked().len(), 0);
12044         assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
12045     }
12046 
12047     #[test]
app_limited_true()12048     fn app_limited_true() {
12049         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
12050         config
12051             .set_application_protos(&[b"proto1", b"proto2"])
12052             .unwrap();
12053         config.set_initial_max_data(50000);
12054         config.set_initial_max_stream_data_bidi_local(50000);
12055         config.set_initial_max_stream_data_bidi_remote(50000);
12056         config.set_max_recv_udp_payload_size(1200);
12057         config.verify_peer(false);
12058 
12059         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
12060         assert_eq!(pipe.handshake(), Ok(()));
12061 
12062         // Client sends stream data.
12063         assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
12064         assert_eq!(pipe.advance(), Ok(()));
12065 
12066         // Server reads stream data.
12067         let mut b = [0; 15];
12068         pipe.server.stream_recv(0, &mut b).unwrap();
12069         assert_eq!(pipe.advance(), Ok(()));
12070 
12071         // Server sends stream data smaller than cwnd.
12072         let send_buf = [0; 10000];
12073         assert_eq!(pipe.server.stream_send(0, &send_buf, false), Ok(10000));
12074         assert_eq!(pipe.advance(), Ok(()));
12075 
12076         // app_limited should be true because we send less than cwnd.
12077         assert_eq!(
12078             pipe.server
12079                 .paths
12080                 .get_active()
12081                 .expect("no active")
12082                 .recovery
12083                 .app_limited(),
12084             true
12085         );
12086     }
12087 
12088     #[test]
app_limited_false()12089     fn app_limited_false() {
12090         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
12091         config
12092             .set_application_protos(&[b"proto1", b"proto2"])
12093             .unwrap();
12094         config.set_initial_max_data(50000);
12095         config.set_initial_max_stream_data_bidi_local(50000);
12096         config.set_initial_max_stream_data_bidi_remote(50000);
12097         config.set_max_recv_udp_payload_size(1200);
12098         config.verify_peer(false);
12099 
12100         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
12101         assert_eq!(pipe.handshake(), Ok(()));
12102 
12103         // Client sends stream data.
12104         assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
12105         assert_eq!(pipe.advance(), Ok(()));
12106 
12107         // Server reads stream data.
12108         let mut b = [0; 15];
12109         pipe.server.stream_recv(0, &mut b).unwrap();
12110         assert_eq!(pipe.advance(), Ok(()));
12111 
12112         // Server sends stream data bigger than cwnd.
12113         let send_buf1 = [0; 20000];
12114         assert_eq!(pipe.server.stream_send(0, &send_buf1, false), Ok(12000));
12115 
12116         testing::emit_flight(&mut pipe.server).ok();
12117 
12118         // We can't create a new packet header because there is no room by cwnd.
12119         // app_limited should be false because we can't send more by cwnd.
12120         assert_eq!(
12121             pipe.server
12122                 .paths
12123                 .get_active()
12124                 .expect("no active")
12125                 .recovery
12126                 .app_limited(),
12127             false
12128         );
12129     }
12130 
12131     #[test]
sends_ack_only_pkt_when_full_cwnd_and_ack_elicited()12132     fn sends_ack_only_pkt_when_full_cwnd_and_ack_elicited() {
12133         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
12134         config
12135             .load_cert_chain_from_pem_file("examples/cert.crt")
12136             .unwrap();
12137         config
12138             .load_priv_key_from_pem_file("examples/cert.key")
12139             .unwrap();
12140         config
12141             .set_application_protos(&[b"proto1", b"proto2"])
12142             .unwrap();
12143         config.set_initial_max_data(50000);
12144         config.set_initial_max_stream_data_bidi_local(50000);
12145         config.set_initial_max_stream_data_bidi_remote(50000);
12146         config.set_initial_max_streams_bidi(3);
12147         config.set_initial_max_streams_uni(3);
12148         config.set_max_recv_udp_payload_size(1200);
12149         config.verify_peer(false);
12150 
12151         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12152         assert_eq!(pipe.handshake(), Ok(()));
12153 
12154         // Client sends stream data bigger than cwnd (it will never arrive to the
12155         // server).
12156         let send_buf1 = [0; 20000];
12157         assert_eq!(pipe.client.stream_send(0, &send_buf1, false), Ok(12000));
12158 
12159         testing::emit_flight(&mut pipe.client).ok();
12160 
12161         // Server sends some stream data that will need ACKs.
12162         assert_eq!(
12163             pipe.server.stream_send(1, &send_buf1[..500], false),
12164             Ok(500)
12165         );
12166 
12167         testing::process_flight(
12168             &mut pipe.client,
12169             testing::emit_flight(&mut pipe.server).unwrap(),
12170         )
12171         .unwrap();
12172 
12173         let mut buf = [0; 2000];
12174 
12175         let ret = pipe.client.send(&mut buf);
12176 
12177         assert_eq!(pipe.client.tx_cap, 0);
12178 
12179         assert!(matches!(ret, Ok((_, _))), "the client should at least send one packet to acknowledge the newly received data");
12180 
12181         let (sent, _) = ret.unwrap();
12182 
12183         assert_ne!(sent, 0, "the client should at least send a pure ACK packet");
12184 
12185         let frames =
12186             testing::decode_pkt(&mut pipe.server, &mut buf, sent).unwrap();
12187         assert_eq!(1, frames.len());
12188         assert!(
12189             matches!(frames[0], frame::Frame::ACK { .. }),
12190             "the packet sent by the client must be an ACK only packet"
12191         );
12192     }
12193 
12194     /// Like sends_ack_only_pkt_when_full_cwnd_and_ack_elicited, but when
12195     /// ack_eliciting is explicitly requested.
12196     #[test]
sends_ack_only_pkt_when_full_cwnd_and_ack_elicited_despite_max_unacknowledging( )12197     fn sends_ack_only_pkt_when_full_cwnd_and_ack_elicited_despite_max_unacknowledging(
12198     ) {
12199         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
12200         config
12201             .load_cert_chain_from_pem_file("examples/cert.crt")
12202             .unwrap();
12203         config
12204             .load_priv_key_from_pem_file("examples/cert.key")
12205             .unwrap();
12206         config
12207             .set_application_protos(&[b"proto1", b"proto2"])
12208             .unwrap();
12209         config.set_initial_max_data(50000);
12210         config.set_initial_max_stream_data_bidi_local(50000);
12211         config.set_initial_max_stream_data_bidi_remote(50000);
12212         config.set_initial_max_streams_bidi(3);
12213         config.set_initial_max_streams_uni(3);
12214         config.set_max_recv_udp_payload_size(1200);
12215         config.verify_peer(false);
12216 
12217         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12218         assert_eq!(pipe.handshake(), Ok(()));
12219 
12220         // Client sends stream data bigger than cwnd (it will never arrive to the
12221         // server). This exhausts the congestion window.
12222         let send_buf1 = [0; 20000];
12223         assert_eq!(pipe.client.stream_send(0, &send_buf1, false), Ok(12000));
12224 
12225         testing::emit_flight(&mut pipe.client).ok();
12226 
12227         // Client gets PING frames from server, which elicit ACK
12228         let mut buf = [0; 2000];
12229         for _ in 0..recovery::MAX_OUTSTANDING_NON_ACK_ELICITING {
12230             let written = testing::encode_pkt(
12231                 &mut pipe.server,
12232                 packet::Type::Short,
12233                 &[frame::Frame::Ping],
12234                 &mut buf,
12235             )
12236             .unwrap();
12237 
12238             pipe.client_recv(&mut buf[..written])
12239                 .expect("client recv ping");
12240 
12241             // Client acknowledges despite a full congestion window
12242             let ret = pipe.client.send(&mut buf);
12243 
12244             assert!(matches!(ret, Ok((_, _))), "the client should at least send one packet to acknowledge the newly received data");
12245 
12246             let (sent, _) = ret.unwrap();
12247 
12248             assert_ne!(
12249                 sent, 0,
12250                 "the client should at least send a pure ACK packet"
12251             );
12252 
12253             let frames =
12254                 testing::decode_pkt(&mut pipe.server, &mut buf, sent).unwrap();
12255 
12256             assert_eq!(1, frames.len());
12257 
12258             assert!(
12259                 matches!(frames[0], frame::Frame::ACK { .. }),
12260                 "the packet sent by the client must be an ACK only packet"
12261             );
12262         }
12263 
12264         // The client shouldn't need to send any more packets after the ACK only
12265         // packet it just sent.
12266         assert_eq!(
12267             pipe.client.send(&mut buf),
12268             Err(Error::Done),
12269             "nothing for client to send after ACK-only packet"
12270         );
12271     }
12272 
12273     #[test]
app_limited_false_no_frame()12274     fn app_limited_false_no_frame() {
12275         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
12276         config
12277             .set_application_protos(&[b"proto1", b"proto2"])
12278             .unwrap();
12279         config.set_initial_max_data(50000);
12280         config.set_initial_max_stream_data_bidi_local(50000);
12281         config.set_initial_max_stream_data_bidi_remote(50000);
12282         config.set_max_recv_udp_payload_size(1405);
12283         config.verify_peer(false);
12284 
12285         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
12286         assert_eq!(pipe.handshake(), Ok(()));
12287 
12288         // Client sends stream data.
12289         assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
12290         assert_eq!(pipe.advance(), Ok(()));
12291 
12292         // Server reads stream data.
12293         let mut b = [0; 15];
12294         pipe.server.stream_recv(0, &mut b).unwrap();
12295         assert_eq!(pipe.advance(), Ok(()));
12296 
12297         // Server sends stream data bigger than cwnd.
12298         let send_buf1 = [0; 20000];
12299         assert_eq!(pipe.server.stream_send(0, &send_buf1, false), Ok(12000));
12300 
12301         testing::emit_flight(&mut pipe.server).ok();
12302 
12303         // We can't create a new packet header because there is no room by cwnd.
12304         // app_limited should be false because we can't send more by cwnd.
12305         assert_eq!(
12306             pipe.server
12307                 .paths
12308                 .get_active()
12309                 .expect("no active")
12310                 .recovery
12311                 .app_limited(),
12312             false
12313         );
12314     }
12315 
12316     #[test]
app_limited_false_no_header()12317     fn app_limited_false_no_header() {
12318         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
12319         config
12320             .set_application_protos(&[b"proto1", b"proto2"])
12321             .unwrap();
12322         config.set_initial_max_data(50000);
12323         config.set_initial_max_stream_data_bidi_local(50000);
12324         config.set_initial_max_stream_data_bidi_remote(50000);
12325         config.set_max_recv_udp_payload_size(1406);
12326         config.verify_peer(false);
12327 
12328         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
12329         assert_eq!(pipe.handshake(), Ok(()));
12330 
12331         // Client sends stream data.
12332         assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
12333         assert_eq!(pipe.advance(), Ok(()));
12334 
12335         // Server reads stream data.
12336         let mut b = [0; 15];
12337         pipe.server.stream_recv(0, &mut b).unwrap();
12338         assert_eq!(pipe.advance(), Ok(()));
12339 
12340         // Server sends stream data bigger than cwnd.
12341         let send_buf1 = [0; 20000];
12342         assert_eq!(pipe.server.stream_send(0, &send_buf1, false), Ok(12000));
12343 
12344         testing::emit_flight(&mut pipe.server).ok();
12345 
12346         // We can't create a new frame because there is no room by cwnd.
12347         // app_limited should be false because we can't send more by cwnd.
12348         assert_eq!(
12349             pipe.server
12350                 .paths
12351                 .get_active()
12352                 .expect("no active")
12353                 .recovery
12354                 .app_limited(),
12355             false
12356         );
12357     }
12358 
12359     #[test]
app_limited_not_changed_on_no_new_frames()12360     fn app_limited_not_changed_on_no_new_frames() {
12361         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
12362         config
12363             .set_application_protos(&[b"proto1", b"proto2"])
12364             .unwrap();
12365         config.set_initial_max_data(50000);
12366         config.set_initial_max_stream_data_bidi_local(50000);
12367         config.set_initial_max_stream_data_bidi_remote(50000);
12368         config.set_max_recv_udp_payload_size(1200);
12369         config.verify_peer(false);
12370 
12371         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
12372         assert_eq!(pipe.handshake(), Ok(()));
12373 
12374         // Client sends stream data.
12375         assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
12376         assert_eq!(pipe.advance(), Ok(()));
12377 
12378         // Server reads stream data.
12379         let mut b = [0; 15];
12380         pipe.server.stream_recv(0, &mut b).unwrap();
12381         assert_eq!(pipe.advance(), Ok(()));
12382 
12383         // Client's app_limited is true because its bytes-in-flight
12384         // is much smaller than the current cwnd.
12385         assert_eq!(
12386             pipe.client
12387                 .paths
12388                 .get_active()
12389                 .expect("no active")
12390                 .recovery
12391                 .app_limited(),
12392             true
12393         );
12394 
12395         // Client has no new frames to send - returns Done.
12396         assert_eq!(testing::emit_flight(&mut pipe.client), Err(Error::Done));
12397 
12398         // Client's app_limited should remain the same.
12399         assert_eq!(
12400             pipe.client
12401                 .paths
12402                 .get_active()
12403                 .expect("no active")
12404                 .recovery
12405                 .app_limited(),
12406             true
12407         );
12408     }
12409 
12410     #[test]
limit_ack_ranges()12411     fn limit_ack_ranges() {
12412         let mut buf = [0; 65535];
12413 
12414         let mut pipe = testing::Pipe::new().unwrap();
12415         assert_eq!(pipe.handshake(), Ok(()));
12416 
12417         let epoch = packet::Epoch::Application;
12418 
12419         assert_eq!(pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.len(), 0);
12420 
12421         let frames = [frame::Frame::Ping, frame::Frame::Padding { len: 3 }];
12422 
12423         let pkt_type = packet::Type::Short;
12424 
12425         let mut last_packet_sent = 0;
12426 
12427         for _ in 0..512 {
12428             let recv_count = pipe.server.recv_count;
12429 
12430             last_packet_sent = pipe.client.pkt_num_spaces[epoch].next_pkt_num;
12431 
12432             pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
12433                 .unwrap();
12434 
12435             assert_eq!(pipe.server.recv_count, recv_count + 1);
12436 
12437             // Skip packet number.
12438             pipe.client.pkt_num_spaces[epoch].next_pkt_num += 1;
12439         }
12440 
12441         assert_eq!(
12442             pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.len(),
12443             MAX_ACK_RANGES
12444         );
12445 
12446         assert_eq!(
12447             pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.first(),
12448             Some(last_packet_sent - ((MAX_ACK_RANGES as u64) - 1) * 2)
12449         );
12450 
12451         assert_eq!(
12452             pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.last(),
12453             Some(last_packet_sent)
12454         );
12455     }
12456 
12457     #[test]
12458     /// Tests that streams are correctly scheduled based on their priority.
stream_priority()12459     fn stream_priority() {
12460         // Limit 1-RTT packet size to avoid congestion control interference.
12461         const MAX_TEST_PACKET_SIZE: usize = 540;
12462 
12463         let mut buf = [0; 65535];
12464 
12465         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12466         config
12467             .load_cert_chain_from_pem_file("examples/cert.crt")
12468             .unwrap();
12469         config
12470             .load_priv_key_from_pem_file("examples/cert.key")
12471             .unwrap();
12472         config
12473             .set_application_protos(&[b"proto1", b"proto2"])
12474             .unwrap();
12475         config.set_initial_max_data(1_000_000);
12476         config.set_initial_max_stream_data_bidi_local(1_000_000);
12477         config.set_initial_max_stream_data_bidi_remote(1_000_000);
12478         config.set_initial_max_stream_data_uni(0);
12479         config.set_initial_max_streams_bidi(100);
12480         config.set_initial_max_streams_uni(0);
12481         config.verify_peer(false);
12482 
12483         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12484         assert_eq!(pipe.handshake(), Ok(()));
12485 
12486         assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
12487         assert_eq!(pipe.advance(), Ok(()));
12488 
12489         assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
12490         assert_eq!(pipe.advance(), Ok(()));
12491 
12492         assert_eq!(pipe.client.stream_send(8, b"a", false), Ok(1));
12493         assert_eq!(pipe.advance(), Ok(()));
12494 
12495         assert_eq!(pipe.client.stream_send(12, b"a", false), Ok(1));
12496         assert_eq!(pipe.advance(), Ok(()));
12497 
12498         assert_eq!(pipe.client.stream_send(16, b"a", false), Ok(1));
12499         assert_eq!(pipe.advance(), Ok(()));
12500 
12501         assert_eq!(pipe.client.stream_send(20, b"a", false), Ok(1));
12502         assert_eq!(pipe.advance(), Ok(()));
12503 
12504         let mut b = [0; 1];
12505 
12506         let out = [b'b'; 500];
12507 
12508         // Server prioritizes streams as follows:
12509         //  * Stream 8 and 16 have the same priority but are non-incremental.
12510         //  * Stream 4, 12 and 20 have the same priority but 20 is non-incremental
12511         //    and 4 and 12 are incremental.
12512         //  * Stream 0 is on its own.
12513 
12514         pipe.server.stream_recv(0, &mut b).unwrap();
12515         assert_eq!(pipe.server.stream_priority(0, 255, true), Ok(()));
12516         pipe.server.stream_send(0, &out, false).unwrap();
12517         pipe.server.stream_send(0, &out, false).unwrap();
12518         pipe.server.stream_send(0, &out, false).unwrap();
12519 
12520         pipe.server.stream_recv(12, &mut b).unwrap();
12521         assert_eq!(pipe.server.stream_priority(12, 42, true), Ok(()));
12522         pipe.server.stream_send(12, &out, false).unwrap();
12523         pipe.server.stream_send(12, &out, false).unwrap();
12524         pipe.server.stream_send(12, &out, false).unwrap();
12525 
12526         pipe.server.stream_recv(16, &mut b).unwrap();
12527         assert_eq!(pipe.server.stream_priority(16, 10, false), Ok(()));
12528         pipe.server.stream_send(16, &out, false).unwrap();
12529         pipe.server.stream_send(16, &out, false).unwrap();
12530         pipe.server.stream_send(16, &out, false).unwrap();
12531 
12532         pipe.server.stream_recv(4, &mut b).unwrap();
12533         assert_eq!(pipe.server.stream_priority(4, 42, true), Ok(()));
12534         pipe.server.stream_send(4, &out, false).unwrap();
12535         pipe.server.stream_send(4, &out, false).unwrap();
12536         pipe.server.stream_send(4, &out, false).unwrap();
12537 
12538         pipe.server.stream_recv(8, &mut b).unwrap();
12539         assert_eq!(pipe.server.stream_priority(8, 10, false), Ok(()));
12540         pipe.server.stream_send(8, &out, false).unwrap();
12541         pipe.server.stream_send(8, &out, false).unwrap();
12542         pipe.server.stream_send(8, &out, false).unwrap();
12543 
12544         pipe.server.stream_recv(20, &mut b).unwrap();
12545         assert_eq!(pipe.server.stream_priority(20, 42, false), Ok(()));
12546         pipe.server.stream_send(20, &out, false).unwrap();
12547         pipe.server.stream_send(20, &out, false).unwrap();
12548         pipe.server.stream_send(20, &out, false).unwrap();
12549 
12550         // First is stream 8.
12551         let mut off = 0;
12552 
12553         for _ in 1..=3 {
12554             let (len, _) =
12555                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12556 
12557             let frames =
12558                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12559             let stream = frames.first().unwrap();
12560 
12561             assert_eq!(stream, &frame::Frame::Stream {
12562                 stream_id: 8,
12563                 data: stream::RangeBuf::from(&out, off, false),
12564             });
12565 
12566             off = match stream {
12567                 frame::Frame::Stream { data, .. } => data.max_off(),
12568 
12569                 _ => unreachable!(),
12570             };
12571         }
12572 
12573         // Then is stream 16.
12574         let mut off = 0;
12575 
12576         for _ in 1..=3 {
12577             let (len, _) =
12578                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12579 
12580             let frames =
12581                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12582             let stream = frames.first().unwrap();
12583 
12584             assert_eq!(stream, &frame::Frame::Stream {
12585                 stream_id: 16,
12586                 data: stream::RangeBuf::from(&out, off, false),
12587             });
12588 
12589             off = match stream {
12590                 frame::Frame::Stream { data, .. } => data.max_off(),
12591 
12592                 _ => unreachable!(),
12593             };
12594         }
12595 
12596         // Then is stream 20.
12597         let mut off = 0;
12598 
12599         for _ in 1..=3 {
12600             let (len, _) =
12601                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12602 
12603             let frames =
12604                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12605             let stream = frames.first().unwrap();
12606 
12607             assert_eq!(stream, &frame::Frame::Stream {
12608                 stream_id: 20,
12609                 data: stream::RangeBuf::from(&out, off, false),
12610             });
12611 
12612             off = match stream {
12613                 frame::Frame::Stream { data, .. } => data.max_off(),
12614 
12615                 _ => unreachable!(),
12616             };
12617         }
12618 
12619         // Then are stream 12 and 4, with the same priority, incrementally.
12620         let mut off = 0;
12621 
12622         for _ in 1..=3 {
12623             let (len, _) =
12624                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12625 
12626             let frames =
12627                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12628 
12629             assert_eq!(
12630                 frames.first(),
12631                 Some(&frame::Frame::Stream {
12632                     stream_id: 12,
12633                     data: stream::RangeBuf::from(&out, off, false),
12634                 })
12635             );
12636 
12637             let (len, _) =
12638                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12639 
12640             let frames =
12641                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12642 
12643             let stream = frames.first().unwrap();
12644 
12645             assert_eq!(stream, &frame::Frame::Stream {
12646                 stream_id: 4,
12647                 data: stream::RangeBuf::from(&out, off, false),
12648             });
12649 
12650             off = match stream {
12651                 frame::Frame::Stream { data, .. } => data.max_off(),
12652 
12653                 _ => unreachable!(),
12654             };
12655         }
12656 
12657         // Final is stream 0.
12658         let mut off = 0;
12659 
12660         for _ in 1..=3 {
12661             let (len, _) =
12662                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12663 
12664             let frames =
12665                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12666             let stream = frames.first().unwrap();
12667 
12668             assert_eq!(stream, &frame::Frame::Stream {
12669                 stream_id: 0,
12670                 data: stream::RangeBuf::from(&out, off, false),
12671             });
12672 
12673             off = match stream {
12674                 frame::Frame::Stream { data, .. } => data.max_off(),
12675 
12676                 _ => unreachable!(),
12677             };
12678         }
12679 
12680         assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
12681     }
12682 
12683     #[test]
12684     /// Tests that changing a stream's priority is correctly propagated.
12685     ///
12686     /// Re-prioritization is not supported, so this should fail.
12687     #[should_panic]
stream_reprioritize()12688     fn stream_reprioritize() {
12689         let mut buf = [0; 65535];
12690 
12691         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12692         config
12693             .load_cert_chain_from_pem_file("examples/cert.crt")
12694             .unwrap();
12695         config
12696             .load_priv_key_from_pem_file("examples/cert.key")
12697             .unwrap();
12698         config
12699             .set_application_protos(&[b"proto1", b"proto2"])
12700             .unwrap();
12701         config.set_initial_max_data(30);
12702         config.set_initial_max_stream_data_bidi_local(15);
12703         config.set_initial_max_stream_data_bidi_remote(15);
12704         config.set_initial_max_stream_data_uni(0);
12705         config.set_initial_max_streams_bidi(5);
12706         config.set_initial_max_streams_uni(0);
12707         config.verify_peer(false);
12708 
12709         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12710         assert_eq!(pipe.handshake(), Ok(()));
12711 
12712         assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
12713         assert_eq!(pipe.advance(), Ok(()));
12714 
12715         assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
12716         assert_eq!(pipe.advance(), Ok(()));
12717 
12718         assert_eq!(pipe.client.stream_send(8, b"a", false), Ok(1));
12719         assert_eq!(pipe.advance(), Ok(()));
12720 
12721         assert_eq!(pipe.client.stream_send(12, b"a", false), Ok(1));
12722         assert_eq!(pipe.advance(), Ok(()));
12723 
12724         let mut b = [0; 1];
12725 
12726         pipe.server.stream_recv(0, &mut b).unwrap();
12727         assert_eq!(pipe.server.stream_priority(0, 255, true), Ok(()));
12728         pipe.server.stream_send(0, b"b", false).unwrap();
12729 
12730         pipe.server.stream_recv(12, &mut b).unwrap();
12731         assert_eq!(pipe.server.stream_priority(12, 42, true), Ok(()));
12732         pipe.server.stream_send(12, b"b", false).unwrap();
12733 
12734         pipe.server.stream_recv(8, &mut b).unwrap();
12735         assert_eq!(pipe.server.stream_priority(8, 10, true), Ok(()));
12736         pipe.server.stream_send(8, b"b", false).unwrap();
12737 
12738         pipe.server.stream_recv(4, &mut b).unwrap();
12739         assert_eq!(pipe.server.stream_priority(4, 42, true), Ok(()));
12740         pipe.server.stream_send(4, b"b", false).unwrap();
12741 
12742         // Stream 0 is re-prioritized!!!
12743         assert_eq!(pipe.server.stream_priority(0, 20, true), Ok(()));
12744 
12745         // First is stream 8.
12746         let (len, _) = pipe.server.send(&mut buf).unwrap();
12747 
12748         let frames =
12749             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12750 
12751         assert_eq!(
12752             frames.first(),
12753             Some(&frame::Frame::Stream {
12754                 stream_id: 8,
12755                 data: stream::RangeBuf::from(b"b", 0, false),
12756             })
12757         );
12758 
12759         // Then is stream 0.
12760         let (len, _) = pipe.server.send(&mut buf).unwrap();
12761 
12762         let frames =
12763             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12764 
12765         assert_eq!(
12766             frames.first(),
12767             Some(&frame::Frame::Stream {
12768                 stream_id: 0,
12769                 data: stream::RangeBuf::from(b"b", 0, false),
12770             })
12771         );
12772 
12773         // Then are stream 12 and 4, with the same priority.
12774         let (len, _) = pipe.server.send(&mut buf).unwrap();
12775 
12776         let frames =
12777             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12778 
12779         assert_eq!(
12780             frames.first(),
12781             Some(&frame::Frame::Stream {
12782                 stream_id: 12,
12783                 data: stream::RangeBuf::from(b"b", 0, false),
12784             })
12785         );
12786 
12787         let (len, _) = pipe.server.send(&mut buf).unwrap();
12788 
12789         let frames =
12790             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12791 
12792         assert_eq!(
12793             frames.first(),
12794             Some(&frame::Frame::Stream {
12795                 stream_id: 4,
12796                 data: stream::RangeBuf::from(b"b", 0, false),
12797             })
12798         );
12799 
12800         assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
12801     }
12802 
12803     #[test]
12804     /// Tests that streams and datagrams are correctly scheduled.
stream_datagram_priority()12805     fn stream_datagram_priority() {
12806         // Limit 1-RTT packet size to avoid congestion control interference.
12807         const MAX_TEST_PACKET_SIZE: usize = 540;
12808 
12809         let mut buf = [0; 65535];
12810 
12811         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12812         config
12813             .load_cert_chain_from_pem_file("examples/cert.crt")
12814             .unwrap();
12815         config
12816             .load_priv_key_from_pem_file("examples/cert.key")
12817             .unwrap();
12818         config
12819             .set_application_protos(&[b"proto1", b"proto2"])
12820             .unwrap();
12821         config.set_initial_max_data(1_000_000);
12822         config.set_initial_max_stream_data_bidi_local(1_000_000);
12823         config.set_initial_max_stream_data_bidi_remote(1_000_000);
12824         config.set_initial_max_stream_data_uni(0);
12825         config.set_initial_max_streams_bidi(100);
12826         config.set_initial_max_streams_uni(0);
12827         config.enable_dgram(true, 10, 10);
12828         config.verify_peer(false);
12829 
12830         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12831         assert_eq!(pipe.handshake(), Ok(()));
12832 
12833         assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
12834         assert_eq!(pipe.advance(), Ok(()));
12835 
12836         assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
12837         assert_eq!(pipe.advance(), Ok(()));
12838 
12839         let mut b = [0; 1];
12840 
12841         let out = [b'b'; 500];
12842 
12843         // Server prioritizes Stream 0 and 4 with the same urgency with
12844         // incremental, meaning the frames should be sent in round-robin
12845         // fashion. It also sends DATAGRAMS which are always interleaved with
12846         // STREAM frames. So we'll expect a mix of frame types regardless
12847         // of the order that the application writes things in.
12848 
12849         pipe.server.stream_recv(0, &mut b).unwrap();
12850         assert_eq!(pipe.server.stream_priority(0, 255, true), Ok(()));
12851         pipe.server.stream_send(0, &out, false).unwrap();
12852         pipe.server.stream_send(0, &out, false).unwrap();
12853         pipe.server.stream_send(0, &out, false).unwrap();
12854 
12855         assert_eq!(pipe.server.stream_priority(4, 255, true), Ok(()));
12856         pipe.server.stream_send(4, &out, false).unwrap();
12857         pipe.server.stream_send(4, &out, false).unwrap();
12858         pipe.server.stream_send(4, &out, false).unwrap();
12859 
12860         for _ in 1..=6 {
12861             assert_eq!(pipe.server.dgram_send(&out), Ok(()));
12862         }
12863 
12864         let mut off_0 = 0;
12865         let mut off_4 = 0;
12866 
12867         for _ in 1..=3 {
12868             // DATAGRAM
12869             let (len, _) =
12870                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12871 
12872             let frames =
12873                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12874             let mut frame_iter = frames.iter();
12875 
12876             assert_eq!(frame_iter.next().unwrap(), &frame::Frame::Datagram {
12877                 data: out.into(),
12878             });
12879             assert_eq!(frame_iter.next(), None);
12880 
12881             // STREAM 0
12882             let (len, _) =
12883                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12884 
12885             let frames =
12886                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12887             let mut frame_iter = frames.iter();
12888             let stream = frame_iter.next().unwrap();
12889 
12890             assert_eq!(stream, &frame::Frame::Stream {
12891                 stream_id: 0,
12892                 data: stream::RangeBuf::from(&out, off_0, false),
12893             });
12894 
12895             off_0 = match stream {
12896                 frame::Frame::Stream { data, .. } => data.max_off(),
12897 
12898                 _ => unreachable!(),
12899             };
12900             assert_eq!(frame_iter.next(), None);
12901 
12902             // DATAGRAM
12903             let (len, _) =
12904                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12905 
12906             let frames =
12907                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12908             let mut frame_iter = frames.iter();
12909 
12910             assert_eq!(frame_iter.next().unwrap(), &frame::Frame::Datagram {
12911                 data: out.into(),
12912             });
12913             assert_eq!(frame_iter.next(), None);
12914 
12915             // STREAM 4
12916             let (len, _) =
12917                 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
12918 
12919             let frames =
12920                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
12921             let mut frame_iter = frames.iter();
12922             let stream = frame_iter.next().unwrap();
12923 
12924             assert_eq!(stream, &frame::Frame::Stream {
12925                 stream_id: 4,
12926                 data: stream::RangeBuf::from(&out, off_4, false),
12927             });
12928 
12929             off_4 = match stream {
12930                 frame::Frame::Stream { data, .. } => data.max_off(),
12931 
12932                 _ => unreachable!(),
12933             };
12934             assert_eq!(frame_iter.next(), None);
12935         }
12936     }
12937 
12938     #[test]
12939     /// Tests that old data is retransmitted on PTO.
early_retransmit()12940     fn early_retransmit() {
12941         let mut buf = [0; 65535];
12942 
12943         let mut pipe = testing::Pipe::new().unwrap();
12944         assert_eq!(pipe.handshake(), Ok(()));
12945 
12946         // Client sends stream data.
12947         assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
12948         assert_eq!(pipe.advance(), Ok(()));
12949 
12950         // Client sends more stream data, but packet is lost
12951         assert_eq!(pipe.client.stream_send(4, b"b", false), Ok(1));
12952         assert!(pipe.client.send(&mut buf).is_ok());
12953 
12954         // Wait until PTO expires. Since the RTT is very low, wait a bit more.
12955         let timer = pipe.client.timeout().unwrap();
12956         std::thread::sleep(timer + time::Duration::from_millis(1));
12957 
12958         pipe.client.on_timeout();
12959 
12960         let epoch = packet::Epoch::Application;
12961         assert_eq!(
12962             pipe.client
12963                 .paths
12964                 .get_active()
12965                 .expect("no active")
12966                 .recovery
12967                 .loss_probes[epoch],
12968             1,
12969         );
12970 
12971         // Client retransmits stream data in PTO probe.
12972         let (len, _) = pipe.client.send(&mut buf).unwrap();
12973         assert_eq!(
12974             pipe.client
12975                 .paths
12976                 .get_active()
12977                 .expect("no active")
12978                 .recovery
12979                 .loss_probes[epoch],
12980             0,
12981         );
12982 
12983         let frames =
12984             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
12985 
12986         let mut iter = frames.iter();
12987 
12988         // Skip ACK frame.
12989         iter.next();
12990 
12991         assert_eq!(
12992             iter.next(),
12993             Some(&frame::Frame::Stream {
12994                 stream_id: 4,
12995                 data: stream::RangeBuf::from(b"b", 0, false),
12996             })
12997         );
12998         assert_eq!(pipe.client.stats().retrans, 1);
12999     }
13000 
13001     #[test]
13002     /// Tests that PTO probe packets are not coalesced together.
dont_coalesce_probes()13003     fn dont_coalesce_probes() {
13004         let mut buf = [0; 65535];
13005 
13006         let mut pipe = testing::Pipe::new().unwrap();
13007 
13008         // Client sends Initial packet.
13009         let (len, _) = pipe.client.send(&mut buf).unwrap();
13010         assert_eq!(len, 1200);
13011 
13012         // Wait for PTO to expire.
13013         let timer = pipe.client.timeout().unwrap();
13014         std::thread::sleep(timer + time::Duration::from_millis(1));
13015 
13016         pipe.client.on_timeout();
13017 
13018         let epoch = packet::Epoch::Initial;
13019         assert_eq!(
13020             pipe.client
13021                 .paths
13022                 .get_active()
13023                 .expect("no active")
13024                 .recovery
13025                 .loss_probes[epoch],
13026             1,
13027         );
13028 
13029         // Client sends PTO probe.
13030         let (len, _) = pipe.client.send(&mut buf).unwrap();
13031         assert_eq!(len, 1200);
13032         assert_eq!(
13033             pipe.client
13034                 .paths
13035                 .get_active()
13036                 .expect("no active")
13037                 .recovery
13038                 .loss_probes[epoch],
13039             0,
13040         );
13041 
13042         // Wait for PTO to expire.
13043         let timer = pipe.client.timeout().unwrap();
13044         std::thread::sleep(timer + time::Duration::from_millis(1));
13045 
13046         pipe.client.on_timeout();
13047 
13048         assert_eq!(
13049             pipe.client
13050                 .paths
13051                 .get_active()
13052                 .expect("no active")
13053                 .recovery
13054                 .loss_probes[epoch],
13055             2,
13056         );
13057 
13058         // Client sends first PTO probe.
13059         let (len, _) = pipe.client.send(&mut buf).unwrap();
13060         assert_eq!(len, 1200);
13061         assert_eq!(
13062             pipe.client
13063                 .paths
13064                 .get_active()
13065                 .expect("no active")
13066                 .recovery
13067                 .loss_probes[epoch],
13068             1,
13069         );
13070 
13071         // Client sends second PTO probe.
13072         let (len, _) = pipe.client.send(&mut buf).unwrap();
13073         assert_eq!(len, 1200);
13074         assert_eq!(
13075             pipe.client
13076                 .paths
13077                 .get_active()
13078                 .expect("no active")
13079                 .recovery
13080                 .loss_probes[epoch],
13081             0,
13082         );
13083     }
13084 
13085     #[test]
coalesce_padding_short()13086     fn coalesce_padding_short() {
13087         let mut buf = [0; 65535];
13088 
13089         let mut pipe = testing::Pipe::new().unwrap();
13090 
13091         // Client sends first flight.
13092         let (len, _) = pipe.client.send(&mut buf).unwrap();
13093         assert_eq!(len, MIN_CLIENT_INITIAL_LEN);
13094         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13095 
13096         // Server sends first flight.
13097         let (len, _) = pipe.server.send(&mut buf).unwrap();
13098         assert_eq!(len, MIN_CLIENT_INITIAL_LEN);
13099         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
13100 
13101         let (len, _) = pipe.server.send(&mut buf).unwrap();
13102         assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
13103 
13104         // Client sends stream data.
13105         assert_eq!(pipe.client.is_established(), true);
13106         assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
13107 
13108         // Client sends second flight.
13109         let (len, _) = pipe.client.send(&mut buf).unwrap();
13110         assert_eq!(len, MIN_CLIENT_INITIAL_LEN);
13111         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13112 
13113         // None of the sent packets should have been dropped.
13114         assert_eq!(pipe.client.sent_count, pipe.server.recv_count);
13115         assert_eq!(pipe.server.sent_count, pipe.client.recv_count);
13116     }
13117 
13118     #[test]
13119     /// Tests that client avoids handshake deadlock by arming PTO.
handshake_anti_deadlock()13120     fn handshake_anti_deadlock() {
13121         let mut buf = [0; 65535];
13122 
13123         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13124         config
13125             .load_cert_chain_from_pem_file("examples/cert-big.crt")
13126             .unwrap();
13127         config
13128             .load_priv_key_from_pem_file("examples/cert.key")
13129             .unwrap();
13130         config
13131             .set_application_protos(&[b"proto1", b"proto2"])
13132             .unwrap();
13133 
13134         let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
13135 
13136         assert_eq!(pipe.client.handshake_status().has_handshake_keys, false);
13137         assert_eq!(pipe.client.handshake_status().peer_verified_address, false);
13138         assert_eq!(pipe.server.handshake_status().has_handshake_keys, false);
13139         assert_eq!(pipe.server.handshake_status().peer_verified_address, true);
13140 
13141         // Client sends padded Initial.
13142         let (len, _) = pipe.client.send(&mut buf).unwrap();
13143         assert_eq!(len, 1200);
13144 
13145         // Server receives client's Initial and sends own Initial and Handshake
13146         // until it's blocked by the anti-amplification limit.
13147         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13148         let flight = testing::emit_flight(&mut pipe.server).unwrap();
13149 
13150         assert_eq!(pipe.client.handshake_status().has_handshake_keys, false);
13151         assert_eq!(pipe.client.handshake_status().peer_verified_address, false);
13152         assert_eq!(pipe.server.handshake_status().has_handshake_keys, true);
13153         assert_eq!(pipe.server.handshake_status().peer_verified_address, true);
13154 
13155         // Client receives the server flight and sends Handshake ACK, but it is
13156         // lost.
13157         testing::process_flight(&mut pipe.client, flight).unwrap();
13158         testing::emit_flight(&mut pipe.client).unwrap();
13159 
13160         assert_eq!(pipe.client.handshake_status().has_handshake_keys, true);
13161         assert_eq!(pipe.client.handshake_status().peer_verified_address, false);
13162         assert_eq!(pipe.server.handshake_status().has_handshake_keys, true);
13163         assert_eq!(pipe.server.handshake_status().peer_verified_address, true);
13164 
13165         // Make sure client's PTO timer is armed.
13166         assert!(pipe.client.timeout().is_some());
13167     }
13168 
13169     #[test]
13170     /// Tests that packets with corrupted type (from Handshake to Initial) are
13171     /// properly ignored.
handshake_packet_type_corruption()13172     fn handshake_packet_type_corruption() {
13173         let mut buf = [0; 65535];
13174 
13175         let mut pipe = testing::Pipe::new().unwrap();
13176 
13177         // Client sends padded Initial.
13178         let (len, _) = pipe.client.send(&mut buf).unwrap();
13179         assert_eq!(len, 1200);
13180 
13181         // Server receives client's Initial and sends own Initial and Handshake.
13182         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13183 
13184         let flight = testing::emit_flight(&mut pipe.server).unwrap();
13185         testing::process_flight(&mut pipe.client, flight).unwrap();
13186 
13187         // Client sends Initial packet with ACK.
13188         let active_pid =
13189             pipe.client.paths.get_active_path_id().expect("no active");
13190         let (ty, len) = pipe
13191             .client
13192             .send_single(&mut buf, active_pid, false)
13193             .unwrap();
13194         assert_eq!(ty, Type::Initial);
13195 
13196         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13197 
13198         // Client sends Handshake packet.
13199         let (ty, len) = pipe
13200             .client
13201             .send_single(&mut buf, active_pid, false)
13202             .unwrap();
13203         assert_eq!(ty, Type::Handshake);
13204 
13205         // Packet type is corrupted to Initial.
13206         buf[0] &= !(0x20);
13207 
13208         let hdr = Header::from_slice(&mut buf[..len], 0).unwrap();
13209         assert_eq!(hdr.ty, Type::Initial);
13210 
13211         // Server receives corrupted packet without returning an error.
13212         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13213     }
13214 
13215     #[test]
dgram_send_fails_invalidstate()13216     fn dgram_send_fails_invalidstate() {
13217         let mut pipe = testing::Pipe::new().unwrap();
13218         assert_eq!(pipe.handshake(), Ok(()));
13219 
13220         assert_eq!(
13221             pipe.client.dgram_send(b"hello, world"),
13222             Err(Error::InvalidState)
13223         );
13224     }
13225 
13226     #[test]
dgram_send_app_limited()13227     fn dgram_send_app_limited() {
13228         let mut buf = [0; 65535];
13229         let send_buf = [0xcf; 1000];
13230 
13231         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13232         config
13233             .load_cert_chain_from_pem_file("examples/cert.crt")
13234             .unwrap();
13235         config
13236             .load_priv_key_from_pem_file("examples/cert.key")
13237             .unwrap();
13238         config
13239             .set_application_protos(&[b"proto1", b"proto2"])
13240             .unwrap();
13241         config.set_initial_max_data(30);
13242         config.set_initial_max_stream_data_bidi_local(15);
13243         config.set_initial_max_stream_data_bidi_remote(15);
13244         config.set_initial_max_stream_data_uni(10);
13245         config.set_initial_max_streams_bidi(3);
13246         config.set_initial_max_streams_uni(3);
13247         config.enable_dgram(true, 1000, 1000);
13248         config.set_max_recv_udp_payload_size(1200);
13249         config.verify_peer(false);
13250 
13251         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13252         assert_eq!(pipe.handshake(), Ok(()));
13253 
13254         for _ in 0..1000 {
13255             assert_eq!(pipe.client.dgram_send(&send_buf), Ok(()));
13256         }
13257 
13258         assert!(!pipe
13259             .client
13260             .paths
13261             .get_active()
13262             .expect("no active")
13263             .recovery
13264             .app_limited());
13265         assert_eq!(pipe.client.dgram_send_queue.byte_size(), 1_000_000);
13266 
13267         let (len, _) = pipe.client.send(&mut buf).unwrap();
13268 
13269         assert_ne!(pipe.client.dgram_send_queue.byte_size(), 0);
13270         assert_ne!(pipe.client.dgram_send_queue.byte_size(), 1_000_000);
13271         assert!(!pipe
13272             .client
13273             .paths
13274             .get_active()
13275             .expect("no active")
13276             .recovery
13277             .app_limited());
13278 
13279         assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13280 
13281         let flight = testing::emit_flight(&mut pipe.client).unwrap();
13282         testing::process_flight(&mut pipe.server, flight).unwrap();
13283 
13284         let flight = testing::emit_flight(&mut pipe.server).unwrap();
13285         testing::process_flight(&mut pipe.client, flight).unwrap();
13286 
13287         assert_ne!(pipe.client.dgram_send_queue.byte_size(), 0);
13288         assert_ne!(pipe.client.dgram_send_queue.byte_size(), 1_000_000);
13289 
13290         assert!(!pipe
13291             .client
13292             .paths
13293             .get_active()
13294             .expect("no active")
13295             .recovery
13296             .app_limited());
13297     }
13298 
13299     #[test]
dgram_single_datagram()13300     fn dgram_single_datagram() {
13301         let mut buf = [0; 65535];
13302 
13303         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13304         config
13305             .load_cert_chain_from_pem_file("examples/cert.crt")
13306             .unwrap();
13307         config
13308             .load_priv_key_from_pem_file("examples/cert.key")
13309             .unwrap();
13310         config
13311             .set_application_protos(&[b"proto1", b"proto2"])
13312             .unwrap();
13313         config.set_initial_max_data(30);
13314         config.set_initial_max_stream_data_bidi_local(15);
13315         config.set_initial_max_stream_data_bidi_remote(15);
13316         config.set_initial_max_stream_data_uni(10);
13317         config.set_initial_max_streams_bidi(3);
13318         config.set_initial_max_streams_uni(3);
13319         config.enable_dgram(true, 10, 10);
13320         config.verify_peer(false);
13321 
13322         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13323         assert_eq!(pipe.handshake(), Ok(()));
13324 
13325         assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
13326 
13327         assert_eq!(pipe.advance(), Ok(()));
13328 
13329         let result1 = pipe.server.dgram_recv(&mut buf);
13330         assert_eq!(result1, Ok(12));
13331 
13332         let result2 = pipe.server.dgram_recv(&mut buf);
13333         assert_eq!(result2, Err(Error::Done));
13334     }
13335 
13336     #[test]
dgram_multiple_datagrams()13337     fn dgram_multiple_datagrams() {
13338         let mut buf = [0; 65535];
13339 
13340         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13341         config
13342             .load_cert_chain_from_pem_file("examples/cert.crt")
13343             .unwrap();
13344         config
13345             .load_priv_key_from_pem_file("examples/cert.key")
13346             .unwrap();
13347         config
13348             .set_application_protos(&[b"proto1", b"proto2"])
13349             .unwrap();
13350         config.set_initial_max_data(30);
13351         config.set_initial_max_stream_data_bidi_local(15);
13352         config.set_initial_max_stream_data_bidi_remote(15);
13353         config.set_initial_max_stream_data_uni(10);
13354         config.set_initial_max_streams_bidi(3);
13355         config.set_initial_max_streams_uni(3);
13356         config.enable_dgram(true, 2, 3);
13357         config.verify_peer(false);
13358 
13359         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13360         assert_eq!(pipe.handshake(), Ok(()));
13361 
13362         assert_eq!(pipe.client.dgram_send_queue_len(), 0);
13363         assert_eq!(pipe.client.dgram_send_queue_byte_size(), 0);
13364 
13365         assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
13366         assert_eq!(pipe.client.dgram_send(b"ciao, mondo"), Ok(()));
13367         assert_eq!(pipe.client.dgram_send(b"hola, mundo"), Ok(()));
13368         assert!(pipe.client.is_dgram_send_queue_full());
13369 
13370         assert_eq!(pipe.client.dgram_send_queue_byte_size(), 34);
13371 
13372         pipe.client
13373             .dgram_purge_outgoing(|d: &[u8]| -> bool { d[0] == b'c' });
13374 
13375         assert_eq!(pipe.client.dgram_send_queue_len(), 2);
13376         assert_eq!(pipe.client.dgram_send_queue_byte_size(), 23);
13377         assert!(!pipe.client.is_dgram_send_queue_full());
13378 
13379         // Before packets exchanged, no dgrams on server receive side.
13380         assert_eq!(pipe.server.dgram_recv_queue_len(), 0);
13381 
13382         assert_eq!(pipe.advance(), Ok(()));
13383 
13384         // After packets exchanged, no dgrams on client send side.
13385         assert_eq!(pipe.client.dgram_send_queue_len(), 0);
13386         assert_eq!(pipe.client.dgram_send_queue_byte_size(), 0);
13387 
13388         assert_eq!(pipe.server.dgram_recv_queue_len(), 2);
13389         assert_eq!(pipe.server.dgram_recv_queue_byte_size(), 23);
13390         assert!(pipe.server.is_dgram_recv_queue_full());
13391 
13392         let result1 = pipe.server.dgram_recv(&mut buf);
13393         assert_eq!(result1, Ok(12));
13394         assert_eq!(buf[0], b'h');
13395         assert_eq!(buf[1], b'e');
13396         assert!(!pipe.server.is_dgram_recv_queue_full());
13397 
13398         let result2 = pipe.server.dgram_recv(&mut buf);
13399         assert_eq!(result2, Ok(11));
13400         assert_eq!(buf[0], b'h');
13401         assert_eq!(buf[1], b'o');
13402 
13403         let result3 = pipe.server.dgram_recv(&mut buf);
13404         assert_eq!(result3, Err(Error::Done));
13405 
13406         assert_eq!(pipe.server.dgram_recv_queue_len(), 0);
13407         assert_eq!(pipe.server.dgram_recv_queue_byte_size(), 0);
13408     }
13409 
13410     #[test]
dgram_send_queue_overflow()13411     fn dgram_send_queue_overflow() {
13412         let mut buf = [0; 65535];
13413 
13414         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13415         config
13416             .load_cert_chain_from_pem_file("examples/cert.crt")
13417             .unwrap();
13418         config
13419             .load_priv_key_from_pem_file("examples/cert.key")
13420             .unwrap();
13421         config
13422             .set_application_protos(&[b"proto1", b"proto2"])
13423             .unwrap();
13424         config.set_initial_max_data(30);
13425         config.set_initial_max_stream_data_bidi_local(15);
13426         config.set_initial_max_stream_data_bidi_remote(15);
13427         config.set_initial_max_stream_data_uni(10);
13428         config.set_initial_max_streams_bidi(3);
13429         config.set_initial_max_streams_uni(3);
13430         config.enable_dgram(true, 10, 2);
13431         config.verify_peer(false);
13432 
13433         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13434         assert_eq!(pipe.handshake(), Ok(()));
13435 
13436         assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
13437         assert_eq!(pipe.client.dgram_send(b"ciao, mondo"), Ok(()));
13438         assert_eq!(pipe.client.dgram_send(b"hola, mundo"), Err(Error::Done));
13439 
13440         assert_eq!(pipe.advance(), Ok(()));
13441 
13442         let result1 = pipe.server.dgram_recv(&mut buf);
13443         assert_eq!(result1, Ok(12));
13444         assert_eq!(buf[0], b'h');
13445         assert_eq!(buf[1], b'e');
13446 
13447         let result2 = pipe.server.dgram_recv(&mut buf);
13448         assert_eq!(result2, Ok(11));
13449         assert_eq!(buf[0], b'c');
13450         assert_eq!(buf[1], b'i');
13451 
13452         let result3 = pipe.server.dgram_recv(&mut buf);
13453         assert_eq!(result3, Err(Error::Done));
13454     }
13455 
13456     #[test]
dgram_recv_queue_overflow()13457     fn dgram_recv_queue_overflow() {
13458         let mut buf = [0; 65535];
13459 
13460         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13461         config
13462             .load_cert_chain_from_pem_file("examples/cert.crt")
13463             .unwrap();
13464         config
13465             .load_priv_key_from_pem_file("examples/cert.key")
13466             .unwrap();
13467         config
13468             .set_application_protos(&[b"proto1", b"proto2"])
13469             .unwrap();
13470         config.set_initial_max_data(30);
13471         config.set_initial_max_stream_data_bidi_local(15);
13472         config.set_initial_max_stream_data_bidi_remote(15);
13473         config.set_initial_max_stream_data_uni(10);
13474         config.set_initial_max_streams_bidi(3);
13475         config.set_initial_max_streams_uni(3);
13476         config.enable_dgram(true, 2, 10);
13477         config.set_max_recv_udp_payload_size(1200);
13478         config.verify_peer(false);
13479 
13480         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13481         assert_eq!(pipe.handshake(), Ok(()));
13482 
13483         assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
13484         assert_eq!(pipe.client.dgram_send(b"ciao, mondo"), Ok(()));
13485         assert_eq!(pipe.client.dgram_send(b"hola, mundo"), Ok(()));
13486 
13487         assert_eq!(pipe.advance(), Ok(()));
13488 
13489         let result1 = pipe.server.dgram_recv(&mut buf);
13490         assert_eq!(result1, Ok(11));
13491         assert_eq!(buf[0], b'c');
13492         assert_eq!(buf[1], b'i');
13493 
13494         let result2 = pipe.server.dgram_recv(&mut buf);
13495         assert_eq!(result2, Ok(11));
13496         assert_eq!(buf[0], b'h');
13497         assert_eq!(buf[1], b'o');
13498 
13499         let result3 = pipe.server.dgram_recv(&mut buf);
13500         assert_eq!(result3, Err(Error::Done));
13501     }
13502 
13503     #[test]
dgram_send_max_size()13504     fn dgram_send_max_size() {
13505         let mut buf = [0; MAX_DGRAM_FRAME_SIZE as usize];
13506 
13507         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13508         config
13509             .load_cert_chain_from_pem_file("examples/cert.crt")
13510             .unwrap();
13511         config
13512             .load_priv_key_from_pem_file("examples/cert.key")
13513             .unwrap();
13514         config
13515             .set_application_protos(&[b"proto1", b"proto2"])
13516             .unwrap();
13517         config.set_initial_max_data(30);
13518         config.set_initial_max_stream_data_bidi_local(15);
13519         config.set_initial_max_stream_data_bidi_remote(15);
13520         config.set_initial_max_stream_data_uni(10);
13521         config.set_initial_max_streams_bidi(3);
13522         config.set_initial_max_streams_uni(3);
13523         config.enable_dgram(true, 10, 10);
13524         config.set_max_recv_udp_payload_size(1452);
13525         config.verify_peer(false);
13526 
13527         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13528 
13529         // Before handshake (before peer settings) we don't know max dgram size
13530         assert_eq!(pipe.client.dgram_max_writable_len(), None);
13531 
13532         assert_eq!(pipe.handshake(), Ok(()));
13533 
13534         let max_dgram_size = pipe.client.dgram_max_writable_len().unwrap();
13535 
13536         // Tests use a 16-byte connection ID, so the max datagram frame payload
13537         // size is (1200 byte-long packet - 40 bytes overhead)
13538         assert_eq!(max_dgram_size, 1160);
13539 
13540         let dgram_packet: Vec<u8> = vec![42; max_dgram_size];
13541 
13542         assert_eq!(pipe.client.dgram_send(&dgram_packet), Ok(()));
13543 
13544         assert_eq!(pipe.advance(), Ok(()));
13545 
13546         let result1 = pipe.server.dgram_recv(&mut buf);
13547         assert_eq!(result1, Ok(max_dgram_size));
13548 
13549         let result2 = pipe.server.dgram_recv(&mut buf);
13550         assert_eq!(result2, Err(Error::Done));
13551     }
13552 
13553     #[test]
13554     /// Tests is_readable check.
is_readable()13555     fn is_readable() {
13556         let mut buf = [0; 65535];
13557 
13558         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13559         config
13560             .load_cert_chain_from_pem_file("examples/cert.crt")
13561             .unwrap();
13562         config
13563             .load_priv_key_from_pem_file("examples/cert.key")
13564             .unwrap();
13565         config
13566             .set_application_protos(&[b"proto1", b"proto2"])
13567             .unwrap();
13568         config.set_initial_max_data(30);
13569         config.set_initial_max_stream_data_bidi_local(15);
13570         config.set_initial_max_stream_data_bidi_remote(15);
13571         config.set_initial_max_stream_data_uni(10);
13572         config.set_initial_max_streams_bidi(3);
13573         config.set_initial_max_streams_uni(3);
13574         config.enable_dgram(true, 10, 10);
13575         config.set_max_recv_udp_payload_size(1452);
13576         config.verify_peer(false);
13577 
13578         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13579         assert_eq!(pipe.handshake(), Ok(()));
13580 
13581         // No readable data.
13582         assert_eq!(pipe.client.is_readable(), false);
13583         assert_eq!(pipe.server.is_readable(), false);
13584 
13585         assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
13586         assert_eq!(pipe.advance(), Ok(()));
13587 
13588         // Server received stream.
13589         assert_eq!(pipe.client.is_readable(), false);
13590         assert_eq!(pipe.server.is_readable(), true);
13591 
13592         assert_eq!(
13593             pipe.server.stream_send(4, b"aaaaaaaaaaaaaaa", false),
13594             Ok(15)
13595         );
13596         assert_eq!(pipe.advance(), Ok(()));
13597 
13598         // Client received stream.
13599         assert_eq!(pipe.client.is_readable(), true);
13600         assert_eq!(pipe.server.is_readable(), true);
13601 
13602         // Client drains stream.
13603         let mut b = [0; 15];
13604         pipe.client.stream_recv(4, &mut b).unwrap();
13605         assert_eq!(pipe.advance(), Ok(()));
13606 
13607         assert_eq!(pipe.client.is_readable(), false);
13608         assert_eq!(pipe.server.is_readable(), true);
13609 
13610         // Server shuts down stream.
13611         assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 0), Ok(()));
13612         assert_eq!(pipe.server.is_readable(), false);
13613 
13614         // Server received dgram.
13615         assert_eq!(pipe.client.dgram_send(b"dddddddddddddd"), Ok(()));
13616         assert_eq!(pipe.advance(), Ok(()));
13617 
13618         assert_eq!(pipe.client.is_readable(), false);
13619         assert_eq!(pipe.server.is_readable(), true);
13620 
13621         // Client received dgram.
13622         assert_eq!(pipe.server.dgram_send(b"dddddddddddddd"), Ok(()));
13623         assert_eq!(pipe.advance(), Ok(()));
13624 
13625         assert_eq!(pipe.client.is_readable(), true);
13626         assert_eq!(pipe.server.is_readable(), true);
13627 
13628         // Drain the dgram queues.
13629         let r = pipe.server.dgram_recv(&mut buf);
13630         assert_eq!(r, Ok(14));
13631         assert_eq!(pipe.server.is_readable(), false);
13632 
13633         let r = pipe.client.dgram_recv(&mut buf);
13634         assert_eq!(r, Ok(14));
13635         assert_eq!(pipe.client.is_readable(), false);
13636     }
13637 
13638     #[test]
close()13639     fn close() {
13640         let mut buf = [0; 65535];
13641 
13642         let mut pipe = testing::Pipe::new().unwrap();
13643         assert_eq!(pipe.handshake(), Ok(()));
13644 
13645         assert_eq!(pipe.client.close(false, 0x1234, b"hello?"), Ok(()));
13646 
13647         assert_eq!(
13648             pipe.client.close(false, 0x4321, b"hello?"),
13649             Err(Error::Done)
13650         );
13651 
13652         let (len, _) = pipe.client.send(&mut buf).unwrap();
13653 
13654         let frames =
13655             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
13656 
13657         assert_eq!(
13658             frames.first(),
13659             Some(&frame::Frame::ConnectionClose {
13660                 error_code: 0x1234,
13661                 frame_type: 0,
13662                 reason: b"hello?".to_vec(),
13663             })
13664         );
13665     }
13666 
13667     #[test]
app_close_by_client()13668     fn app_close_by_client() {
13669         let mut buf = [0; 65535];
13670 
13671         let mut pipe = testing::Pipe::new().unwrap();
13672         assert_eq!(pipe.handshake(), Ok(()));
13673 
13674         assert_eq!(pipe.client.close(true, 0x1234, b"hello!"), Ok(()));
13675 
13676         assert_eq!(pipe.client.close(true, 0x4321, b"hello!"), Err(Error::Done));
13677 
13678         let (len, _) = pipe.client.send(&mut buf).unwrap();
13679 
13680         let frames =
13681             testing::decode_pkt(&mut pipe.server, &mut buf, len).unwrap();
13682 
13683         assert_eq!(
13684             frames.first(),
13685             Some(&frame::Frame::ApplicationClose {
13686                 error_code: 0x1234,
13687                 reason: b"hello!".to_vec(),
13688             })
13689         );
13690     }
13691 
13692     #[test]
app_close_by_server_during_handshake_private_key_failure()13693     fn app_close_by_server_during_handshake_private_key_failure() {
13694         let mut pipe = testing::Pipe::new().unwrap();
13695         pipe.server.handshake.set_failing_private_key_method();
13696 
13697         // Client sends initial flight.
13698         let flight = testing::emit_flight(&mut pipe.client).unwrap();
13699         assert_eq!(
13700             testing::process_flight(&mut pipe.server, flight),
13701             Err(Error::TlsFail)
13702         );
13703 
13704         let flight = testing::emit_flight(&mut pipe.server).unwrap();
13705 
13706         // Both connections are not established.
13707         assert!(!pipe.server.is_established());
13708         assert!(!pipe.client.is_established());
13709 
13710         // Connection should already be closed due the failure during key signing.
13711         assert_eq!(
13712             pipe.server.close(true, 123, b"fail whale"),
13713             Err(Error::Done)
13714         );
13715 
13716         testing::process_flight(&mut pipe.client, flight).unwrap();
13717 
13718         // Connection should already be closed due the failure during key signing.
13719         assert_eq!(
13720             pipe.client.close(true, 123, b"fail whale"),
13721             Err(Error::Done)
13722         );
13723 
13724         // Connection is not established on the server / client (and never
13725         // will be)
13726         assert!(!pipe.server.is_established());
13727         assert!(!pipe.client.is_established());
13728 
13729         assert_eq!(pipe.advance(), Ok(()));
13730 
13731         assert_eq!(
13732             pipe.server.local_error(),
13733             Some(&ConnectionError {
13734                 is_app: false,
13735                 error_code: 0x01,
13736                 reason: vec![],
13737             })
13738         );
13739         assert_eq!(
13740             pipe.client.peer_error(),
13741             Some(&ConnectionError {
13742                 is_app: false,
13743                 error_code: 0x01,
13744                 reason: vec![],
13745             })
13746         );
13747     }
13748 
13749     #[test]
app_close_by_server_during_handshake_not_established()13750     fn app_close_by_server_during_handshake_not_established() {
13751         let mut pipe = testing::Pipe::new().unwrap();
13752 
13753         // Client sends initial flight.
13754         let flight = testing::emit_flight(&mut pipe.client).unwrap();
13755         testing::process_flight(&mut pipe.server, flight).unwrap();
13756 
13757         let flight = testing::emit_flight(&mut pipe.server).unwrap();
13758 
13759         // Both connections are not established.
13760         assert!(!pipe.client.is_established() && !pipe.server.is_established());
13761 
13762         // Server closes before connection is established.
13763         pipe.server.close(true, 123, b"fail whale").unwrap();
13764 
13765         testing::process_flight(&mut pipe.client, flight).unwrap();
13766 
13767         // Connection is established on the client.
13768         assert!(pipe.client.is_established());
13769 
13770         // Client sends after connection is established.
13771         pipe.client.stream_send(0, b"badauthtoken", true).unwrap();
13772 
13773         let flight = testing::emit_flight(&mut pipe.client).unwrap();
13774         testing::process_flight(&mut pipe.server, flight).unwrap();
13775 
13776         // Connection is not established on the server (and never will be)
13777         assert!(!pipe.server.is_established());
13778 
13779         assert_eq!(pipe.advance(), Ok(()));
13780 
13781         assert_eq!(
13782             pipe.server.local_error(),
13783             Some(&ConnectionError {
13784                 is_app: false,
13785                 error_code: 0x0c,
13786                 reason: vec![],
13787             })
13788         );
13789         assert_eq!(
13790             pipe.client.peer_error(),
13791             Some(&ConnectionError {
13792                 is_app: false,
13793                 error_code: 0x0c,
13794                 reason: vec![],
13795             })
13796         );
13797     }
13798 
13799     #[test]
app_close_by_server_during_handshake_established()13800     fn app_close_by_server_during_handshake_established() {
13801         let mut pipe = testing::Pipe::new().unwrap();
13802 
13803         // Client sends initial flight.
13804         let flight = testing::emit_flight(&mut pipe.client).unwrap();
13805         testing::process_flight(&mut pipe.server, flight).unwrap();
13806 
13807         let flight = testing::emit_flight(&mut pipe.server).unwrap();
13808 
13809         // Both connections are not established.
13810         assert!(!pipe.client.is_established() && !pipe.server.is_established());
13811 
13812         testing::process_flight(&mut pipe.client, flight).unwrap();
13813 
13814         // Connection is established on the client.
13815         assert!(pipe.client.is_established());
13816 
13817         // Client sends after connection is established.
13818         pipe.client.stream_send(0, b"badauthtoken", true).unwrap();
13819 
13820         let flight = testing::emit_flight(&mut pipe.client).unwrap();
13821         testing::process_flight(&mut pipe.server, flight).unwrap();
13822 
13823         // Connection is established on the server but the Handshake ACK has not
13824         // been sent yet.
13825         assert!(pipe.server.is_established());
13826 
13827         // Server closes after connection is established.
13828         pipe.server
13829             .close(true, 123, b"Invalid authentication")
13830             .unwrap();
13831 
13832         // Server sends Handshake ACK and then 1RTT CONNECTION_CLOSE.
13833         assert_eq!(pipe.advance(), Ok(()));
13834 
13835         assert_eq!(
13836             pipe.server.local_error(),
13837             Some(&ConnectionError {
13838                 is_app: true,
13839                 error_code: 123,
13840                 reason: b"Invalid authentication".to_vec()
13841             })
13842         );
13843         assert_eq!(
13844             pipe.client.peer_error(),
13845             Some(&ConnectionError {
13846                 is_app: true,
13847                 error_code: 123,
13848                 reason: b"Invalid authentication".to_vec()
13849             })
13850         );
13851     }
13852 
13853     #[test]
peer_error()13854     fn peer_error() {
13855         let mut pipe = testing::Pipe::new().unwrap();
13856         assert_eq!(pipe.handshake(), Ok(()));
13857 
13858         assert_eq!(pipe.server.close(false, 0x1234, b"hello?"), Ok(()));
13859         assert_eq!(pipe.advance(), Ok(()));
13860 
13861         assert_eq!(
13862             pipe.client.peer_error(),
13863             Some(&ConnectionError {
13864                 is_app: false,
13865                 error_code: 0x1234u64,
13866                 reason: b"hello?".to_vec()
13867             })
13868         );
13869     }
13870 
13871     #[test]
app_peer_error()13872     fn app_peer_error() {
13873         let mut pipe = testing::Pipe::new().unwrap();
13874         assert_eq!(pipe.handshake(), Ok(()));
13875 
13876         assert_eq!(pipe.server.close(true, 0x1234, b"hello!"), Ok(()));
13877         assert_eq!(pipe.advance(), Ok(()));
13878 
13879         assert_eq!(
13880             pipe.client.peer_error(),
13881             Some(&ConnectionError {
13882                 is_app: true,
13883                 error_code: 0x1234u64,
13884                 reason: b"hello!".to_vec()
13885             })
13886         );
13887     }
13888 
13889     #[test]
local_error()13890     fn local_error() {
13891         let mut pipe = testing::Pipe::new().unwrap();
13892         assert_eq!(pipe.handshake(), Ok(()));
13893 
13894         assert_eq!(pipe.server.local_error(), None);
13895 
13896         assert_eq!(pipe.server.close(true, 0x1234, b"hello!"), Ok(()));
13897 
13898         assert_eq!(
13899             pipe.server.local_error(),
13900             Some(&ConnectionError {
13901                 is_app: true,
13902                 error_code: 0x1234u64,
13903                 reason: b"hello!".to_vec()
13904             })
13905         );
13906     }
13907 
13908     #[test]
update_max_datagram_size()13909     fn update_max_datagram_size() {
13910         let mut client_scid = [0; 16];
13911         rand::rand_bytes(&mut client_scid[..]);
13912         let client_scid = ConnectionId::from_ref(&client_scid);
13913         let client_addr = "127.0.0.1:1234".parse().unwrap();
13914 
13915         let mut server_scid = [0; 16];
13916         rand::rand_bytes(&mut server_scid[..]);
13917         let server_scid = ConnectionId::from_ref(&server_scid);
13918         let server_addr = "127.0.0.1:4321".parse().unwrap();
13919 
13920         let mut client_config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13921         client_config
13922             .set_application_protos(&[b"proto1", b"proto2"])
13923             .unwrap();
13924         client_config.set_max_recv_udp_payload_size(1200);
13925 
13926         let mut server_config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13927         server_config
13928             .load_cert_chain_from_pem_file("examples/cert.crt")
13929             .unwrap();
13930         server_config
13931             .load_priv_key_from_pem_file("examples/cert.key")
13932             .unwrap();
13933         server_config
13934             .set_application_protos(&[b"proto1", b"proto2"])
13935             .unwrap();
13936         server_config.verify_peer(false);
13937         server_config
13938             .set_application_protos(&[b"proto1", b"proto2"])
13939             .unwrap();
13940         // Larger than the client
13941         server_config.set_max_send_udp_payload_size(1500);
13942 
13943         let mut pipe = testing::Pipe {
13944             client: connect(
13945                 Some("quic.tech"),
13946                 &client_scid,
13947                 client_addr,
13948                 server_addr,
13949                 &mut client_config,
13950             )
13951             .unwrap(),
13952             server: accept(
13953                 &server_scid,
13954                 None,
13955                 server_addr,
13956                 client_addr,
13957                 &mut server_config,
13958             )
13959             .unwrap(),
13960         };
13961 
13962         // Before handshake
13963         assert_eq!(
13964             pipe.server
13965                 .paths
13966                 .get_active()
13967                 .expect("no active")
13968                 .recovery
13969                 .max_datagram_size(),
13970             1500,
13971         );
13972 
13973         assert_eq!(pipe.handshake(), Ok(()));
13974 
13975         // After handshake, max_datagram_size should match to client's
13976         // max_recv_udp_payload_size which is smaller
13977         assert_eq!(
13978             pipe.server
13979                 .paths
13980                 .get_active()
13981                 .expect("no active")
13982                 .recovery
13983                 .max_datagram_size(),
13984             1200,
13985         );
13986         assert_eq!(
13987             pipe.server
13988                 .paths
13989                 .get_active()
13990                 .expect("no active")
13991                 .recovery
13992                 .cwnd(),
13993             12000,
13994         );
13995     }
13996 
13997     #[test]
13998     /// Tests that connection-level send capacity decreases as more stream data
13999     /// is buffered.
send_capacity()14000     fn send_capacity() {
14001         let mut buf = [0; 65535];
14002 
14003         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14004         config
14005             .load_cert_chain_from_pem_file("examples/cert.crt")
14006             .unwrap();
14007         config
14008             .load_priv_key_from_pem_file("examples/cert.key")
14009             .unwrap();
14010         config
14011             .set_application_protos(&[b"proto1", b"proto2"])
14012             .unwrap();
14013         config.set_initial_max_data(100000);
14014         config.set_initial_max_stream_data_bidi_local(10000);
14015         config.set_initial_max_stream_data_bidi_remote(10000);
14016         config.set_initial_max_streams_bidi(10);
14017         config.verify_peer(false);
14018 
14019         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14020         assert_eq!(pipe.handshake(), Ok(()));
14021 
14022         assert_eq!(pipe.client.stream_send(0, b"hello!", true), Ok(6));
14023         assert_eq!(pipe.advance(), Ok(()));
14024 
14025         assert_eq!(pipe.client.stream_send(4, b"hello!", true), Ok(6));
14026         assert_eq!(pipe.advance(), Ok(()));
14027 
14028         assert_eq!(pipe.client.stream_send(8, b"hello!", true), Ok(6));
14029         assert_eq!(pipe.advance(), Ok(()));
14030 
14031         assert_eq!(pipe.client.stream_send(12, b"hello!", true), Ok(6));
14032         assert_eq!(pipe.advance(), Ok(()));
14033 
14034         let mut r = pipe.server.readable().collect::<Vec<u64>>();
14035         assert_eq!(r.len(), 4);
14036 
14037         r.sort();
14038 
14039         assert_eq!(r, [0, 4, 8, 12]);
14040 
14041         assert_eq!(pipe.server.stream_recv(0, &mut buf), Ok((6, true)));
14042         assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((6, true)));
14043         assert_eq!(pipe.server.stream_recv(8, &mut buf), Ok((6, true)));
14044         assert_eq!(pipe.server.stream_recv(12, &mut buf), Ok((6, true)));
14045 
14046         assert_eq!(pipe.server.tx_cap, 12000);
14047 
14048         assert_eq!(pipe.server.stream_send(0, &buf[..5000], false), Ok(5000));
14049         assert_eq!(pipe.server.stream_send(4, &buf[..5000], false), Ok(5000));
14050         assert_eq!(pipe.server.stream_send(8, &buf[..5000], false), Ok(2000));
14051 
14052         // No more connection send capacity.
14053         assert_eq!(
14054             pipe.server.stream_send(12, &buf[..5000], false),
14055             Err(Error::Done)
14056         );
14057         assert_eq!(pipe.server.tx_cap, 0);
14058 
14059         assert_eq!(pipe.advance(), Ok(()));
14060     }
14061 
14062     #[cfg(feature = "boringssl-boring-crate")]
14063     #[test]
user_provided_boring_ctx() -> Result<()>14064     fn user_provided_boring_ctx() -> Result<()> {
14065         // Manually construct boring ssl ctx for server
14066         let server_tls_ctx = {
14067             let mut builder = boring::ssl::SslContextBuilder::new(
14068                 boring::ssl::SslMethod::tls(),
14069             )
14070             .unwrap();
14071             builder
14072                 .set_certificate_chain_file("examples/cert.crt")
14073                 .unwrap();
14074             builder
14075                 .set_private_key_file(
14076                     "examples/cert.key",
14077                     boring::ssl::SslFiletype::PEM,
14078                 )
14079                 .unwrap();
14080             builder.build()
14081         };
14082 
14083         let mut server_config =
14084             Config::with_boring_ssl_ctx(crate::PROTOCOL_VERSION, server_tls_ctx)?;
14085         let mut client_config = Config::new(crate::PROTOCOL_VERSION)?;
14086         client_config.load_cert_chain_from_pem_file("examples/cert.crt")?;
14087         client_config.load_priv_key_from_pem_file("examples/cert.key")?;
14088 
14089         for config in [&mut client_config, &mut server_config] {
14090             config.set_application_protos(&[b"proto1", b"proto2"])?;
14091             config.set_initial_max_data(30);
14092             config.set_initial_max_stream_data_bidi_local(15);
14093             config.set_initial_max_stream_data_bidi_remote(15);
14094             config.set_initial_max_stream_data_uni(10);
14095             config.set_initial_max_streams_bidi(3);
14096             config.set_initial_max_streams_uni(3);
14097             config.set_max_idle_timeout(180_000);
14098             config.verify_peer(false);
14099             config.set_ack_delay_exponent(8);
14100         }
14101 
14102         let mut client_scid = [0; 16];
14103         rand::rand_bytes(&mut client_scid[..]);
14104         let client_scid = ConnectionId::from_ref(&client_scid);
14105         let client_addr = "127.0.0.1:1234".parse().unwrap();
14106 
14107         let mut server_scid = [0; 16];
14108         rand::rand_bytes(&mut server_scid[..]);
14109         let server_scid = ConnectionId::from_ref(&server_scid);
14110         let server_addr = "127.0.0.1:4321".parse().unwrap();
14111 
14112         let mut pipe = testing::Pipe {
14113             client: connect(
14114                 Some("quic.tech"),
14115                 &client_scid,
14116                 client_addr,
14117                 server_addr,
14118                 &mut client_config,
14119             )?,
14120             server: accept(
14121                 &server_scid,
14122                 None,
14123                 server_addr,
14124                 client_addr,
14125                 &mut server_config,
14126             )?,
14127         };
14128 
14129         assert_eq!(pipe.handshake(), Ok(()));
14130 
14131         Ok(())
14132     }
14133 
14134     #[test]
14135     /// Tests that resetting a stream restores flow control for unsent data.
last_tx_data_larger_than_tx_data()14136     fn last_tx_data_larger_than_tx_data() {
14137         let mut config = Config::new(PROTOCOL_VERSION).unwrap();
14138         config
14139             .set_application_protos(&[b"proto1", b"proto2"])
14140             .unwrap();
14141         config.set_initial_max_data(12000);
14142         config.set_initial_max_stream_data_bidi_local(20000);
14143         config.set_initial_max_stream_data_bidi_remote(20000);
14144         config.set_max_recv_udp_payload_size(1200);
14145         config.verify_peer(false);
14146 
14147         let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
14148         assert_eq!(pipe.handshake(), Ok(()));
14149 
14150         // Client opens stream 4 and 8.
14151         assert_eq!(pipe.client.stream_send(4, b"a", true), Ok(1));
14152         assert_eq!(pipe.client.stream_send(8, b"b", true), Ok(1));
14153         assert_eq!(pipe.advance(), Ok(()));
14154 
14155         // Server reads stream data.
14156         let mut b = [0; 15];
14157         pipe.server.stream_recv(4, &mut b).unwrap();
14158 
14159         // Server sends stream data close to cwnd (12000).
14160         let buf = [0; 10000];
14161         assert_eq!(pipe.server.stream_send(4, &buf, false), Ok(10000));
14162 
14163         testing::emit_flight(&mut pipe.server).unwrap();
14164 
14165         // Server buffers some data, until send capacity limit reached.
14166         let mut buf = [0; 1200];
14167         assert_eq!(pipe.server.stream_send(4, &buf, false), Ok(1200));
14168         assert_eq!(pipe.server.stream_send(8, &buf, false), Ok(800));
14169         assert_eq!(pipe.server.stream_send(4, &buf, false), Err(Error::Done));
14170 
14171         // Wait for PTO to expire.
14172         let timer = pipe.server.timeout().unwrap();
14173         std::thread::sleep(timer + time::Duration::from_millis(1));
14174 
14175         pipe.server.on_timeout();
14176 
14177         // Server sends PTO probe (not limited to cwnd),
14178         // to update last_tx_data.
14179         let (len, _) = pipe.server.send(&mut buf).unwrap();
14180         assert_eq!(len, 1200);
14181 
14182         // Client sends STOP_SENDING to decrease tx_data
14183         // by unsent data. It will make last_tx_data > tx_data
14184         // and trigger #1232 bug.
14185         let frames = [frame::Frame::StopSending {
14186             stream_id: 4,
14187             error_code: 42,
14188         }];
14189 
14190         let pkt_type = packet::Type::Short;
14191         pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
14192             .unwrap();
14193     }
14194 
14195     /// Tests that when the client provides a new ConnectionId, it eventually
14196     /// reaches the server and notifies the application.
14197     #[test]
send_connection_ids()14198     fn send_connection_ids() {
14199         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14200         config
14201             .load_cert_chain_from_pem_file("examples/cert.crt")
14202             .unwrap();
14203         config
14204             .load_priv_key_from_pem_file("examples/cert.key")
14205             .unwrap();
14206         config
14207             .set_application_protos(&[b"proto1", b"proto2"])
14208             .unwrap();
14209         config.verify_peer(false);
14210         config.set_active_connection_id_limit(3);
14211 
14212         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14213         assert_eq!(pipe.handshake(), Ok(()));
14214 
14215         // So far, there should not have any QUIC event.
14216         assert_eq!(pipe.client.path_event_next(), None);
14217         assert_eq!(pipe.server.path_event_next(), None);
14218         assert_eq!(pipe.client.source_cids_left(), 2);
14219 
14220         let (scid, reset_token) = testing::create_cid_and_reset_token(16);
14221         assert_eq!(pipe.client.new_source_cid(&scid, reset_token, false), Ok(1));
14222 
14223         // Let exchange packets over the connection.
14224         assert_eq!(pipe.advance(), Ok(()));
14225 
14226         // At this point, the server should be notified that it has a new CID.
14227         assert_eq!(pipe.server.available_dcids(), 1);
14228         assert_eq!(pipe.server.path_event_next(), None);
14229         assert_eq!(pipe.client.path_event_next(), None);
14230         assert_eq!(pipe.client.source_cids_left(), 1);
14231 
14232         // Now, a second CID can be provided.
14233         let (scid, reset_token) = testing::create_cid_and_reset_token(16);
14234         assert_eq!(pipe.client.new_source_cid(&scid, reset_token, false), Ok(2));
14235 
14236         // Let exchange packets over the connection.
14237         assert_eq!(pipe.advance(), Ok(()));
14238 
14239         // At this point, the server should be notified that it has a new CID.
14240         assert_eq!(pipe.server.available_dcids(), 2);
14241         assert_eq!(pipe.server.path_event_next(), None);
14242         assert_eq!(pipe.client.path_event_next(), None);
14243         assert_eq!(pipe.client.source_cids_left(), 0);
14244 
14245         // If now the client tries to send another CID, it reports an error
14246         // since it exceeds the limit of active CIDs.
14247         let (scid, reset_token) = testing::create_cid_and_reset_token(16);
14248         assert_eq!(
14249             pipe.client.new_source_cid(&scid, reset_token, false),
14250             Err(Error::IdLimit),
14251         );
14252     }
14253 
14254     #[test]
14255     /// Exercices the handling of NEW_CONNECTION_ID and RETIRE_CONNECTION_ID
14256     /// frames.
connection_id_handling()14257     fn connection_id_handling() {
14258         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14259         config
14260             .load_cert_chain_from_pem_file("examples/cert.crt")
14261             .unwrap();
14262         config
14263             .load_priv_key_from_pem_file("examples/cert.key")
14264             .unwrap();
14265         config
14266             .set_application_protos(&[b"proto1", b"proto2"])
14267             .unwrap();
14268         config.verify_peer(false);
14269         config.set_active_connection_id_limit(2);
14270 
14271         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14272         assert_eq!(pipe.handshake(), Ok(()));
14273 
14274         // So far, there should not have any QUIC event.
14275         assert_eq!(pipe.client.path_event_next(), None);
14276         assert_eq!(pipe.server.path_event_next(), None);
14277         assert_eq!(pipe.client.source_cids_left(), 1);
14278 
14279         let scid = pipe.client.source_id().into_owned();
14280 
14281         let (scid_1, reset_token_1) = testing::create_cid_and_reset_token(16);
14282         assert_eq!(
14283             pipe.client.new_source_cid(&scid_1, reset_token_1, false),
14284             Ok(1)
14285         );
14286 
14287         // Let exchange packets over the connection.
14288         assert_eq!(pipe.advance(), Ok(()));
14289 
14290         // At this point, the server should be notified that it has a new CID.
14291         assert_eq!(pipe.server.available_dcids(), 1);
14292         assert_eq!(pipe.server.path_event_next(), None);
14293         assert_eq!(pipe.client.path_event_next(), None);
14294         assert_eq!(pipe.client.source_cids_left(), 0);
14295 
14296         // Now we assume that the client wants to advertise more source
14297         // Connection IDs than the advertised limit. This is valid if it
14298         // requests its peer to retire enough Connection IDs to fit within the
14299         // limits.
14300 
14301         let (scid_2, reset_token_2) = testing::create_cid_and_reset_token(16);
14302         assert_eq!(
14303             pipe.client.new_source_cid(&scid_2, reset_token_2, true),
14304             Ok(2)
14305         );
14306 
14307         // Let exchange packets over the connection.
14308         assert_eq!(pipe.advance(), Ok(()));
14309 
14310         // At this point, the server still have a spare DCID.
14311         assert_eq!(pipe.server.available_dcids(), 1);
14312         assert_eq!(pipe.server.path_event_next(), None);
14313 
14314         // Client should have received a retired notification.
14315         assert_eq!(pipe.client.retired_scid_next(), Some(scid));
14316         assert_eq!(pipe.client.retired_scid_next(), None);
14317 
14318         assert_eq!(pipe.client.path_event_next(), None);
14319         assert_eq!(pipe.client.source_cids_left(), 0);
14320 
14321         // The active Destination Connection ID of the server should now be the
14322         // one with sequence number 1.
14323         assert_eq!(pipe.server.destination_id(), scid_1);
14324 
14325         // Now tries to experience CID retirement. If the server tries to remove
14326         // non-existing DCIDs, it fails.
14327         assert_eq!(
14328             pipe.server.retire_destination_cid(0),
14329             Err(Error::InvalidState)
14330         );
14331         assert_eq!(
14332             pipe.server.retire_destination_cid(3),
14333             Err(Error::InvalidState)
14334         );
14335 
14336         // Now it removes DCID with sequence 1.
14337         assert_eq!(pipe.server.retire_destination_cid(1), Ok(()));
14338 
14339         // Let exchange packets over the connection.
14340         assert_eq!(pipe.advance(), Ok(()));
14341 
14342         assert_eq!(pipe.server.path_event_next(), None);
14343         assert_eq!(pipe.client.retired_scid_next(), Some(scid_1));
14344         assert_eq!(pipe.client.retired_scid_next(), None);
14345 
14346         assert_eq!(pipe.server.destination_id(), scid_2);
14347         assert_eq!(pipe.server.available_dcids(), 0);
14348 
14349         // Trying to remove the last DCID triggers an error.
14350         assert_eq!(
14351             pipe.server.retire_destination_cid(2),
14352             Err(Error::OutOfIdentifiers)
14353         );
14354     }
14355 
14356     #[test]
lost_connection_id_frames()14357     fn lost_connection_id_frames() {
14358         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14359         config
14360             .load_cert_chain_from_pem_file("examples/cert.crt")
14361             .unwrap();
14362         config
14363             .load_priv_key_from_pem_file("examples/cert.key")
14364             .unwrap();
14365         config
14366             .set_application_protos(&[b"proto1", b"proto2"])
14367             .unwrap();
14368         config.verify_peer(false);
14369         config.set_active_connection_id_limit(2);
14370 
14371         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14372         assert_eq!(pipe.handshake(), Ok(()));
14373 
14374         let scid = pipe.client.source_id().into_owned();
14375 
14376         let (scid_1, reset_token_1) = testing::create_cid_and_reset_token(16);
14377         assert_eq!(
14378             pipe.client.new_source_cid(&scid_1, reset_token_1, false),
14379             Ok(1)
14380         );
14381 
14382         // Packets are sent, but never received.
14383         testing::emit_flight(&mut pipe.client).unwrap();
14384 
14385         // Wait until timer expires. Since the RTT is very low, wait a bit more.
14386         let timer = pipe.client.timeout().unwrap();
14387         std::thread::sleep(timer + time::Duration::from_millis(1));
14388 
14389         pipe.client.on_timeout();
14390 
14391         // Let exchange packets over the connection.
14392         assert_eq!(pipe.advance(), Ok(()));
14393 
14394         // At this point, the server should be notified that it has a new CID.
14395         assert_eq!(pipe.server.available_dcids(), 1);
14396 
14397         // Now the server retires the first Destination CID.
14398         assert_eq!(pipe.server.retire_destination_cid(0), Ok(()));
14399 
14400         // But the packet never reaches the client.
14401         testing::emit_flight(&mut pipe.server).unwrap();
14402 
14403         // Wait until timer expires. Since the RTT is very low, wait a bit more.
14404         let timer = pipe.server.timeout().unwrap();
14405         std::thread::sleep(timer + time::Duration::from_millis(1));
14406 
14407         pipe.server.on_timeout();
14408 
14409         // Let exchange packets over the connection.
14410         assert_eq!(pipe.advance(), Ok(()));
14411 
14412         assert_eq!(pipe.client.retired_scid_next(), Some(scid));
14413         assert_eq!(pipe.client.retired_scid_next(), None);
14414     }
14415 
14416     #[test]
sending_duplicate_scids()14417     fn sending_duplicate_scids() {
14418         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14419         config
14420             .load_cert_chain_from_pem_file("examples/cert.crt")
14421             .unwrap();
14422         config
14423             .load_priv_key_from_pem_file("examples/cert.key")
14424             .unwrap();
14425         config
14426             .set_application_protos(&[b"proto1", b"proto2"])
14427             .unwrap();
14428         config.verify_peer(false);
14429         config.set_active_connection_id_limit(3);
14430 
14431         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14432         assert_eq!(pipe.handshake(), Ok(()));
14433 
14434         let (scid_1, reset_token_1) = testing::create_cid_and_reset_token(16);
14435         assert_eq!(
14436             pipe.client.new_source_cid(&scid_1, reset_token_1, false),
14437             Ok(1)
14438         );
14439         assert_eq!(pipe.advance(), Ok(()));
14440 
14441         // Trying to send the same CID with a different reset token raises an
14442         // InvalidState error.
14443         let reset_token_2 = reset_token_1.wrapping_add(1);
14444         assert_eq!(
14445             pipe.client.new_source_cid(&scid_1, reset_token_2, false),
14446             Err(Error::InvalidState),
14447         );
14448 
14449         // Retrying to send the exact same CID with the same token returns the
14450         // previously assigned CID seq, but without sending anything.
14451         assert_eq!(
14452             pipe.client.new_source_cid(&scid_1, reset_token_1, false),
14453             Ok(1)
14454         );
14455         assert_eq!(pipe.client.ids.has_new_scids(), false);
14456 
14457         // Now retire this new CID.
14458         assert_eq!(pipe.server.retire_destination_cid(1), Ok(()));
14459         assert_eq!(pipe.advance(), Ok(()));
14460 
14461         // It is up to the application to ensure that a given SCID is not reused
14462         // later.
14463         assert_eq!(
14464             pipe.client.new_source_cid(&scid_1, reset_token_1, false),
14465             Ok(2),
14466         );
14467     }
14468 
14469     // Utility function.
pipe_with_exchanged_cids( config: &mut Config, client_scid_len: usize, server_scid_len: usize, additional_cids: usize, ) -> testing::Pipe14470     fn pipe_with_exchanged_cids(
14471         config: &mut Config, client_scid_len: usize, server_scid_len: usize,
14472         additional_cids: usize,
14473     ) -> testing::Pipe {
14474         let mut pipe = testing::Pipe::with_config_and_scid_lengths(
14475             config,
14476             client_scid_len,
14477             server_scid_len,
14478         )
14479         .unwrap();
14480         assert_eq!(pipe.handshake(), Ok(()));
14481 
14482         let mut c_cids = Vec::new();
14483         let mut c_reset_tokens = Vec::new();
14484         let mut s_cids = Vec::new();
14485         let mut s_reset_tokens = Vec::new();
14486 
14487         for i in 0..additional_cids {
14488             if client_scid_len > 0 {
14489                 let (c_cid, c_reset_token) =
14490                     testing::create_cid_and_reset_token(client_scid_len);
14491                 c_cids.push(c_cid);
14492                 c_reset_tokens.push(c_reset_token);
14493 
14494                 assert_eq!(
14495                     pipe.client.new_source_cid(
14496                         &c_cids[i],
14497                         c_reset_tokens[i],
14498                         true
14499                     ),
14500                     Ok(i as u64 + 1)
14501                 );
14502             }
14503 
14504             if server_scid_len > 0 {
14505                 let (s_cid, s_reset_token) =
14506                     testing::create_cid_and_reset_token(server_scid_len);
14507                 s_cids.push(s_cid);
14508                 s_reset_tokens.push(s_reset_token);
14509                 assert_eq!(
14510                     pipe.server.new_source_cid(
14511                         &s_cids[i],
14512                         s_reset_tokens[i],
14513                         true
14514                     ),
14515                     Ok(i as u64 + 1)
14516                 );
14517             }
14518         }
14519 
14520         // Let exchange packets over the connection.
14521         assert_eq!(pipe.advance(), Ok(()));
14522 
14523         if client_scid_len > 0 {
14524             assert_eq!(pipe.server.available_dcids(), additional_cids);
14525         }
14526 
14527         if server_scid_len > 0 {
14528             assert_eq!(pipe.client.available_dcids(), additional_cids);
14529         }
14530 
14531         assert_eq!(pipe.server.path_event_next(), None);
14532         assert_eq!(pipe.client.path_event_next(), None);
14533 
14534         pipe
14535     }
14536 
14537     #[test]
path_validation()14538     fn path_validation() {
14539         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14540         config
14541             .load_cert_chain_from_pem_file("examples/cert.crt")
14542             .unwrap();
14543         config
14544             .load_priv_key_from_pem_file("examples/cert.key")
14545             .unwrap();
14546         config
14547             .set_application_protos(&[b"proto1", b"proto2"])
14548             .unwrap();
14549         config.verify_peer(false);
14550         config.set_active_connection_id_limit(2);
14551 
14552         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14553         assert_eq!(pipe.handshake(), Ok(()));
14554 
14555         let server_addr = testing::Pipe::server_addr();
14556         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
14557 
14558         // We cannot probe a new path if there are not enough identifiers.
14559         assert_eq!(
14560             pipe.client.probe_path(client_addr_2, server_addr),
14561             Err(Error::OutOfIdentifiers)
14562         );
14563 
14564         let (c_cid, c_reset_token) = testing::create_cid_and_reset_token(16);
14565 
14566         assert_eq!(
14567             pipe.client.new_source_cid(&c_cid, c_reset_token, true),
14568             Ok(1)
14569         );
14570 
14571         let (s_cid, s_reset_token) = testing::create_cid_and_reset_token(16);
14572         assert_eq!(
14573             pipe.server.new_source_cid(&s_cid, s_reset_token, true),
14574             Ok(1)
14575         );
14576 
14577         // We need to exchange the CIDs first.
14578         assert_eq!(
14579             pipe.client.probe_path(client_addr_2, server_addr),
14580             Err(Error::OutOfIdentifiers)
14581         );
14582 
14583         // Let exchange packets over the connection.
14584         assert_eq!(pipe.advance(), Ok(()));
14585 
14586         assert_eq!(pipe.server.available_dcids(), 1);
14587         assert_eq!(pipe.server.path_event_next(), None);
14588         assert_eq!(pipe.client.available_dcids(), 1);
14589         assert_eq!(pipe.client.path_event_next(), None);
14590 
14591         // Now the path probing can work.
14592         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14593 
14594         // But the server cannot probe a yet-unseen path.
14595         assert_eq!(
14596             pipe.server.probe_path(server_addr, client_addr_2),
14597             Err(Error::InvalidState),
14598         );
14599 
14600         assert_eq!(pipe.advance(), Ok(()));
14601 
14602         // The path should be validated at some point.
14603         assert_eq!(
14604             pipe.client.path_event_next(),
14605             Some(PathEvent::Validated(client_addr_2, server_addr)),
14606         );
14607         assert_eq!(pipe.client.path_event_next(), None);
14608 
14609         // The server should be notified of this new path.
14610         assert_eq!(
14611             pipe.server.path_event_next(),
14612             Some(PathEvent::New(server_addr, client_addr_2)),
14613         );
14614         assert_eq!(
14615             pipe.server.path_event_next(),
14616             Some(PathEvent::Validated(server_addr, client_addr_2)),
14617         );
14618         assert_eq!(pipe.server.path_event_next(), None);
14619 
14620         // The server can later probe the path again.
14621         assert_eq!(pipe.server.probe_path(server_addr, client_addr_2), Ok(1));
14622 
14623         // This should not trigger any event at client side.
14624         assert_eq!(pipe.client.path_event_next(), None);
14625         assert_eq!(pipe.server.path_event_next(), None);
14626     }
14627 
14628     #[test]
losing_probing_packets()14629     fn losing_probing_packets() {
14630         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14631         config
14632             .load_cert_chain_from_pem_file("examples/cert.crt")
14633             .unwrap();
14634         config
14635             .load_priv_key_from_pem_file("examples/cert.key")
14636             .unwrap();
14637         config
14638             .set_application_protos(&[b"proto1", b"proto2"])
14639             .unwrap();
14640         config.verify_peer(false);
14641         config.set_active_connection_id_limit(2);
14642 
14643         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
14644 
14645         let server_addr = testing::Pipe::server_addr();
14646         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
14647         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14648 
14649         // The client creates the PATH CHALLENGE, but it is lost.
14650         testing::emit_flight(&mut pipe.client).unwrap();
14651 
14652         // Wait until probing timer expires. Since the RTT is very low,
14653         // wait a bit more.
14654         let probed_pid = pipe
14655             .client
14656             .paths
14657             .path_id_from_addrs(&(client_addr_2, server_addr))
14658             .unwrap();
14659         let probe_instant = pipe
14660             .client
14661             .paths
14662             .get(probed_pid)
14663             .unwrap()
14664             .recovery
14665             .loss_detection_timer()
14666             .unwrap();
14667         let timer = probe_instant.duration_since(time::Instant::now());
14668         std::thread::sleep(timer + time::Duration::from_millis(1));
14669 
14670         pipe.client.on_timeout();
14671 
14672         assert_eq!(pipe.advance(), Ok(()));
14673 
14674         // The path should be validated at some point.
14675         assert_eq!(
14676             pipe.client.path_event_next(),
14677             Some(PathEvent::Validated(client_addr_2, server_addr))
14678         );
14679         assert_eq!(pipe.client.path_event_next(), None);
14680 
14681         assert_eq!(
14682             pipe.server.path_event_next(),
14683             Some(PathEvent::New(server_addr, client_addr_2))
14684         );
14685         // The path should be validated at some point.
14686         assert_eq!(
14687             pipe.server.path_event_next(),
14688             Some(PathEvent::Validated(server_addr, client_addr_2))
14689         );
14690         assert_eq!(pipe.server.path_event_next(), None);
14691     }
14692 
14693     #[test]
failed_path_validation()14694     fn failed_path_validation() {
14695         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14696         config
14697             .load_cert_chain_from_pem_file("examples/cert.crt")
14698             .unwrap();
14699         config
14700             .load_priv_key_from_pem_file("examples/cert.key")
14701             .unwrap();
14702         config
14703             .set_application_protos(&[b"proto1", b"proto2"])
14704             .unwrap();
14705         config.verify_peer(false);
14706         config.set_active_connection_id_limit(2);
14707 
14708         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
14709 
14710         let server_addr = testing::Pipe::server_addr();
14711         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
14712         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14713 
14714         for _ in 0..MAX_PROBING_TIMEOUTS {
14715             // The client creates the PATH CHALLENGE, but it is always lost.
14716             testing::emit_flight(&mut pipe.client).unwrap();
14717 
14718             // Wait until probing timer expires. Since the RTT is very low,
14719             // wait a bit more.
14720             let probed_pid = pipe
14721                 .client
14722                 .paths
14723                 .path_id_from_addrs(&(client_addr_2, server_addr))
14724                 .unwrap();
14725             let probe_instant = pipe
14726                 .client
14727                 .paths
14728                 .get(probed_pid)
14729                 .unwrap()
14730                 .recovery
14731                 .loss_detection_timer()
14732                 .unwrap();
14733             let timer = probe_instant.duration_since(time::Instant::now());
14734             std::thread::sleep(timer + time::Duration::from_millis(1));
14735 
14736             pipe.client.on_timeout();
14737         }
14738 
14739         assert_eq!(
14740             pipe.client.path_event_next(),
14741             Some(PathEvent::FailedValidation(client_addr_2, server_addr)),
14742         );
14743     }
14744 
14745     #[test]
client_discard_unknown_address()14746     fn client_discard_unknown_address() {
14747         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14748         config
14749             .load_cert_chain_from_pem_file("examples/cert.crt")
14750             .unwrap();
14751         config
14752             .load_priv_key_from_pem_file("examples/cert.key")
14753             .unwrap();
14754         config
14755             .set_application_protos(&[b"proto1", b"proto2"])
14756             .unwrap();
14757         config.verify_peer(false);
14758         config.set_initial_max_data(30);
14759         config.set_initial_max_stream_data_uni(10);
14760         config.set_initial_max_streams_uni(3);
14761 
14762         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14763         assert_eq!(pipe.handshake(), Ok(()));
14764 
14765         // Server sends stream data.
14766         assert_eq!(pipe.server.stream_send(3, b"a", true), Ok(1));
14767 
14768         let mut flight =
14769             testing::emit_flight(&mut pipe.server).expect("no packet");
14770         // Let's change the address info.
14771         flight
14772             .iter_mut()
14773             .for_each(|(_, si)| si.from = "127.0.0.1:9292".parse().unwrap());
14774         assert_eq!(testing::process_flight(&mut pipe.client, flight), Ok(()));
14775         assert_eq!(pipe.client.paths.len(), 1);
14776     }
14777 
14778     #[test]
path_validation_limited_mtu()14779     fn path_validation_limited_mtu() {
14780         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14781         config
14782             .load_cert_chain_from_pem_file("examples/cert.crt")
14783             .unwrap();
14784         config
14785             .load_priv_key_from_pem_file("examples/cert.key")
14786             .unwrap();
14787         config
14788             .set_application_protos(&[b"proto1", b"proto2"])
14789             .unwrap();
14790         config.verify_peer(false);
14791         config.set_active_connection_id_limit(2);
14792 
14793         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
14794 
14795         let server_addr = testing::Pipe::server_addr();
14796         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
14797         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14798         // Limited MTU of 1199 bytes for some reason.
14799         testing::process_flight(
14800             &mut pipe.server,
14801             testing::emit_flight_with_max_buffer(&mut pipe.client, 1199)
14802                 .expect("no packet"),
14803         )
14804         .expect("error when processing client packets");
14805         testing::process_flight(
14806             &mut pipe.client,
14807             testing::emit_flight(&mut pipe.server).expect("no packet"),
14808         )
14809         .expect("error when processing client packets");
14810         let probed_pid = pipe
14811             .client
14812             .paths
14813             .path_id_from_addrs(&(client_addr_2, server_addr))
14814             .unwrap();
14815         assert_eq!(
14816             pipe.client.paths.get(probed_pid).unwrap().validated(),
14817             false,
14818         );
14819         assert_eq!(pipe.client.path_event_next(), None);
14820         // Now let the client probe at its MTU.
14821         assert_eq!(pipe.advance(), Ok(()));
14822         assert_eq!(pipe.client.paths.get(probed_pid).unwrap().validated(), true);
14823         assert_eq!(
14824             pipe.client.path_event_next(),
14825             Some(PathEvent::Validated(client_addr_2, server_addr))
14826         );
14827     }
14828 
14829     #[test]
path_probing_dos()14830     fn path_probing_dos() {
14831         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14832         config
14833             .load_cert_chain_from_pem_file("examples/cert.crt")
14834             .unwrap();
14835         config
14836             .load_priv_key_from_pem_file("examples/cert.key")
14837             .unwrap();
14838         config
14839             .set_application_protos(&[b"proto1", b"proto2"])
14840             .unwrap();
14841         config.verify_peer(false);
14842         config.set_active_connection_id_limit(2);
14843 
14844         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
14845 
14846         let server_addr = testing::Pipe::server_addr();
14847         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
14848         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14849 
14850         assert_eq!(pipe.advance(), Ok(()));
14851 
14852         // The path should be validated at some point.
14853         assert_eq!(
14854             pipe.client.path_event_next(),
14855             Some(PathEvent::Validated(client_addr_2, server_addr))
14856         );
14857         assert_eq!(pipe.client.path_event_next(), None);
14858 
14859         // The server should be notified of this new path.
14860         assert_eq!(
14861             pipe.server.path_event_next(),
14862             Some(PathEvent::New(server_addr, client_addr_2))
14863         );
14864         assert_eq!(
14865             pipe.server.path_event_next(),
14866             Some(PathEvent::Validated(server_addr, client_addr_2))
14867         );
14868         assert_eq!(pipe.server.path_event_next(), None);
14869 
14870         assert_eq!(pipe.server.paths.len(), 2);
14871 
14872         // Now forge a packet reusing the unverified path's CID over another
14873         // 4-tuple.
14874         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14875         let client_addr_3 = "127.0.0.1:9012".parse().unwrap();
14876         let mut flight =
14877             testing::emit_flight(&mut pipe.client).expect("no generated packet");
14878         flight
14879             .iter_mut()
14880             .for_each(|(_, si)| si.from = client_addr_3);
14881         testing::process_flight(&mut pipe.server, flight)
14882             .expect("failed to process");
14883         assert_eq!(pipe.server.paths.len(), 2);
14884         assert_eq!(
14885             pipe.server.path_event_next(),
14886             Some(PathEvent::ReusedSourceConnectionId(
14887                 1,
14888                 (server_addr, client_addr_2),
14889                 (server_addr, client_addr_3)
14890             ))
14891         );
14892         assert_eq!(pipe.server.path_event_next(), None);
14893     }
14894 
14895     #[test]
retiring_active_path_dcid()14896     fn retiring_active_path_dcid() {
14897         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14898         config
14899             .load_cert_chain_from_pem_file("examples/cert.crt")
14900             .unwrap();
14901         config
14902             .load_priv_key_from_pem_file("examples/cert.key")
14903             .unwrap();
14904         config
14905             .set_application_protos(&[b"proto1", b"proto2"])
14906             .unwrap();
14907         config.verify_peer(false);
14908         config.set_active_connection_id_limit(2);
14909 
14910         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
14911         let server_addr = testing::Pipe::server_addr();
14912         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
14913         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14914 
14915         assert_eq!(
14916             pipe.client.retire_destination_cid(0),
14917             Err(Error::OutOfIdentifiers)
14918         );
14919     }
14920 
14921     #[test]
send_on_path_test()14922     fn send_on_path_test() {
14923         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14924         config
14925             .load_cert_chain_from_pem_file("examples/cert.crt")
14926             .unwrap();
14927         config
14928             .load_priv_key_from_pem_file("examples/cert.key")
14929             .unwrap();
14930         config
14931             .set_application_protos(&[b"proto1", b"proto2"])
14932             .unwrap();
14933         config.verify_peer(false);
14934         config.set_initial_max_data(100000);
14935         config.set_initial_max_stream_data_bidi_local(100000);
14936         config.set_initial_max_stream_data_bidi_remote(100000);
14937         config.set_initial_max_streams_bidi(2);
14938         config.set_active_connection_id_limit(4);
14939 
14940         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 3);
14941 
14942         let server_addr = testing::Pipe::server_addr();
14943         let client_addr = testing::Pipe::client_addr();
14944         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
14945         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
14946 
14947         let mut buf = [0; 65535];
14948         // There is nothing to send on the initial path.
14949         assert_eq!(
14950             pipe.client.send_on_path(
14951                 &mut buf,
14952                 Some(client_addr),
14953                 Some(server_addr)
14954             ),
14955             Err(Error::Done)
14956         );
14957         // Client should send padded PATH_CHALLENGE.
14958         let (sent, si) = pipe
14959             .client
14960             .send_on_path(&mut buf, Some(client_addr_2), Some(server_addr))
14961             .expect("No error");
14962         assert_eq!(sent, MIN_CLIENT_INITIAL_LEN);
14963         assert_eq!(si.from, client_addr_2);
14964         assert_eq!(si.to, server_addr);
14965         // A non-existing 4-tuple raises an InvalidState.
14966         let client_addr_3 = "127.0.0.1:9012".parse().unwrap();
14967         let server_addr_2 = "127.0.0.1:9876".parse().unwrap();
14968         assert_eq!(
14969             pipe.client.send_on_path(
14970                 &mut buf,
14971                 Some(client_addr_3),
14972                 Some(server_addr)
14973             ),
14974             Err(Error::InvalidState)
14975         );
14976         assert_eq!(
14977             pipe.client.send_on_path(
14978                 &mut buf,
14979                 Some(client_addr),
14980                 Some(server_addr_2)
14981             ),
14982             Err(Error::InvalidState)
14983         );
14984 
14985         // Let's introduce some additional path challenges and data exchange.
14986         assert_eq!(pipe.client.probe_path(client_addr, server_addr_2), Ok(2));
14987         assert_eq!(pipe.client.probe_path(client_addr_3, server_addr), Ok(3));
14988         // Just to fit in two packets.
14989         assert_eq!(pipe.client.stream_send(0, &buf[..1201], true), Ok(1201));
14990 
14991         // PATH_CHALLENGE
14992         let (sent, si) = pipe
14993             .client
14994             .send_on_path(&mut buf, Some(client_addr), None)
14995             .expect("No error");
14996         assert_eq!(sent, MIN_CLIENT_INITIAL_LEN);
14997         assert_eq!(si.from, client_addr);
14998         assert_eq!(si.to, server_addr_2);
14999         // STREAM frame on active path.
15000         let (_, si) = pipe
15001             .client
15002             .send_on_path(&mut buf, Some(client_addr), None)
15003             .expect("No error");
15004         assert_eq!(si.from, client_addr);
15005         assert_eq!(si.to, server_addr);
15006         // PATH_CHALLENGE
15007         let (sent, si) = pipe
15008             .client
15009             .send_on_path(&mut buf, None, Some(server_addr))
15010             .expect("No error");
15011         assert_eq!(sent, MIN_CLIENT_INITIAL_LEN);
15012         assert_eq!(si.from, client_addr_3);
15013         assert_eq!(si.to, server_addr);
15014         // STREAM frame on active path.
15015         let (_, si) = pipe
15016             .client
15017             .send_on_path(&mut buf, None, Some(server_addr))
15018             .expect("No error");
15019         assert_eq!(si.from, client_addr);
15020         assert_eq!(si.to, server_addr);
15021 
15022         // No more data to exchange leads to Error::Done.
15023         assert_eq!(
15024             pipe.client.send_on_path(&mut buf, Some(client_addr), None),
15025             Err(Error::Done)
15026         );
15027         assert_eq!(
15028             pipe.client.send_on_path(&mut buf, None, Some(server_addr)),
15029             Err(Error::Done)
15030         );
15031 
15032         assert_eq!(
15033             pipe.client
15034                 .paths_iter(client_addr)
15035                 .collect::<Vec<_>>()
15036                 .sort(),
15037             vec![server_addr, server_addr_2].sort(),
15038         );
15039         assert_eq!(
15040             pipe.client
15041                 .paths_iter(client_addr_2)
15042                 .collect::<Vec<_>>()
15043                 .sort(),
15044             vec![server_addr].sort(),
15045         );
15046         assert_eq!(
15047             pipe.client
15048                 .paths_iter(client_addr_3)
15049                 .collect::<Vec<_>>()
15050                 .sort(),
15051             vec![server_addr].sort(),
15052         );
15053     }
15054 
15055     #[test]
connection_migration()15056     fn connection_migration() {
15057         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15058         config
15059             .load_cert_chain_from_pem_file("examples/cert.crt")
15060             .unwrap();
15061         config
15062             .load_priv_key_from_pem_file("examples/cert.key")
15063             .unwrap();
15064         config
15065             .set_application_protos(&[b"proto1", b"proto2"])
15066             .unwrap();
15067         config.verify_peer(false);
15068         config.set_active_connection_id_limit(3);
15069         config.set_initial_max_data(30);
15070         config.set_initial_max_stream_data_bidi_local(15);
15071         config.set_initial_max_stream_data_bidi_remote(15);
15072         config.set_initial_max_stream_data_uni(10);
15073         config.set_initial_max_streams_bidi(3);
15074 
15075         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 2);
15076 
15077         let server_addr = testing::Pipe::server_addr();
15078         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
15079         let client_addr_3 = "127.0.0.1:9012".parse().unwrap();
15080         let client_addr_4 = "127.0.0.1:8908".parse().unwrap();
15081 
15082         // Case 1: the client first probes the new address, the server too, and
15083         // then migrates.
15084         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
15085         assert_eq!(pipe.advance(), Ok(()));
15086         assert_eq!(
15087             pipe.client.path_event_next(),
15088             Some(PathEvent::Validated(client_addr_2, server_addr))
15089         );
15090         assert_eq!(pipe.client.path_event_next(), None);
15091         assert_eq!(
15092             pipe.server.path_event_next(),
15093             Some(PathEvent::New(server_addr, client_addr_2))
15094         );
15095         assert_eq!(
15096             pipe.server.path_event_next(),
15097             Some(PathEvent::Validated(server_addr, client_addr_2))
15098         );
15099         assert_eq!(
15100             pipe.client.is_path_validated(client_addr_2, server_addr),
15101             Ok(true)
15102         );
15103         assert_eq!(
15104             pipe.server.is_path_validated(server_addr, client_addr_2),
15105             Ok(true)
15106         );
15107         // The server can never initiates the connection migration.
15108         assert_eq!(
15109             pipe.server.migrate(server_addr, client_addr_2),
15110             Err(Error::InvalidState)
15111         );
15112         assert_eq!(pipe.client.migrate(client_addr_2, server_addr), Ok(1));
15113         assert_eq!(pipe.client.stream_send(0, b"data", true), Ok(4));
15114         assert_eq!(pipe.advance(), Ok(()));
15115         assert_eq!(
15116             pipe.client
15117                 .paths
15118                 .get_active()
15119                 .expect("no active")
15120                 .local_addr(),
15121             client_addr_2
15122         );
15123         assert_eq!(
15124             pipe.client
15125                 .paths
15126                 .get_active()
15127                 .expect("no active")
15128                 .peer_addr(),
15129             server_addr
15130         );
15131         assert_eq!(
15132             pipe.server.path_event_next(),
15133             Some(PathEvent::PeerMigrated(server_addr, client_addr_2))
15134         );
15135         assert_eq!(pipe.server.path_event_next(), None);
15136         assert_eq!(
15137             pipe.server
15138                 .paths
15139                 .get_active()
15140                 .expect("no active")
15141                 .local_addr(),
15142             server_addr
15143         );
15144         assert_eq!(
15145             pipe.server
15146                 .paths
15147                 .get_active()
15148                 .expect("no active")
15149                 .peer_addr(),
15150             client_addr_2
15151         );
15152 
15153         // Case 2: the client migrates on a path that was not previously
15154         // validated, and has spare SCIDs/DCIDs to do so.
15155         assert_eq!(pipe.client.migrate(client_addr_3, server_addr), Ok(2));
15156         assert_eq!(pipe.client.stream_send(4, b"data", true), Ok(4));
15157         assert_eq!(pipe.advance(), Ok(()));
15158         assert_eq!(
15159             pipe.client
15160                 .paths
15161                 .get_active()
15162                 .expect("no active")
15163                 .local_addr(),
15164             client_addr_3
15165         );
15166         assert_eq!(
15167             pipe.client
15168                 .paths
15169                 .get_active()
15170                 .expect("no active")
15171                 .peer_addr(),
15172             server_addr
15173         );
15174         assert_eq!(
15175             pipe.server.path_event_next(),
15176             Some(PathEvent::New(server_addr, client_addr_3))
15177         );
15178         assert_eq!(
15179             pipe.server.path_event_next(),
15180             Some(PathEvent::Validated(server_addr, client_addr_3))
15181         );
15182         assert_eq!(
15183             pipe.server.path_event_next(),
15184             Some(PathEvent::PeerMigrated(server_addr, client_addr_3))
15185         );
15186         assert_eq!(pipe.server.path_event_next(), None);
15187         assert_eq!(
15188             pipe.server
15189                 .paths
15190                 .get_active()
15191                 .expect("no active")
15192                 .local_addr(),
15193             server_addr
15194         );
15195         assert_eq!(
15196             pipe.server
15197                 .paths
15198                 .get_active()
15199                 .expect("no active")
15200                 .peer_addr(),
15201             client_addr_3
15202         );
15203 
15204         // Case 3: the client tries to migrate on the current active path.
15205         // This is not an error, but it triggers nothing.
15206         assert_eq!(pipe.client.migrate(client_addr_3, server_addr), Ok(2));
15207         assert_eq!(pipe.client.stream_send(8, b"data", true), Ok(4));
15208         assert_eq!(pipe.advance(), Ok(()));
15209         assert_eq!(pipe.client.path_event_next(), None);
15210         assert_eq!(
15211             pipe.client
15212                 .paths
15213                 .get_active()
15214                 .expect("no active")
15215                 .local_addr(),
15216             client_addr_3
15217         );
15218         assert_eq!(
15219             pipe.client
15220                 .paths
15221                 .get_active()
15222                 .expect("no active")
15223                 .peer_addr(),
15224             server_addr
15225         );
15226         assert_eq!(pipe.server.path_event_next(), None);
15227         assert_eq!(
15228             pipe.server
15229                 .paths
15230                 .get_active()
15231                 .expect("no active")
15232                 .local_addr(),
15233             server_addr
15234         );
15235         assert_eq!(
15236             pipe.server
15237                 .paths
15238                 .get_active()
15239                 .expect("no active")
15240                 .peer_addr(),
15241             client_addr_3
15242         );
15243 
15244         // Case 4: the client tries to migrate on a path that was not previously
15245         // validated, and has no spare SCIDs/DCIDs. Prevent active migration.
15246         assert_eq!(
15247             pipe.client.migrate(client_addr_4, server_addr),
15248             Err(Error::OutOfIdentifiers)
15249         );
15250         assert_eq!(
15251             pipe.client
15252                 .paths
15253                 .get_active()
15254                 .expect("no active")
15255                 .local_addr(),
15256             client_addr_3
15257         );
15258         assert_eq!(
15259             pipe.client
15260                 .paths
15261                 .get_active()
15262                 .expect("no active")
15263                 .peer_addr(),
15264             server_addr
15265         );
15266     }
15267 
15268     #[test]
connection_migration_zero_length_cid()15269     fn connection_migration_zero_length_cid() {
15270         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15271         config
15272             .load_cert_chain_from_pem_file("examples/cert.crt")
15273             .unwrap();
15274         config
15275             .load_priv_key_from_pem_file("examples/cert.key")
15276             .unwrap();
15277         config
15278             .set_application_protos(&[b"proto1", b"proto2"])
15279             .unwrap();
15280         config.verify_peer(false);
15281         config.set_active_connection_id_limit(2);
15282         config.set_initial_max_data(30);
15283         config.set_initial_max_stream_data_bidi_local(15);
15284         config.set_initial_max_stream_data_bidi_remote(15);
15285         config.set_initial_max_stream_data_uni(10);
15286         config.set_initial_max_streams_bidi(3);
15287 
15288         let mut pipe = pipe_with_exchanged_cids(&mut config, 0, 16, 1);
15289 
15290         let server_addr = testing::Pipe::server_addr();
15291         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
15292 
15293         // The client migrates on a path that was not previously
15294         // validated, and has spare SCIDs/DCIDs to do so.
15295         assert_eq!(pipe.client.migrate(client_addr_2, server_addr), Ok(1));
15296         assert_eq!(pipe.client.stream_send(4, b"data", true), Ok(4));
15297         assert_eq!(pipe.advance(), Ok(()));
15298         assert_eq!(
15299             pipe.client
15300                 .paths
15301                 .get_active()
15302                 .expect("no active")
15303                 .local_addr(),
15304             client_addr_2
15305         );
15306         assert_eq!(
15307             pipe.client
15308                 .paths
15309                 .get_active()
15310                 .expect("no active")
15311                 .peer_addr(),
15312             server_addr
15313         );
15314         assert_eq!(
15315             pipe.server.path_event_next(),
15316             Some(PathEvent::New(server_addr, client_addr_2))
15317         );
15318         assert_eq!(
15319             pipe.server.path_event_next(),
15320             Some(PathEvent::Validated(server_addr, client_addr_2))
15321         );
15322         assert_eq!(
15323             pipe.server.path_event_next(),
15324             Some(PathEvent::PeerMigrated(server_addr, client_addr_2))
15325         );
15326         assert_eq!(pipe.server.path_event_next(), None);
15327         assert_eq!(
15328             pipe.server
15329                 .paths
15330                 .get_active()
15331                 .expect("no active")
15332                 .local_addr(),
15333             server_addr
15334         );
15335         assert_eq!(
15336             pipe.server
15337                 .paths
15338                 .get_active()
15339                 .expect("no active")
15340                 .peer_addr(),
15341             client_addr_2
15342         );
15343     }
15344 
15345     #[test]
connection_migration_reordered_non_probing()15346     fn connection_migration_reordered_non_probing() {
15347         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15348         config
15349             .load_cert_chain_from_pem_file("examples/cert.crt")
15350             .unwrap();
15351         config
15352             .load_priv_key_from_pem_file("examples/cert.key")
15353             .unwrap();
15354         config
15355             .set_application_protos(&[b"proto1", b"proto2"])
15356             .unwrap();
15357         config.verify_peer(false);
15358         config.set_active_connection_id_limit(2);
15359         config.set_initial_max_data(30);
15360         config.set_initial_max_stream_data_bidi_local(15);
15361         config.set_initial_max_stream_data_bidi_remote(15);
15362         config.set_initial_max_stream_data_uni(10);
15363         config.set_initial_max_streams_bidi(3);
15364 
15365         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
15366 
15367         let client_addr = testing::Pipe::client_addr();
15368         let server_addr = testing::Pipe::server_addr();
15369         let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
15370 
15371         assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
15372         assert_eq!(pipe.advance(), Ok(()));
15373         assert_eq!(
15374             pipe.client.path_event_next(),
15375             Some(PathEvent::Validated(client_addr_2, server_addr))
15376         );
15377         assert_eq!(pipe.client.path_event_next(), None);
15378         assert_eq!(
15379             pipe.server.path_event_next(),
15380             Some(PathEvent::New(server_addr, client_addr_2))
15381         );
15382         assert_eq!(
15383             pipe.server.path_event_next(),
15384             Some(PathEvent::Validated(server_addr, client_addr_2))
15385         );
15386         assert_eq!(pipe.server.path_event_next(), None);
15387 
15388         // A first flight sent from secondary address.
15389         assert_eq!(pipe.client.stream_send(0, b"data", true), Ok(4));
15390         let mut first = testing::emit_flight(&mut pipe.client).unwrap();
15391         first.iter_mut().for_each(|(_, si)| si.from = client_addr_2);
15392         // A second one, but sent from the original one.
15393         assert_eq!(pipe.client.stream_send(4, b"data", true), Ok(4));
15394         let second = testing::emit_flight(&mut pipe.client).unwrap();
15395         // Second flight is received before first one.
15396         assert_eq!(testing::process_flight(&mut pipe.server, second), Ok(()));
15397         assert_eq!(testing::process_flight(&mut pipe.server, first), Ok(()));
15398 
15399         // Server does not perform connection migration because of packet
15400         // reordering.
15401         assert_eq!(pipe.server.path_event_next(), None);
15402         assert_eq!(
15403             pipe.server
15404                 .paths
15405                 .get_active()
15406                 .expect("no active")
15407                 .peer_addr(),
15408             client_addr
15409         );
15410     }
15411 
15412     #[test]
resilience_against_migration_attack()15413     fn resilience_against_migration_attack() {
15414         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15415         config
15416             .load_cert_chain_from_pem_file("examples/cert.crt")
15417             .unwrap();
15418         config
15419             .load_priv_key_from_pem_file("examples/cert.key")
15420             .unwrap();
15421         config
15422             .set_application_protos(&[b"proto1", b"proto2"])
15423             .unwrap();
15424         config.verify_peer(false);
15425         config.set_active_connection_id_limit(3);
15426         config.set_initial_max_data(100000);
15427         config.set_initial_max_stream_data_bidi_local(100000);
15428         config.set_initial_max_stream_data_bidi_remote(100000);
15429         config.set_initial_max_streams_bidi(2);
15430 
15431         let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
15432 
15433         let client_addr = testing::Pipe::client_addr();
15434         let server_addr = testing::Pipe::server_addr();
15435         let spoofed_client_addr = "127.0.0.1:6666".parse().unwrap();
15436 
15437         const DATA_BYTES: usize = 24000;
15438         let buf = [42; DATA_BYTES];
15439         let mut recv_buf = [0; DATA_BYTES];
15440         assert_eq!(pipe.server.stream_send(1, &buf, true), Ok(12000));
15441         assert_eq!(
15442             testing::process_flight(
15443                 &mut pipe.client,
15444                 testing::emit_flight(&mut pipe.server).unwrap()
15445             ),
15446             Ok(())
15447         );
15448         let (rcv_data_1, _) = pipe.client.stream_recv(1, &mut recv_buf).unwrap();
15449 
15450         // Fake the source address of client.
15451         let mut faked_addr_flight =
15452             testing::emit_flight(&mut pipe.client).unwrap();
15453         faked_addr_flight
15454             .iter_mut()
15455             .for_each(|(_, si)| si.from = spoofed_client_addr);
15456         assert_eq!(
15457             testing::process_flight(&mut pipe.server, faked_addr_flight),
15458             Ok(())
15459         );
15460         assert_eq!(pipe.server.stream_send(1, &buf[12000..], true), Ok(12000));
15461         assert_eq!(
15462             pipe.server.path_event_next(),
15463             Some(PathEvent::ReusedSourceConnectionId(
15464                 0,
15465                 (server_addr, client_addr),
15466                 (server_addr, spoofed_client_addr)
15467             ))
15468         );
15469         assert_eq!(
15470             pipe.server.path_event_next(),
15471             Some(PathEvent::New(server_addr, spoofed_client_addr))
15472         );
15473 
15474         assert_eq!(
15475             pipe.server.is_path_validated(server_addr, client_addr),
15476             Ok(true)
15477         );
15478         assert_eq!(
15479             pipe.server
15480                 .is_path_validated(server_addr, spoofed_client_addr),
15481             Ok(false)
15482         );
15483 
15484         // The client creates the PATH CHALLENGE, but it is always lost.
15485         testing::emit_flight(&mut pipe.server).unwrap();
15486 
15487         // Wait until probing timer expires. Since the RTT is very low,
15488         // wait a bit more.
15489         let probed_pid = pipe
15490             .server
15491             .paths
15492             .path_id_from_addrs(&(server_addr, spoofed_client_addr))
15493             .unwrap();
15494         let probe_instant = pipe
15495             .server
15496             .paths
15497             .get(probed_pid)
15498             .unwrap()
15499             .recovery
15500             .loss_detection_timer()
15501             .unwrap();
15502         let timer = probe_instant.duration_since(time::Instant::now());
15503         std::thread::sleep(timer + time::Duration::from_millis(1));
15504 
15505         pipe.server.on_timeout();
15506 
15507         // Because of the small ACK size, the server cannot send more to the
15508         // client. Fallback on the previous active path.
15509         assert_eq!(
15510             pipe.server.path_event_next(),
15511             Some(PathEvent::FailedValidation(
15512                 server_addr,
15513                 spoofed_client_addr
15514             ))
15515         );
15516 
15517         assert_eq!(
15518             pipe.server.is_path_validated(server_addr, client_addr),
15519             Ok(true)
15520         );
15521         assert_eq!(
15522             pipe.server
15523                 .is_path_validated(server_addr, spoofed_client_addr),
15524             Ok(false)
15525         );
15526 
15527         let server_active_path = pipe.server.paths.get_active().unwrap();
15528         assert_eq!(server_active_path.local_addr(), server_addr);
15529         assert_eq!(server_active_path.peer_addr(), client_addr);
15530         assert_eq!(pipe.advance(), Ok(()));
15531         let (rcv_data_2, fin) =
15532             pipe.client.stream_recv(1, &mut recv_buf).unwrap();
15533         assert_eq!(fin, true);
15534         assert_eq!(rcv_data_1 + rcv_data_2, DATA_BYTES);
15535     }
15536 
15537     #[test]
consecutive_non_ack_eliciting()15538     fn consecutive_non_ack_eliciting() {
15539         let mut buf = [0; 65535];
15540 
15541         let mut pipe = testing::Pipe::new().unwrap();
15542         assert_eq!(pipe.handshake(), Ok(()));
15543 
15544         // Client sends a bunch of PING frames, causing server to ACK (ACKs aren't
15545         // ack-eliciting)
15546         let frames = [frame::Frame::Ping];
15547         let pkt_type = packet::Type::Short;
15548         for _ in 0..24 {
15549             let len = pipe
15550                 .send_pkt_to_server(pkt_type, &frames, &mut buf)
15551                 .unwrap();
15552             assert!(len > 0);
15553 
15554             let frames =
15555                 testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
15556             assert!(
15557                 frames
15558                     .iter()
15559                     .all(|frame| matches!(frame, frame::Frame::ACK { .. })),
15560                 "ACK only"
15561             );
15562         }
15563 
15564         // After 24 non-ack-eliciting, an ACK is explicitly elicited with a PING
15565         let len = pipe
15566             .send_pkt_to_server(pkt_type, &frames, &mut buf)
15567             .unwrap();
15568         assert!(len > 0);
15569 
15570         let frames =
15571             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
15572         assert!(
15573             frames
15574                 .iter()
15575                 .any(|frame| matches!(frame, frame::Frame::Ping)),
15576             "found a PING"
15577         );
15578     }
15579 
15580     #[test]
send_ack_eliciting_causes_ping()15581     fn send_ack_eliciting_causes_ping() {
15582         // First establish a connection
15583         let mut pipe = testing::Pipe::new().unwrap();
15584         assert_eq!(pipe.handshake(), Ok(()));
15585 
15586         // Queue a PING frame
15587         pipe.server.send_ack_eliciting().unwrap();
15588 
15589         // Make sure ping is sent
15590         let mut buf = [0; 1500];
15591         let (len, _) = pipe.server.send(&mut buf).unwrap();
15592 
15593         let frames =
15594             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
15595         let mut iter = frames.iter();
15596 
15597         assert_eq!(iter.next(), Some(&frame::Frame::Ping));
15598     }
15599 
15600     #[test]
send_ack_eliciting_no_ping()15601     fn send_ack_eliciting_no_ping() {
15602         // First establish a connection
15603         let mut pipe = testing::Pipe::new().unwrap();
15604         assert_eq!(pipe.handshake(), Ok(()));
15605 
15606         // Queue a PING frame
15607         pipe.server.send_ack_eliciting().unwrap();
15608 
15609         // Send a stream frame, which is ACK-eliciting to make sure the ping is
15610         // not sent
15611         assert_eq!(pipe.server.stream_send(1, b"a", false), Ok(1));
15612 
15613         // Make sure ping is not sent
15614         let mut buf = [0; 1500];
15615         let (len, _) = pipe.server.send(&mut buf).unwrap();
15616 
15617         let frames =
15618             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
15619         let mut iter = frames.iter();
15620 
15621         assert!(matches!(
15622             iter.next(),
15623             Some(&frame::Frame::Stream {
15624                 stream_id: 1,
15625                 data: _
15626             })
15627         ));
15628         assert!(iter.next().is_none());
15629     }
15630 
15631     /// Tests that streams do not keep being "writable" after being collected
15632     /// on reset.
15633     #[test]
stop_sending_stream_send_after_reset_stream_ack()15634     fn stop_sending_stream_send_after_reset_stream_ack() {
15635         let mut b = [0; 15];
15636 
15637         let mut buf = [0; 65535];
15638 
15639         let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15640         config
15641             .load_cert_chain_from_pem_file("examples/cert.crt")
15642             .unwrap();
15643         config
15644             .load_priv_key_from_pem_file("examples/cert.key")
15645             .unwrap();
15646         config
15647             .set_application_protos(&[b"proto1", b"proto2"])
15648             .unwrap();
15649         config.set_initial_max_data(999999999);
15650         config.set_initial_max_stream_data_bidi_local(30);
15651         config.set_initial_max_stream_data_bidi_remote(30);
15652         config.set_initial_max_stream_data_uni(30);
15653         config.set_initial_max_streams_bidi(1000);
15654         config.set_initial_max_streams_uni(0);
15655         config.verify_peer(false);
15656 
15657         let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15658         assert_eq!(pipe.handshake(), Ok(()));
15659 
15660         assert_eq!(pipe.server.streams.len(), 0);
15661         assert_eq!(pipe.server.readable().len(), 0);
15662         assert_eq!(pipe.server.writable().len(), 0);
15663 
15664         // Client opens a load of streams
15665         assert_eq!(pipe.client.stream_send(0, b"hello", true), Ok(5));
15666         assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
15667         assert_eq!(pipe.client.stream_send(8, b"hello", true), Ok(5));
15668         assert_eq!(pipe.client.stream_send(12, b"hello", true), Ok(5));
15669         assert_eq!(pipe.client.stream_send(16, b"hello", true), Ok(5));
15670         assert_eq!(pipe.client.stream_send(20, b"hello", true), Ok(5));
15671         assert_eq!(pipe.client.stream_send(24, b"hello", true), Ok(5));
15672         assert_eq!(pipe.client.stream_send(28, b"hello", true), Ok(5));
15673         assert_eq!(pipe.client.stream_send(32, b"hello", true), Ok(5));
15674         assert_eq!(pipe.client.stream_send(36, b"hello", true), Ok(5));
15675         assert_eq!(pipe.advance(), Ok(()));
15676 
15677         // Server iterators are populated
15678         let mut r = pipe.server.readable();
15679         assert_eq!(r.len(), 10);
15680         assert_eq!(r.next(), Some(28));
15681         assert_eq!(r.next(), Some(12));
15682         assert_eq!(r.next(), Some(24));
15683         assert_eq!(r.next(), Some(8));
15684         assert_eq!(r.next(), Some(36));
15685         assert_eq!(r.next(), Some(20));
15686         assert_eq!(r.next(), Some(4));
15687         assert_eq!(r.next(), Some(32));
15688         assert_eq!(r.next(), Some(16));
15689         assert_eq!(r.next(), Some(0));
15690         assert_eq!(r.next(), None);
15691 
15692         let mut w = pipe.server.writable();
15693         assert_eq!(w.len(), 10);
15694         assert_eq!(w.next(), Some(28));
15695         assert_eq!(w.next(), Some(12));
15696         assert_eq!(w.next(), Some(24));
15697         assert_eq!(w.next(), Some(8));
15698         assert_eq!(w.next(), Some(36));
15699         assert_eq!(w.next(), Some(20));
15700         assert_eq!(w.next(), Some(4));
15701         assert_eq!(w.next(), Some(32));
15702         assert_eq!(w.next(), Some(16));
15703         assert_eq!(w.next(), Some(0));
15704         assert_eq!(w.next(), None);
15705 
15706         // Read one stream
15707         assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, true)));
15708         assert!(pipe.server.stream_finished(0));
15709 
15710         assert_eq!(pipe.server.readable().len(), 9);
15711         assert_eq!(pipe.server.writable().len(), 10);
15712 
15713         assert_eq!(pipe.server.stream_writable(0, 0), Ok(true));
15714 
15715         // Server sends data on stream 0, until blocked.
15716         loop {
15717             if pipe.server.stream_send(0, b"world", false) == Err(Error::Done) {
15718                 break;
15719             }
15720 
15721             assert_eq!(pipe.advance(), Ok(()));
15722         }
15723 
15724         assert_eq!(pipe.server.writable().len(), 9);
15725         assert_eq!(pipe.server.stream_writable(0, 0), Ok(true));
15726 
15727         // Client sends STOP_SENDING.
15728         let frames = [frame::Frame::StopSending {
15729             stream_id: 0,
15730             error_code: 42,
15731         }];
15732 
15733         let pkt_type = packet::Type::Short;
15734         let len = pipe
15735             .send_pkt_to_server(pkt_type, &frames, &mut buf)
15736             .unwrap();
15737 
15738         // Server sent a RESET_STREAM frame in response.
15739         let frames =
15740             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
15741 
15742         let mut iter = frames.iter();
15743 
15744         // Skip ACK frame.
15745         iter.next();
15746 
15747         assert_eq!(
15748             iter.next(),
15749             Some(&frame::Frame::ResetStream {
15750                 stream_id: 0,
15751                 error_code: 42,
15752                 final_size: 30,
15753             })
15754         );
15755 
15756         // Stream 0 is now writable in order to make apps aware of STOP_SENDING
15757         // via returning an error.
15758         let mut w = pipe.server.writable();
15759         assert_eq!(w.len(), 10);
15760 
15761         assert!(w.find(|&s| s == 0).is_some());
15762         assert_eq!(
15763             pipe.server.stream_writable(0, 1),
15764             Err(Error::StreamStopped(42))
15765         );
15766 
15767         assert_eq!(pipe.server.writable().len(), 10);
15768         assert_eq!(pipe.server.streams.len(), 10);
15769 
15770         // Client acks RESET_STREAM frame.
15771         let mut ranges = ranges::RangeSet::default();
15772         ranges.insert(0..12);
15773 
15774         let frames = [frame::Frame::ACK {
15775             ack_delay: 15,
15776             ranges,
15777             ecn_counts: None,
15778         }];
15779 
15780         assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(0));
15781 
15782         // Stream is collected on the server after RESET_STREAM is acked.
15783         assert_eq!(pipe.server.streams.len(), 9);
15784 
15785         // Sending STOP_SENDING again shouldn't trigger RESET_STREAM again.
15786         let frames = [frame::Frame::StopSending {
15787             stream_id: 0,
15788             error_code: 42,
15789         }];
15790 
15791         let len = pipe
15792             .send_pkt_to_server(pkt_type, &frames, &mut buf)
15793             .unwrap();
15794 
15795         let frames =
15796             testing::decode_pkt(&mut pipe.client, &mut buf, len).unwrap();
15797 
15798         assert_eq!(frames.len(), 1);
15799 
15800         match frames.first() {
15801             Some(frame::Frame::ACK { .. }) => (),
15802 
15803             f => panic!("expected ACK frame, got {:?}", f),
15804         };
15805 
15806         assert_eq!(pipe.server.streams.len(), 9);
15807 
15808         // Stream 0 has been collected and must not be writable anymore.
15809         let mut w = pipe.server.writable();
15810         assert_eq!(w.len(), 9);
15811         assert!(w.find(|&s| s == 0).is_none());
15812 
15813         // If we called send before the client ACK of reset stream, it would
15814         // have failed with StreamStopped.
15815         assert_eq!(pipe.server.stream_send(0, b"world", true), Err(Error::Done),);
15816 
15817         // Stream 0 is still not writable.
15818         let mut w = pipe.server.writable();
15819         assert_eq!(w.len(), 9);
15820         assert!(w.find(|&s| s == 0).is_none());
15821     }
15822 }
15823 
15824 pub use crate::packet::ConnectionId;
15825 pub use crate::packet::Header;
15826 pub use crate::packet::Type;
15827 
15828 pub use crate::path::PathEvent;
15829 pub use crate::path::PathStats;
15830 pub use crate::path::SocketAddrIter;
15831 
15832 pub use crate::recovery::CongestionControlAlgorithm;
15833 
15834 pub use crate::stream::StreamIter;
15835 
15836 mod cid;
15837 mod crypto;
15838 mod dgram;
15839 #[cfg(feature = "ffi")]
15840 mod ffi;
15841 mod flowcontrol;
15842 mod frame;
15843 pub mod h3;
15844 mod minmax;
15845 mod packet;
15846 mod path;
15847 mod rand;
15848 mod ranges;
15849 mod recovery;
15850 mod stream;
15851 mod tls;
15852