Skip to main content

quiche/h3/
mod.rs

1// Copyright (C) 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//! HTTP/3 wire protocol and QPACK implementation.
28//!
29//! This module provides a high level API for sending and receiving HTTP/3
30//! requests and responses on top of the QUIC transport protocol.
31//!
32//! ## Connection setup
33//!
34//! HTTP/3 connections require a QUIC transport-layer connection, see
35//! [Connection setup] for a full description of the setup process.
36//!
37//! To use HTTP/3, the QUIC connection must be configured with a suitable
38//! Application Layer Protocol Negotiation (ALPN) Protocol ID:
39//!
40//! ```
41//! let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION)?;
42//! config.set_application_protos(quiche::h3::APPLICATION_PROTOCOL)?;
43//! # Ok::<(), quiche::Error>(())
44//! ```
45//!
46//! The QUIC handshake is driven by [sending] and [receiving] QUIC packets.
47//!
48//! Once the handshake has completed, the first step in establishing an HTTP/3
49//! connection is creating its configuration object:
50//!
51//! ```
52//! let h3_config = quiche::h3::Config::new()?;
53//! # Ok::<(), quiche::h3::Error>(())
54//! ```
55//!
56//! HTTP/3 client and server connections are both created using the
57//! [`with_transport()`] function, the role is inferred from the type of QUIC
58//! connection:
59//!
60//! ```no_run
61//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
62//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
63//! # let peer = "127.0.0.1:1234".parse().unwrap();
64//! # let local = "127.0.0.1:4321".parse().unwrap();
65//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config).unwrap();
66//! # let h3_config = quiche::h3::Config::new()?;
67//! let h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
68//! # Ok::<(), quiche::h3::Error>(())
69//! ```
70//!
71//! ## Sending a request
72//!
73//! An HTTP/3 client can send a request by using the connection's
74//! [`send_request()`] method to queue request headers; [sending] QUIC packets
75//! causes the requests to get sent to the peer:
76//!
77//! ```no_run
78//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
79//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
80//! # let peer = "127.0.0.1:1234".parse().unwrap();
81//! # let local = "127.0.0.1:4321".parse().unwrap();
82//! # let mut conn = quiche::connect(None, &scid, local, peer, &mut config).unwrap();
83//! # let h3_config = quiche::h3::Config::new()?;
84//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
85//! let req = vec![
86//!     quiche::h3::Header::new(b":method", b"GET"),
87//!     quiche::h3::Header::new(b":scheme", b"https"),
88//!     quiche::h3::Header::new(b":authority", b"quic.tech"),
89//!     quiche::h3::Header::new(b":path", b"/"),
90//!     quiche::h3::Header::new(b"user-agent", b"quiche"),
91//! ];
92//!
93//! h3_conn.send_request(&mut conn, &req, true)?;
94//! # Ok::<(), quiche::h3::Error>(())
95//! ```
96//!
97//! An HTTP/3 client can send a request with additional body data by using
98//! the connection's [`send_body()`] method:
99//!
100//! ```no_run
101//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
102//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
103//! # let peer = "127.0.0.1:1234".parse().unwrap();
104//! # let local = "127.0.0.1:4321".parse().unwrap();
105//! # let mut conn = quiche::connect(None, &scid, local, peer, &mut config).unwrap();
106//! # let h3_config = quiche::h3::Config::new()?;
107//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
108//! let req = vec![
109//!     quiche::h3::Header::new(b":method", b"GET"),
110//!     quiche::h3::Header::new(b":scheme", b"https"),
111//!     quiche::h3::Header::new(b":authority", b"quic.tech"),
112//!     quiche::h3::Header::new(b":path", b"/"),
113//!     quiche::h3::Header::new(b"user-agent", b"quiche"),
114//! ];
115//!
116//! let stream_id = h3_conn.send_request(&mut conn, &req, false)?;
117//! h3_conn.send_body(&mut conn, stream_id, b"Hello World!", true)?;
118//! # Ok::<(), quiche::h3::Error>(())
119//! ```
120//!
121//! ## Handling requests and responses
122//!
123//! After [receiving] QUIC packets, HTTP/3 data is processed using the
124//! connection's [`poll()`] method. On success, this returns an [`Event`] object
125//! and an ID corresponding to the stream where the `Event` originated.
126//!
127//! An HTTP/3 server uses [`poll()`] to read requests and responds to them using
128//! [`send_response()`] and [`send_body()`]:
129//!
130//! ```no_run
131//! use quiche::h3::NameValue;
132//!
133//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
134//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
135//! # let peer = "127.0.0.1:1234".parse().unwrap();
136//! # let local = "127.0.0.1:1234".parse().unwrap();
137//! # let mut conn = quiche::accept(&scid, None, local, peer, &mut config).unwrap();
138//! # let h3_config = quiche::h3::Config::new()?;
139//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
140//! loop {
141//!     match h3_conn.poll(&mut conn) {
142//!         Ok((stream_id, quiche::h3::Event::Headers{list, more_frames})) => {
143//!             let mut headers = list.into_iter();
144//!
145//!             // Look for the request's method.
146//!             let method = headers.find(|h| h.name() == b":method").unwrap();
147//!
148//!             // Look for the request's path.
149//!             let path = headers.find(|h| h.name() == b":path").unwrap();
150//!
151//!             if method.value() == b"GET" && path.value() == b"/" {
152//!                 let resp = vec![
153//!                     quiche::h3::Header::new(b":status", 200.to_string().as_bytes()),
154//!                     quiche::h3::Header::new(b"server", b"quiche"),
155//!                 ];
156//!
157//!                 h3_conn.send_response(&mut conn, stream_id, &resp, false)?;
158//!                 h3_conn.send_body(&mut conn, stream_id, b"Hello World!", true)?;
159//!             }
160//!         },
161//!
162//!         Ok((stream_id, quiche::h3::Event::Data)) => {
163//!             // Request body data, handle it.
164//!             # return Ok(());
165//!         },
166//!
167//!         Ok((stream_id, quiche::h3::Event::Finished)) => {
168//!             // Peer terminated stream, handle it.
169//!         },
170//!
171//!         Ok((stream_id, quiche::h3::Event::Reset(err))) => {
172//!             // Peer reset the stream, handle it.
173//!         },
174//!
175//!         Ok((_flow_id, quiche::h3::Event::PriorityUpdate)) => (),
176//!
177//!         Ok((goaway_id, quiche::h3::Event::GoAway)) => {
178//!              // Peer signalled it is going away, handle it.
179//!         },
180//!
181//!         Err(quiche::h3::Error::Done) => {
182//!             // Done reading.
183//!             break;
184//!         },
185//!
186//!         Err(e) => {
187//!             // An error occurred, handle it.
188//!             break;
189//!         },
190//!     }
191//! }
192//! # Ok::<(), quiche::h3::Error>(())
193//! ```
194//!
195//! An HTTP/3 client uses [`poll()`] to read responses:
196//!
197//! ```no_run
198//! use quiche::h3::NameValue;
199//!
200//! # let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
201//! # let scid = quiche::ConnectionId::from_ref(&[0xba; 16]);
202//! # let peer = "127.0.0.1:1234".parse().unwrap();
203//! # let local = "127.0.0.1:1234".parse().unwrap();
204//! # let mut conn = quiche::connect(None, &scid, local, peer, &mut config).unwrap();
205//! # let h3_config = quiche::h3::Config::new()?;
206//! # let mut h3_conn = quiche::h3::Connection::with_transport(&mut conn, &h3_config)?;
207//! loop {
208//!     match h3_conn.poll(&mut conn) {
209//!         Ok((stream_id, quiche::h3::Event::Headers{list, more_frames})) => {
210//!             let status = list.iter().find(|h| h.name() == b":status").unwrap();
211//!             println!("Received {} response on stream {}",
212//!                      std::str::from_utf8(status.value()).unwrap(),
213//!                      stream_id);
214//!         },
215//!
216//!         Ok((stream_id, quiche::h3::Event::Data)) => {
217//!             let mut body = vec![0; 4096];
218//!
219//!             // Consume all body data received on the stream.
220//!             while let Ok(read) =
221//!                 h3_conn.recv_body(&mut conn, stream_id, &mut body)
222//!             {
223//!                 println!("Received {} bytes of payload on stream {}",
224//!                          read, stream_id);
225//!             }
226//!         },
227//!
228//!         Ok((stream_id, quiche::h3::Event::Finished)) => {
229//!             // Peer terminated stream, handle it.
230//!         },
231//!
232//!         Ok((stream_id, quiche::h3::Event::Reset(err))) => {
233//!             // Peer reset the stream, handle it.
234//!         },
235//!
236//!         Ok((_prioritized_element_id, quiche::h3::Event::PriorityUpdate)) => (),
237//!
238//!         Ok((goaway_id, quiche::h3::Event::GoAway)) => {
239//!              // Peer signalled it is going away, handle it.
240//!         },
241//!
242//!         Err(quiche::h3::Error::Done) => {
243//!             // Done reading.
244//!             break;
245//!         },
246//!
247//!         Err(e) => {
248//!             // An error occurred, handle it.
249//!             break;
250//!         },
251//!     }
252//! }
253//! # Ok::<(), quiche::h3::Error>(())
254//! ```
255//!
256//! ## Detecting end of request or response
257//!
258//! A single HTTP/3 request or response may consist of several HEADERS and DATA
259//! frames; it is finished when the QUIC stream is closed. Calling [`poll()`]
260//! repeatedly will generate an [`Event`] for each of these. The application may
261//! use these event to do additional HTTP semantic validation.
262//!
263//! ## HTTP/3 protocol errors
264//!
265//! Quiche is responsible for managing the HTTP/3 connection, ensuring it is in
266//! a correct state and validating all messages received by a peer. This mainly
267//! takes place in the [`poll()`] method. If an HTTP/3 error occurs, quiche will
268//! close the connection and send an appropriate CONNECTION_CLOSE frame to the
269//! peer. An [`Error`] is returned to the application so that it can perform any
270//! required tidy up such as closing sockets.
271//!
272//! [`application_proto()`]: ../struct.Connection.html#method.application_proto
273//! [`stream_finished()`]: ../struct.Connection.html#method.stream_finished
274//! [Connection setup]: ../index.html#connection-setup
275//! [sending]: ../index.html#generating-outgoing-packets
276//! [receiving]: ../index.html#handling-incoming-packets
277//! [`with_transport()`]: struct.Connection.html#method.with_transport
278//! [`poll()`]: struct.Connection.html#method.poll
279//! [`Event`]: enum.Event.html
280//! [`Error`]: enum.Error.html
281//! [`send_request()`]: struct.Connection.html#method.send_response
282//! [`send_response()`]: struct.Connection.html#method.send_response
283//! [`send_body()`]: struct.Connection.html#method.send_body
284
285use std::collections::hash_map;
286use std::collections::HashSet;
287use std::collections::VecDeque;
288
289#[cfg(feature = "sfv")]
290use std::convert::TryFrom;
291use std::fmt;
292use std::fmt::Write;
293
294#[cfg(feature = "qlog")]
295use qlog::events::http3::FrameCreated;
296#[cfg(feature = "qlog")]
297use qlog::events::http3::FrameParsed;
298#[cfg(feature = "qlog")]
299use qlog::events::http3::Http3EventType;
300#[cfg(feature = "qlog")]
301use qlog::events::http3::Http3Frame;
302#[cfg(feature = "qlog")]
303use qlog::events::http3::Initiator;
304#[cfg(feature = "qlog")]
305use qlog::events::http3::StreamType;
306#[cfg(feature = "qlog")]
307use qlog::events::http3::StreamTypeSet;
308#[cfg(feature = "qlog")]
309use qlog::events::EventData;
310#[cfg(feature = "qlog")]
311use qlog::events::EventImportance;
312#[cfg(feature = "qlog")]
313use qlog::events::EventType;
314
315use crate::buffers::BufFactory;
316use crate::BufSplit;
317
318/// List of ALPN tokens of supported HTTP/3 versions.
319///
320/// This can be passed directly to the [`Config::set_application_protos()`]
321/// method when implementing HTTP/3 applications.
322///
323/// [`Config::set_application_protos()`]:
324/// ../struct.Config.html#method.set_application_protos
325pub const APPLICATION_PROTOCOL: &[&[u8]] = &[b"h3"];
326
327// The offset used when converting HTTP/3 urgency to quiche urgency.
328const PRIORITY_URGENCY_OFFSET: u8 = 124;
329
330// Parameter values as specified in [Extensible Priorities].
331//
332// [Extensible Priorities]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
333const PRIORITY_URGENCY_LOWER_BOUND: u8 = 0;
334const PRIORITY_URGENCY_UPPER_BOUND: u8 = 7;
335const PRIORITY_URGENCY_DEFAULT: u8 = 3;
336const PRIORITY_INCREMENTAL_DEFAULT: bool = false;
337
338/// The default value for the maximum size of PRIORITY_UPDATE
339/// frame payload.
340///
341/// See <https://datatracker.ietf.org/doc/html/rfc9218#section-7.2>
342pub const PRIORITY_UPDATE_FRAME_PAYLOAD_MAX_SIZE_DEFAULT: u64 = 256;
343
344/// The default value for SETTINGS_MAX_FIELD_SECTION_SIZE
345///
346/// See <https://datatracker.ietf.org/doc/html/rfc9114#section-4.2.2>.
347pub const SETTINGS_MAX_FIELD_SECTION_SIZE_DEFAULT: u64 = 32_768;
348
349#[cfg(feature = "qlog")]
350const QLOG_FRAME_CREATED: EventType =
351    EventType::Http3EventType(Http3EventType::FrameCreated);
352#[cfg(feature = "qlog")]
353const QLOG_FRAME_PARSED: EventType =
354    EventType::Http3EventType(Http3EventType::FrameParsed);
355#[cfg(feature = "qlog")]
356const QLOG_STREAM_TYPE_SET: EventType =
357    EventType::Http3EventType(Http3EventType::StreamTypeSet);
358
359/// A specialized [`Result`] type for quiche HTTP/3 operations.
360///
361/// This type is used throughout quiche's HTTP/3 public API for any operation
362/// that can produce an error.
363///
364/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
365pub type Result<T> = std::result::Result<T, Error>;
366
367/// An HTTP/3 error.
368#[derive(Clone, Copy, Debug, PartialEq, Eq)]
369pub enum Error {
370    /// There is no error or no work to do
371    Done,
372
373    /// The provided buffer is too short.
374    BufferTooShort,
375
376    /// Internal error in the HTTP/3 stack.
377    InternalError,
378
379    /// Endpoint detected that the peer is exhibiting behavior that causes.
380    /// excessive load.
381    ExcessiveLoad,
382
383    /// Stream ID or Push ID greater that current maximum was
384    /// used incorrectly, such as exceeding a limit, reducing a limit,
385    /// or being reused.
386    IdError,
387
388    /// The endpoint detected that its peer created a stream that it will not
389    /// accept.
390    StreamCreationError,
391
392    /// A required critical stream was closed.
393    ClosedCriticalStream,
394
395    /// No SETTINGS frame at beginning of control stream.
396    MissingSettings,
397
398    /// A frame was received which is not permitted in the current state.
399    FrameUnexpected,
400
401    /// Frame violated layout or size rules.
402    FrameError,
403
404    /// QPACK Header block decompression failure.
405    QpackDecompressionFailed,
406
407    /// Error originated from the transport layer.
408    TransportError(crate::Error),
409
410    /// The underlying QUIC stream (or connection) doesn't have enough capacity
411    /// for the operation to complete. The application should retry later on.
412    StreamBlocked,
413
414    /// Error in the payload of a SETTINGS frame.
415    SettingsError,
416
417    /// Server rejected request.
418    RequestRejected,
419
420    /// Request or its response cancelled.
421    RequestCancelled,
422
423    /// Client's request stream terminated without containing a full-formed
424    /// request.
425    RequestIncomplete,
426
427    /// An HTTP message was malformed and cannot be processed.
428    MessageError,
429
430    /// The TCP connection established in response to a CONNECT request was
431    /// reset or abnormally closed.
432    ConnectError,
433
434    /// The requested operation cannot be served over HTTP/3. Peer should retry
435    /// over HTTP/1.1.
436    VersionFallback,
437}
438
439/// HTTP/3 error codes sent on the wire.
440///
441/// As defined in [RFC9114](https://www.rfc-editor.org/rfc/rfc9114.html#http-error-codes).
442#[derive(Copy, Clone, Debug, Eq, PartialEq)]
443pub enum WireErrorCode {
444    /// No error. This is used when the connection or stream needs to be closed,
445    /// but there is no error to signal.
446    NoError              = 0x100,
447    /// Peer violated protocol requirements in a way that does not match a more
448    /// specific error code or endpoint declines to use the more specific
449    /// error code.
450    GeneralProtocolError = 0x101,
451    /// An internal error has occurred in the HTTP stack.
452    InternalError        = 0x102,
453    /// The endpoint detected that its peer created a stream that it will not
454    /// accept.
455    StreamCreationError  = 0x103,
456    /// A stream required by the HTTP/3 connection was closed or reset.
457    ClosedCriticalStream = 0x104,
458    /// A frame was received that was not permitted in the current state or on
459    /// the current stream.
460    FrameUnexpected      = 0x105,
461    /// A frame that fails to satisfy layout requirements or with an invalid
462    /// size was received.
463    FrameError           = 0x106,
464    /// The endpoint detected that its peer is exhibiting a behavior that might
465    /// be generating excessive load.
466    ExcessiveLoad        = 0x107,
467    /// A stream ID or push ID was used incorrectly, such as exceeding a limit,
468    /// reducing a limit, or being reused.
469    IdError              = 0x108,
470    /// An endpoint detected an error in the payload of a SETTINGS frame.
471    SettingsError        = 0x109,
472    /// No SETTINGS frame was received at the beginning of the control stream.
473    MissingSettings      = 0x10a,
474    /// A server rejected a request without performing any application
475    /// processing.
476    RequestRejected      = 0x10b,
477    /// The request or its response (including pushed response) is cancelled.
478    RequestCancelled     = 0x10c,
479    /// The client's stream terminated without containing a fully formed
480    /// request.
481    RequestIncomplete    = 0x10d,
482    /// An HTTP message was malformed and cannot be processed.
483    MessageError         = 0x10e,
484    /// The TCP connection established in response to a CONNECT request was
485    /// reset or abnormally closed.
486    ConnectError         = 0x10f,
487    /// The requested operation cannot be served over HTTP/3. The peer should
488    /// retry over HTTP/1.1.
489    VersionFallback      = 0x110,
490}
491
492impl Error {
493    fn to_wire(self) -> u64 {
494        match self {
495            Error::Done => WireErrorCode::NoError as u64,
496            Error::InternalError => WireErrorCode::InternalError as u64,
497            Error::StreamCreationError =>
498                WireErrorCode::StreamCreationError as u64,
499            Error::ClosedCriticalStream =>
500                WireErrorCode::ClosedCriticalStream as u64,
501            Error::FrameUnexpected => WireErrorCode::FrameUnexpected as u64,
502            Error::FrameError => WireErrorCode::FrameError as u64,
503            Error::ExcessiveLoad => WireErrorCode::ExcessiveLoad as u64,
504            Error::IdError => WireErrorCode::IdError as u64,
505            Error::MissingSettings => WireErrorCode::MissingSettings as u64,
506            Error::QpackDecompressionFailed => 0x200,
507            Error::BufferTooShort => 0x999,
508            Error::TransportError { .. } | Error::StreamBlocked => 0xFF,
509            Error::SettingsError => WireErrorCode::SettingsError as u64,
510            Error::RequestRejected => WireErrorCode::RequestRejected as u64,
511            Error::RequestCancelled => WireErrorCode::RequestCancelled as u64,
512            Error::RequestIncomplete => WireErrorCode::RequestIncomplete as u64,
513            Error::MessageError => WireErrorCode::MessageError as u64,
514            Error::ConnectError => WireErrorCode::ConnectError as u64,
515            Error::VersionFallback => WireErrorCode::VersionFallback as u64,
516        }
517    }
518
519    #[cfg(feature = "ffi")]
520    fn to_c(self) -> libc::ssize_t {
521        match self {
522            Error::Done => -1,
523            Error::BufferTooShort => -2,
524            Error::InternalError => -3,
525            Error::ExcessiveLoad => -4,
526            Error::IdError => -5,
527            Error::StreamCreationError => -6,
528            Error::ClosedCriticalStream => -7,
529            Error::MissingSettings => -8,
530            Error::FrameUnexpected => -9,
531            Error::FrameError => -10,
532            Error::QpackDecompressionFailed => -11,
533            // -12 was previously used for TransportError, skip it
534            Error::StreamBlocked => -13,
535            Error::SettingsError => -14,
536            Error::RequestRejected => -15,
537            Error::RequestCancelled => -16,
538            Error::RequestIncomplete => -17,
539            Error::MessageError => -18,
540            Error::ConnectError => -19,
541            Error::VersionFallback => -20,
542
543            Error::TransportError(quic_error) => quic_error.to_c() - 1000,
544        }
545    }
546}
547
548impl fmt::Display for Error {
549    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
550        write!(f, "{self:?}")
551    }
552}
553
554impl std::error::Error for Error {
555    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
556        None
557    }
558}
559
560impl From<super::Error> for Error {
561    fn from(err: super::Error) -> Self {
562        match err {
563            super::Error::Done => Error::Done,
564
565            _ => Error::TransportError(err),
566        }
567    }
568}
569
570impl From<octets::BufferTooShortError> for Error {
571    fn from(_err: octets::BufferTooShortError) -> Self {
572        Error::BufferTooShort
573    }
574}
575
576/// An HTTP/3 configuration.
577pub struct Config {
578    max_field_section_size: Option<u64>,
579    qpack_max_table_capacity: Option<u64>,
580    qpack_blocked_streams: Option<u64>,
581    connect_protocol_enabled: Option<u64>,
582    /// additional settings are settings that are not part of the H3
583    /// settings explicitly handled above
584    additional_settings: Option<Vec<(u64, u64)>>,
585
586    max_priority_update_size: u64,
587}
588
589impl Config {
590    /// Creates a new configuration object with default settings.
591    pub const fn new() -> Result<Config> {
592        Ok(Config {
593            max_field_section_size: Some(SETTINGS_MAX_FIELD_SECTION_SIZE_DEFAULT),
594            qpack_max_table_capacity: None,
595            qpack_blocked_streams: None,
596            connect_protocol_enabled: None,
597            additional_settings: None,
598            max_priority_update_size:
599                PRIORITY_UPDATE_FRAME_PAYLOAD_MAX_SIZE_DEFAULT,
600        })
601    }
602
603    /// Sets the `SETTINGS_MAX_FIELD_SECTION_SIZE` setting.
604    ///
605    /// The default is [`SETTINGS_MAX_FIELD_SECTION_SIZE_DEFAULT`]. The value is
606    /// measured in units of bytes, it is used as a limit when parsing frames
607    /// that contain encoded HTTP headers when [`poll()`] is called. A first
608    /// check is applied when handling HEADERS and PUSH_PROMISE frames
609    /// themselves, with some margin allowed on top of the provided size. A
610    /// second check is applied when decoding QPACK, implementing the rules
611    /// described in <https://datatracker.ietf.org/doc/html/rfc9114#section-4.2.2>.
612    ///
613    /// When headers exceed the limit set by the application, the call to the
614    /// [`poll()`] method will return the [`Error::ExcessiveLoad`] error, and
615    /// the connection will be closed.
616    ///
617    /// [`poll()`]: struct.Connection.html#method.poll
618    /// [`Error::ExcessiveLoad`]: enum.Error.html#variant.ExcessiveLoad
619    pub fn set_max_field_section_size(&mut self, v: u64) {
620        self.max_field_section_size = Some(v);
621    }
622
623    /// Sets the `SETTINGS_QPACK_MAX_TABLE_CAPACITY` setting.
624    ///
625    /// The default value is `0`.
626    pub fn set_qpack_max_table_capacity(&mut self, v: u64) {
627        self.qpack_max_table_capacity = Some(v);
628    }
629
630    /// Sets the `SETTINGS_QPACK_BLOCKED_STREAMS` setting.
631    ///
632    /// The default value is `0`.
633    pub fn set_qpack_blocked_streams(&mut self, v: u64) {
634        self.qpack_blocked_streams = Some(v);
635    }
636
637    /// Sets or omits the `SETTINGS_ENABLE_CONNECT_PROTOCOL` setting.
638    ///
639    /// The default value is `false`.
640    pub fn enable_extended_connect(&mut self, enabled: bool) {
641        if enabled {
642            self.connect_protocol_enabled = Some(1);
643        } else {
644            self.connect_protocol_enabled = None;
645        }
646    }
647
648    /// Sets additional HTTP/3 settings.
649    ///
650    /// The default value is no additional settings.
651    /// The `additional_settings` parameter must not the following
652    /// settings as they are already handled by this library:
653    ///
654    /// - SETTINGS_QPACK_MAX_TABLE_CAPACITY
655    /// - SETTINGS_MAX_FIELD_SECTION_SIZE
656    /// - SETTINGS_QPACK_BLOCKED_STREAMS
657    /// - SETTINGS_ENABLE_CONNECT_PROTOCOL
658    /// - SETTINGS_H3_DATAGRAM
659    ///
660    /// If such a setting is present in the `additional_settings`,
661    /// the method will return the [`Error::SettingsError`] error.
662    ///
663    /// If a setting identifier is present twice in `additional_settings`,
664    /// the method will return the [`Error::SettingsError`] error.
665    ///
666    /// [`Error::SettingsError`]: enum.Error.html#variant.SettingsError
667    pub fn set_additional_settings(
668        &mut self, additional_settings: Vec<(u64, u64)>,
669    ) -> Result<()> {
670        let explicit_quiche_settings = HashSet::from([
671            frame::SETTINGS_QPACK_MAX_TABLE_CAPACITY,
672            frame::SETTINGS_MAX_FIELD_SECTION_SIZE,
673            frame::SETTINGS_QPACK_BLOCKED_STREAMS,
674            frame::SETTINGS_ENABLE_CONNECT_PROTOCOL,
675            frame::SETTINGS_H3_DATAGRAM,
676            frame::SETTINGS_H3_DATAGRAM_00,
677        ]);
678
679        let dedup_settings: HashSet<u64> =
680            additional_settings.iter().map(|(key, _)| *key).collect();
681
682        if dedup_settings.len() != additional_settings.len() ||
683            !explicit_quiche_settings.is_disjoint(&dedup_settings)
684        {
685            return Err(Error::SettingsError);
686        }
687        self.additional_settings = Some(additional_settings);
688        Ok(())
689    }
690
691    /// Sets the maximum size for the payload of PRIORITY_UPDATE frames.
692    ///
693    /// The default is [`PRIORITY_UPDATE_FRAME_PAYLOAD_MAX_SIZE_DEFAULT`]. The
694    /// value uses units of bytes.
695    ///
696    /// When a PRIORITY_UPDATE frame exceeds the limit set by the application,
697    /// the call to the [`poll()`] method will return the
698    /// [`Error::ExcessiveLoad`] error, and the connection will be closed.
699    ///
700    /// [`poll()`]: struct.Connection.html#method.poll
701    /// [`Error::ExcessiveLoad`]: enum.Error.html#variant.ExcessiveLoad
702    pub fn set_max_priority_update_size(&mut self, v: u64) {
703        self.max_priority_update_size = v;
704    }
705}
706
707/// A trait for types with associated string name and value.
708pub trait NameValue {
709    /// Returns the object's name.
710    fn name(&self) -> &[u8];
711
712    /// Returns the object's value.
713    fn value(&self) -> &[u8];
714}
715
716impl<N, V> NameValue for (N, V)
717where
718    N: AsRef<[u8]>,
719    V: AsRef<[u8]>,
720{
721    fn name(&self) -> &[u8] {
722        self.0.as_ref()
723    }
724
725    fn value(&self) -> &[u8] {
726        self.1.as_ref()
727    }
728}
729
730/// An owned name-value pair representing a raw HTTP header.
731#[derive(Clone, PartialEq, Eq)]
732pub struct Header(Vec<u8>, Vec<u8>);
733
734fn try_print_as_readable(hdr: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
735    match std::str::from_utf8(hdr) {
736        Ok(s) => f.write_str(&s.escape_default().to_string()),
737        Err(_) => write!(f, "{hdr:?}"),
738    }
739}
740
741impl fmt::Debug for Header {
742    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743        f.write_char('"')?;
744        try_print_as_readable(&self.0, f)?;
745        f.write_str(": ")?;
746        try_print_as_readable(&self.1, f)?;
747        f.write_char('"')
748    }
749}
750
751impl Header {
752    /// Creates a new header.
753    ///
754    /// Both `name` and `value` will be cloned.
755    pub fn new(name: &[u8], value: &[u8]) -> Self {
756        Self(name.to_vec(), value.to_vec())
757    }
758}
759
760impl NameValue for Header {
761    fn name(&self) -> &[u8] {
762        &self.0
763    }
764
765    fn value(&self) -> &[u8] {
766        &self.1
767    }
768}
769
770/// A non-owned name-value pair representing a raw HTTP header.
771#[derive(Clone, Debug, PartialEq, Eq)]
772pub struct HeaderRef<'a>(&'a [u8], &'a [u8]);
773
774impl<'a> HeaderRef<'a> {
775    /// Creates a new header.
776    pub const fn new(name: &'a [u8], value: &'a [u8]) -> Self {
777        Self(name, value)
778    }
779}
780
781impl NameValue for HeaderRef<'_> {
782    fn name(&self) -> &[u8] {
783        self.0
784    }
785
786    fn value(&self) -> &[u8] {
787        self.1
788    }
789}
790
791/// An HTTP/3 connection event.
792#[derive(Clone, Debug, PartialEq, Eq)]
793pub enum Event {
794    /// Request/response headers were received.
795    Headers {
796        /// The list of received header fields. The application should validate
797        /// pseudo-headers and headers.
798        list: Vec<Header>,
799
800        /// Whether more frames will follow the headers on the stream.
801        more_frames: bool,
802    },
803
804    /// Data was received.
805    ///
806    /// This indicates that the application can use the [`recv_body()`] method
807    /// to retrieve the data from the stream.
808    ///
809    /// Note that [`recv_body()`] will need to be called repeatedly until the
810    /// [`Done`] value is returned, as the event will not be re-armed until all
811    /// buffered data is read.
812    ///
813    /// [`recv_body()`]: struct.Connection.html#method.recv_body
814    /// [`Done`]: enum.Error.html#variant.Done
815    Data,
816
817    /// Stream was closed,
818    Finished,
819
820    /// Stream was reset.
821    ///
822    /// The associated data represents the error code sent by the peer.
823    Reset(u64),
824
825    /// PRIORITY_UPDATE was received.
826    ///
827    /// This indicates that the application can use the
828    /// [`take_last_priority_update()`] method to take the last received
829    /// PRIORITY_UPDATE for a specified stream.
830    ///
831    /// This event is triggered once per stream until the last PRIORITY_UPDATE
832    /// is taken. It is recommended that applications defer taking the
833    /// PRIORITY_UPDATE until after [`poll()`] returns [`Done`].
834    ///
835    /// [`take_last_priority_update()`]: struct.Connection.html#method.take_last_priority_update
836    /// [`poll()`]: struct.Connection.html#method.poll
837    /// [`Done`]: enum.Error.html#variant.Done
838    PriorityUpdate,
839
840    /// GOAWAY was received.
841    GoAway,
842}
843
844/// Extensible Priorities parameters.
845///
846/// The `TryFrom` trait supports constructing this object from the serialized
847/// Structured Fields Dictionary field value. I.e, use `TryFrom` to parse the
848/// value of a Priority header field or a PRIORITY_UPDATE frame. Using this
849/// trait requires the `sfv` feature to be enabled.
850#[derive(Clone, Copy, Debug, PartialEq, Eq)]
851#[repr(C)]
852pub struct Priority {
853    urgency: u8,
854    incremental: bool,
855}
856
857impl Default for Priority {
858    fn default() -> Self {
859        Priority {
860            urgency: PRIORITY_URGENCY_DEFAULT,
861            incremental: PRIORITY_INCREMENTAL_DEFAULT,
862        }
863    }
864}
865
866impl Priority {
867    /// Creates a new Priority.
868    pub const fn new(urgency: u8, incremental: bool) -> Self {
869        Priority {
870            urgency,
871            incremental,
872        }
873    }
874}
875
876#[cfg(feature = "sfv")]
877#[cfg_attr(docsrs, doc(cfg(feature = "sfv")))]
878impl TryFrom<&[u8]> for Priority {
879    type Error = Error;
880
881    /// Try to parse an Extensible Priority field value.
882    ///
883    /// The field value is expected to be a Structured Fields Dictionary; see
884    /// [Extensible Priorities].
885    ///
886    /// If the `u` or `i` fields are contained with correct types, a constructed
887    /// Priority object is returned. Note that urgency values outside of valid
888    /// range (0 through 7) are clamped to 7.
889    ///
890    /// If the `u` or `i` fields are contained with the wrong types,
891    /// Error::Done is returned.
892    ///
893    /// Omitted parameters will yield default values.
894    ///
895    /// [Extensible Priorities]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
896    fn try_from(value: &[u8]) -> std::result::Result<Self, Self::Error> {
897        let dict = match sfv::Parser::parse_dictionary(value) {
898            Ok(v) => v,
899
900            Err(_) => return Err(Error::Done),
901        };
902
903        let urgency = match dict.get("u") {
904            // If there is a u parameter, try to read it as an Item of type
905            // Integer. If the value out of the spec's allowed range
906            // (0 through 7), that's an error so set it to the upper
907            // bound (lowest priority) to avoid interference with
908            // other streams.
909            Some(sfv::ListEntry::Item(item)) => match item.bare_item.as_int() {
910                Some(v) => {
911                    if !(PRIORITY_URGENCY_LOWER_BOUND as i64..=
912                        PRIORITY_URGENCY_UPPER_BOUND as i64)
913                        .contains(&v)
914                    {
915                        PRIORITY_URGENCY_UPPER_BOUND
916                    } else {
917                        v as u8
918                    }
919                },
920
921                None => return Err(Error::Done),
922            },
923
924            Some(sfv::ListEntry::InnerList(_)) => return Err(Error::Done),
925
926            // Omitted so use default value.
927            None => PRIORITY_URGENCY_DEFAULT,
928        };
929
930        let incremental = match dict.get("i") {
931            Some(sfv::ListEntry::Item(item)) =>
932                item.bare_item.as_bool().ok_or(Error::Done)?,
933
934            // Omitted so use default value.
935            _ => false,
936        };
937
938        Ok(Priority::new(urgency, incremental))
939    }
940}
941
942struct ConnectionSettings {
943    pub max_field_section_size: Option<u64>,
944    pub qpack_max_table_capacity: Option<u64>,
945    pub qpack_blocked_streams: Option<u64>,
946    pub connect_protocol_enabled: Option<u64>,
947    pub h3_datagram: Option<u64>,
948    pub additional_settings: Option<Vec<(u64, u64)>>,
949    pub raw: Option<Vec<(u64, u64)>>,
950}
951
952#[derive(Default)]
953struct QpackStreams {
954    pub encoder_stream_id: Option<u64>,
955    pub encoder_stream_bytes: u64,
956    pub decoder_stream_id: Option<u64>,
957    pub decoder_stream_bytes: u64,
958}
959
960/// Statistics about the connection.
961///
962/// A connection's statistics can be collected using the [`stats()`] method.
963///
964/// [`stats()`]: struct.Connection.html#method.stats
965#[derive(Clone, Default)]
966#[non_exhaustive]
967pub struct Stats {
968    /// The number of bytes received on the QPACK encoder stream.
969    pub qpack_encoder_stream_recv_bytes: u64,
970    /// The number of bytes received on the QPACK decoder stream.
971    pub qpack_decoder_stream_recv_bytes: u64,
972}
973
974fn close_conn_critical_stream<F: BufFactory>(
975    conn: &mut super::Connection<F>,
976) -> Result<()> {
977    conn.close(
978        true,
979        Error::ClosedCriticalStream.to_wire(),
980        b"Critical stream closed.",
981    )?;
982
983    Err(Error::ClosedCriticalStream)
984}
985
986fn close_conn_if_critical_stream_finished<F: BufFactory>(
987    conn: &mut super::Connection<F>, stream_id: u64,
988) -> Result<()> {
989    if conn.stream_finished(stream_id) {
990        close_conn_critical_stream(conn)?;
991    }
992
993    Ok(())
994}
995
996/// An HTTP/3 connection.
997pub struct Connection {
998    is_server: bool,
999
1000    next_request_stream_id: u64,
1001    next_uni_stream_id: u64,
1002
1003    streams: crate::stream::StreamIdHashMap<stream::Stream>,
1004
1005    local_settings: ConnectionSettings,
1006    peer_settings: ConnectionSettings,
1007
1008    control_stream_id: Option<u64>,
1009    peer_control_stream_id: Option<u64>,
1010
1011    qpack_encoder: qpack::Encoder,
1012    qpack_decoder: qpack::Decoder,
1013
1014    local_qpack_streams: QpackStreams,
1015    peer_qpack_streams: QpackStreams,
1016
1017    max_push_id: u64,
1018
1019    // Streams whose peer send side has finished and still need a Finished
1020    // event. If the local send side is already done, poll() removes the H3
1021    // stream state when returning the event. Otherwise the send path removes it
1022    // when the local side finishes later.
1023    finished_streams: VecDeque<u64>,
1024
1025    frames_greased: bool,
1026
1027    local_goaway_id: Option<u64>,
1028    peer_goaway_id: Option<u64>,
1029
1030    max_priority_update_size: u64,
1031}
1032
1033impl Connection {
1034    fn new(
1035        config: &Config, is_server: bool, enable_dgram: bool,
1036    ) -> Result<Connection> {
1037        let initial_uni_stream_id = if is_server { 0x3 } else { 0x2 };
1038        let h3_datagram = if enable_dgram { Some(1) } else { None };
1039
1040        Ok(Connection {
1041            is_server,
1042
1043            next_request_stream_id: 0,
1044
1045            next_uni_stream_id: initial_uni_stream_id,
1046
1047            streams: Default::default(),
1048
1049            local_settings: ConnectionSettings {
1050                max_field_section_size: config.max_field_section_size,
1051                qpack_max_table_capacity: config.qpack_max_table_capacity,
1052                qpack_blocked_streams: config.qpack_blocked_streams,
1053                connect_protocol_enabled: config.connect_protocol_enabled,
1054                h3_datagram,
1055                additional_settings: config.additional_settings.clone(),
1056                raw: Default::default(),
1057            },
1058
1059            peer_settings: ConnectionSettings {
1060                max_field_section_size: None,
1061                qpack_max_table_capacity: None,
1062                qpack_blocked_streams: None,
1063                h3_datagram: None,
1064                connect_protocol_enabled: None,
1065                additional_settings: Default::default(),
1066                raw: Default::default(),
1067            },
1068
1069            control_stream_id: None,
1070            peer_control_stream_id: None,
1071
1072            qpack_encoder: qpack::Encoder::new(),
1073            qpack_decoder: qpack::Decoder::new(),
1074
1075            local_qpack_streams: Default::default(),
1076            peer_qpack_streams: Default::default(),
1077
1078            max_push_id: 0,
1079
1080            finished_streams: VecDeque::new(),
1081
1082            frames_greased: false,
1083
1084            local_goaway_id: None,
1085            peer_goaway_id: None,
1086
1087            max_priority_update_size: config.max_priority_update_size,
1088        })
1089    }
1090
1091    /// Creates a new HTTP/3 connection using the provided QUIC connection.
1092    ///
1093    /// This will also initiate the HTTP/3 handshake with the peer by opening
1094    /// all control streams (including QPACK) and sending the local settings.
1095    ///
1096    /// On success the new connection is returned.
1097    ///
1098    /// The [`StreamLimit`] error is returned when the HTTP/3 control stream
1099    /// cannot be created due to stream limits.
1100    ///
1101    /// The [`InternalError`] error is returned when either the underlying QUIC
1102    /// connection is not in a suitable state, or the HTTP/3 control stream
1103    /// cannot be created due to flow control limits.
1104    ///
1105    /// [`StreamLimit`]: ../enum.Error.html#variant.StreamLimit
1106    /// [`InternalError`]: ../enum.Error.html#variant.InternalError
1107    pub fn with_transport<F: BufFactory>(
1108        conn: &mut super::Connection<F>, config: &Config,
1109    ) -> Result<Connection> {
1110        let is_client = !conn.is_server;
1111        if is_client && !(conn.is_established() || conn.is_in_early_data()) {
1112            trace!("{} QUIC connection must be established or in early data before creating an HTTP/3 connection", conn.trace_id());
1113            return Err(Error::InternalError);
1114        }
1115
1116        let mut http3_conn =
1117            Connection::new(config, conn.is_server, conn.dgram_enabled())?;
1118
1119        match http3_conn.send_settings(conn) {
1120            Ok(_) => (),
1121
1122            Err(e) => {
1123                conn.close(true, e.to_wire(), b"Error opening control stream")?;
1124                return Err(e);
1125            },
1126        };
1127
1128        // Try opening QPACK streams, but ignore errors if it fails since we
1129        // don't need them right now.
1130        http3_conn.open_qpack_encoder_stream(conn).ok();
1131        http3_conn.open_qpack_decoder_stream(conn).ok();
1132
1133        if conn.grease {
1134            // Try opening a GREASE stream, but ignore errors since it's not
1135            // critical.
1136            http3_conn.open_grease_stream(conn).ok();
1137        }
1138
1139        Ok(http3_conn)
1140    }
1141
1142    /// Sends an HTTP/3 request.
1143    ///
1144    /// The request is encoded from the provided list of headers without a
1145    /// body, and sent on a newly allocated stream. To include a body,
1146    /// set `fin` as `false` and subsequently call [`send_body()`] with the
1147    /// same `conn` and the `stream_id` returned from this method.
1148    ///
1149    /// On success the newly allocated stream ID is returned.
1150    ///
1151    /// The [`StreamBlocked`] error is returned when the underlying QUIC stream
1152    /// doesn't have enough capacity for the operation to complete. When this
1153    /// happens the application should retry the **entire** `send_request` call
1154    /// once the stream is reported as writable again. Any partial state created
1155    /// by the failed call is rolled back, so repeating the call with the same
1156    /// arguments is safe.
1157    ///
1158    /// [`send_body()`]: struct.Connection.html#method.send_body
1159    /// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
1160    pub fn send_request<T: NameValue, F: BufFactory>(
1161        &mut self, conn: &mut super::Connection<F>, headers: &[T], fin: bool,
1162    ) -> Result<u64> {
1163        // If we received a GOAWAY from the peer, MUST NOT initiate new
1164        // requests.
1165        if self.peer_goaway_id.is_some() {
1166            return Err(Error::FrameUnexpected);
1167        }
1168
1169        let stream_id = self.next_request_stream_id;
1170
1171        self.streams.insert(
1172            stream_id,
1173            <stream::Stream>::new(
1174                stream_id,
1175                true,
1176                self.local_settings
1177                    .max_field_section_size
1178                    .unwrap_or(SETTINGS_MAX_FIELD_SECTION_SIZE_DEFAULT),
1179                self.max_priority_update_size,
1180            ),
1181        );
1182
1183        // The underlying QUIC stream does not exist yet, so calls to e.g.
1184        // stream_capacity() will fail. By writing a 0-length buffer, we force
1185        // the creation of the QUIC stream state, without actually writing
1186        // anything.
1187        if let Err(e) = conn.stream_send(stream_id, b"", false) {
1188            self.streams.remove(&stream_id);
1189
1190            if e == super::Error::Done {
1191                return Err(Error::StreamBlocked);
1192            }
1193
1194            return Err(e.into());
1195        };
1196
1197        if let Err(e) = self.send_headers(conn, stream_id, headers, fin) {
1198            // If the stream was blocked before any header bytes were written,
1199            // the QUIC stream exists but carries no H3 data yet. Roll back the
1200            // H3-layer stream entry so the stream ID is not consumed and a
1201            // subsequent retry of `send_request` starts from a clean state,
1202            // consistent with the `StreamBlocked` path above.
1203            if e == Error::StreamBlocked {
1204                self.streams.remove(&stream_id);
1205            }
1206
1207            return Err(e);
1208        }
1209
1210        // To avoid skipping stream IDs, we only calculate the next available
1211        // stream ID when a request has been successfully buffered.
1212        self.next_request_stream_id = self
1213            .next_request_stream_id
1214            .checked_add(4)
1215            .ok_or(Error::IdError)?;
1216
1217        Ok(stream_id)
1218    }
1219
1220    /// Sends an HTTP/3 response on the specified stream with default priority.
1221    ///
1222    /// This method sends the provided `headers` as a single initial response
1223    /// without a body.
1224    ///
1225    /// To send a non-final 1xx, then a final 200+ without body:
1226    ///   * send_response() with `fin` set to `false`.
1227    ///   * [`send_additional_headers()`] with fin set to `true` using the same
1228    ///     `stream_id` value.
1229    ///
1230    /// To send a non-final 1xx, then a final 200+ with body:
1231    ///   * send_response() with `fin` set to `false`.
1232    ///   * [`send_additional_headers()`] with fin set to `false` and same
1233    ///     `stream_id` value.
1234    ///   * [`send_body()`] with same `stream_id`.
1235    ///
1236    /// To send a final 200+ with body:
1237    ///   * send_response() with `fin` set to `false`.
1238    ///   * [`send_body()`] with same `stream_id`.
1239    ///
1240    /// Additional headers can only be sent during certain phases of an HTTP/3
1241    /// message exchange, see [Section 4.1 of RFC 9114]. The [`FrameUnexpected`]
1242    /// error is returned if this method, or [`send_response_with_priority()`],
1243    /// are called multiple times with the same `stream_id` value.
1244    ///
1245    /// The [`StreamBlocked`] error is returned when the underlying QUIC stream
1246    /// doesn't have enough capacity for the operation to complete. When this
1247    /// happens the application should retry the operation once the stream is
1248    /// reported as writable again.
1249    ///
1250    /// [`send_body()`]: struct.Connection.html#method.send_body
1251    /// [`send_additional_headers()`]:
1252    ///     struct.Connection.html#method.send_additional_headers
1253    /// [`send_response_with_priority()`]:
1254    ///     struct.Connection.html#method.send_response_with_priority
1255    /// [`FrameUnexpected`]: enum.Error.html#variant.FrameUnexpected
1256    /// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
1257    pub fn send_response<T: NameValue, F: BufFactory>(
1258        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1259        headers: &[T], fin: bool,
1260    ) -> Result<()> {
1261        let priority = Default::default();
1262
1263        self.send_response_with_priority(
1264            conn, stream_id, headers, &priority, fin,
1265        )?;
1266
1267        Ok(())
1268    }
1269
1270    /// Sends an HTTP/3 response on the specified stream with specified
1271    /// priority.
1272    ///
1273    /// This method sends the provided `headers` as a single initial response
1274    /// without a body.
1275    ///
1276    /// To send a non-final 1xx, then a final 200+ without body:
1277    ///   * send_response_with_priority() with `fin` set to `false`.
1278    ///   * [`send_additional_headers()`] with fin set to `true` using the same
1279    ///     `stream_id` value.
1280    ///
1281    /// To send a non-final 1xx, then a final 200+ with body:
1282    ///   * send_response_with_priority() with `fin` set to `false`.
1283    ///   * [`send_additional_headers()`] with fin set to `false` and same
1284    ///     `stream_id` value.
1285    ///   * [`send_body()`] with same `stream_id`.
1286    ///
1287    /// To send a final 200+ with body:
1288    ///   * send_response_with_priority() with `fin` set to `false`.
1289    ///   * [`send_body()`] with same `stream_id`.
1290    ///
1291    /// The `priority` parameter represents [Extensible Priority]
1292    /// parameters. If the urgency is outside the range 0-7, it will be clamped
1293    /// to 7.
1294    ///
1295    /// Additional headers can only be sent during certain phases of an HTTP/3
1296    /// message exchange, see [Section 4.1 of RFC 9114]. The [`FrameUnexpected`]
1297    /// error is returned if this method, or [`send_response()`],
1298    /// are called multiple times with the same `stream_id` value.
1299    ///
1300    /// The [`StreamBlocked`] error is returned when the underlying QUIC stream
1301    /// doesn't have enough capacity for the operation to complete. When this
1302    /// happens the application should retry the operation once the stream is
1303    /// reported as writable again.
1304    ///
1305    /// [`send_body()`]: struct.Connection.html#method.send_body
1306    /// [`send_additional_headers()`]:
1307    ///     struct.Connection.html#method.send_additional_headers
1308    /// [`send_response()`]:
1309    ///     struct.Connection.html#method.send_response
1310    /// [`FrameUnexpected`]: enum.Error.html#variant.FrameUnexpected
1311    /// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
1312    /// [Extensible Priority]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
1313    pub fn send_response_with_priority<T: NameValue, F: BufFactory>(
1314        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1315        headers: &[T], priority: &Priority, fin: bool,
1316    ) -> Result<()> {
1317        match self.streams.get(&stream_id) {
1318            Some(s) => {
1319                // Only one initial HEADERS allowed.
1320                if s.local_initialized() {
1321                    return Err(Error::FrameUnexpected);
1322                }
1323
1324                s
1325            },
1326
1327            None => return Err(Error::FrameUnexpected),
1328        };
1329
1330        self.send_headers(conn, stream_id, headers, fin)?;
1331
1332        // Clamp and shift urgency into quiche-priority space
1333        let urgency = priority
1334            .urgency
1335            .clamp(PRIORITY_URGENCY_LOWER_BOUND, PRIORITY_URGENCY_UPPER_BOUND) +
1336            PRIORITY_URGENCY_OFFSET;
1337
1338        conn.stream_priority(stream_id, urgency, priority.incremental)?;
1339
1340        Ok(())
1341    }
1342
1343    /// Sends additional HTTP/3 headers.
1344    ///
1345    /// After the initial request or response headers have been sent, using
1346    /// [`send_request()`] or [`send_response()`] respectively, this method can
1347    /// be used send an additional HEADERS frame. For example, to send a single
1348    /// instance of trailers after a request with a body, or to issue another
1349    /// non-final 1xx after a preceding 1xx, or to issue a final response after
1350    /// a preceding 1xx.
1351    ///
1352    /// Additional headers can only be sent during certain phases of an HTTP/3
1353    /// message exchange, see [Section 4.1 of RFC 9114]. The [`FrameUnexpected`]
1354    /// error is returned when this method is called during the wrong phase,
1355    /// such as before initial headers have been sent, or if trailers have
1356    /// already been sent.
1357    ///
1358    /// The [`StreamBlocked`] error is returned when the underlying QUIC stream
1359    /// doesn't have enough capacity for the operation to complete. When this
1360    /// happens the application should retry the operation once the stream is
1361    /// reported as writable again.
1362    ///
1363    /// [`send_request()`]: struct.Connection.html#method.send_request
1364    /// [`send_response()`]: struct.Connection.html#method.send_response
1365    /// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
1366    /// [`FrameUnexpected`]: enum.Error.html#variant.FrameUnexpected
1367    /// [Section 4.1 of RFC 9114]:
1368    ///     https://www.rfc-editor.org/rfc/rfc9114.html#section-4.1.
1369    pub fn send_additional_headers<T: NameValue, F: BufFactory>(
1370        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1371        headers: &[T], is_trailer_section: bool, fin: bool,
1372    ) -> Result<()> {
1373        // Clients can only send trailer headers.
1374        if !self.is_server && !is_trailer_section {
1375            return Err(Error::FrameUnexpected);
1376        }
1377
1378        match self.streams.get(&stream_id) {
1379            Some(s) => {
1380                // Initial HEADERS must have been sent.
1381                if !s.local_initialized() {
1382                    return Err(Error::FrameUnexpected);
1383                }
1384
1385                // Only one trailing HEADERS allowed.
1386                if s.trailers_sent() {
1387                    return Err(Error::FrameUnexpected);
1388                }
1389
1390                s
1391            },
1392
1393            None => return Err(Error::FrameUnexpected),
1394        };
1395
1396        self.send_headers(conn, stream_id, headers, fin)?;
1397
1398        if is_trailer_section {
1399            // send_headers() might have tidied the stream away, so we need to
1400            // check again.
1401            if let Some(s) = self.streams.get_mut(&stream_id) {
1402                s.mark_trailers_sent();
1403            }
1404        }
1405
1406        Ok(())
1407    }
1408
1409    /// Sends additional HTTP/3 headers with specified priority.
1410    ///
1411    /// After the initial request or response headers have been sent, using
1412    /// [`send_request()`] or [`send_response()`] respectively, this method can
1413    /// be used send an additional HEADERS frame. For example, to send a single
1414    /// instance of trailers after a request with a body, or to issue another
1415    /// non-final 1xx after a preceding 1xx, or to issue a final response after
1416    /// a preceding 1xx.
1417    ///
1418    /// The `priority` parameter represents [Extensible Priority]
1419    /// parameters. If the urgency is outside the range 0-7, it will be clamped
1420    /// to 7.
1421    ///
1422    /// Additional headers can only be sent during certain phases of an HTTP/3
1423    /// message exchange, see [Section 4.1 of RFC 9114]. The [`FrameUnexpected`]
1424    /// error is returned when this method is called during the wrong phase,
1425    /// such as before initial headers have been sent, or if trailers have
1426    /// already been sent.
1427    ///
1428    /// The [`StreamBlocked`] error is returned when the underlying QUIC stream
1429    /// doesn't have enough capacity for the operation to complete. When this
1430    /// happens the application should retry the operation once the stream is
1431    /// reported as writable again.
1432    ///
1433    /// [`send_request()`]: struct.Connection.html#method.send_request
1434    /// [`send_response()`]: struct.Connection.html#method.send_response
1435    /// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
1436    /// [`FrameUnexpected`]: enum.Error.html#variant.FrameUnexpected
1437    /// [Section 4.1 of RFC 9114]:
1438    ///     https://www.rfc-editor.org/rfc/rfc9114.html#section-4.1.
1439    /// [Extensible Priority]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
1440    pub fn send_additional_headers_with_priority<T: NameValue, F: BufFactory>(
1441        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1442        headers: &[T], priority: &Priority, is_trailer_section: bool, fin: bool,
1443    ) -> Result<()> {
1444        self.send_additional_headers(
1445            conn,
1446            stream_id,
1447            headers,
1448            is_trailer_section,
1449            fin,
1450        )?;
1451
1452        // Clamp and shift urgency into quiche-priority space
1453        let urgency = priority
1454            .urgency
1455            .clamp(PRIORITY_URGENCY_LOWER_BOUND, PRIORITY_URGENCY_UPPER_BOUND) +
1456            PRIORITY_URGENCY_OFFSET;
1457
1458        conn.stream_priority(stream_id, urgency, priority.incremental)?;
1459
1460        Ok(())
1461    }
1462
1463    fn encode_header_block<T: NameValue>(
1464        &mut self, headers: &[T],
1465    ) -> Result<Vec<u8>> {
1466        let headers_len = headers
1467            .iter()
1468            .fold(0, |acc, h| acc + h.value().len() + h.name().len() + 32);
1469
1470        let mut header_block = vec![0; headers_len];
1471        let len = self
1472            .qpack_encoder
1473            .encode(headers, &mut header_block)
1474            .map_err(|_| Error::InternalError)?;
1475
1476        header_block.truncate(len);
1477
1478        Ok(header_block)
1479    }
1480
1481    fn send_headers<T: NameValue, F: BufFactory>(
1482        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1483        headers: &[T], fin: bool,
1484    ) -> Result<()> {
1485        let mut d = [42; 10];
1486        let mut b = octets::OctetsMut::with_slice(&mut d);
1487
1488        if !self.frames_greased && conn.grease {
1489            self.send_grease_frames(conn, stream_id)?;
1490            self.frames_greased = true;
1491        }
1492
1493        let header_block = self.encode_header_block(headers)?;
1494
1495        let overhead = octets::varint_len(frame::HEADERS_FRAME_TYPE_ID) +
1496            octets::varint_len(header_block.len() as u64);
1497
1498        // Headers need to be sent atomically, so make sure the stream has
1499        // enough capacity.
1500        match conn.stream_writable(stream_id, overhead + header_block.len()) {
1501            Ok(true) => (),
1502
1503            Ok(false) => return Err(Error::StreamBlocked),
1504
1505            Err(e) => {
1506                if conn.stream_finished(stream_id) {
1507                    self.streams.remove(&stream_id);
1508                }
1509
1510                return Err(e.into());
1511            },
1512        };
1513
1514        b.put_varint(frame::HEADERS_FRAME_TYPE_ID)?;
1515        b.put_varint(header_block.len() as u64)?;
1516        let off = b.off();
1517        conn.stream_send(stream_id, &d[..off], false)?;
1518
1519        // Sending header block separately avoids unnecessary copy.
1520        conn.stream_send(stream_id, &header_block, fin)?;
1521
1522        trace!(
1523            "{} tx frm HEADERS stream={} len={} fin={}",
1524            conn.trace_id(),
1525            stream_id,
1526            header_block.len(),
1527            fin
1528        );
1529
1530        qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
1531            let qlog_headers = headers
1532                .iter()
1533                .map(|h| qlog::events::http3::HttpHeader {
1534                    name: Some(String::from_utf8_lossy(h.name()).into_owned()),
1535                    name_bytes: None,
1536                    value: Some(String::from_utf8_lossy(h.value()).into_owned()),
1537                    value_bytes: None,
1538                })
1539                .collect();
1540
1541            let frame = Http3Frame::Headers {
1542                headers: qlog_headers,
1543                raw: None,
1544            };
1545            let ev_data = EventData::Http3FrameCreated(FrameCreated {
1546                stream_id,
1547                length: Some(header_block.len() as u64),
1548                frame,
1549                ..Default::default()
1550            });
1551
1552            q.add_event_data_now(ev_data).ok();
1553        });
1554
1555        if fin {
1556            self.finish_local_stream(conn, stream_id, true);
1557        } else if let Some(s) = self.streams.get_mut(&stream_id) {
1558            s.initialize_local();
1559        }
1560
1561        Ok(())
1562    }
1563
1564    /// Sends an HTTP/3 body chunk on the given stream.
1565    ///
1566    /// On success the number of bytes written is returned, or [`Done`] if no
1567    /// bytes could be written (e.g. because the stream is blocked).
1568    ///
1569    /// Note that the number of written bytes returned can be lower than the
1570    /// length of the input buffer when the underlying QUIC stream doesn't have
1571    /// enough capacity for the operation to complete.
1572    ///
1573    /// When a partial write happens (including when [`Done`] is returned) the
1574    /// application should retry the operation once the stream is reported as
1575    /// writable again.
1576    ///
1577    /// [`Done`]: enum.Error.html#variant.Done
1578    pub fn send_body<F: BufFactory>(
1579        &mut self, conn: &mut super::Connection<F>, stream_id: u64, body: &[u8],
1580        fin: bool,
1581    ) -> Result<usize> {
1582        self.do_send_body(
1583            conn,
1584            stream_id,
1585            body,
1586            fin,
1587            |conn: &mut super::Connection<F>,
1588             header: &[u8],
1589             stream_id: u64,
1590             body: &[u8],
1591             body_len: usize,
1592             fin: bool| {
1593                conn.stream_send(stream_id, header, false)?;
1594                Ok(conn
1595                    .stream_send(stream_id, &body[..body_len], fin)
1596                    .map(|v| (v, v))?)
1597            },
1598        )
1599    }
1600
1601    /// Sends an HTTP/3 body chunk provided as a raw buffer on the given stream.
1602    ///
1603    /// If the capacity allows it the buffer will be appended to the stream's
1604    /// send queue with zero copying.
1605    ///
1606    /// On success the number of bytes written is returned, or [`Done`] if no
1607    /// bytes could be written (e.g. because the stream is blocked).
1608    ///
1609    /// Note that the number of written bytes returned can be lower than the
1610    /// length of the input buffer when the underlying QUIC stream doesn't have
1611    /// enough capacity for the operation to complete.
1612    ///
1613    /// When a partial write happens (including when [`Done`] is returned) the
1614    /// remaining (unwrittent) buffer will also be returned. The application
1615    /// should retry the operation once the stream is reported as writable
1616    /// again.
1617    ///
1618    /// [`Done`]: enum.Error.html#variant.Done
1619    pub fn send_body_zc<F>(
1620        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1621        body: &mut F::Buf, fin: bool,
1622    ) -> Result<usize>
1623    where
1624        F: BufFactory,
1625        F::Buf: BufSplit,
1626    {
1627        self.do_send_body(
1628            conn,
1629            stream_id,
1630            body,
1631            fin,
1632            |conn: &mut super::Connection<F>,
1633             header: &[u8],
1634             stream_id: u64,
1635             body: &mut F::Buf,
1636             mut body_len: usize,
1637             fin: bool| {
1638                let with_prefix = body.try_add_prefix(header);
1639                if !with_prefix {
1640                    conn.stream_send(stream_id, header, false)?;
1641                } else {
1642                    body_len += header.len();
1643                }
1644
1645                let remainder = body.split_at(body_len);
1646                // body now contains the first `body_len` bytes of the original
1647                // buffer
1648                debug_assert_eq!(body.as_ref().len(), body_len);
1649
1650                let (mut n, rem) =
1651                    conn.stream_send_zc(stream_id, body.clone(), fin)?;
1652                if rem.as_ref().is_some_and(|v| !v.as_ref().is_empty()) {
1653                    // `do_send_body()` checked capacity before this write, so
1654                    // `rem` should always be `None` or empty.
1655                    debug_assert!(false);
1656                    return Err(Error::InternalError);
1657                }
1658
1659                if with_prefix {
1660                    n -= header.len();
1661                }
1662
1663                if !remainder.as_ref().is_empty() {
1664                    let _ = std::mem::replace(body, remainder);
1665                }
1666
1667                Ok((n, n))
1668            },
1669        )
1670    }
1671
1672    fn do_send_body<F, B, R, SND>(
1673        &mut self, conn: &mut super::Connection<F>, stream_id: u64, body: B,
1674        fin: bool, write_fn: SND,
1675    ) -> Result<R>
1676    where
1677        F: BufFactory,
1678        B: AsRef<[u8]>,
1679        SND: FnOnce(
1680            &mut super::Connection<F>,
1681            &[u8],
1682            u64,
1683            B,
1684            usize,
1685            bool,
1686        ) -> Result<(usize, R)>,
1687    {
1688        let mut d = [42; 10];
1689        let mut b = octets::OctetsMut::with_slice(&mut d);
1690
1691        let len = body.as_ref().len();
1692
1693        // Validate that it is sane to send data on the stream.
1694        if !stream_id.is_multiple_of(4) {
1695            return Err(Error::FrameUnexpected);
1696        }
1697
1698        match self.streams.get_mut(&stream_id) {
1699            Some(s) => {
1700                if !s.local_initialized() {
1701                    return Err(Error::FrameUnexpected);
1702                }
1703
1704                if s.trailers_sent() {
1705                    return Err(Error::FrameUnexpected);
1706                }
1707            },
1708
1709            None => {
1710                return Err(Error::FrameUnexpected);
1711            },
1712        };
1713
1714        // Avoid sending 0-length DATA frames when the fin flag is false.
1715        if len == 0 && !fin {
1716            return Err(Error::Done);
1717        }
1718
1719        let overhead = octets::varint_len(frame::DATA_FRAME_TYPE_ID) +
1720            octets::varint_len(len as u64);
1721
1722        let stream_cap = match conn.stream_capacity(stream_id) {
1723            Ok(v) => v,
1724
1725            Err(e) => {
1726                if conn.stream_finished(stream_id) {
1727                    self.streams.remove(&stream_id);
1728                }
1729
1730                return Err(e.into());
1731            },
1732        };
1733
1734        // Make sure there is enough capacity to send the DATA frame header.
1735        if stream_cap < overhead {
1736            let _ = conn.stream_writable(stream_id, overhead + 1);
1737            return Err(Error::Done);
1738        }
1739
1740        // Cap the frame payload length to the stream's capacity.
1741        let body_len = std::cmp::min(len, stream_cap - overhead);
1742
1743        // If we can't send the entire body, set the fin flag to false so the
1744        // application can try again later.
1745        let fin = if body_len != len { false } else { fin };
1746
1747        // Again, avoid sending 0-length DATA frames when the fin flag is false.
1748        if body_len == 0 && !fin {
1749            let _ = conn.stream_writable(stream_id, overhead + 1);
1750            return Err(Error::Done);
1751        }
1752
1753        b.put_varint(frame::DATA_FRAME_TYPE_ID)?;
1754        b.put_varint(body_len as u64)?;
1755        let off = b.off();
1756
1757        // Return how many bytes were written, excluding the frame header.
1758        // Sending body separately avoids unnecessary copy.
1759        let (written, ret) =
1760            write_fn(conn, &d[..off], stream_id, body, body_len, fin)?;
1761        if written != body_len {
1762            // This should never happen. If it does, it means we wrote an
1763            // incorrect frame length and thus we can't really continue.
1764            debug_assert!(false);
1765            return Err(Error::InternalError);
1766        }
1767
1768        trace!(
1769            "{} tx frm DATA stream={} len={} fin={}",
1770            conn.trace_id(),
1771            stream_id,
1772            written,
1773            fin
1774        );
1775
1776        qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
1777            let frame = Http3Frame::Data { raw: None };
1778            let ev_data = EventData::Http3FrameCreated(FrameCreated {
1779                stream_id,
1780                length: Some(written as u64),
1781                frame,
1782                ..Default::default()
1783            });
1784
1785            q.add_event_data_now(ev_data).ok();
1786        });
1787
1788        if written < len {
1789            // Ensure the peer is notified that the connection or stream is
1790            // blocked when the stream's capacity is limited by flow control.
1791            //
1792            // We only need enough capacity to send a few bytes, to make sure
1793            // the stream doesn't hang due to congestion window not growing
1794            // enough.
1795            let _ = conn.stream_writable(stream_id, overhead + 1);
1796        }
1797
1798        if fin && written == len {
1799            self.finish_local_stream(conn, stream_id, false);
1800        }
1801
1802        Ok(ret)
1803    }
1804
1805    /// Returns whether the peer enabled HTTP/3 DATAGRAM frame support.
1806    ///
1807    /// Support is signalled by the peer's SETTINGS, so this method always
1808    /// returns false until they have been processed using the [`poll()`]
1809    /// method.
1810    ///
1811    /// [`poll()`]: struct.Connection.html#method.poll
1812    pub fn dgram_enabled_by_peer<F: BufFactory>(
1813        &self, conn: &super::Connection<F>,
1814    ) -> bool {
1815        self.peer_settings.h3_datagram == Some(1) &&
1816            conn.dgram_max_writable_len().is_some()
1817    }
1818
1819    /// Returns whether the peer enabled extended CONNECT support.
1820    ///
1821    /// Support is signalled by the peer's SETTINGS, so this method always
1822    /// returns false until they have been processed using the [`poll()`]
1823    /// method.
1824    ///
1825    /// [`poll()`]: struct.Connection.html#method.poll
1826    pub fn extended_connect_enabled_by_peer(&self) -> bool {
1827        self.peer_settings.connect_protocol_enabled == Some(1)
1828    }
1829
1830    /// Reads request or response body data into the provided buffer.
1831    ///
1832    /// Applications should call this method whenever the [`poll()`] method
1833    /// returns a [`Data`] event.
1834    ///
1835    /// On success the amount of bytes read is returned, or [`Done`] if there
1836    /// is no data to read.
1837    ///
1838    /// [`poll()`]: struct.Connection.html#method.poll
1839    /// [`Data`]: enum.Event.html#variant.Data
1840    /// [`Done`]: enum.Error.html#variant.Done
1841    pub fn recv_body<F: BufFactory>(
1842        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1843        out: &mut [u8],
1844    ) -> Result<usize> {
1845        self.recv_body_buf(conn, stream_id, out)
1846    }
1847
1848    /// Reads request or response body data into the provided BufMut buffer.
1849    ///
1850    /// **NOTE**:
1851    /// The BufMut will be populated with all available data up to its capacity.
1852    /// Since some BufMut implementations, e.g., [`Vec<u8>`], dynamically
1853    /// allocate additional memory, the caller may use
1854    /// [`BufMut::limit()`] to limit the maximum amount of data that
1855    /// can be written.
1856    ///
1857    /// Applications should call this method (or [`recv_body()`]) whenever
1858    /// the [`poll()`] method returns a [`Data`] event.
1859    ///
1860    /// On success the amount of bytes read is returned, or [`Done`] if there
1861    /// is no data to read.
1862    ///
1863    /// [`BufMut::limit()`]: bytes::BufMut::limit()
1864    /// [`recv_body()`]: Self::recv_body()
1865    /// [`poll()`]: struct.Connection.html#method.poll
1866    /// [`Data`]: enum.Event.html#variant.Data
1867    /// [`Done`]: enum.Error.html#variant.Done
1868    ///
1869    /// ## Example:
1870    /// ```no_run
1871    /// # use quiche::h3;
1872    /// fn receive(
1873    ///     qconn: &mut quiche::Connection, h3conn: &mut h3::Connection,
1874    /// ) -> Result<Vec<u8>, h3::Error> {
1875    ///     use bytes::BufMut as _;
1876    ///     let mut buffer = Vec::with_capacity(2048).limit(2048);
1877    ///     let bytes = h3conn.recv_body_buf(qconn, 0, &mut buffer)?;
1878    ///     let buffer = buffer.into_inner();
1879    ///     // The vec has been filled with exactly `bytes` number of bytes
1880    ///     assert_eq!(buffer.len(), bytes);
1881    ///     Ok(buffer)
1882    /// }
1883    /// ```
1884    pub fn recv_body_buf<F: BufFactory, OUT: bytes::BufMut>(
1885        &mut self, conn: &mut super::Connection<F>, stream_id: u64, mut out: OUT,
1886    ) -> Result<usize> {
1887        let mut total = 0;
1888
1889        // Try to consume all buffered data for the stream, even across multiple
1890        // DATA frames.
1891        // Note, that even if the BufMut does not have a limit defined, we are
1892        // inherently limited by how much data is in quiche's receive buffer for
1893        // that stream, so the BufMut cannot grow unbounded.
1894        while out.has_remaining_mut() {
1895            let stream = self.streams.get_mut(&stream_id).ok_or(Error::Done)?;
1896
1897            if stream.state() != stream::State::Data {
1898                break;
1899            }
1900
1901            let (read, fin) = match stream.try_consume_data(conn, &mut out) {
1902                Ok(v) => v,
1903
1904                Err(Error::Done) => break,
1905
1906                Err(e) => return Err(e),
1907            };
1908
1909            total += read;
1910
1911            // No more data to read, we are done.
1912            if read == 0 || fin {
1913                break;
1914            }
1915
1916            // Process incoming data from the stream. For example, if a whole
1917            // DATA frame was consumed, and another one is queued behind it,
1918            // this will ensure the additional data will also be returned to
1919            // the application.
1920            match self.process_readable_stream(conn, stream_id, false) {
1921                Ok(_) => unreachable!(),
1922
1923                Err(Error::Done) => (),
1924
1925                Err(e) => return Err(e),
1926            };
1927
1928            if conn.stream_finished(stream_id) {
1929                break;
1930            }
1931        }
1932
1933        // While body is being received, the stream is marked as finished only
1934        // when all data is read by the application.
1935        if conn.stream_finished(stream_id) {
1936            self.process_finished_stream(stream_id);
1937        }
1938
1939        if total == 0 {
1940            return Err(Error::Done);
1941        }
1942
1943        Ok(total)
1944    }
1945
1946    /// Sends a PRIORITY_UPDATE frame on the control stream with specified
1947    /// request stream ID and priority.
1948    ///
1949    /// The `priority` parameter represents [Extensible Priority]
1950    /// parameters. If the urgency is outside the range 0-7, it will be clamped
1951    /// to 7.
1952    ///
1953    /// The [`StreamBlocked`] error is returned when the underlying QUIC stream
1954    /// doesn't have enough capacity for the operation to complete. When this
1955    /// happens the application should retry the operation once the stream is
1956    /// reported as writable again.
1957    ///
1958    /// [`StreamBlocked`]: enum.Error.html#variant.StreamBlocked
1959    /// [Extensible Priority]: https://www.rfc-editor.org/rfc/rfc9218.html#section-4.
1960    pub fn send_priority_update_for_request<F: BufFactory>(
1961        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
1962        priority: &Priority,
1963    ) -> Result<()> {
1964        let mut d = [42; 20];
1965        let mut b = octets::OctetsMut::with_slice(&mut d);
1966
1967        // Validate that it is sane to send PRIORITY_UPDATE.
1968        if self.is_server {
1969            return Err(Error::FrameUnexpected);
1970        }
1971
1972        if !stream_id.is_multiple_of(4) {
1973            return Err(Error::FrameUnexpected);
1974        }
1975
1976        let control_stream_id =
1977            self.control_stream_id.ok_or(Error::FrameUnexpected)?;
1978
1979        let urgency = priority
1980            .urgency
1981            .clamp(PRIORITY_URGENCY_LOWER_BOUND, PRIORITY_URGENCY_UPPER_BOUND);
1982
1983        let mut field_value = format!("u={urgency}");
1984
1985        if priority.incremental {
1986            field_value.push_str(",i");
1987        }
1988
1989        let priority_field_value = field_value.as_bytes();
1990        let frame_payload_len =
1991            octets::varint_len(stream_id) + priority_field_value.len();
1992
1993        let overhead =
1994            octets::varint_len(frame::PRIORITY_UPDATE_FRAME_REQUEST_TYPE_ID) +
1995                octets::varint_len(stream_id) +
1996                octets::varint_len(frame_payload_len as u64);
1997
1998        // Make sure the control stream has enough capacity.
1999        match conn.stream_writable(
2000            control_stream_id,
2001            overhead + priority_field_value.len(),
2002        ) {
2003            Ok(true) => (),
2004
2005            Ok(false) => return Err(Error::StreamBlocked),
2006
2007            Err(e) => {
2008                return Err(e.into());
2009            },
2010        }
2011
2012        b.put_varint(frame::PRIORITY_UPDATE_FRAME_REQUEST_TYPE_ID)?;
2013        b.put_varint(frame_payload_len as u64)?;
2014        b.put_varint(stream_id)?;
2015        let off = b.off();
2016        conn.stream_send(control_stream_id, &d[..off], false)?;
2017
2018        // Sending field value separately avoids unnecessary copy.
2019        conn.stream_send(control_stream_id, priority_field_value, false)?;
2020
2021        trace!(
2022            "{} tx frm PRIORITY_UPDATE request_stream={} priority_field_value={}",
2023            conn.trace_id(),
2024            stream_id,
2025            field_value,
2026        );
2027
2028        qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
2029            let frame = Http3Frame::PriorityUpdate {
2030                stream_id: Some(stream_id),
2031                push_id: None,
2032                priority_field_value: field_value.clone(),
2033                raw: None,
2034            };
2035
2036            let ev_data = EventData::Http3FrameCreated(FrameCreated {
2037                stream_id,
2038                length: Some(priority_field_value.len() as u64),
2039                frame,
2040                ..Default::default()
2041            });
2042
2043            q.add_event_data_now(ev_data).ok();
2044        });
2045
2046        Ok(())
2047    }
2048
2049    /// Take the last PRIORITY_UPDATE for a prioritized element ID.
2050    ///
2051    /// When the [`poll()`] method returns a [`PriorityUpdate`] event for a
2052    /// prioritized element, the event has triggered and will not rearm until
2053    /// applications call this method. It is recommended that applications defer
2054    /// taking the PRIORITY_UPDATE until after [`poll()`] returns [`Done`].
2055    ///
2056    /// On success the Priority Field Value is returned, or [`Done`] if there is
2057    /// no PRIORITY_UPDATE to read (either because there is no value to take, or
2058    /// because the prioritized element does not exist).
2059    ///
2060    /// [`poll()`]: struct.Connection.html#method.poll
2061    /// [`PriorityUpdate`]: enum.Event.html#variant.PriorityUpdate
2062    /// [`Done`]: enum.Error.html#variant.Done
2063    pub fn take_last_priority_update(
2064        &mut self, prioritized_element_id: u64,
2065    ) -> Result<Vec<u8>> {
2066        if let Some(stream) = self.streams.get_mut(&prioritized_element_id) {
2067            return stream.take_last_priority_update().ok_or(Error::Done);
2068        }
2069
2070        Err(Error::Done)
2071    }
2072
2073    /// Processes HTTP/3 data received from the peer.
2074    ///
2075    /// On success it returns an [`Event`] and an ID, or [`Done`] when there are
2076    /// no events to report.
2077    ///
2078    /// Note that all events are edge-triggered, meaning that once reported they
2079    /// will not be reported again by calling this method again, until the event
2080    /// is re-armed.
2081    ///
2082    /// The events [`Headers`], [`Data`] and [`Finished`] return a stream ID,
2083    /// which is used in methods [`recv_body()`], [`send_response()`] or
2084    /// [`send_body()`].
2085    ///
2086    /// The event [`GoAway`] returns an ID that depends on the connection role.
2087    /// A client receives the largest processed stream ID. A server receives the
2088    /// the largest permitted push ID.
2089    ///
2090    /// The event [`PriorityUpdate`] only occurs at servers. It returns a
2091    /// prioritized element ID that is used in the method
2092    /// [`take_last_priority_update()`], which rearms the event for that ID.
2093    ///
2094    /// If an error occurs while processing data, the connection is closed with
2095    /// the appropriate error code, using the transport's [`close()`] method.
2096    ///
2097    /// [`Event`]: enum.Event.html
2098    /// [`Done`]: enum.Error.html#variant.Done
2099    /// [`Headers`]: enum.Event.html#variant.Headers
2100    /// [`Data`]: enum.Event.html#variant.Data
2101    /// [`Finished`]: enum.Event.html#variant.Finished
2102    /// [`GoAway`]: enum.Event.html#variant.GoAWay
2103    /// [`PriorityUpdate`]: enum.Event.html#variant.PriorityUpdate
2104    /// [`recv_body()`]: struct.Connection.html#method.recv_body
2105    /// [`send_response()`]: struct.Connection.html#method.send_response
2106    /// [`send_body()`]: struct.Connection.html#method.send_body
2107    /// [`recv_dgram()`]: struct.Connection.html#method.recv_dgram
2108    /// [`take_last_priority_update()`]: struct.Connection.html#method.take_last_priority_update
2109    /// [`close()`]: ../struct.Connection.html#method.close
2110    pub fn poll<F: BufFactory>(
2111        &mut self, conn: &mut super::Connection<F>,
2112    ) -> Result<(u64, Event)> {
2113        // When connection close is initiated by the local application (e.g. due
2114        // to a protocol error), the connection itself might be in a broken
2115        // state, so return early.
2116        if conn.local_error.is_some() {
2117            return Err(Error::Done);
2118        }
2119
2120        // Process control streams first.
2121        if let Some(stream_id) = self.peer_control_stream_id {
2122            match self.process_control_stream(conn, stream_id) {
2123                Ok(ev) => return Ok(ev),
2124
2125                Err(Error::Done) => (),
2126
2127                Err(e) => return Err(e),
2128            };
2129        }
2130
2131        if let Some(stream_id) = self.peer_qpack_streams.encoder_stream_id {
2132            match self.process_control_stream(conn, stream_id) {
2133                Ok(ev) => return Ok(ev),
2134
2135                Err(Error::Done) => (),
2136
2137                Err(e) => return Err(e),
2138            };
2139        }
2140
2141        if let Some(stream_id) = self.peer_qpack_streams.decoder_stream_id {
2142            match self.process_control_stream(conn, stream_id) {
2143                Ok(ev) => return Ok(ev),
2144
2145                Err(Error::Done) => (),
2146
2147                Err(e) => return Err(e),
2148            };
2149        }
2150
2151        // Process finished streams list.
2152        if let Some(ev) = self.pop_finished_stream(conn) {
2153            return Ok(ev);
2154        }
2155
2156        // Process HTTP/3 data from readable streams.
2157        for s in conn.readable() {
2158            trace!("{} stream id {} is readable", conn.trace_id(), s);
2159
2160            let ev = match self.process_readable_stream(conn, s, true) {
2161                Ok(v) => Some(v),
2162
2163                Err(Error::Done) => None,
2164
2165                // Return early if the stream was reset, and mark it as
2166                // finished, so that neither this loop nor a later
2167                // `recv_body()` call queues a Finished event as well.
2168                Err(Error::TransportError(crate::Error::StreamReset(e))) => {
2169                    if let Some(stream) = self.streams.get_mut(&s) {
2170                        stream.finished();
2171                    }
2172
2173                    self.remove_local_finished_stream(s);
2174
2175                    return Ok((s, Event::Reset(e)));
2176                },
2177
2178                Err(e) => return Err(e),
2179            };
2180
2181            if conn.stream_finished(s) {
2182                self.process_finished_stream(s);
2183            }
2184
2185            // TODO: check if stream is completed so it can be freed
2186            if let Some(ev) = ev {
2187                return Ok(ev);
2188            }
2189        }
2190
2191        // Process finished streams list once again, to make sure `Finished`
2192        // events are returned when receiving empty stream frames with the fin
2193        // flag set.
2194        if let Some(ev) = self.pop_finished_stream(conn) {
2195            return Ok(ev);
2196        }
2197
2198        Err(Error::Done)
2199    }
2200
2201    /// Sends a GOAWAY frame to initiate graceful connection closure.
2202    ///
2203    /// When quiche is used in the server role, the `id` parameter is the stream
2204    /// ID of the highest processed request. This can be any valid ID between 0
2205    /// and 2^62-4. However, the ID cannot be increased. Failure to satisfy
2206    /// these conditions will return an error.
2207    ///
2208    /// This method does not close the QUIC connection. Applications are
2209    /// required to call [`close()`] themselves.
2210    ///
2211    /// [`close()`]: ../struct.Connection.html#method.close
2212    pub fn send_goaway<F: BufFactory>(
2213        &mut self, conn: &mut super::Connection<F>, id: u64,
2214    ) -> Result<()> {
2215        let mut id = id;
2216
2217        // TODO: server push
2218        //
2219        // In the meantime always send 0 from client.
2220        if !self.is_server {
2221            id = 0;
2222        }
2223
2224        if self.is_server && !id.is_multiple_of(4) {
2225            return Err(Error::IdError);
2226        }
2227
2228        if let Some(sent_id) = self.local_goaway_id {
2229            if id > sent_id {
2230                return Err(Error::IdError);
2231            }
2232        }
2233
2234        if let Some(stream_id) = self.control_stream_id {
2235            let mut d = [42; 10];
2236            let mut b = octets::OctetsMut::with_slice(&mut d);
2237
2238            let frame = frame::Frame::GoAway { id };
2239
2240            let wire_len = frame.to_bytes(&mut b)?;
2241            let stream_cap = conn.stream_capacity(stream_id)?;
2242
2243            if stream_cap < wire_len {
2244                return Err(Error::StreamBlocked);
2245            }
2246
2247            trace!("{} tx frm {:?}", conn.trace_id(), frame);
2248
2249            qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
2250                let ev_data = EventData::Http3FrameCreated(FrameCreated {
2251                    stream_id,
2252                    length: Some(octets::varint_len(id) as u64),
2253                    frame: frame.to_qlog(),
2254                    ..Default::default()
2255                });
2256
2257                q.add_event_data_now(ev_data).ok();
2258            });
2259
2260            let off = b.off();
2261            conn.stream_send(stream_id, &d[..off], false)?;
2262
2263            self.local_goaway_id = Some(id);
2264        }
2265
2266        Ok(())
2267    }
2268
2269    /// Gets the raw settings from peer including unknown and reserved types.
2270    ///
2271    /// The order of settings is the same as received in the SETTINGS frame.
2272    pub fn peer_settings_raw(&self) -> Option<&[(u64, u64)]> {
2273        self.peer_settings.raw.as_deref()
2274    }
2275
2276    fn open_uni_stream<F: BufFactory>(
2277        &mut self, conn: &mut super::Connection<F>, ty: u64,
2278    ) -> Result<u64> {
2279        let stream_id = self.next_uni_stream_id;
2280
2281        let mut d = [0; 8];
2282        let mut b = octets::OctetsMut::with_slice(&mut d);
2283
2284        match ty {
2285            // Control and QPACK streams are the most important to schedule.
2286            stream::HTTP3_CONTROL_STREAM_TYPE_ID |
2287            stream::QPACK_ENCODER_STREAM_TYPE_ID |
2288            stream::QPACK_DECODER_STREAM_TYPE_ID => {
2289                conn.stream_priority(stream_id, 0, false)?;
2290            },
2291
2292            // TODO: Server push
2293            stream::HTTP3_PUSH_STREAM_TYPE_ID => (),
2294
2295            // Anything else is a GREASE stream, so make it the least important.
2296            _ => {
2297                conn.stream_priority(stream_id, 255, false)?;
2298            },
2299        }
2300
2301        conn.stream_send(stream_id, b.put_varint(ty)?, false)?;
2302
2303        // To avoid skipping stream IDs, we only calculate the next available
2304        // stream ID when data has been successfully buffered.
2305        self.next_uni_stream_id = self
2306            .next_uni_stream_id
2307            .checked_add(4)
2308            .ok_or(Error::IdError)?;
2309
2310        Ok(stream_id)
2311    }
2312
2313    fn open_qpack_encoder_stream<F: BufFactory>(
2314        &mut self, conn: &mut super::Connection<F>,
2315    ) -> Result<()> {
2316        let stream_id =
2317            self.open_uni_stream(conn, stream::QPACK_ENCODER_STREAM_TYPE_ID)?;
2318
2319        self.local_qpack_streams.encoder_stream_id = Some(stream_id);
2320
2321        qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
2322            let ev_data = EventData::Http3StreamTypeSet(StreamTypeSet {
2323                stream_id,
2324                initiator: Some(Initiator::Local),
2325                stream_type: StreamType::QpackEncode,
2326                ..Default::default()
2327            });
2328
2329            q.add_event_data_now(ev_data).ok();
2330        });
2331
2332        Ok(())
2333    }
2334
2335    fn open_qpack_decoder_stream<F: BufFactory>(
2336        &mut self, conn: &mut super::Connection<F>,
2337    ) -> Result<()> {
2338        let stream_id =
2339            self.open_uni_stream(conn, stream::QPACK_DECODER_STREAM_TYPE_ID)?;
2340
2341        self.local_qpack_streams.decoder_stream_id = Some(stream_id);
2342
2343        qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
2344            let ev_data = EventData::Http3StreamTypeSet(StreamTypeSet {
2345                stream_id,
2346                initiator: Some(Initiator::Local),
2347                stream_type: StreamType::QpackDecode,
2348                ..Default::default()
2349            });
2350
2351            q.add_event_data_now(ev_data).ok();
2352        });
2353
2354        Ok(())
2355    }
2356
2357    /// Send GREASE frames on the provided stream ID.
2358    fn send_grease_frames<F: BufFactory>(
2359        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
2360    ) -> Result<()> {
2361        let mut d = [0; 8];
2362
2363        let stream_cap = match conn.stream_capacity(stream_id) {
2364            Ok(v) => v,
2365
2366            Err(e) => {
2367                if conn.stream_finished(stream_id) {
2368                    self.streams.remove(&stream_id);
2369                }
2370
2371                return Err(e.into());
2372            },
2373        };
2374
2375        let grease_frame1 = grease_value();
2376        let grease_frame2 = grease_value();
2377        let grease_payload = b"GREASE is the word";
2378
2379        let overhead = octets::varint_len(grease_frame1) + // frame type
2380            1 + // payload len
2381            octets::varint_len(grease_frame2) + // frame type
2382            1 + // payload len
2383            grease_payload.len(); // payload
2384
2385        // Don't send GREASE if there is not enough capacity for it. Greasing
2386        // will _not_ be attempted again later on.
2387        if stream_cap < overhead {
2388            return Ok(());
2389        }
2390
2391        // Empty GREASE frame.
2392        let mut b = octets::OctetsMut::with_slice(&mut d);
2393        conn.stream_send(stream_id, b.put_varint(grease_frame1)?, false)?;
2394
2395        let mut b = octets::OctetsMut::with_slice(&mut d);
2396        conn.stream_send(stream_id, b.put_varint(0)?, false)?;
2397
2398        trace!(
2399            "{} tx frm GREASE stream={} len=0",
2400            conn.trace_id(),
2401            stream_id
2402        );
2403
2404        qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
2405            let frame = Http3Frame::Reserved {
2406                frame_type_bytes: grease_frame1,
2407                raw: None,
2408            };
2409            let ev_data = EventData::Http3FrameCreated(FrameCreated {
2410                stream_id,
2411                length: Some(0),
2412                frame,
2413                ..Default::default()
2414            });
2415
2416            q.add_event_data_now(ev_data).ok();
2417        });
2418
2419        // GREASE frame with payload.
2420        let mut b = octets::OctetsMut::with_slice(&mut d);
2421        conn.stream_send(stream_id, b.put_varint(grease_frame2)?, false)?;
2422
2423        let mut b = octets::OctetsMut::with_slice(&mut d);
2424        conn.stream_send(stream_id, b.put_varint(18)?, false)?;
2425
2426        conn.stream_send(stream_id, grease_payload, false)?;
2427
2428        trace!(
2429            "{} tx frm GREASE stream={} len={}",
2430            conn.trace_id(),
2431            stream_id,
2432            grease_payload.len()
2433        );
2434
2435        qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
2436            let frame = Http3Frame::Reserved {
2437                frame_type_bytes: grease_frame2,
2438                raw: None,
2439            };
2440            let ev_data = EventData::Http3FrameCreated(FrameCreated {
2441                stream_id,
2442                length: Some(grease_payload.len() as u64),
2443                frame,
2444                ..Default::default()
2445            });
2446
2447            q.add_event_data_now(ev_data).ok();
2448        });
2449
2450        Ok(())
2451    }
2452
2453    /// Opens a new unidirectional stream with a GREASE type and sends some
2454    /// unframed payload.
2455    fn open_grease_stream<F: BufFactory>(
2456        &mut self, conn: &mut super::Connection<F>,
2457    ) -> Result<()> {
2458        let ty = grease_value();
2459        match self.open_uni_stream(conn, ty) {
2460            Ok(stream_id) => {
2461                conn.stream_send(stream_id, b"GREASE is the word", true)?;
2462
2463                trace!("{} open GREASE stream {}", conn.trace_id(), stream_id);
2464
2465                qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
2466                    let ev_data = EventData::Http3StreamTypeSet(StreamTypeSet {
2467                        stream_id,
2468                        initiator: Some(Initiator::Local),
2469                        stream_type: StreamType::Unknown,
2470                        stream_type_bytes: Some(ty),
2471                        ..Default::default()
2472                    });
2473
2474                    q.add_event_data_now(ev_data).ok();
2475                });
2476            },
2477
2478            Err(Error::IdError) => {
2479                trace!("{} GREASE stream blocked", conn.trace_id(),);
2480
2481                return Ok(());
2482            },
2483
2484            Err(e) => return Err(e),
2485        };
2486
2487        Ok(())
2488    }
2489
2490    /// Sends SETTINGS frame based on HTTP/3 configuration.
2491    fn send_settings<F: BufFactory>(
2492        &mut self, conn: &mut super::Connection<F>,
2493    ) -> Result<()> {
2494        let stream_id = match self
2495            .open_uni_stream(conn, stream::HTTP3_CONTROL_STREAM_TYPE_ID)
2496        {
2497            Ok(v) => v,
2498
2499            Err(e) => {
2500                trace!("{} Control stream blocked", conn.trace_id(),);
2501
2502                if e == Error::Done {
2503                    return Err(Error::InternalError);
2504                }
2505
2506                return Err(e);
2507            },
2508        };
2509
2510        self.control_stream_id = Some(stream_id);
2511
2512        qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
2513            let ev_data = EventData::Http3StreamTypeSet(StreamTypeSet {
2514                stream_id,
2515                initiator: Some(Initiator::Local),
2516                stream_type: StreamType::Control,
2517                ..Default::default()
2518            });
2519
2520            q.add_event_data_now(ev_data).ok();
2521        });
2522
2523        let grease = if conn.grease {
2524            Some((grease_value(), grease_value()))
2525        } else {
2526            None
2527        };
2528
2529        let frame = frame::Frame::Settings {
2530            max_field_section_size: self.local_settings.max_field_section_size,
2531            qpack_max_table_capacity: self
2532                .local_settings
2533                .qpack_max_table_capacity,
2534            qpack_blocked_streams: self.local_settings.qpack_blocked_streams,
2535            connect_protocol_enabled: self
2536                .local_settings
2537                .connect_protocol_enabled,
2538            h3_datagram: self.local_settings.h3_datagram,
2539            grease,
2540            additional_settings: self.local_settings.additional_settings.clone(),
2541            raw: Default::default(),
2542        };
2543
2544        let mut d = [42; 128];
2545        let mut b = octets::OctetsMut::with_slice(&mut d);
2546
2547        frame.to_bytes(&mut b)?;
2548
2549        let off = b.off();
2550
2551        if let Some(id) = self.control_stream_id {
2552            conn.stream_send(id, &d[..off], false)?;
2553
2554            trace!(
2555                "{} tx frm SETTINGS stream={} len={}",
2556                conn.trace_id(),
2557                id,
2558                off
2559            );
2560
2561            qlog_with_type!(QLOG_FRAME_CREATED, conn.qlog, q, {
2562                let frame = frame.to_qlog();
2563                let ev_data = EventData::Http3FrameCreated(FrameCreated {
2564                    stream_id: id,
2565                    length: Some(off as u64),
2566                    frame,
2567                    ..Default::default()
2568                });
2569
2570                q.add_event_data_now(ev_data).ok();
2571            });
2572        }
2573
2574        Ok(())
2575    }
2576
2577    fn process_control_stream<F: BufFactory>(
2578        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
2579    ) -> Result<(u64, Event)> {
2580        close_conn_if_critical_stream_finished(conn, stream_id)?;
2581
2582        if !conn.stream_readable(stream_id) {
2583            return Err(Error::Done);
2584        }
2585
2586        match self.process_readable_stream(conn, stream_id, true) {
2587            Ok(ev) => return Ok(ev),
2588
2589            Err(Error::Done) => (),
2590
2591            Err(e) => return Err(e),
2592        };
2593
2594        close_conn_if_critical_stream_finished(conn, stream_id)?;
2595
2596        Err(Error::Done)
2597    }
2598
2599    fn process_readable_stream<F: BufFactory>(
2600        &mut self, conn: &mut super::Connection<F>, stream_id: u64, polling: bool,
2601    ) -> Result<(u64, Event)> {
2602        self.streams.entry(stream_id).or_insert_with(|| {
2603            <stream::Stream>::new(
2604                stream_id,
2605                false,
2606                self.local_settings
2607                    .max_field_section_size
2608                    .unwrap_or(SETTINGS_MAX_FIELD_SECTION_SIZE_DEFAULT),
2609                self.max_priority_update_size,
2610            )
2611        });
2612
2613        // We need to get a fresh reference to the stream for each
2614        // iteration, to avoid borrowing `self` for the entire duration
2615        // of the loop, because we'll need to borrow it again in the
2616        // `State::FramePayload` case below.
2617        while let Some(stream) = self.streams.get_mut(&stream_id) {
2618            match stream.state() {
2619                stream::State::StreamType => {
2620                    stream.try_fill_buffer(conn)?;
2621
2622                    let varint = match stream.try_consume_varint() {
2623                        Ok(v) => v,
2624
2625                        Err(_) => continue,
2626                    };
2627
2628                    let ty = stream::Type::deserialize(varint)?;
2629
2630                    if let Err(e) = stream.set_ty(ty) {
2631                        conn.close(true, e.to_wire(), b"")?;
2632                        return Err(e);
2633                    }
2634
2635                    qlog_with_type!(QLOG_STREAM_TYPE_SET, conn.qlog, q, {
2636                        let ty_val = if matches!(ty, stream::Type::Unknown) {
2637                            Some(varint)
2638                        } else {
2639                            None
2640                        };
2641
2642                        let ev_data =
2643                            EventData::Http3StreamTypeSet(StreamTypeSet {
2644                                stream_id,
2645                                initiator: Some(Initiator::Remote),
2646                                stream_type: ty.to_qlog(),
2647                                stream_type_bytes: ty_val,
2648                                ..Default::default()
2649                            });
2650
2651                        q.add_event_data_now(ev_data).ok();
2652                    });
2653
2654                    match &ty {
2655                        stream::Type::Control => {
2656                            // Only one control stream allowed.
2657                            if self.peer_control_stream_id.is_some() {
2658                                conn.close(
2659                                    true,
2660                                    Error::StreamCreationError.to_wire(),
2661                                    b"Received multiple control streams",
2662                                )?;
2663
2664                                return Err(Error::StreamCreationError);
2665                            }
2666
2667                            trace!(
2668                                "{} open peer's control stream {}",
2669                                conn.trace_id(),
2670                                stream_id
2671                            );
2672
2673                            close_conn_if_critical_stream_finished(
2674                                conn, stream_id,
2675                            )?;
2676
2677                            self.peer_control_stream_id = Some(stream_id);
2678                        },
2679
2680                        stream::Type::Push => {
2681                            // Server push is not supported, so push streams at
2682                            // either client or server is a critical protocol
2683                            // error.
2684                            conn.close(
2685                                true,
2686                                Error::StreamCreationError.to_wire(),
2687                                b"Received push stream.",
2688                            )?;
2689
2690                            return Err(Error::StreamCreationError);
2691                        },
2692
2693                        stream::Type::QpackEncoder => {
2694                            // Only one qpack encoder stream allowed.
2695                            if self.peer_qpack_streams.encoder_stream_id.is_some()
2696                            {
2697                                conn.close(
2698                                    true,
2699                                    Error::StreamCreationError.to_wire(),
2700                                    b"Received multiple QPACK encoder streams",
2701                                )?;
2702
2703                                return Err(Error::StreamCreationError);
2704                            }
2705
2706                            close_conn_if_critical_stream_finished(
2707                                conn, stream_id,
2708                            )?;
2709
2710                            self.peer_qpack_streams.encoder_stream_id =
2711                                Some(stream_id);
2712                        },
2713
2714                        stream::Type::QpackDecoder => {
2715                            // Only one qpack decoder allowed.
2716                            if self.peer_qpack_streams.decoder_stream_id.is_some()
2717                            {
2718                                conn.close(
2719                                    true,
2720                                    Error::StreamCreationError.to_wire(),
2721                                    b"Received multiple QPACK decoder streams",
2722                                )?;
2723
2724                                return Err(Error::StreamCreationError);
2725                            }
2726
2727                            close_conn_if_critical_stream_finished(
2728                                conn, stream_id,
2729                            )?;
2730
2731                            self.peer_qpack_streams.decoder_stream_id =
2732                                Some(stream_id);
2733                        },
2734
2735                        stream::Type::Unknown => {
2736                            // Unknown stream types are ignored.
2737                            // TODO: we MAY send STOP_SENDING
2738                        },
2739
2740                        stream::Type::Request => unreachable!(),
2741                    }
2742                },
2743
2744                stream::State::PushId => {
2745                    stream.try_fill_buffer(conn)?;
2746
2747                    let varint = match stream.try_consume_varint() {
2748                        Ok(v) => v,
2749
2750                        Err(_) => continue,
2751                    };
2752
2753                    if let Err(e) = stream.set_push_id(varint) {
2754                        conn.close(true, e.to_wire(), b"")?;
2755                        return Err(e);
2756                    }
2757                },
2758
2759                stream::State::FrameType => {
2760                    stream.try_fill_buffer(conn)?;
2761
2762                    let varint = match stream.try_consume_varint() {
2763                        Ok(v) => v,
2764
2765                        Err(_) => continue,
2766                    };
2767
2768                    match stream.set_frame_type(varint) {
2769                        Err(Error::FrameUnexpected) => {
2770                            let msg = format!("Unexpected frame type {varint}");
2771
2772                            conn.close(
2773                                true,
2774                                Error::FrameUnexpected.to_wire(),
2775                                msg.as_bytes(),
2776                            )?;
2777
2778                            return Err(Error::FrameUnexpected);
2779                        },
2780
2781                        Err(e) => {
2782                            conn.close(
2783                                true,
2784                                e.to_wire(),
2785                                b"Error handling frame.",
2786                            )?;
2787
2788                            return Err(e);
2789                        },
2790
2791                        _ => (),
2792                    }
2793                },
2794
2795                stream::State::FramePayloadLen => {
2796                    stream.try_fill_buffer(conn)?;
2797
2798                    let payload_len = match stream.try_consume_varint() {
2799                        Ok(v) => v,
2800
2801                        Err(_) => continue,
2802                    };
2803
2804                    // DATA frames are handled uniquely. Log them here because
2805                    // DATA framing is no longer visible after this point.
2806                    if Some(frame::DATA_FRAME_TYPE_ID) == stream.frame_type() {
2807                        trace!(
2808                            "{} rx frm DATA stream={} wire_payload_len={}",
2809                            conn.trace_id(),
2810                            stream_id,
2811                            payload_len
2812                        );
2813
2814                        qlog_with_type!(QLOG_FRAME_PARSED, conn.qlog, q, {
2815                            let frame = Http3Frame::Data { raw: None };
2816
2817                            let ev_data =
2818                                EventData::Http3FrameParsed(FrameParsed {
2819                                    stream_id,
2820                                    length: Some(payload_len),
2821                                    frame,
2822                                    ..Default::default()
2823                                });
2824
2825                            q.add_event_data_now(ev_data).ok();
2826                        });
2827                    }
2828
2829                    let res = stream.set_frame_payload_len(payload_len);
2830
2831                    if let Err(e) = res {
2832                        conn.close(true, e.to_wire(), b"")?;
2833                        return Err(e);
2834                    }
2835                },
2836
2837                stream::State::FramePayload => {
2838                    // Do not emit events when not polling.
2839                    if !polling {
2840                        break;
2841                    }
2842
2843                    stream.try_fill_buffer(conn)?;
2844
2845                    let (frame, payload_len) = match stream.try_consume_frame() {
2846                        Ok(frame) => frame,
2847
2848                        Err(Error::Done) => return Err(Error::Done),
2849
2850                        Err(e) => {
2851                            conn.close(
2852                                true,
2853                                e.to_wire(),
2854                                b"Error handling frame.",
2855                            )?;
2856
2857                            return Err(e);
2858                        },
2859                    };
2860
2861                    match self.process_frame(conn, stream_id, frame, payload_len)
2862                    {
2863                        Ok(ev) => return Ok(ev),
2864
2865                        Err(Error::Done) => {
2866                            // Internal frames do not produce events. Avoid
2867                            // reading again if QUIC marked the stream finished.
2868                            if conn.stream_finished(stream_id) {
2869                                break;
2870                            }
2871                        },
2872
2873                        Err(e) => return Err(e),
2874                    };
2875                },
2876
2877                stream::State::Data => {
2878                    // Do not emit events when not polling.
2879                    if !polling {
2880                        break;
2881                    }
2882
2883                    // A reset received while waiting for the rest of a DATA
2884                    // frame makes the stream readable, with no payload left to
2885                    // read. Use a dummy read to return the reset directly,
2886                    // instead of an Event::Data after which `recv_body()`
2887                    // returns `Done` and the stream looks finished, as if the
2888                    // body were complete. The dummy read has side effects, such
2889                    // as qlog events, so only do it for finished streams,
2890                    // which include all reset streams.
2891                    if conn.stream_finished(stream_id) {
2892                        if let Err(crate::Error::StreamReset(e)) =
2893                            conn.stream_recv(stream_id, &mut [])
2894                        {
2895                            return Err(Error::TransportError(
2896                                crate::Error::StreamReset(e),
2897                            ));
2898                        }
2899                    }
2900
2901                    if !stream.try_trigger_data_event() {
2902                        break;
2903                    }
2904
2905                    return Ok((stream_id, Event::Data));
2906                },
2907
2908                stream::State::QpackInstruction => {
2909                    let mut d = [0; 4096];
2910
2911                    // Read data from the stream and discard immediately.
2912                    loop {
2913                        let (recv, fin) = conn.stream_recv(stream_id, &mut d)?;
2914
2915                        match stream.ty() {
2916                            Some(stream::Type::QpackEncoder) =>
2917                                self.peer_qpack_streams.encoder_stream_bytes +=
2918                                    recv as u64,
2919                            Some(stream::Type::QpackDecoder) =>
2920                                self.peer_qpack_streams.decoder_stream_bytes +=
2921                                    recv as u64,
2922                            _ => unreachable!(),
2923                        };
2924
2925                        if fin {
2926                            close_conn_critical_stream(conn)?;
2927                        }
2928                    }
2929                },
2930
2931                stream::State::SkipFramePayload => {
2932                    stream.try_skip_frame(conn)?;
2933
2934                    // Check whether the frame has FIN'd by QUIC to prevent
2935                    // trying to read again on a closed stream.
2936                    if conn.stream_finished(stream_id) {
2937                        break;
2938                    }
2939                },
2940
2941                stream::State::Drain => {
2942                    // Discard incoming data on the stream.
2943                    conn.stream_shutdown(
2944                        stream_id,
2945                        crate::Shutdown::Read,
2946                        0x100,
2947                    )?;
2948
2949                    break;
2950                },
2951
2952                stream::State::Finished => break,
2953            }
2954        }
2955
2956        Err(Error::Done)
2957    }
2958
2959    fn process_finished_stream(&mut self, stream_id: u64) {
2960        let stream = match self.streams.get_mut(&stream_id) {
2961            Some(v) => v,
2962
2963            None => return,
2964        };
2965
2966        if stream.state() == stream::State::Finished {
2967            return;
2968        }
2969
2970        match stream.ty() {
2971            Some(stream::Type::Request) | Some(stream::Type::Push) => {
2972                stream.finished();
2973
2974                self.finished_streams.push_back(stream_id);
2975            },
2976            Some(stream::Type::Unknown) | None => {
2977                self.streams.remove(&stream_id);
2978            },
2979            // Closing any of the critical streams leads to connection close,
2980            // so there is no need for any cleanup actions here.
2981            Some(stream::Type::Control) |
2982            Some(stream::Type::QpackEncoder) |
2983            Some(stream::Type::QpackDecoder) => (),
2984        };
2985    }
2986
2987    fn finish_local_stream<F: BufFactory>(
2988        &mut self, conn: &super::Connection<F>, stream_id: u64,
2989        initialize_local: bool,
2990    ) {
2991        let hash_map::Entry::Occupied(mut stream) = self.streams.entry(stream_id)
2992        else {
2993            return;
2994        };
2995
2996        {
2997            let stream = stream.get_mut();
2998
2999            if initialize_local {
3000                stream.initialize_local();
3001            }
3002
3003            stream.finish_local();
3004        }
3005
3006        if conn.stream_finished(stream_id) {
3007            stream.remove();
3008        }
3009    }
3010
3011    fn remove_local_finished_stream(&mut self, stream_id: u64) {
3012        if let hash_map::Entry::Occupied(stream) = self.streams.entry(stream_id) {
3013            if stream.get().local_finished() {
3014                stream.remove();
3015            }
3016        }
3017    }
3018
3019    fn pop_finished_stream<F: BufFactory>(
3020        &mut self, conn: &mut super::Connection<F>,
3021    ) -> Option<(u64, Event)> {
3022        let finished = self.finished_streams.pop_front()?;
3023
3024        self.remove_local_finished_stream(finished);
3025
3026        if conn.stream_readable(finished) {
3027            // The stream is finished, but is still readable, it may indicate
3028            // that there is a pending error, such as reset.
3029            if let Err(crate::Error::StreamReset(e)) =
3030                conn.stream_recv(finished, &mut [])
3031            {
3032                return Some((finished, Event::Reset(e)));
3033            }
3034        }
3035
3036        Some((finished, Event::Finished))
3037    }
3038
3039    fn process_frame<F: BufFactory>(
3040        &mut self, conn: &mut super::Connection<F>, stream_id: u64,
3041        frame: frame::Frame, payload_len: u64,
3042    ) -> Result<(u64, Event)> {
3043        trace!(
3044            "{} rx frm {:?} stream={} payload_len={}",
3045            conn.trace_id(),
3046            frame,
3047            stream_id,
3048            payload_len
3049        );
3050
3051        qlog_with_type!(QLOG_FRAME_PARSED, conn.qlog, q, {
3052            // HEADERS frames are special case and will be logged below.
3053            if !matches!(frame, frame::Frame::Headers { .. }) {
3054                let frame = frame.to_qlog();
3055                let ev_data = EventData::Http3FrameParsed(FrameParsed {
3056                    stream_id,
3057                    length: Some(payload_len),
3058                    frame,
3059                    ..Default::default()
3060                });
3061
3062                q.add_event_data_now(ev_data).ok();
3063            }
3064        });
3065
3066        match frame {
3067            frame::Frame::Settings {
3068                max_field_section_size,
3069                qpack_max_table_capacity,
3070                qpack_blocked_streams,
3071                connect_protocol_enabled,
3072                h3_datagram,
3073                additional_settings,
3074                raw,
3075                ..
3076            } => {
3077                self.peer_settings = ConnectionSettings {
3078                    max_field_section_size,
3079                    qpack_max_table_capacity,
3080                    qpack_blocked_streams,
3081                    connect_protocol_enabled,
3082                    h3_datagram,
3083                    additional_settings,
3084                    raw,
3085                };
3086
3087                if let Some(1) = h3_datagram {
3088                    // The peer MUST have also enabled DATAGRAM with a TP
3089                    if conn.dgram_max_writable_len().is_none() {
3090                        conn.close(
3091                            true,
3092                            Error::SettingsError.to_wire(),
3093                            b"H3_DATAGRAM sent with value 1 but max_datagram_frame_size TP not set.",
3094                        )?;
3095
3096                        return Err(Error::SettingsError);
3097                    }
3098                }
3099            },
3100
3101            frame::Frame::Headers { header_block } => {
3102                // Servers reject too many HEADERS frames.
3103                if let Some(s) = self.streams.get_mut(&stream_id) {
3104                    if self.is_server && s.headers_received_count() == 2 {
3105                        conn.close(
3106                            true,
3107                            Error::FrameUnexpected.to_wire(),
3108                            b"Too many HEADERS frames",
3109                        )?;
3110                        return Err(Error::FrameUnexpected);
3111                    }
3112
3113                    s.increment_headers_received();
3114                }
3115
3116                // Use "infinite" as default value for max_field_section_size if
3117                // it is not configured by the application.
3118                let max_size = self
3119                    .local_settings
3120                    .max_field_section_size
3121                    .unwrap_or(u64::MAX);
3122
3123                let headers = match self
3124                    .qpack_decoder
3125                    .decode(&header_block[..], max_size)
3126                {
3127                    Ok(v) => v,
3128
3129                    Err(e) => {
3130                        let e = match e {
3131                            qpack::Error::HeaderListTooLarge =>
3132                                Error::ExcessiveLoad,
3133
3134                            _ => Error::QpackDecompressionFailed,
3135                        };
3136
3137                        conn.close(true, e.to_wire(), b"Error parsing headers.")?;
3138
3139                        return Err(e);
3140                    },
3141                };
3142
3143                qlog_with_type!(QLOG_FRAME_PARSED, conn.qlog, q, {
3144                    let qlog_headers = headers
3145                        .iter()
3146                        .map(|h| qlog::events::http3::HttpHeader {
3147                            name: Some(
3148                                String::from_utf8_lossy(h.name()).into_owned(),
3149                            ),
3150                            name_bytes: None,
3151                            value: Some(
3152                                String::from_utf8_lossy(h.value()).into_owned(),
3153                            ),
3154                            value_bytes: None,
3155                        })
3156                        .collect();
3157
3158                    let frame = Http3Frame::Headers {
3159                        headers: qlog_headers,
3160                        raw: None,
3161                    };
3162
3163                    let ev_data = EventData::Http3FrameParsed(FrameParsed {
3164                        stream_id,
3165                        length: Some(payload_len),
3166                        frame,
3167                        ..Default::default()
3168                    });
3169
3170                    q.add_event_data_now(ev_data).ok();
3171                });
3172
3173                let more_frames = !conn.stream_finished(stream_id);
3174
3175                return Ok((stream_id, Event::Headers {
3176                    list: headers,
3177                    more_frames,
3178                }));
3179            },
3180
3181            frame::Frame::Data { .. } => {
3182                // Do nothing. The Data event is returned separately.
3183            },
3184
3185            frame::Frame::GoAway { id } => {
3186                if !self.is_server && id % 4 != 0 {
3187                    conn.close(
3188                        true,
3189                        Error::FrameUnexpected.to_wire(),
3190                        b"GOAWAY received with ID of non-request stream",
3191                    )?;
3192
3193                    return Err(Error::IdError);
3194                }
3195
3196                if let Some(received_id) = self.peer_goaway_id {
3197                    if id > received_id {
3198                        conn.close(
3199                            true,
3200                            Error::IdError.to_wire(),
3201                            b"GOAWAY received with ID larger than previously received",
3202                        )?;
3203
3204                        return Err(Error::IdError);
3205                    }
3206                }
3207
3208                self.peer_goaway_id = Some(id);
3209
3210                return Ok((id, Event::GoAway));
3211            },
3212
3213            frame::Frame::MaxPushId { push_id } => {
3214                if !self.is_server {
3215                    conn.close(
3216                        true,
3217                        Error::FrameUnexpected.to_wire(),
3218                        b"MAX_PUSH_ID received by client",
3219                    )?;
3220
3221                    return Err(Error::FrameUnexpected);
3222                }
3223
3224                if push_id < self.max_push_id {
3225                    conn.close(
3226                        true,
3227                        Error::IdError.to_wire(),
3228                        b"MAX_PUSH_ID reduced limit",
3229                    )?;
3230
3231                    return Err(Error::IdError);
3232                }
3233
3234                self.max_push_id = push_id;
3235            },
3236
3237            frame::Frame::PushPromise { .. } => {
3238                if self.is_server {
3239                    conn.close(
3240                        true,
3241                        Error::FrameUnexpected.to_wire(),
3242                        b"PUSH_PROMISE received by server",
3243                    )?;
3244
3245                    return Err(Error::FrameUnexpected);
3246                }
3247
3248                if !stream_id.is_multiple_of(4) {
3249                    conn.close(
3250                        true,
3251                        Error::FrameUnexpected.to_wire(),
3252                        b"PUSH_PROMISE received on non-request stream",
3253                    )?;
3254
3255                    return Err(Error::FrameUnexpected);
3256                }
3257
3258                // TODO: implement more checks and PUSH_PROMISE event
3259            },
3260
3261            frame::Frame::CancelPush { .. } => {
3262                // TODO: implement CANCEL_PUSH frame
3263            },
3264
3265            frame::Frame::PriorityUpdateRequest {
3266                prioritized_element_id,
3267                priority_field_value,
3268            } => {
3269                if !self.is_server {
3270                    conn.close(
3271                        true,
3272                        Error::FrameUnexpected.to_wire(),
3273                        b"PRIORITY_UPDATE received by client",
3274                    )?;
3275
3276                    return Err(Error::FrameUnexpected);
3277                }
3278
3279                if prioritized_element_id % 4 != 0 {
3280                    conn.close(
3281                        true,
3282                        Error::FrameUnexpected.to_wire(),
3283                        b"PRIORITY_UPDATE for request stream type with wrong ID",
3284                    )?;
3285
3286                    return Err(Error::FrameUnexpected);
3287                }
3288
3289                if prioritized_element_id > conn.streams.max_streams_bidi() * 4 {
3290                    conn.close(
3291                        true,
3292                        Error::IdError.to_wire(),
3293                        b"PRIORITY_UPDATE for request stream beyond max streams limit",
3294                    )?;
3295
3296                    return Err(Error::IdError);
3297                }
3298
3299                // PRIORITY_UPDATE can arrive before the request stream exists,
3300                // so a missing transport stream is allowed. Ignore updates only
3301                // once the transport stream was collected or both transport
3302                // directions are finished.
3303                if conn.stream_closed(prioritized_element_id) {
3304                    return Err(Error::Done);
3305                }
3306
3307                // If the stream did not yet exist, create it and store.
3308                let stream = self
3309                    .streams
3310                    .entry(prioritized_element_id)
3311                    .or_insert_with(|| {
3312                        <stream::Stream>::new(
3313                            prioritized_element_id,
3314                            false,
3315                            self.local_settings.max_field_section_size.unwrap_or(
3316                                SETTINGS_MAX_FIELD_SECTION_SIZE_DEFAULT,
3317                            ),
3318                            self.max_priority_update_size,
3319                        )
3320                    });
3321
3322                let had_priority_update = stream.has_last_priority_update();
3323                stream.set_last_priority_update(Some(priority_field_value));
3324
3325                // Only trigger the event when there wasn't already a stored
3326                // PRIORITY_UPDATE.
3327                if !had_priority_update {
3328                    return Ok((prioritized_element_id, Event::PriorityUpdate));
3329                } else {
3330                    return Err(Error::Done);
3331                }
3332            },
3333
3334            frame::Frame::PriorityUpdatePush {
3335                prioritized_element_id,
3336                ..
3337            } => {
3338                if !self.is_server {
3339                    conn.close(
3340                        true,
3341                        Error::FrameUnexpected.to_wire(),
3342                        b"PRIORITY_UPDATE received by client",
3343                    )?;
3344
3345                    return Err(Error::FrameUnexpected);
3346                }
3347
3348                if prioritized_element_id % 3 != 0 {
3349                    conn.close(
3350                        true,
3351                        Error::FrameUnexpected.to_wire(),
3352                        b"PRIORITY_UPDATE for push stream type with wrong ID",
3353                    )?;
3354
3355                    return Err(Error::FrameUnexpected);
3356                }
3357
3358                // TODO: we only implement this if we implement server push
3359            },
3360
3361            frame::Frame::Unknown { .. } => (),
3362        }
3363
3364        Err(Error::Done)
3365    }
3366
3367    /// Collects and returns statistics about the connection.
3368    #[inline]
3369    pub fn stats(&self) -> Stats {
3370        Stats {
3371            qpack_encoder_stream_recv_bytes: self
3372                .peer_qpack_streams
3373                .encoder_stream_bytes,
3374            qpack_decoder_stream_recv_bytes: self
3375                .peer_qpack_streams
3376                .decoder_stream_bytes,
3377        }
3378    }
3379}
3380
3381/// Generates an HTTP/3 GREASE variable length integer.
3382pub fn grease_value() -> u64 {
3383    let n = super::rand::rand_u64_uniform(148_764_065_110_560_899);
3384    31 * n + 33
3385}
3386
3387#[doc(hidden)]
3388#[cfg(any(test, feature = "internal"))]
3389pub mod testing {
3390    use super::*;
3391
3392    use crate::test_utils;
3393    use crate::DefaultBufFactory;
3394
3395    /// Session is an HTTP/3 test helper structure. It holds a client, server
3396    /// and pipe that allows them to communicate.
3397    ///
3398    /// `default()` creates a session with some sensible default
3399    /// configuration. `with_configs()` allows for providing a specific
3400    /// configuration.
3401    ///
3402    /// `handshake()` performs all the steps needed to establish an HTTP/3
3403    /// connection.
3404    ///
3405    /// Some utility functions are provided that make it less verbose to send
3406    /// request, responses and individual headers. The full quiche API remains
3407    /// available for any test that need to do unconventional things (such as
3408    /// bad behaviour that triggers errors).
3409    pub struct Session<F = DefaultBufFactory>
3410    where
3411        F: BufFactory,
3412    {
3413        pub pipe: test_utils::Pipe<F>,
3414        pub client: Connection,
3415        pub server: Connection,
3416    }
3417
3418    impl Session {
3419        pub fn new() -> Result<Session> {
3420            Session::<DefaultBufFactory>::new_with_buf()
3421        }
3422
3423        pub fn with_configs(
3424            config: &mut crate::Config, h3_config: &Config,
3425        ) -> Result<Session> {
3426            Session::<DefaultBufFactory>::with_configs_and_buf(config, h3_config)
3427        }
3428
3429        pub fn default_configs() -> Result<(crate::Config, Config)> {
3430            fn path_relative_to_manifest_dir(path: &str) -> String {
3431                std::fs::canonicalize(
3432                    std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(path),
3433                )
3434                .unwrap()
3435                .to_string_lossy()
3436                .into_owned()
3437            }
3438
3439            let mut config = crate::Config::new(crate::PROTOCOL_VERSION)?;
3440            config.load_cert_chain_from_pem_file(
3441                &path_relative_to_manifest_dir("examples/cert.crt"),
3442            )?;
3443            config.load_priv_key_from_pem_file(
3444                &path_relative_to_manifest_dir("examples/cert.key"),
3445            )?;
3446            config.set_application_protos(&[b"h3"])?;
3447            config.set_initial_max_data(1500);
3448            config.set_initial_max_stream_data_bidi_local(150);
3449            config.set_initial_max_stream_data_bidi_remote(150);
3450            config.set_initial_max_stream_data_uni(150);
3451            config.set_initial_max_streams_bidi(5);
3452            config.set_initial_max_streams_uni(5);
3453            config.verify_peer(false);
3454            config.enable_dgram(true, 3, 3);
3455            config.set_ack_delay_exponent(8);
3456
3457            let h3_config = Config::new()?;
3458            Ok((config, h3_config))
3459        }
3460    }
3461
3462    impl<F: BufFactory> Session<F> {
3463        pub fn new_with_buf() -> Result<Session<F>> {
3464            let (mut config, h3_config) = Session::default_configs()?;
3465            Session::with_configs_and_buf(&mut config, &h3_config)
3466        }
3467
3468        pub fn with_configs_and_buf(
3469            config: &mut crate::Config, h3_config: &Config,
3470        ) -> Result<Session<F>> {
3471            let pipe = test_utils::Pipe::with_config_and_buf(config)?;
3472            let client_dgram = pipe.client.dgram_enabled();
3473            let server_dgram = pipe.server.dgram_enabled();
3474            Ok(Session {
3475                pipe,
3476                client: Connection::new(h3_config, false, client_dgram)?,
3477                server: Connection::new(h3_config, true, server_dgram)?,
3478            })
3479        }
3480
3481        /// Do the HTTP/3 handshake so both ends are in sane initial state.
3482        pub fn handshake(&mut self) -> Result<()> {
3483            self.pipe.handshake()?;
3484
3485            // Client streams.
3486            self.client.send_settings(&mut self.pipe.client)?;
3487            self.pipe.advance().ok();
3488
3489            self.client
3490                .open_qpack_encoder_stream(&mut self.pipe.client)?;
3491            self.pipe.advance().ok();
3492
3493            self.client
3494                .open_qpack_decoder_stream(&mut self.pipe.client)?;
3495            self.pipe.advance().ok();
3496
3497            if self.pipe.client.grease {
3498                self.client.open_grease_stream(&mut self.pipe.client)?;
3499            }
3500
3501            self.pipe.advance().ok();
3502
3503            // Server streams.
3504            self.server.send_settings(&mut self.pipe.server)?;
3505            self.pipe.advance().ok();
3506
3507            self.server
3508                .open_qpack_encoder_stream(&mut self.pipe.server)?;
3509            self.pipe.advance().ok();
3510
3511            self.server
3512                .open_qpack_decoder_stream(&mut self.pipe.server)?;
3513            self.pipe.advance().ok();
3514
3515            if self.pipe.server.grease {
3516                self.server.open_grease_stream(&mut self.pipe.server)?;
3517            }
3518
3519            self.advance().ok();
3520
3521            while self.client.poll(&mut self.pipe.client).is_ok() {
3522                // Do nothing.
3523            }
3524
3525            while self.server.poll(&mut self.pipe.server).is_ok() {
3526                // Do nothing.
3527            }
3528
3529            Ok(())
3530        }
3531
3532        /// Advances the session pipe over the buffer.
3533        pub fn advance(&mut self) -> crate::Result<()> {
3534            self.pipe.advance()
3535        }
3536
3537        /// Polls the client for events.
3538        pub fn poll_client(&mut self) -> Result<(u64, Event)> {
3539            self.client.poll(&mut self.pipe.client)
3540        }
3541
3542        /// Polls the server for events.
3543        pub fn poll_server(&mut self) -> Result<(u64, Event)> {
3544            self.server.poll(&mut self.pipe.server)
3545        }
3546
3547        /// Sends a request from client with default headers.
3548        ///
3549        /// On success it returns the newly allocated stream and the headers.
3550        pub fn send_request(&mut self, fin: bool) -> Result<(u64, Vec<Header>)> {
3551            let req = vec![
3552                Header::new(b":method", b"GET"),
3553                Header::new(b":scheme", b"https"),
3554                Header::new(b":authority", b"quic.tech"),
3555                Header::new(b":path", b"/test"),
3556                Header::new(b"user-agent", b"quiche-test"),
3557            ];
3558
3559            let stream =
3560                self.client.send_request(&mut self.pipe.client, &req, fin)?;
3561
3562            self.advance().ok();
3563
3564            Ok((stream, req))
3565        }
3566
3567        /// Sends a response from server with default headers.
3568        ///
3569        /// On success it returns the headers.
3570        pub fn send_response(
3571            &mut self, stream: u64, fin: bool,
3572        ) -> Result<Vec<Header>> {
3573            let resp = vec![
3574                Header::new(b":status", b"200"),
3575                Header::new(b"server", b"quiche-test"),
3576            ];
3577
3578            self.server.send_response(
3579                &mut self.pipe.server,
3580                stream,
3581                &resp,
3582                fin,
3583            )?;
3584
3585            self.advance().ok();
3586
3587            Ok(resp)
3588        }
3589
3590        /// Sends some default payload from client.
3591        ///
3592        /// On success it returns the payload.
3593        pub fn send_body_client(
3594            &mut self, stream: u64, fin: bool,
3595        ) -> Result<Vec<u8>> {
3596            let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
3597
3598            self.client
3599                .send_body(&mut self.pipe.client, stream, &bytes, fin)?;
3600
3601            self.advance().ok();
3602
3603            Ok(bytes)
3604        }
3605
3606        /// Fetches DATA payload from the server.
3607        ///
3608        /// On success it returns the number of bytes received.
3609        pub fn recv_body_client(
3610            &mut self, stream: u64, buf: &mut [u8],
3611        ) -> Result<usize> {
3612            self.client.recv_body(&mut self.pipe.client, stream, buf)
3613        }
3614
3615        /// Fetches DATA payload from the server.
3616        ///
3617        /// On success it returns the number of bytes received.
3618        pub fn recv_body_buf_client<B: bytes::BufMut>(
3619            &mut self, stream: u64, buf: B,
3620        ) -> Result<usize> {
3621            self.client
3622                .recv_body_buf(&mut self.pipe.client, stream, buf)
3623        }
3624
3625        /// Sends some default payload from server.
3626        ///
3627        /// On success it returns the payload.
3628        pub fn send_body_server(
3629            &mut self, stream: u64, fin: bool,
3630        ) -> Result<Vec<u8>> {
3631            let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
3632
3633            self.server
3634                .send_body(&mut self.pipe.server, stream, &bytes, fin)?;
3635
3636            self.advance().ok();
3637
3638            Ok(bytes)
3639        }
3640
3641        /// Fetches DATA payload from the client.
3642        ///
3643        /// On success it returns the number of bytes received.
3644        pub fn recv_body_server(
3645            &mut self, stream: u64, buf: &mut [u8],
3646        ) -> Result<usize> {
3647            self.server.recv_body(&mut self.pipe.server, stream, buf)
3648        }
3649
3650        /// Fetches DATA payload from the client.
3651        ///
3652        /// On success it returns the number of bytes received.
3653        pub fn recv_body_buf_server<B: bytes::BufMut>(
3654            &mut self, stream: u64, buf: B,
3655        ) -> Result<usize> {
3656            self.server
3657                .recv_body_buf(&mut self.pipe.server, stream, buf)
3658        }
3659
3660        /// Sends a single HTTP/3 frame from the client.
3661        pub fn send_frame_client(
3662            &mut self, frame: frame::Frame, stream_id: u64, fin: bool,
3663        ) -> Result<()> {
3664            let mut d = [42; 65535];
3665
3666            let mut b = octets::OctetsMut::with_slice(&mut d);
3667
3668            frame.to_bytes(&mut b)?;
3669
3670            let off = b.off();
3671            self.pipe.client.stream_send(stream_id, &d[..off], fin)?;
3672
3673            self.advance().ok();
3674
3675            Ok(())
3676        }
3677
3678        /// Send an HTTP/3 DATAGRAM with default data from the client.
3679        ///
3680        /// On success it returns the data.
3681        pub fn send_dgram_client(&mut self, flow_id: u64) -> Result<Vec<u8>> {
3682            let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
3683            let len = octets::varint_len(flow_id) + bytes.len();
3684            let mut d = vec![0; len];
3685            let mut b = octets::OctetsMut::with_slice(&mut d);
3686
3687            b.put_varint(flow_id)?;
3688            b.put_bytes(&bytes)?;
3689
3690            self.pipe.client.dgram_send(&d)?;
3691
3692            self.advance().ok();
3693
3694            Ok(bytes)
3695        }
3696
3697        /// Receives an HTTP/3 DATAGRAM from the server.
3698        ///
3699        /// On success it returns the DATAGRAM length, flow ID and flow ID
3700        /// length.
3701        pub fn recv_dgram_client(
3702            &mut self, buf: &mut [u8],
3703        ) -> Result<(usize, u64, usize)> {
3704            let len = self.pipe.client.dgram_recv(buf)?;
3705            let mut b = octets::Octets::with_slice(buf);
3706            let flow_id = b.get_varint()?;
3707
3708            Ok((len, flow_id, b.off()))
3709        }
3710
3711        /// Send an HTTP/3 DATAGRAM with default data from the server
3712        ///
3713        /// On success it returns the data.
3714        pub fn send_dgram_server(&mut self, flow_id: u64) -> Result<Vec<u8>> {
3715            let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
3716            let len = octets::varint_len(flow_id) + bytes.len();
3717            let mut d = vec![0; len];
3718            let mut b = octets::OctetsMut::with_slice(&mut d);
3719
3720            b.put_varint(flow_id)?;
3721            b.put_bytes(&bytes)?;
3722
3723            self.pipe.server.dgram_send(&d)?;
3724
3725            self.advance().ok();
3726
3727            Ok(bytes)
3728        }
3729
3730        /// Receives an HTTP/3 DATAGRAM from the client.
3731        ///
3732        /// On success it returns the DATAGRAM length, flow ID and flow ID
3733        /// length.
3734        pub fn recv_dgram_server(
3735            &mut self, buf: &mut [u8],
3736        ) -> Result<(usize, u64, usize)> {
3737            let len = self.pipe.server.dgram_recv(buf)?;
3738            let mut b = octets::Octets::with_slice(buf);
3739            let flow_id = b.get_varint()?;
3740
3741            Ok((len, flow_id, b.off()))
3742        }
3743
3744        /// Sends a single HTTP/3 frame from the server.
3745        pub fn send_frame_server(
3746            &mut self, frame: frame::Frame, stream_id: u64, fin: bool,
3747        ) -> Result<()> {
3748            let mut d = [42; 65535];
3749
3750            let mut b = octets::OctetsMut::with_slice(&mut d);
3751
3752            frame.to_bytes(&mut b)?;
3753
3754            let off = b.off();
3755            self.pipe.server.stream_send(stream_id, &d[..off], fin)?;
3756
3757            self.advance().ok();
3758
3759            Ok(())
3760        }
3761
3762        /// Sends an arbitrary buffer of HTTP/3 stream data from the client.
3763        pub fn send_arbitrary_stream_data_client(
3764            &mut self, data: &[u8], stream_id: u64, fin: bool,
3765        ) -> Result<()> {
3766            self.pipe.client.stream_send(stream_id, data, fin)?;
3767
3768            self.advance().ok();
3769
3770            Ok(())
3771        }
3772
3773        /// Sends an arbitrary buffer of HTTP/3 stream data from the server.
3774        pub fn send_arbitrary_stream_data_server(
3775            &mut self, data: &[u8], stream_id: u64, fin: bool,
3776        ) -> Result<()> {
3777            self.pipe.server.stream_send(stream_id, data, fin)?;
3778
3779            self.advance().ok();
3780
3781            Ok(())
3782        }
3783    }
3784}
3785
3786#[cfg(test)]
3787mod tests {
3788    use bytes::BufMut as _;
3789
3790    use super::*;
3791
3792    use super::testing::*;
3793
3794    #[test]
3795    /// Make sure that random GREASE values is within the specified limit.
3796    fn grease_value_in_varint_limit() {
3797        assert!(grease_value() < 2u64.pow(62) - 1);
3798    }
3799
3800    #[test]
3801    fn h3_handshake_0rtt() {
3802        let mut buf = [0; 65535];
3803
3804        // Test drives the handshake one Initial at a time; requires a
3805        // single-Initial ClientHello.
3806        let mut config =
3807            crate::test_utils::config_no_pq(crate::PROTOCOL_VERSION).unwrap();
3808        config
3809            .load_cert_chain_from_pem_file("examples/cert.crt")
3810            .unwrap();
3811        config
3812            .load_priv_key_from_pem_file("examples/cert.key")
3813            .unwrap();
3814        config
3815            .set_application_protos(&[b"proto1", b"proto2"])
3816            .unwrap();
3817        config.set_initial_max_data(30);
3818        config.set_initial_max_stream_data_bidi_local(15);
3819        config.set_initial_max_stream_data_bidi_remote(15);
3820        config.set_initial_max_stream_data_uni(15);
3821        config.set_initial_max_streams_bidi(3);
3822        config.set_initial_max_streams_uni(3);
3823        config.enable_early_data();
3824        config.verify_peer(false);
3825
3826        let h3_config = Config::new().unwrap();
3827
3828        // Perform initial handshake.
3829        let mut pipe = crate::test_utils::Pipe::with_config(&mut config).unwrap();
3830        assert_eq!(pipe.handshake(), Ok(()));
3831
3832        // Extract session,
3833        let session = pipe.client.session().unwrap();
3834
3835        // Configure session on new connection.
3836        let mut pipe = crate::test_utils::Pipe::with_config(&mut config).unwrap();
3837        assert_eq!(pipe.client.set_session(session), Ok(()));
3838
3839        // Can't create an H3 connection until the QUIC connection is determined
3840        // to have made sufficient early data progress.
3841        assert!(matches!(
3842            Connection::with_transport(&mut pipe.client, &h3_config),
3843            Err(Error::InternalError)
3844        ));
3845
3846        // Client sends initial flight.
3847        let (len, _) = pipe.client.send(&mut buf).unwrap();
3848
3849        // Now an H3 connection can be created.
3850        assert!(Connection::with_transport(&mut pipe.client, &h3_config).is_ok());
3851        assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
3852
3853        // Client sends 0-RTT packet.
3854        let pkt_type = crate::packet::Type::ZeroRTT;
3855
3856        let frames = [crate::frame::Frame::Stream {
3857            stream_id: 6,
3858            data: <crate::range_buf::RangeBuf>::from(b"aaaaa", 0, true),
3859        }];
3860
3861        assert_eq!(
3862            pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
3863            Ok(1200)
3864        );
3865
3866        assert_eq!(pipe.server.undecryptable_pkts.len(), 0);
3867
3868        // 0-RTT stream data is readable.
3869        let mut r = pipe.server.readable();
3870        assert_eq!(r.next(), Some(6));
3871        assert_eq!(r.next(), None);
3872
3873        let mut b = [0; 15];
3874        assert_eq!(pipe.server.stream_recv(6, &mut b), Ok((5, true)));
3875        assert_eq!(&b[..5], b"aaaaa");
3876    }
3877
3878    #[test]
3879    /// Send a request with no body, get a response with no body.
3880    fn request_no_body_response_no_body() {
3881        let mut s = Session::new().unwrap();
3882        s.handshake().unwrap();
3883
3884        let (stream, req) = s.send_request(true).unwrap();
3885
3886        assert_eq!(stream, 0);
3887
3888        let ev_headers = Event::Headers {
3889            list: req,
3890            more_frames: false,
3891        };
3892
3893        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
3894        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
3895
3896        let resp = s.send_response(stream, true).unwrap();
3897
3898        let ev_headers = Event::Headers {
3899            list: resp,
3900            more_frames: false,
3901        };
3902
3903        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
3904        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
3905        assert_eq!(s.poll_client(), Err(Error::Done));
3906    }
3907
3908    #[test]
3909    /// Send a request with no body, get a response with one DATA frame.
3910    fn request_no_body_response_one_chunk() {
3911        let mut s = Session::new().unwrap();
3912        s.handshake().unwrap();
3913
3914        let (stream, req) = s.send_request(true).unwrap();
3915        assert_eq!(stream, 0);
3916
3917        let ev_headers = Event::Headers {
3918            list: req,
3919            more_frames: false,
3920        };
3921
3922        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
3923
3924        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
3925
3926        let resp = s.send_response(stream, false).unwrap();
3927
3928        let body = s.send_body_server(stream, true).unwrap();
3929
3930        let mut recv_buf = vec![0; body.len()];
3931
3932        let ev_headers = Event::Headers {
3933            list: resp,
3934            more_frames: true,
3935        };
3936
3937        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
3938
3939        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
3940        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
3941
3942        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
3943        assert_eq!(s.poll_client(), Err(Error::Done));
3944    }
3945
3946    #[test]
3947    /// Send a request with no body, get a response with multiple DATA frames.
3948    fn request_no_body_response_many_chunks() {
3949        let mut s = Session::new().unwrap();
3950        s.handshake().unwrap();
3951
3952        let (stream, req) = s.send_request(true).unwrap();
3953
3954        let ev_headers = Event::Headers {
3955            list: req,
3956            more_frames: false,
3957        };
3958
3959        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
3960        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
3961
3962        let total_data_frames = 4;
3963
3964        let resp = s.send_response(stream, false).unwrap();
3965
3966        for _ in 0..total_data_frames - 1 {
3967            s.send_body_server(stream, false).unwrap();
3968        }
3969
3970        let body = s.send_body_server(stream, true).unwrap();
3971
3972        let mut recv_buf = vec![0; body.len()];
3973
3974        let ev_headers = Event::Headers {
3975            list: resp,
3976            more_frames: true,
3977        };
3978
3979        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
3980        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
3981        assert_eq!(s.poll_client(), Err(Error::Done));
3982
3983        for _ in 0..total_data_frames {
3984            assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
3985        }
3986
3987        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
3988        assert_eq!(s.poll_client(), Err(Error::Done));
3989    }
3990
3991    #[test]
3992    /// Send a request with no body, get a response with multiple DATA frames.
3993    fn request_no_body_response_many_chunks_with_buf() {
3994        let (mut config, h3_config) = Session::default_configs().unwrap();
3995        // we don't want to be limited by flow or cong. control
3996        config.set_initial_congestion_window_packets(100);
3997        config.set_initial_max_data(200_000);
3998        config.set_initial_max_stream_data_bidi_local(200_000);
3999        config.set_initial_max_stream_data_bidi_remote(200_000);
4000        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
4001        s.handshake().unwrap();
4002
4003        let (stream, req) = s.send_request(true).unwrap();
4004
4005        let ev_headers = Event::Headers {
4006            list: req,
4007            more_frames: false,
4008        };
4009
4010        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4011        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4012
4013        let total_data_frames = 4;
4014
4015        // Use a large body
4016        let data = vec![0xab_u8; 16 * 1024];
4017
4018        let resp = s.send_response(stream, false).unwrap();
4019
4020        for _ in 0..total_data_frames - 1 {
4021            assert_eq!(
4022                s.server.send_body(&mut s.pipe.server, stream, &data, false),
4023                Ok(data.len())
4024            );
4025            s.advance().ok();
4026        }
4027
4028        s.server
4029            .send_body(&mut s.pipe.server, stream, &data, true)
4030            .unwrap();
4031        s.advance().ok();
4032
4033        let ev_headers = Event::Headers {
4034            list: resp,
4035            more_frames: true,
4036        };
4037
4038        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
4039        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
4040        assert_eq!(s.poll_client(), Err(Error::Done));
4041
4042        // Reads may span multiple DATA frames and need not end at frame
4043        // boundaries. Read one and a half times the payload of one frame.
4044        let how_much_to_read_per_call = data.len() * 2 / 3;
4045        let mut remaining_to_read = total_data_frames * data.len();
4046        let mut recv_buf = Vec::new().limit(how_much_to_read_per_call);
4047        assert_eq!(
4048            s.recv_body_buf_client(stream, &mut recv_buf),
4049            Ok(how_much_to_read_per_call)
4050        );
4051        remaining_to_read -= how_much_to_read_per_call;
4052        assert_eq!(recv_buf.get_ref().len(), how_much_to_read_per_call);
4053
4054        while remaining_to_read > 0 {
4055            // Set a different limit for the following reads.
4056            recv_buf.set_limit(data.len());
4057            // We should either read up to the limit we set above, or to
4058            // the end of buffered data.
4059            let expected = std::cmp::min(data.len(), remaining_to_read);
4060            assert_eq!(
4061                s.recv_body_buf_client(stream, &mut recv_buf),
4062                Ok(expected)
4063            );
4064            remaining_to_read -= expected;
4065        }
4066        // We've read everything now. Ensure the Vec reflects that
4067        assert_eq!(recv_buf.get_ref().len(), total_data_frames * data.len());
4068
4069        // No more data to read.
4070        assert_eq!(
4071            s.recv_body_buf_client(stream, &mut recv_buf),
4072            Err(Error::Done)
4073        );
4074
4075        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
4076        assert_eq!(s.poll_client(), Err(Error::Done));
4077    }
4078
4079    #[test]
4080    /// Send a request with one DATA frame, get a response with no body.
4081    fn request_one_chunk_response_no_body() {
4082        let mut s = Session::new().unwrap();
4083        s.handshake().unwrap();
4084
4085        let (stream, req) = s.send_request(false).unwrap();
4086
4087        let body = s.send_body_client(stream, true).unwrap();
4088
4089        let mut recv_buf = vec![0; body.len()];
4090
4091        let ev_headers = Event::Headers {
4092            list: req,
4093            more_frames: true,
4094        };
4095
4096        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4097
4098        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
4099        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
4100
4101        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4102
4103        let resp = s.send_response(stream, true).unwrap();
4104
4105        let ev_headers = Event::Headers {
4106            list: resp,
4107            more_frames: false,
4108        };
4109
4110        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
4111        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
4112    }
4113
4114    #[test]
4115    /// Send a request with multiple DATA frames, get a response with no body.
4116    fn request_many_chunks_response_no_body() {
4117        let mut s = Session::new().unwrap();
4118        s.handshake().unwrap();
4119
4120        let (stream, req) = s.send_request(false).unwrap();
4121
4122        let total_data_frames = 4;
4123
4124        for _ in 0..total_data_frames - 1 {
4125            s.send_body_client(stream, false).unwrap();
4126        }
4127
4128        let body = s.send_body_client(stream, true).unwrap();
4129
4130        let mut recv_buf = vec![0; body.len()];
4131
4132        let ev_headers = Event::Headers {
4133            list: req,
4134            more_frames: true,
4135        };
4136
4137        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4138        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
4139        assert_eq!(s.poll_server(), Err(Error::Done));
4140
4141        for _ in 0..total_data_frames {
4142            assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
4143        }
4144
4145        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4146
4147        let resp = s.send_response(stream, true).unwrap();
4148
4149        let ev_headers = Event::Headers {
4150            list: resp,
4151            more_frames: false,
4152        };
4153
4154        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
4155        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
4156    }
4157
4158    #[test]
4159    /// Send a request with multiple DATA frames, get a response with one DATA
4160    /// frame.
4161    fn many_requests_many_chunks_response_one_chunk() {
4162        let mut s = Session::new().unwrap();
4163        s.handshake().unwrap();
4164
4165        let mut reqs = Vec::new();
4166
4167        let (stream1, req1) = s.send_request(false).unwrap();
4168        assert_eq!(stream1, 0);
4169        reqs.push(req1);
4170
4171        let (stream2, req2) = s.send_request(false).unwrap();
4172        assert_eq!(stream2, 4);
4173        reqs.push(req2);
4174
4175        let (stream3, req3) = s.send_request(false).unwrap();
4176        assert_eq!(stream3, 8);
4177        reqs.push(req3);
4178
4179        let body = s.send_body_client(stream1, false).unwrap();
4180        s.send_body_client(stream2, false).unwrap();
4181        s.send_body_client(stream3, false).unwrap();
4182
4183        let mut recv_buf = vec![0; body.len()];
4184
4185        // Reverse order of writes.
4186
4187        s.send_body_client(stream3, true).unwrap();
4188        s.send_body_client(stream2, true).unwrap();
4189        s.send_body_client(stream1, true).unwrap();
4190
4191        let (_, ev) = s.poll_server().unwrap();
4192        let ev_headers = Event::Headers {
4193            list: reqs[0].clone(),
4194            more_frames: true,
4195        };
4196        assert_eq!(ev, ev_headers);
4197
4198        let (_, ev) = s.poll_server().unwrap();
4199        let ev_headers = Event::Headers {
4200            list: reqs[1].clone(),
4201            more_frames: true,
4202        };
4203        assert_eq!(ev, ev_headers);
4204
4205        let (_, ev) = s.poll_server().unwrap();
4206        let ev_headers = Event::Headers {
4207            list: reqs[2].clone(),
4208            more_frames: true,
4209        };
4210        assert_eq!(ev, ev_headers);
4211
4212        assert_eq!(s.poll_server(), Ok((0, Event::Data)));
4213        assert_eq!(s.recv_body_server(0, &mut recv_buf), Ok(body.len()));
4214        assert_eq!(s.poll_client(), Err(Error::Done));
4215        assert_eq!(s.recv_body_server(0, &mut recv_buf), Ok(body.len()));
4216        assert_eq!(s.poll_server(), Ok((0, Event::Finished)));
4217
4218        assert_eq!(s.poll_server(), Ok((4, Event::Data)));
4219        assert_eq!(s.recv_body_server(4, &mut recv_buf), Ok(body.len()));
4220        assert_eq!(s.poll_client(), Err(Error::Done));
4221        assert_eq!(s.recv_body_server(4, &mut recv_buf), Ok(body.len()));
4222        assert_eq!(s.poll_server(), Ok((4, Event::Finished)));
4223
4224        assert_eq!(s.poll_server(), Ok((8, Event::Data)));
4225        assert_eq!(s.recv_body_server(8, &mut recv_buf), Ok(body.len()));
4226        assert_eq!(s.poll_client(), Err(Error::Done));
4227        assert_eq!(s.recv_body_server(8, &mut recv_buf), Ok(body.len()));
4228        assert_eq!(s.poll_server(), Ok((8, Event::Finished)));
4229
4230        assert_eq!(s.poll_server(), Err(Error::Done));
4231
4232        let mut resps = Vec::new();
4233
4234        let resp1 = s.send_response(stream1, true).unwrap();
4235        resps.push(resp1);
4236
4237        let resp2 = s.send_response(stream2, true).unwrap();
4238        resps.push(resp2);
4239
4240        let resp3 = s.send_response(stream3, true).unwrap();
4241        resps.push(resp3);
4242
4243        for _ in 0..resps.len() {
4244            let (stream, ev) = s.poll_client().unwrap();
4245            let ev_headers = Event::Headers {
4246                list: resps[(stream / 4) as usize].clone(),
4247                more_frames: false,
4248            };
4249            assert_eq!(ev, ev_headers);
4250            assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
4251        }
4252
4253        assert_eq!(s.poll_client(), Err(Error::Done));
4254    }
4255
4256    #[test]
4257    /// Send a request with no body, get a response with one DATA frame and an
4258    /// empty FIN after reception from the client.
4259    fn request_no_body_response_one_chunk_empty_fin() {
4260        let mut s = Session::new().unwrap();
4261        s.handshake().unwrap();
4262
4263        let (stream, req) = s.send_request(true).unwrap();
4264
4265        let ev_headers = Event::Headers {
4266            list: req,
4267            more_frames: false,
4268        };
4269
4270        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4271        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4272
4273        let resp = s.send_response(stream, false).unwrap();
4274
4275        let body = s.send_body_server(stream, false).unwrap();
4276
4277        let mut recv_buf = vec![0; body.len()];
4278
4279        let ev_headers = Event::Headers {
4280            list: resp,
4281            more_frames: true,
4282        };
4283
4284        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
4285
4286        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
4287        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
4288
4289        assert_eq!(s.pipe.server.stream_send(stream, &[], true), Ok(0));
4290        s.advance().ok();
4291
4292        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
4293        assert_eq!(s.poll_client(), Err(Error::Done));
4294    }
4295
4296    #[test]
4297    /// Send a request with no body, get a response with no body followed by
4298    /// GREASE that is STREAM frame with a FIN.
4299    fn request_no_body_response_no_body_with_grease() {
4300        let mut s = Session::new().unwrap();
4301        s.handshake().unwrap();
4302
4303        let (stream, req) = s.send_request(true).unwrap();
4304
4305        assert_eq!(stream, 0);
4306
4307        let ev_headers = Event::Headers {
4308            list: req,
4309            more_frames: false,
4310        };
4311
4312        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4313        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4314
4315        let resp = s.send_response(stream, false).unwrap();
4316
4317        let ev_headers = Event::Headers {
4318            list: resp,
4319            more_frames: true,
4320        };
4321
4322        // Inject a GREASE frame.
4323        let mut d = [42; 10];
4324        let mut b = octets::OctetsMut::with_slice(&mut d);
4325
4326        let frame_type = b.put_varint(148_764_065_110_560_899).unwrap();
4327        s.pipe.server.stream_send(0, frame_type, false).unwrap();
4328
4329        let frame_len = b.put_varint(10).unwrap();
4330        s.pipe.server.stream_send(0, frame_len, false).unwrap();
4331
4332        s.pipe.server.stream_send(0, &d, true).unwrap();
4333
4334        s.advance().ok();
4335
4336        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
4337        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
4338        assert_eq!(s.poll_client(), Err(Error::Done));
4339    }
4340
4341    #[test]
4342    /// Try to send DATA frames before HEADERS.
4343    fn body_response_before_headers() {
4344        let mut s = Session::new().unwrap();
4345        s.handshake().unwrap();
4346
4347        let (stream, req) = s.send_request(true).unwrap();
4348        assert_eq!(stream, 0);
4349
4350        let ev_headers = Event::Headers {
4351            list: req,
4352            more_frames: false,
4353        };
4354
4355        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4356
4357        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4358
4359        assert_eq!(
4360            s.send_body_server(stream, true),
4361            Err(Error::FrameUnexpected)
4362        );
4363
4364        assert_eq!(s.poll_client(), Err(Error::Done));
4365    }
4366
4367    #[test]
4368    /// Try to send DATA frames on wrong streams, ensure the API returns an
4369    /// error before anything hits the transport layer.
4370    fn send_body_invalid_client_stream() {
4371        let mut s = Session::new().unwrap();
4372        s.handshake().unwrap();
4373
4374        assert_eq!(s.send_body_client(0, true), Err(Error::FrameUnexpected));
4375
4376        assert_eq!(
4377            s.send_body_client(s.client.control_stream_id.unwrap(), true),
4378            Err(Error::FrameUnexpected)
4379        );
4380
4381        assert_eq!(
4382            s.send_body_client(
4383                s.client.local_qpack_streams.encoder_stream_id.unwrap(),
4384                true
4385            ),
4386            Err(Error::FrameUnexpected)
4387        );
4388
4389        assert_eq!(
4390            s.send_body_client(
4391                s.client.local_qpack_streams.decoder_stream_id.unwrap(),
4392                true
4393            ),
4394            Err(Error::FrameUnexpected)
4395        );
4396
4397        assert_eq!(
4398            s.send_body_client(s.client.peer_control_stream_id.unwrap(), true),
4399            Err(Error::FrameUnexpected)
4400        );
4401
4402        assert_eq!(
4403            s.send_body_client(
4404                s.client.peer_qpack_streams.encoder_stream_id.unwrap(),
4405                true
4406            ),
4407            Err(Error::FrameUnexpected)
4408        );
4409
4410        assert_eq!(
4411            s.send_body_client(
4412                s.client.peer_qpack_streams.decoder_stream_id.unwrap(),
4413                true
4414            ),
4415            Err(Error::FrameUnexpected)
4416        );
4417    }
4418
4419    #[test]
4420    /// Try to send DATA frames on wrong streams, ensure the API returns an
4421    /// error before anything hits the transport layer.
4422    fn send_body_invalid_server_stream() {
4423        let mut s = Session::new().unwrap();
4424        s.handshake().unwrap();
4425
4426        assert_eq!(s.send_body_server(0, true), Err(Error::FrameUnexpected));
4427
4428        assert_eq!(
4429            s.send_body_server(s.server.control_stream_id.unwrap(), true),
4430            Err(Error::FrameUnexpected)
4431        );
4432
4433        assert_eq!(
4434            s.send_body_server(
4435                s.server.local_qpack_streams.encoder_stream_id.unwrap(),
4436                true
4437            ),
4438            Err(Error::FrameUnexpected)
4439        );
4440
4441        assert_eq!(
4442            s.send_body_server(
4443                s.server.local_qpack_streams.decoder_stream_id.unwrap(),
4444                true
4445            ),
4446            Err(Error::FrameUnexpected)
4447        );
4448
4449        assert_eq!(
4450            s.send_body_server(s.server.peer_control_stream_id.unwrap(), true),
4451            Err(Error::FrameUnexpected)
4452        );
4453
4454        assert_eq!(
4455            s.send_body_server(
4456                s.server.peer_qpack_streams.encoder_stream_id.unwrap(),
4457                true
4458            ),
4459            Err(Error::FrameUnexpected)
4460        );
4461
4462        assert_eq!(
4463            s.send_body_server(
4464                s.server.peer_qpack_streams.decoder_stream_id.unwrap(),
4465                true
4466            ),
4467            Err(Error::FrameUnexpected)
4468        );
4469    }
4470
4471    #[test]
4472    /// Client sends request with body and trailers.
4473    fn trailers() {
4474        let mut s = Session::new().unwrap();
4475        s.handshake().unwrap();
4476
4477        let (stream, req) = s.send_request(false).unwrap();
4478
4479        let body = s.send_body_client(stream, false).unwrap();
4480
4481        let mut recv_buf = vec![0; body.len()];
4482
4483        let req_trailers = vec![Header::new(b"foo", b"bar")];
4484
4485        s.client
4486            .send_additional_headers(
4487                &mut s.pipe.client,
4488                stream,
4489                &req_trailers,
4490                true,
4491                true,
4492            )
4493            .unwrap();
4494
4495        s.advance().ok();
4496
4497        let ev_headers = Event::Headers {
4498            list: req,
4499            more_frames: true,
4500        };
4501
4502        let ev_trailers = Event::Headers {
4503            list: req_trailers,
4504            more_frames: false,
4505        };
4506
4507        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4508
4509        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
4510        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
4511
4512        assert_eq!(s.poll_server(), Ok((stream, ev_trailers)));
4513        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4514    }
4515
4516    #[test]
4517    /// Server responds with a 103, then a 200 with no body.
4518    fn informational_response() {
4519        let mut s = Session::new().unwrap();
4520        s.handshake().unwrap();
4521
4522        let (stream, req) = s.send_request(true).unwrap();
4523
4524        assert_eq!(stream, 0);
4525
4526        let ev_headers = Event::Headers {
4527            list: req,
4528            more_frames: false,
4529        };
4530
4531        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4532        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4533
4534        let info_resp = vec![
4535            Header::new(b":status", b"103"),
4536            Header::new(b"link", b"<https://example.com>; rel=\"preconnect\""),
4537        ];
4538
4539        let resp = vec![
4540            Header::new(b":status", b"200"),
4541            Header::new(b"server", b"quiche-test"),
4542        ];
4543
4544        s.server
4545            .send_response(&mut s.pipe.server, stream, &info_resp, false)
4546            .unwrap();
4547
4548        s.server
4549            .send_additional_headers(
4550                &mut s.pipe.server,
4551                stream,
4552                &resp,
4553                false,
4554                true,
4555            )
4556            .unwrap();
4557
4558        s.advance().ok();
4559
4560        let ev_info_headers = Event::Headers {
4561            list: info_resp,
4562            more_frames: true,
4563        };
4564
4565        let ev_headers = Event::Headers {
4566            list: resp,
4567            more_frames: false,
4568        };
4569
4570        assert_eq!(s.poll_client(), Ok((stream, ev_info_headers)));
4571        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
4572        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
4573        assert_eq!(s.poll_client(), Err(Error::Done));
4574    }
4575
4576    #[test]
4577    /// Server responds with a 103, then attempts to send a 200 using
4578    /// send_response again, which should fail.
4579    fn no_multiple_response() {
4580        let mut s = Session::new().unwrap();
4581        s.handshake().unwrap();
4582
4583        let (stream, req) = s.send_request(true).unwrap();
4584
4585        assert_eq!(stream, 0);
4586
4587        let ev_headers = Event::Headers {
4588            list: req,
4589            more_frames: false,
4590        };
4591
4592        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4593        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4594
4595        let info_resp = vec![
4596            Header::new(b":status", b"103"),
4597            Header::new(b"link", b"<https://example.com>; rel=\"preconnect\""),
4598        ];
4599
4600        let resp = vec![
4601            Header::new(b":status", b"200"),
4602            Header::new(b"server", b"quiche-test"),
4603        ];
4604
4605        s.server
4606            .send_response(&mut s.pipe.server, stream, &info_resp, false)
4607            .unwrap();
4608
4609        assert_eq!(
4610            Err(Error::FrameUnexpected),
4611            s.server
4612                .send_response(&mut s.pipe.server, stream, &resp, true)
4613        );
4614
4615        s.advance().ok();
4616
4617        let ev_info_headers = Event::Headers {
4618            list: info_resp,
4619            more_frames: true,
4620        };
4621
4622        assert_eq!(s.poll_client(), Ok((stream, ev_info_headers)));
4623        assert_eq!(s.poll_client(), Err(Error::Done));
4624    }
4625
4626    #[test]
4627    /// Server attempts to use send_additional_headers before initial response.
4628    fn no_send_additional_before_initial_response() {
4629        let mut s = Session::new().unwrap();
4630        s.handshake().unwrap();
4631
4632        let (stream, req) = s.send_request(true).unwrap();
4633
4634        assert_eq!(stream, 0);
4635
4636        let ev_headers = Event::Headers {
4637            list: req,
4638            more_frames: false,
4639        };
4640
4641        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4642        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
4643
4644        let info_resp = vec![
4645            Header::new(b":status", b"103"),
4646            Header::new(b"link", b"<https://example.com>; rel=\"preconnect\""),
4647        ];
4648
4649        assert_eq!(
4650            Err(Error::FrameUnexpected),
4651            s.server.send_additional_headers(
4652                &mut s.pipe.server,
4653                stream,
4654                &info_resp,
4655                false,
4656                false
4657            )
4658        );
4659
4660        s.advance().ok();
4661
4662        assert_eq!(s.poll_client(), Err(Error::Done));
4663    }
4664
4665    #[test]
4666    /// Client sends multiple HEADERS before data.
4667    fn additional_headers_before_data_client() {
4668        let mut s = Session::new().unwrap();
4669        s.handshake().unwrap();
4670
4671        let (stream, req) = s.send_request(false).unwrap();
4672
4673        let req_trailer = vec![Header::new(b"goodbye", b"world")];
4674
4675        assert_eq!(
4676            s.client.send_additional_headers(
4677                &mut s.pipe.client,
4678                stream,
4679                &req_trailer,
4680                true,
4681                false
4682            ),
4683            Ok(())
4684        );
4685
4686        s.advance().ok();
4687
4688        let ev_initial_headers = Event::Headers {
4689            list: req,
4690            more_frames: true,
4691        };
4692
4693        let ev_trailing_headers = Event::Headers {
4694            list: req_trailer,
4695            more_frames: true,
4696        };
4697
4698        assert_eq!(s.poll_server(), Ok((stream, ev_initial_headers)));
4699        assert_eq!(s.poll_server(), Ok((stream, ev_trailing_headers)));
4700        assert_eq!(s.poll_server(), Err(Error::Done));
4701    }
4702
4703    #[test]
4704    /// Client sends multiple HEADERS before data.
4705    fn data_after_trailers_client() {
4706        let mut s = Session::new().unwrap();
4707        s.handshake().unwrap();
4708
4709        let (stream, req) = s.send_request(false).unwrap();
4710
4711        let body = s.send_body_client(stream, false).unwrap();
4712
4713        let mut recv_buf = vec![0; body.len()];
4714
4715        let req_trailers = vec![Header::new(b"foo", b"bar")];
4716
4717        s.client
4718            .send_additional_headers(
4719                &mut s.pipe.client,
4720                stream,
4721                &req_trailers,
4722                true,
4723                false,
4724            )
4725            .unwrap();
4726
4727        s.advance().ok();
4728
4729        s.send_frame_client(
4730            frame::Frame::Data {
4731                payload: vec![1, 2, 3, 4],
4732            },
4733            stream,
4734            true,
4735        )
4736        .unwrap();
4737
4738        let ev_headers = Event::Headers {
4739            list: req,
4740            more_frames: true,
4741        };
4742
4743        let ev_trailers = Event::Headers {
4744            list: req_trailers,
4745            more_frames: true,
4746        };
4747
4748        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4749        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
4750        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
4751        assert_eq!(s.poll_server(), Ok((stream, ev_trailers)));
4752        assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
4753    }
4754
4755    #[test]
4756    /// Send a MAX_PUSH_ID frame from the client on a valid stream.
4757    fn max_push_id_from_client_good() {
4758        let mut s = Session::new().unwrap();
4759        s.handshake().unwrap();
4760
4761        s.send_frame_client(
4762            frame::Frame::MaxPushId { push_id: 1 },
4763            s.client.control_stream_id.unwrap(),
4764            false,
4765        )
4766        .unwrap();
4767
4768        assert_eq!(s.poll_server(), Err(Error::Done));
4769    }
4770
4771    #[test]
4772    /// Send a MAX_PUSH_ID frame from the client on an invalid stream.
4773    fn max_push_id_from_client_bad_stream() {
4774        let mut s = Session::new().unwrap();
4775        s.handshake().unwrap();
4776
4777        let (stream, req) = s.send_request(false).unwrap();
4778
4779        s.send_frame_client(
4780            frame::Frame::MaxPushId { push_id: 2 },
4781            stream,
4782            false,
4783        )
4784        .unwrap();
4785
4786        let ev_headers = Event::Headers {
4787            list: req,
4788            more_frames: true,
4789        };
4790
4791        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4792        assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
4793    }
4794
4795    #[test]
4796    /// Send a sequence of MAX_PUSH_ID frames from the client that attempt to
4797    /// reduce the limit.
4798    fn max_push_id_from_client_limit_reduction() {
4799        let mut s = Session::new().unwrap();
4800        s.handshake().unwrap();
4801
4802        s.send_frame_client(
4803            frame::Frame::MaxPushId { push_id: 2 },
4804            s.client.control_stream_id.unwrap(),
4805            false,
4806        )
4807        .unwrap();
4808
4809        s.send_frame_client(
4810            frame::Frame::MaxPushId { push_id: 1 },
4811            s.client.control_stream_id.unwrap(),
4812            false,
4813        )
4814        .unwrap();
4815
4816        assert_eq!(s.poll_server(), Err(Error::IdError));
4817    }
4818
4819    #[test]
4820    /// Send a MAX_PUSH_ID frame from the server, which is forbidden.
4821    fn max_push_id_from_server() {
4822        let mut s = Session::new().unwrap();
4823        s.handshake().unwrap();
4824
4825        s.send_frame_server(
4826            frame::Frame::MaxPushId { push_id: 1 },
4827            s.server.control_stream_id.unwrap(),
4828            false,
4829        )
4830        .unwrap();
4831
4832        assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
4833    }
4834
4835    #[test]
4836    /// Send a PUSH_PROMISE frame from the client, which is forbidden.
4837    fn push_promise_from_client() {
4838        let mut s = Session::new().unwrap();
4839        s.handshake().unwrap();
4840
4841        let (stream, req) = s.send_request(false).unwrap();
4842
4843        let header_block = s.client.encode_header_block(&req).unwrap();
4844
4845        s.send_frame_client(
4846            frame::Frame::PushPromise {
4847                push_id: 1,
4848                header_block,
4849            },
4850            stream,
4851            false,
4852        )
4853        .unwrap();
4854
4855        let ev_headers = Event::Headers {
4856            list: req,
4857            more_frames: true,
4858        };
4859
4860        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4861        assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
4862    }
4863
4864    #[test]
4865    /// Server push streams from client are not allowed by the protocol.
4866    fn push_stream_from_client() {
4867        let mut s = Session::new().unwrap();
4868        s.handshake().unwrap();
4869
4870        s.client
4871            .open_uni_stream(
4872                &mut s.pipe.client,
4873                stream::HTTP3_PUSH_STREAM_TYPE_ID,
4874            )
4875            .unwrap();
4876
4877        s.advance().ok();
4878
4879        assert_eq!(s.poll_server(), Err(Error::StreamCreationError));
4880    }
4881
4882    #[test]
4883    /// Server push streams from server are not allowed since the client does
4884    /// not advertise server push support by default.
4885    fn push_stream_from_server() {
4886        let mut s = Session::new().unwrap();
4887        s.handshake().unwrap();
4888
4889        s.server
4890            .open_uni_stream(
4891                &mut s.pipe.server,
4892                stream::HTTP3_PUSH_STREAM_TYPE_ID,
4893            )
4894            .unwrap();
4895
4896        s.advance().ok();
4897
4898        assert_eq!(s.poll_client(), Err(Error::StreamCreationError));
4899    }
4900
4901    #[test]
4902    /// Send a CANCEL_PUSH frame from the client.
4903    fn cancel_push_from_client() {
4904        let mut s = Session::new().unwrap();
4905        s.handshake().unwrap();
4906
4907        s.send_frame_client(
4908            frame::Frame::CancelPush { push_id: 1 },
4909            s.client.control_stream_id.unwrap(),
4910            false,
4911        )
4912        .unwrap();
4913
4914        assert_eq!(s.poll_server(), Err(Error::Done));
4915    }
4916
4917    #[test]
4918    /// Send a CANCEL_PUSH frame from the client on an invalid stream.
4919    fn cancel_push_from_client_bad_stream() {
4920        let mut s = Session::new().unwrap();
4921        s.handshake().unwrap();
4922
4923        let (stream, req) = s.send_request(false).unwrap();
4924
4925        s.send_frame_client(
4926            frame::Frame::CancelPush { push_id: 2 },
4927            stream,
4928            false,
4929        )
4930        .unwrap();
4931
4932        let ev_headers = Event::Headers {
4933            list: req,
4934            more_frames: true,
4935        };
4936
4937        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
4938        assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
4939    }
4940
4941    #[test]
4942    /// Send a CANCEL_PUSH frame from the client.
4943    fn cancel_push_from_server() {
4944        let mut s = Session::new().unwrap();
4945        s.handshake().unwrap();
4946
4947        s.send_frame_server(
4948            frame::Frame::CancelPush { push_id: 1 },
4949            s.server.control_stream_id.unwrap(),
4950            false,
4951        )
4952        .unwrap();
4953
4954        assert_eq!(s.poll_client(), Err(Error::Done));
4955    }
4956
4957    #[test]
4958    /// Send a GOAWAY frame from the client.
4959    fn goaway_from_client_good() {
4960        let mut s = Session::new().unwrap();
4961        s.handshake().unwrap();
4962
4963        s.client.send_goaway(&mut s.pipe.client, 100).unwrap();
4964
4965        s.advance().ok();
4966
4967        // TODO: server push
4968        assert_eq!(s.poll_server(), Ok((0, Event::GoAway)));
4969    }
4970
4971    #[test]
4972    /// Send a GOAWAY frame from the server.
4973    fn goaway_from_server_good() {
4974        let mut s = Session::new().unwrap();
4975        s.handshake().unwrap();
4976
4977        s.server.send_goaway(&mut s.pipe.server, 4000).unwrap();
4978
4979        s.advance().ok();
4980
4981        assert_eq!(s.poll_client(), Ok((4000, Event::GoAway)));
4982    }
4983
4984    #[test]
4985    /// A client MUST NOT send a request after it receives GOAWAY.
4986    fn client_request_after_goaway() {
4987        let mut s = Session::new().unwrap();
4988        s.handshake().unwrap();
4989
4990        s.server.send_goaway(&mut s.pipe.server, 4000).unwrap();
4991
4992        s.advance().ok();
4993
4994        assert_eq!(s.poll_client(), Ok((4000, Event::GoAway)));
4995
4996        assert_eq!(s.send_request(true), Err(Error::FrameUnexpected));
4997    }
4998
4999    #[test]
5000    /// Send a GOAWAY frame from the server, using an invalid goaway ID.
5001    fn goaway_from_server_invalid_id() {
5002        let mut s = Session::new().unwrap();
5003        s.handshake().unwrap();
5004
5005        s.send_frame_server(
5006            frame::Frame::GoAway { id: 1 },
5007            s.server.control_stream_id.unwrap(),
5008            false,
5009        )
5010        .unwrap();
5011
5012        assert_eq!(s.poll_client(), Err(Error::IdError));
5013    }
5014
5015    #[test]
5016    /// Send multiple GOAWAY frames from the server, that increase the goaway
5017    /// ID.
5018    fn goaway_from_server_increase_id() {
5019        let mut s = Session::new().unwrap();
5020        s.handshake().unwrap();
5021
5022        s.send_frame_server(
5023            frame::Frame::GoAway { id: 0 },
5024            s.server.control_stream_id.unwrap(),
5025            false,
5026        )
5027        .unwrap();
5028
5029        s.send_frame_server(
5030            frame::Frame::GoAway { id: 4 },
5031            s.server.control_stream_id.unwrap(),
5032            false,
5033        )
5034        .unwrap();
5035
5036        assert_eq!(s.poll_client(), Ok((0, Event::GoAway)));
5037
5038        assert_eq!(s.poll_client(), Err(Error::IdError));
5039    }
5040
5041    #[test]
5042    #[cfg(feature = "sfv")]
5043    fn parse_priority_field_value() {
5044        // Legal dicts
5045        assert_eq!(
5046            Ok(Priority::new(0, false)),
5047            Priority::try_from(b"u=0".as_slice())
5048        );
5049        assert_eq!(
5050            Ok(Priority::new(3, false)),
5051            Priority::try_from(b"u=3".as_slice())
5052        );
5053        assert_eq!(
5054            Ok(Priority::new(7, false)),
5055            Priority::try_from(b"u=7".as_slice())
5056        );
5057
5058        assert_eq!(
5059            Ok(Priority::new(0, true)),
5060            Priority::try_from(b"u=0, i".as_slice())
5061        );
5062        assert_eq!(
5063            Ok(Priority::new(3, true)),
5064            Priority::try_from(b"u=3, i".as_slice())
5065        );
5066        assert_eq!(
5067            Ok(Priority::new(7, true)),
5068            Priority::try_from(b"u=7, i".as_slice())
5069        );
5070
5071        assert_eq!(
5072            Ok(Priority::new(0, true)),
5073            Priority::try_from(b"u=0, i=?1".as_slice())
5074        );
5075        assert_eq!(
5076            Ok(Priority::new(3, true)),
5077            Priority::try_from(b"u=3, i=?1".as_slice())
5078        );
5079        assert_eq!(
5080            Ok(Priority::new(7, true)),
5081            Priority::try_from(b"u=7, i=?1".as_slice())
5082        );
5083
5084        assert_eq!(
5085            Ok(Priority::new(3, false)),
5086            Priority::try_from(b"".as_slice())
5087        );
5088
5089        assert_eq!(
5090            Ok(Priority::new(0, true)),
5091            Priority::try_from(b"u=0;foo, i;bar".as_slice())
5092        );
5093        assert_eq!(
5094            Ok(Priority::new(3, true)),
5095            Priority::try_from(b"u=3;hello, i;world".as_slice())
5096        );
5097        assert_eq!(
5098            Ok(Priority::new(7, true)),
5099            Priority::try_from(b"u=7;croeso, i;gymru".as_slice())
5100        );
5101
5102        assert_eq!(
5103            Ok(Priority::new(0, true)),
5104            Priority::try_from(b"u=0, i, spinaltap=11".as_slice())
5105        );
5106
5107        // Illegal formats
5108        assert_eq!(Err(Error::Done), Priority::try_from(b"0".as_slice()));
5109        assert_eq!(
5110            Ok(Priority::new(7, false)),
5111            Priority::try_from(b"u=-1".as_slice())
5112        );
5113        assert_eq!(Err(Error::Done), Priority::try_from(b"u=0.2".as_slice()));
5114        assert_eq!(
5115            Ok(Priority::new(7, false)),
5116            Priority::try_from(b"u=100".as_slice())
5117        );
5118        assert_eq!(
5119            Err(Error::Done),
5120            Priority::try_from(b"u=3, i=true".as_slice())
5121        );
5122
5123        // Trailing comma in dict is malformed
5124        assert_eq!(Err(Error::Done), Priority::try_from(b"u=7, ".as_slice()));
5125    }
5126
5127    #[test]
5128    /// Send a PRIORITY_UPDATE for request stream from the client.
5129    fn priority_update_request() {
5130        let mut s = Session::new().unwrap();
5131        s.handshake().unwrap();
5132
5133        s.client
5134            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5135                urgency: 3,
5136                incremental: false,
5137            })
5138            .unwrap();
5139        s.advance().ok();
5140
5141        assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
5142        assert_eq!(s.poll_server(), Err(Error::Done));
5143    }
5144
5145    #[test]
5146    /// Send a PRIORITY_UPDATE for request stream from the client that is too
5147    /// large.
5148    fn priority_update_request_max_size_limit_default() {
5149        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
5150        config
5151            .load_cert_chain_from_pem_file("examples/cert.crt")
5152            .unwrap();
5153        config
5154            .load_priv_key_from_pem_file("examples/cert.key")
5155            .unwrap();
5156        config.set_application_protos(&[b"h3"]).unwrap();
5157        config.set_initial_max_data(1500);
5158        config.set_initial_max_stream_data_bidi_local(1500);
5159        config.set_initial_max_stream_data_bidi_remote(1500);
5160        config.set_initial_max_stream_data_uni(1500);
5161        config.set_initial_max_streams_bidi(5);
5162        config.set_initial_max_streams_uni(5);
5163        config.verify_peer(false);
5164
5165        let h3_config = Config::new().unwrap();
5166
5167        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
5168
5169        s.handshake().unwrap();
5170
5171        let mut d = vec![42; 600];
5172        let mut b = octets::OctetsMut::with_slice(&mut d);
5173
5174        let pu = frame::Frame::PriorityUpdateRequest {
5175            prioritized_element_id: 0,
5176            priority_field_value: vec![0; 512],
5177        };
5178
5179        pu.to_bytes(&mut b).unwrap();
5180
5181        s.pipe.client.stream_send(2, &d, true).unwrap();
5182
5183        s.advance().ok();
5184
5185        assert_eq!(s.poll_server(), Err(Error::ExcessiveLoad));
5186
5187        assert_eq!(
5188            s.pipe.server.local_error.as_ref().unwrap().error_code,
5189            Error::to_wire(Error::ExcessiveLoad)
5190        );
5191    }
5192
5193    #[test]
5194    /// Send a PRIORITY_UPDATE for request stream from the client.
5195    fn priority_update_single_stream_rearm() {
5196        let mut s = Session::new().unwrap();
5197        s.handshake().unwrap();
5198
5199        s.client
5200            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5201                urgency: 3,
5202                incremental: false,
5203            })
5204            .unwrap();
5205        s.advance().ok();
5206
5207        assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
5208        assert_eq!(s.poll_server(), Err(Error::Done));
5209
5210        s.client
5211            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5212                urgency: 5,
5213                incremental: false,
5214            })
5215            .unwrap();
5216        s.advance().ok();
5217
5218        assert_eq!(s.poll_server(), Err(Error::Done));
5219
5220        // There is only one PRIORITY_UPDATE frame to read. Once read, the event
5221        // will rearm ready for more.
5222        assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=5".to_vec()));
5223        assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
5224
5225        s.client
5226            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5227                urgency: 7,
5228                incremental: false,
5229            })
5230            .unwrap();
5231        s.advance().ok();
5232
5233        assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
5234        assert_eq!(s.poll_server(), Err(Error::Done));
5235
5236        assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=7".to_vec()));
5237        assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
5238    }
5239
5240    #[test]
5241    /// Send multiple PRIORITY_UPDATE frames for different streams from the
5242    /// client across multiple flights of exchange.
5243    fn priority_update_request_multiple_stream_arm_multiple_flights() {
5244        let mut s = Session::new().unwrap();
5245        s.handshake().unwrap();
5246
5247        s.client
5248            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5249                urgency: 3,
5250                incremental: false,
5251            })
5252            .unwrap();
5253        s.advance().ok();
5254
5255        assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
5256        assert_eq!(s.poll_server(), Err(Error::Done));
5257
5258        s.client
5259            .send_priority_update_for_request(&mut s.pipe.client, 4, &Priority {
5260                urgency: 1,
5261                incremental: false,
5262            })
5263            .unwrap();
5264        s.advance().ok();
5265
5266        assert_eq!(s.poll_server(), Ok((4, Event::PriorityUpdate)));
5267        assert_eq!(s.poll_server(), Err(Error::Done));
5268
5269        s.client
5270            .send_priority_update_for_request(&mut s.pipe.client, 8, &Priority {
5271                urgency: 2,
5272                incremental: false,
5273            })
5274            .unwrap();
5275        s.advance().ok();
5276
5277        assert_eq!(s.poll_server(), Ok((8, Event::PriorityUpdate)));
5278        assert_eq!(s.poll_server(), Err(Error::Done));
5279
5280        assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
5281        assert_eq!(s.server.take_last_priority_update(4), Ok(b"u=1".to_vec()));
5282        assert_eq!(s.server.take_last_priority_update(8), Ok(b"u=2".to_vec()));
5283        assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
5284    }
5285
5286    #[test]
5287    /// Send multiple PRIORITY_UPDATE frames for different streams from the
5288    /// client across a single flight.
5289    fn priority_update_request_multiple_stream_arm_single_flight() {
5290        let mut s = Session::new().unwrap();
5291        s.handshake().unwrap();
5292
5293        let mut d = [42; 65535];
5294
5295        let mut b = octets::OctetsMut::with_slice(&mut d);
5296
5297        let p1 = frame::Frame::PriorityUpdateRequest {
5298            prioritized_element_id: 0,
5299            priority_field_value: b"u=3".to_vec(),
5300        };
5301
5302        let p2 = frame::Frame::PriorityUpdateRequest {
5303            prioritized_element_id: 4,
5304            priority_field_value: b"u=3".to_vec(),
5305        };
5306
5307        let p3 = frame::Frame::PriorityUpdateRequest {
5308            prioritized_element_id: 8,
5309            priority_field_value: b"u=3".to_vec(),
5310        };
5311
5312        p1.to_bytes(&mut b).unwrap();
5313        p2.to_bytes(&mut b).unwrap();
5314        p3.to_bytes(&mut b).unwrap();
5315
5316        let off = b.off();
5317        s.pipe
5318            .client
5319            .stream_send(s.client.control_stream_id.unwrap(), &d[..off], false)
5320            .unwrap();
5321
5322        s.advance().ok();
5323
5324        assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
5325        assert_eq!(s.poll_server(), Ok((4, Event::PriorityUpdate)));
5326        assert_eq!(s.poll_server(), Ok((8, Event::PriorityUpdate)));
5327        assert_eq!(s.poll_server(), Err(Error::Done));
5328
5329        assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
5330        assert_eq!(s.server.take_last_priority_update(4), Ok(b"u=3".to_vec()));
5331        assert_eq!(s.server.take_last_priority_update(8), Ok(b"u=3".to_vec()));
5332
5333        assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
5334    }
5335
5336    #[test]
5337    /// Send a PRIORITY_UPDATE for a request stream, before and after the stream
5338    /// has been completed.
5339    fn priority_update_request_collected_completed() {
5340        let mut s = Session::new().unwrap();
5341        s.handshake().unwrap();
5342
5343        s.client
5344            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5345                urgency: 3,
5346                incremental: false,
5347            })
5348            .unwrap();
5349        s.advance().ok();
5350
5351        let (stream, req) = s.send_request(true).unwrap();
5352        let ev_headers = Event::Headers {
5353            list: req,
5354            more_frames: false,
5355        };
5356
5357        // Priority event is generated before request headers.
5358        assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
5359        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
5360        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
5361        assert_eq!(s.poll_server(), Err(Error::Done));
5362
5363        assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
5364        assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
5365
5366        let resp = s.send_response(stream, true).unwrap();
5367
5368        let ev_headers = Event::Headers {
5369            list: resp,
5370            more_frames: false,
5371        };
5372
5373        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
5374        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
5375        assert_eq!(s.poll_client(), Err(Error::Done));
5376
5377        // Now send a PRIORITY_UPDATE for the completed request stream.
5378        s.client
5379            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5380                urgency: 3,
5381                incremental: false,
5382            })
5383            .unwrap();
5384        s.advance().ok();
5385
5386        // No event generated at server
5387        assert_eq!(s.poll_server(), Err(Error::Done));
5388    }
5389
5390    #[test]
5391    /// Send a PRIORITY_UPDATE for a request stream after H3 has collected it,
5392    /// but before the transport stream has been collected.
5393    fn priority_update_request_after_h3_collection() {
5394        let mut s = Session::new().unwrap();
5395        s.handshake().unwrap();
5396
5397        let init_streams_server = s.server.streams.len();
5398
5399        let (stream, req) = s.send_request(true).unwrap();
5400        let ev_headers = Event::Headers {
5401            list: req,
5402            more_frames: false,
5403        };
5404
5405        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
5406        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
5407        assert_eq!(s.poll_server(), Err(Error::Done));
5408
5409        let resp = vec![
5410            Header::new(b":status", b"200"),
5411            Header::new(b"server", b"quiche-test"),
5412        ];
5413
5414        s.server
5415            .send_response(&mut s.pipe.server, stream, &resp, true)
5416            .unwrap();
5417
5418        // H3 no longer needs its stream state once it has sent the response
5419        // FIN and consumed the request FIN. The QUIC stream remains until the
5420        // response FIN is acknowledged by the peer.
5421        assert_eq!(s.server.streams.len(), init_streams_server);
5422        assert!(s.pipe.server.stream_finished(stream));
5423        assert!(s.pipe.server.stream_closed(stream));
5424
5425        let stream_state = s.pipe.server.streams.get(stream).unwrap();
5426        assert!(stream_state.recv.is_fin());
5427        assert!(stream_state.send.is_fin());
5428        assert!(!s.pipe.server.streams.is_collected(stream));
5429
5430        s.client
5431            .send_priority_update_for_request(
5432                &mut s.pipe.client,
5433                stream,
5434                &Priority {
5435                    urgency: 3,
5436                    incremental: false,
5437                },
5438            )
5439            .unwrap();
5440
5441        let flight = crate::test_utils::emit_flight(&mut s.pipe.client).unwrap();
5442        crate::test_utils::process_flight(&mut s.pipe.server, flight).unwrap();
5443
5444        assert_eq!(s.poll_server(), Err(Error::Done));
5445        assert_eq!(s.server.streams.len(), init_streams_server);
5446    }
5447
5448    #[test]
5449    /// Send a PRIORITY_UPDATE for a request stream, before and after the stream
5450    /// has been stopped.
5451    fn priority_update_request_collected_stopped() {
5452        let mut s = Session::new().unwrap();
5453        s.handshake().unwrap();
5454
5455        s.client
5456            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5457                urgency: 3,
5458                incremental: false,
5459            })
5460            .unwrap();
5461        s.advance().ok();
5462
5463        let (stream, req) = s.send_request(false).unwrap();
5464        let ev_headers = Event::Headers {
5465            list: req,
5466            more_frames: true,
5467        };
5468
5469        // Priority event is generated before request headers.
5470        assert_eq!(s.poll_server(), Ok((0, Event::PriorityUpdate)));
5471        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
5472        assert_eq!(s.poll_server(), Err(Error::Done));
5473
5474        assert_eq!(s.server.take_last_priority_update(0), Ok(b"u=3".to_vec()));
5475        assert_eq!(s.server.take_last_priority_update(0), Err(Error::Done));
5476
5477        s.pipe
5478            .client
5479            .stream_shutdown(stream, crate::Shutdown::Write, 0x100)
5480            .unwrap();
5481        s.pipe
5482            .client
5483            .stream_shutdown(stream, crate::Shutdown::Read, 0x100)
5484            .unwrap();
5485
5486        s.advance().ok();
5487
5488        assert_eq!(s.poll_server(), Ok((0, Event::Reset(0x100))));
5489        assert_eq!(s.poll_server(), Err(Error::Done));
5490
5491        // Now send a PRIORITY_UPDATE for the closed request stream.
5492        s.client
5493            .send_priority_update_for_request(&mut s.pipe.client, 0, &Priority {
5494                urgency: 3,
5495                incremental: false,
5496            })
5497            .unwrap();
5498        s.advance().ok();
5499
5500        // No event generated at server
5501        assert_eq!(s.poll_server(), Err(Error::Done));
5502
5503        // The receive-side reset does not consume the STOP error.
5504        assert!(!s.pipe.server.streams.is_collected(0));
5505        assert_eq!(
5506            s.pipe.server.stream_capacity(0),
5507            Err(crate::Error::StreamStopped(0x100))
5508        );
5509        assert!(s.pipe.server.streams.is_collected(0));
5510        assert!(s.pipe.client.streams.is_collected(0));
5511    }
5512
5513    #[test]
5514    /// Send a PRIORITY_UPDATE for push stream from the client.
5515    fn priority_update_push() {
5516        let mut s = Session::new().unwrap();
5517        s.handshake().unwrap();
5518
5519        s.send_frame_client(
5520            frame::Frame::PriorityUpdatePush {
5521                prioritized_element_id: 3,
5522                priority_field_value: b"u=3".to_vec(),
5523            },
5524            s.client.control_stream_id.unwrap(),
5525            false,
5526        )
5527        .unwrap();
5528
5529        assert_eq!(s.poll_server(), Err(Error::Done));
5530    }
5531
5532    #[test]
5533    /// Send a PRIORITY_UPDATE for request stream from the client but for an
5534    /// incorrect stream type.
5535    fn priority_update_request_bad_stream() {
5536        let mut s = Session::new().unwrap();
5537        s.handshake().unwrap();
5538
5539        s.send_frame_client(
5540            frame::Frame::PriorityUpdateRequest {
5541                prioritized_element_id: 5,
5542                priority_field_value: b"u=3".to_vec(),
5543            },
5544            s.client.control_stream_id.unwrap(),
5545            false,
5546        )
5547        .unwrap();
5548
5549        assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
5550    }
5551
5552    #[test]
5553    /// Send a PRIORITY_UPDATE for push stream from the client but for an
5554    /// incorrect stream type.
5555    fn priority_update_push_bad_stream() {
5556        let mut s = Session::new().unwrap();
5557        s.handshake().unwrap();
5558
5559        s.send_frame_client(
5560            frame::Frame::PriorityUpdatePush {
5561                prioritized_element_id: 5,
5562                priority_field_value: b"u=3".to_vec(),
5563            },
5564            s.client.control_stream_id.unwrap(),
5565            false,
5566        )
5567        .unwrap();
5568
5569        assert_eq!(s.poll_server(), Err(Error::FrameUnexpected));
5570    }
5571
5572    #[test]
5573    /// Send a PRIORITY_UPDATE for request stream from the server.
5574    fn priority_update_request_from_server() {
5575        let mut s = Session::new().unwrap();
5576        s.handshake().unwrap();
5577
5578        s.send_frame_server(
5579            frame::Frame::PriorityUpdateRequest {
5580                prioritized_element_id: 0,
5581                priority_field_value: b"u=3".to_vec(),
5582            },
5583            s.server.control_stream_id.unwrap(),
5584            false,
5585        )
5586        .unwrap();
5587
5588        assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
5589    }
5590
5591    #[test]
5592    /// Send a PRIORITY_UPDATE for request stream from the server.
5593    fn priority_update_push_from_server() {
5594        let mut s = Session::new().unwrap();
5595        s.handshake().unwrap();
5596
5597        s.send_frame_server(
5598            frame::Frame::PriorityUpdatePush {
5599                prioritized_element_id: 0,
5600                priority_field_value: b"u=3".to_vec(),
5601            },
5602            s.server.control_stream_id.unwrap(),
5603            false,
5604        )
5605        .unwrap();
5606
5607        assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
5608    }
5609
5610    #[test]
5611    /// Ensure quiche allocates streams for client and server roles as expected.
5612    fn uni_stream_local_counting() {
5613        let config = Config::new().unwrap();
5614
5615        let h3_cln = Connection::new(&config, false, false).unwrap();
5616        assert_eq!(h3_cln.next_uni_stream_id, 2);
5617
5618        let h3_srv = Connection::new(&config, true, false).unwrap();
5619        assert_eq!(h3_srv.next_uni_stream_id, 3);
5620    }
5621
5622    #[test]
5623    /// Client opens multiple control streams, which is forbidden.
5624    fn open_multiple_control_streams() {
5625        let mut s = Session::new().unwrap();
5626        s.handshake().unwrap();
5627
5628        let stream_id = s.client.next_uni_stream_id;
5629
5630        let mut d = [42; 8];
5631        let mut b = octets::OctetsMut::with_slice(&mut d);
5632
5633        s.pipe
5634            .client
5635            .stream_send(
5636                stream_id,
5637                b.put_varint(stream::HTTP3_CONTROL_STREAM_TYPE_ID).unwrap(),
5638                false,
5639            )
5640            .unwrap();
5641
5642        s.advance().ok();
5643
5644        assert_eq!(s.poll_server(), Err(Error::StreamCreationError));
5645    }
5646
5647    #[test]
5648    /// Client closes the control stream, which is forbidden.
5649    fn close_control_stream_after_type() {
5650        let mut s = Session::new().unwrap();
5651        s.handshake().unwrap();
5652
5653        s.pipe
5654            .client
5655            .stream_send(s.client.control_stream_id.unwrap(), &[], true)
5656            .unwrap();
5657
5658        s.advance().ok();
5659
5660        assert_eq!(
5661            Err(Error::ClosedCriticalStream),
5662            s.server.poll(&mut s.pipe.server)
5663        );
5664        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5665    }
5666
5667    #[test]
5668    /// Client closes the control stream after a frame is sent, which is
5669    /// forbidden.
5670    fn close_control_stream_after_frame() {
5671        let mut s = Session::new().unwrap();
5672        s.handshake().unwrap();
5673
5674        s.send_frame_client(
5675            frame::Frame::MaxPushId { push_id: 1 },
5676            s.client.control_stream_id.unwrap(),
5677            true,
5678        )
5679        .unwrap();
5680
5681        assert_eq!(
5682            Err(Error::ClosedCriticalStream),
5683            s.server.poll(&mut s.pipe.server)
5684        );
5685        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5686    }
5687
5688    #[test]
5689    /// Client resets the control stream, which is forbidden.
5690    fn reset_control_stream_after_type() {
5691        let mut s = Session::new().unwrap();
5692        s.handshake().unwrap();
5693
5694        s.pipe
5695            .client
5696            .stream_shutdown(
5697                s.client.control_stream_id.unwrap(),
5698                crate::Shutdown::Write,
5699                0,
5700            )
5701            .unwrap();
5702
5703        s.advance().ok();
5704
5705        assert_eq!(
5706            Err(Error::ClosedCriticalStream),
5707            s.server.poll(&mut s.pipe.server)
5708        );
5709        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5710    }
5711
5712    #[test]
5713    /// Client resets the control stream after a frame is sent, which is
5714    /// forbidden.
5715    fn reset_control_stream_after_frame() {
5716        let mut s = Session::new().unwrap();
5717        s.handshake().unwrap();
5718
5719        s.send_frame_client(
5720            frame::Frame::MaxPushId { push_id: 1 },
5721            s.client.control_stream_id.unwrap(),
5722            false,
5723        )
5724        .unwrap();
5725
5726        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5727
5728        s.pipe
5729            .client
5730            .stream_shutdown(
5731                s.client.control_stream_id.unwrap(),
5732                crate::Shutdown::Write,
5733                0,
5734            )
5735            .unwrap();
5736
5737        s.advance().ok();
5738
5739        assert_eq!(
5740            Err(Error::ClosedCriticalStream),
5741            s.server.poll(&mut s.pipe.server)
5742        );
5743        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5744    }
5745
5746    #[test]
5747    /// Client closes QPACK stream, which is forbidden.
5748    fn close_qpack_stream_after_type() {
5749        let mut s = Session::new().unwrap();
5750        s.handshake().unwrap();
5751
5752        s.pipe
5753            .client
5754            .stream_send(
5755                s.client.local_qpack_streams.encoder_stream_id.unwrap(),
5756                &[],
5757                true,
5758            )
5759            .unwrap();
5760
5761        s.advance().ok();
5762
5763        assert_eq!(
5764            Err(Error::ClosedCriticalStream),
5765            s.server.poll(&mut s.pipe.server)
5766        );
5767        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5768    }
5769
5770    #[test]
5771    /// Client closes QPACK stream after sending some stuff, which is forbidden.
5772    fn close_qpack_stream_after_data() {
5773        let mut s = Session::new().unwrap();
5774        s.handshake().unwrap();
5775
5776        let stream_id = s.client.local_qpack_streams.encoder_stream_id.unwrap();
5777        let d = [0; 1];
5778
5779        s.pipe.client.stream_send(stream_id, &d, false).unwrap();
5780        s.pipe.client.stream_send(stream_id, &d, true).unwrap();
5781
5782        s.advance().ok();
5783
5784        assert_eq!(
5785            Err(Error::ClosedCriticalStream),
5786            s.server.poll(&mut s.pipe.server)
5787        );
5788        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5789    }
5790
5791    #[test]
5792    /// Client resets QPACK stream, which is forbidden.
5793    fn reset_qpack_stream_after_type() {
5794        let mut s = Session::new().unwrap();
5795        s.handshake().unwrap();
5796
5797        s.pipe
5798            .client
5799            .stream_shutdown(
5800                s.client.local_qpack_streams.encoder_stream_id.unwrap(),
5801                crate::Shutdown::Write,
5802                0,
5803            )
5804            .unwrap();
5805
5806        s.advance().ok();
5807
5808        assert_eq!(
5809            Err(Error::ClosedCriticalStream),
5810            s.server.poll(&mut s.pipe.server)
5811        );
5812        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5813    }
5814
5815    #[test]
5816    /// Client resets QPACK stream after sending some stuff, which is forbidden.
5817    fn reset_qpack_stream_after_data() {
5818        let mut s = Session::new().unwrap();
5819        s.handshake().unwrap();
5820
5821        let stream_id = s.client.local_qpack_streams.encoder_stream_id.unwrap();
5822        let d = [0; 1];
5823
5824        s.pipe.client.stream_send(stream_id, &d, false).unwrap();
5825        s.pipe.client.stream_send(stream_id, &d, false).unwrap();
5826
5827        s.advance().ok();
5828
5829        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5830
5831        s.pipe
5832            .client
5833            .stream_shutdown(stream_id, crate::Shutdown::Write, 0)
5834            .unwrap();
5835
5836        s.advance().ok();
5837
5838        assert_eq!(
5839            Err(Error::ClosedCriticalStream),
5840            s.server.poll(&mut s.pipe.server)
5841        );
5842        assert_eq!(Err(Error::Done), s.server.poll(&mut s.pipe.server));
5843    }
5844
5845    #[test]
5846    /// Client sends QPACK data.
5847    fn qpack_data() {
5848        // TODO: QPACK instructions are ignored until dynamic table support is
5849        // added so we just test that the data is safely ignored.
5850        let mut s = Session::new().unwrap();
5851        s.handshake().unwrap();
5852
5853        let e_stream_id = s.client.local_qpack_streams.encoder_stream_id.unwrap();
5854        let d_stream_id = s.client.local_qpack_streams.decoder_stream_id.unwrap();
5855        let d = [0; 20];
5856
5857        s.pipe.client.stream_send(e_stream_id, &d, false).unwrap();
5858        s.advance().ok();
5859
5860        s.pipe.client.stream_send(d_stream_id, &d, false).unwrap();
5861        s.advance().ok();
5862
5863        match s.server.poll(&mut s.pipe.server) {
5864            Ok(_) => panic!(),
5865
5866            Err(Error::Done) => {
5867                assert_eq!(s.server.peer_qpack_streams.encoder_stream_bytes, 20);
5868                assert_eq!(s.server.peer_qpack_streams.decoder_stream_bytes, 20);
5869            },
5870
5871            Err(_) => {
5872                panic!();
5873            },
5874        }
5875
5876        let stats = s.server.stats();
5877        assert_eq!(stats.qpack_encoder_stream_recv_bytes, 20);
5878        assert_eq!(stats.qpack_decoder_stream_recv_bytes, 20);
5879    }
5880
5881    #[test]
5882    /// Tests limits for the stream state buffer maximum size.
5883    fn max_state_buf_size() {
5884        let mut s = Session::new().unwrap();
5885        s.handshake().unwrap();
5886
5887        let req = vec![
5888            Header::new(b":method", b"GET"),
5889            Header::new(b":scheme", b"https"),
5890            Header::new(b":authority", b"quic.tech"),
5891            Header::new(b":path", b"/test"),
5892            Header::new(b"user-agent", b"quiche-test"),
5893        ];
5894
5895        assert_eq!(
5896            s.client.send_request(&mut s.pipe.client, &req, false),
5897            Ok(0)
5898        );
5899
5900        s.advance().ok();
5901
5902        let ev_headers = Event::Headers {
5903            list: req,
5904            more_frames: true,
5905        };
5906
5907        assert_eq!(s.server.poll(&mut s.pipe.server), Ok((0, ev_headers)));
5908
5909        // DATA frames don't consume the state buffer, so can be of any size.
5910        let mut d = [42; 128];
5911        let mut b = octets::OctetsMut::with_slice(&mut d);
5912
5913        let frame_type = b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
5914        s.pipe.client.stream_send(0, frame_type, false).unwrap();
5915
5916        let frame_len = b.put_varint(1 << 24).unwrap();
5917        s.pipe.client.stream_send(0, frame_len, false).unwrap();
5918
5919        s.pipe.client.stream_send(0, &d, false).unwrap();
5920
5921        s.advance().ok();
5922
5923        assert_eq!(s.server.poll(&mut s.pipe.server), Ok((0, Event::Data)));
5924
5925        // GREASE frames consume the state buffer, so need to be limited.
5926        let mut s = Session::new().unwrap();
5927        s.handshake().unwrap();
5928
5929        let mut d = [42; 128];
5930        let mut b = octets::OctetsMut::with_slice(&mut d);
5931
5932        let frame_type = b.put_varint(148_764_065_110_560_899).unwrap();
5933        s.pipe.client.stream_send(0, frame_type, false).unwrap();
5934
5935        let frame_len = b.put_varint(1 << 24).unwrap();
5936        s.pipe.client.stream_send(0, frame_len, false).unwrap();
5937
5938        s.pipe.client.stream_send(0, &d, false).unwrap();
5939
5940        s.advance().ok();
5941
5942        assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::ExcessiveLoad));
5943    }
5944
5945    #[test]
5946    /// Tests that DATA frames are properly truncated depending on the request
5947    /// stream's outgoing flow control capacity.
5948    fn stream_backpressure() {
5949        let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
5950
5951        let mut s = Session::new().unwrap();
5952        s.handshake().unwrap();
5953
5954        let (stream, req) = s.send_request(false).unwrap();
5955
5956        let total_data_frames = 6;
5957
5958        for _ in 0..total_data_frames {
5959            assert_eq!(
5960                s.client
5961                    .send_body(&mut s.pipe.client, stream, &bytes, false),
5962                Ok(bytes.len())
5963            );
5964
5965            s.advance().ok();
5966        }
5967
5968        assert_eq!(
5969            s.client.send_body(&mut s.pipe.client, stream, &bytes, true),
5970            Ok(bytes.len() - 2)
5971        );
5972
5973        s.advance().ok();
5974
5975        let mut recv_buf = vec![0; bytes.len()];
5976
5977        let ev_headers = Event::Headers {
5978            list: req,
5979            more_frames: true,
5980        };
5981
5982        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
5983        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
5984        assert_eq!(s.poll_server(), Err(Error::Done));
5985
5986        for _ in 0..total_data_frames {
5987            assert_eq!(
5988                s.recv_body_server(stream, &mut recv_buf),
5989                Ok(bytes.len())
5990            );
5991        }
5992
5993        assert_eq!(
5994            s.recv_body_server(stream, &mut recv_buf),
5995            Ok(bytes.len() - 2)
5996        );
5997
5998        // Fin flag from last send_body() call was not sent as the buffer was
5999        // only partially written.
6000        assert_eq!(s.poll_server(), Err(Error::Done));
6001
6002        assert_eq!(s.pipe.server.data_blocked_sent_count, 0);
6003        assert_eq!(s.pipe.server.stream_data_blocked_sent_count, 0);
6004        assert_eq!(s.pipe.server.data_blocked_recv_count, 0);
6005        assert_eq!(s.pipe.server.stream_data_blocked_recv_count, 1);
6006
6007        assert_eq!(s.pipe.client.data_blocked_sent_count, 0);
6008        assert_eq!(s.pipe.client.stream_data_blocked_sent_count, 1);
6009        assert_eq!(s.pipe.client.data_blocked_recv_count, 0);
6010        assert_eq!(s.pipe.client.stream_data_blocked_recv_count, 0);
6011    }
6012
6013    #[test]
6014    /// Tests that the max header list size setting allows larger headers than
6015    /// default.
6016    fn request_max_header_size_limit_accepts_large_headers() {
6017        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6018        config
6019            .load_cert_chain_from_pem_file("examples/cert.crt")
6020            .unwrap();
6021        config
6022            .load_priv_key_from_pem_file("examples/cert.key")
6023            .unwrap();
6024        config.set_application_protos(&[b"h3"]).unwrap();
6025        config.set_initial_max_data(150000000);
6026        config.set_initial_max_stream_data_bidi_local(150000000);
6027        config.set_initial_max_stream_data_bidi_remote(150000000);
6028        config.set_initial_max_stream_data_uni(150000000);
6029        config.set_initial_max_streams_bidi(5);
6030        config.set_initial_max_streams_uni(5);
6031        config.verify_peer(false);
6032        config.set_initial_congestion_window_packets(100);
6033
6034        let mut h3_config = Config::new().unwrap();
6035        h3_config.set_max_field_section_size(256 * 1024);
6036
6037        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6038
6039        s.handshake().unwrap();
6040
6041        let mut req = vec![
6042            Header::new(b":method", b"GET"),
6043            Header::new(b":scheme", b"https"),
6044            Header::new(b":authority", b"quic.tech"),
6045            Header::new(b":path", b"/test"),
6046        ];
6047
6048        for _ in 1..5000 {
6049            req.push(Header::new(b"aaaaaaaaaa", b"aaaaaaaaa"));
6050        }
6051
6052        let ev_headers = Event::Headers {
6053            list: req.clone(),
6054            more_frames: false,
6055        };
6056
6057        let stream = s
6058            .client
6059            .send_request(&mut s.pipe.client, &req, true)
6060            .unwrap();
6061
6062        s.advance().ok();
6063
6064        assert_eq!(stream, 0);
6065
6066        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
6067        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
6068        assert_eq!(s.poll_server(), Err(Error::Done));
6069    }
6070
6071    #[test]
6072    /// Tests that the max header list size setting is enforced after decoding.
6073    fn request_max_header_size_limit_decoded_field_section() {
6074        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6075        config
6076            .load_cert_chain_from_pem_file("examples/cert.crt")
6077            .unwrap();
6078        config
6079            .load_priv_key_from_pem_file("examples/cert.key")
6080            .unwrap();
6081        config.set_application_protos(&[b"h3"]).unwrap();
6082        config.set_initial_max_data(1500);
6083        config.set_initial_max_stream_data_bidi_local(150);
6084        config.set_initial_max_stream_data_bidi_remote(150);
6085        config.set_initial_max_stream_data_uni(150);
6086        config.set_initial_max_streams_bidi(5);
6087        config.set_initial_max_streams_uni(5);
6088        config.verify_peer(false);
6089
6090        let mut h3_config = Config::new().unwrap();
6091        h3_config.set_max_field_section_size(65);
6092
6093        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6094
6095        s.handshake().unwrap();
6096
6097        let req = vec![
6098            Header::new(b":method", b"GET"),
6099            Header::new(b":scheme", b"https"),
6100            Header::new(b":authority", b"quic.tech"),
6101            Header::new(b":path", b"/test"),
6102            Header::new(b"aaaaaaa", b"aaaaaaaa"),
6103        ];
6104
6105        let stream = s
6106            .client
6107            .send_request(&mut s.pipe.client, &req, true)
6108            .unwrap();
6109
6110        s.advance().ok();
6111
6112        assert_eq!(stream, 0);
6113
6114        assert_eq!(s.poll_server(), Err(Error::ExcessiveLoad));
6115
6116        assert_eq!(
6117            s.pipe.server.local_error.as_ref().unwrap().error_code,
6118            Error::to_wire(Error::ExcessiveLoad)
6119        );
6120    }
6121
6122    #[test]
6123    /// Tests that the max header list size setting is enforced when observing
6124    /// frame size before decode.
6125    fn request_max_header_size_limit_default_abort_before_decode() {
6126        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6127        config
6128            .load_cert_chain_from_pem_file("examples/cert.crt")
6129            .unwrap();
6130        config
6131            .load_priv_key_from_pem_file("examples/cert.key")
6132            .unwrap();
6133        config.set_application_protos(&[b"h3"]).unwrap();
6134        config.set_initial_max_data(150000);
6135        config.set_initial_max_stream_data_bidi_local(150000);
6136        config.set_initial_max_stream_data_bidi_remote(150000);
6137        config.set_initial_max_stream_data_uni(150000);
6138        config.set_initial_max_streams_bidi(5);
6139        config.set_initial_max_streams_uni(5);
6140        config.verify_peer(false);
6141
6142        let h3_config = Config::new().unwrap();
6143
6144        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6145
6146        s.handshake().unwrap();
6147
6148        let mut d = vec![42; 200000];
6149        let mut b = octets::OctetsMut::with_slice(&mut d);
6150
6151        let hdrs = frame::Frame::Headers {
6152            header_block: vec![0; 65536],
6153        };
6154
6155        hdrs.to_bytes(&mut b).unwrap();
6156
6157        s.pipe.client.stream_send(0, &d, true).unwrap();
6158
6159        s.advance().ok();
6160
6161        assert_eq!(s.poll_server(), Err(Error::ExcessiveLoad));
6162
6163        assert_eq!(
6164            s.pipe.server.local_error.as_ref().unwrap().error_code,
6165            Error::to_wire(Error::ExcessiveLoad)
6166        );
6167    }
6168
6169    #[test]
6170    /// Tests that Error::TransportError contains a transport error.
6171    fn transport_error() {
6172        let mut s = Session::new().unwrap();
6173        s.handshake().unwrap();
6174
6175        let req = vec![
6176            Header::new(b":method", b"GET"),
6177            Header::new(b":scheme", b"https"),
6178            Header::new(b":authority", b"quic.tech"),
6179            Header::new(b":path", b"/test"),
6180            Header::new(b"user-agent", b"quiche-test"),
6181        ];
6182
6183        // We need to open all streams in the same flight, so we can't use the
6184        // Session::send_request() method because it also calls advance(),
6185        // otherwise the server would send a MAX_STREAMS frame and the client
6186        // wouldn't hit the streams limit.
6187        assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(0));
6188        assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(4));
6189        assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(8));
6190        assert_eq!(
6191            s.client.send_request(&mut s.pipe.client, &req, true),
6192            Ok(12)
6193        );
6194        assert_eq!(
6195            s.client.send_request(&mut s.pipe.client, &req, true),
6196            Ok(16)
6197        );
6198
6199        assert_eq!(
6200            s.client.send_request(&mut s.pipe.client, &req, true),
6201            Err(Error::TransportError(crate::Error::StreamLimit))
6202        );
6203    }
6204
6205    #[test]
6206    /// Tests that sending DATA before HEADERS causes an error.
6207    fn data_before_headers() {
6208        let mut s = Session::new().unwrap();
6209        s.handshake().unwrap();
6210
6211        let mut d = [42; 128];
6212        let mut b = octets::OctetsMut::with_slice(&mut d);
6213
6214        let frame_type = b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
6215        s.pipe.client.stream_send(0, frame_type, false).unwrap();
6216
6217        let frame_len = b.put_varint(5).unwrap();
6218        s.pipe.client.stream_send(0, frame_len, false).unwrap();
6219
6220        s.pipe.client.stream_send(0, b"hello", false).unwrap();
6221
6222        s.advance().ok();
6223
6224        assert_eq!(
6225            s.server.poll(&mut s.pipe.server),
6226            Err(Error::FrameUnexpected)
6227        );
6228    }
6229
6230    #[test]
6231    /// Tests that calling poll() after an error occurred does nothing.
6232    fn poll_after_error() {
6233        let mut s = Session::new().unwrap();
6234        s.handshake().unwrap();
6235
6236        let mut d = [42; 128];
6237        let mut b = octets::OctetsMut::with_slice(&mut d);
6238
6239        let frame_type = b.put_varint(148_764_065_110_560_899).unwrap();
6240        s.pipe.client.stream_send(0, frame_type, false).unwrap();
6241
6242        let frame_len = b.put_varint(1 << 24).unwrap();
6243        s.pipe.client.stream_send(0, frame_len, false).unwrap();
6244
6245        s.pipe.client.stream_send(0, &d, false).unwrap();
6246
6247        s.advance().ok();
6248
6249        assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::ExcessiveLoad));
6250
6251        // Try to call poll() again after an error occurred.
6252        assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::Done));
6253    }
6254
6255    #[test]
6256    /// Tests that we limit sending HEADERS based on the stream capacity.
6257    fn headers_blocked() {
6258        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6259        config
6260            .load_cert_chain_from_pem_file("examples/cert.crt")
6261            .unwrap();
6262        config
6263            .load_priv_key_from_pem_file("examples/cert.key")
6264            .unwrap();
6265        config.set_application_protos(&[b"h3"]).unwrap();
6266        config.set_initial_max_data(75);
6267        config.set_initial_max_stream_data_bidi_local(150);
6268        config.set_initial_max_stream_data_bidi_remote(150);
6269        config.set_initial_max_stream_data_uni(150);
6270        config.set_initial_max_streams_bidi(100);
6271        config.set_initial_max_streams_uni(5);
6272        config.verify_peer(false);
6273
6274        let h3_config = Config::new().unwrap();
6275
6276        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6277
6278        s.handshake().unwrap();
6279
6280        let req = vec![
6281            Header::new(b":method", b"GET"),
6282            Header::new(b":scheme", b"https"),
6283            Header::new(b":authority", b"quic.tech"),
6284            Header::new(b":path", b"/test"),
6285        ];
6286
6287        assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(0));
6288
6289        assert_eq!(
6290            s.client.send_request(&mut s.pipe.client, &req, true),
6291            Err(Error::StreamBlocked)
6292        );
6293
6294        // Clear the writable stream queue.
6295        assert_eq!(s.pipe.client.stream_writable_next(), Some(2));
6296        assert_eq!(s.pipe.client.stream_writable_next(), Some(6));
6297        assert_eq!(s.pipe.client.stream_writable_next(), Some(10));
6298        assert_eq!(s.pipe.client.stream_writable_next(), None);
6299
6300        s.advance().ok();
6301
6302        // Once the server gives flow control credits back, we can send the
6303        // request.
6304        assert_eq!(s.pipe.client.stream_writable_next(), Some(4));
6305        assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(4));
6306
6307        assert_eq!(s.pipe.server.data_blocked_sent_count, 0);
6308        assert_eq!(s.pipe.server.stream_data_blocked_sent_count, 0);
6309        assert_eq!(s.pipe.server.data_blocked_recv_count, 1);
6310        assert_eq!(s.pipe.server.stream_data_blocked_recv_count, 0);
6311
6312        assert_eq!(s.pipe.client.data_blocked_sent_count, 1);
6313        assert_eq!(s.pipe.client.stream_data_blocked_sent_count, 0);
6314        assert_eq!(s.pipe.client.data_blocked_recv_count, 0);
6315        assert_eq!(s.pipe.client.stream_data_blocked_recv_count, 0);
6316    }
6317
6318    #[test]
6319    /// Ensure StreamBlocked when connection flow control prevents headers.
6320    fn headers_blocked_on_conn() {
6321        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6322        config
6323            .load_cert_chain_from_pem_file("examples/cert.crt")
6324            .unwrap();
6325        config
6326            .load_priv_key_from_pem_file("examples/cert.key")
6327            .unwrap();
6328        config.set_application_protos(&[b"h3"]).unwrap();
6329        config.set_initial_max_data(75);
6330        config.set_initial_max_stream_data_bidi_local(150);
6331        config.set_initial_max_stream_data_bidi_remote(150);
6332        config.set_initial_max_stream_data_uni(150);
6333        config.set_initial_max_streams_bidi(100);
6334        config.set_initial_max_streams_uni(5);
6335        config.verify_peer(false);
6336
6337        let h3_config = Config::new().unwrap();
6338
6339        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6340
6341        s.handshake().unwrap();
6342
6343        // After the HTTP handshake, some bytes of connection flow control have
6344        // been consumed. Fill the connection with more grease data on the
6345        // control stream.
6346        let d = [42; 28];
6347        assert_eq!(s.pipe.client.stream_send(2, &d, false), Ok(23));
6348
6349        let req = vec![
6350            Header::new(b":method", b"GET"),
6351            Header::new(b":scheme", b"https"),
6352            Header::new(b":authority", b"quic.tech"),
6353            Header::new(b":path", b"/test"),
6354        ];
6355
6356        // There is 0 connection-level flow control, so sending a request is
6357        // blocked.
6358        assert_eq!(
6359            s.client.send_request(&mut s.pipe.client, &req, true),
6360            Err(Error::StreamBlocked)
6361        );
6362        assert_eq!(s.pipe.client.stream_writable_next(), None);
6363
6364        // Emit the control stream data and drain it at the server via poll() to
6365        // consumes it via poll() and gives back flow control.
6366        s.advance().ok();
6367        assert_eq!(s.poll_server(), Err(Error::Done));
6368        s.advance().ok();
6369
6370        // Now we can send the request.
6371        assert_eq!(s.pipe.client.stream_writable_next(), Some(2));
6372        assert_eq!(s.pipe.client.stream_writable_next(), Some(6));
6373        assert_eq!(s.client.send_request(&mut s.pipe.client, &req, true), Ok(0));
6374
6375        assert_eq!(s.pipe.server.data_blocked_sent_count, 0);
6376        assert_eq!(s.pipe.server.stream_data_blocked_sent_count, 0);
6377        assert_eq!(s.pipe.server.data_blocked_recv_count, 1);
6378        assert_eq!(s.pipe.server.stream_data_blocked_recv_count, 0);
6379
6380        assert_eq!(s.pipe.client.data_blocked_sent_count, 1);
6381        assert_eq!(s.pipe.client.stream_data_blocked_sent_count, 0);
6382        assert_eq!(s.pipe.client.data_blocked_recv_count, 0);
6383        assert_eq!(s.pipe.client.stream_data_blocked_recv_count, 0);
6384    }
6385
6386    #[test]
6387    /// Ensure that the connection does not consume a stream ID when
6388    /// send_request fails with StreamBlocked due to hitting the
6389    /// MAX_DATA flow control limit when attempting to send headers.
6390    /// The headers are sent successfully after a MAX_DATA update.
6391    fn headers_blocked_by_max_data_success_on_retry() {
6392        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6393        config
6394            .load_cert_chain_from_pem_file("examples/cert.crt")
6395            .unwrap();
6396        config
6397            .load_priv_key_from_pem_file("examples/cert.key")
6398            .unwrap();
6399        config.set_application_protos(&[b"h3"]).unwrap();
6400        config.set_initial_max_data(70);
6401        config.set_initial_max_stream_data_bidi_local(150);
6402        config.set_initial_max_stream_data_bidi_remote(150);
6403        config.set_initial_max_stream_data_uni(150);
6404        config.set_initial_max_streams_bidi(100);
6405        config.set_initial_max_streams_uni(5);
6406        config.verify_peer(false);
6407
6408        let h3_config = Config::new().unwrap();
6409
6410        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6411
6412        s.handshake().unwrap();
6413
6414        let req = vec![
6415            Header::new(b":method", b"GET"),
6416            Header::new(b":scheme", b"https"),
6417            Header::new(b":authority", b"quic.tech"),
6418            Header::new(b":path", b"/test/with/long/url"),
6419        ];
6420
6421        // After the HTTP handshake, some bytes of connection flow
6422        // control have been consumed.  The serialized request does
6423        // not fit in the remaining connection-level flow control
6424        // limit.  send_request fails without creating a stream.
6425        assert_eq!(
6426            s.client.send_request(&mut s.pipe.client, &req, true),
6427            Err(Error::StreamBlocked)
6428        );
6429
6430        // Verify that stream 0 does not exist in the H3 stream map after the
6431        // failed attempt.
6432        assert!(!s.client.streams.contains_key(&0));
6433
6434        // Emit the control stream data and drain it at the server to give back
6435        // flow control.
6436        s.advance().ok();
6437        assert_eq!(s.poll_server(), Err(Error::Done));
6438        s.advance().ok();
6439
6440        // Now we can send the request. The stream ID should be 0 (not 4),
6441        // confirming that the blocked attempt did not consume the stream ID.
6442        let stream_id = s.client.send_request(&mut s.pipe.client, &req, true);
6443        assert_eq!(stream_id, Ok(0));
6444        assert!(s.client.streams.contains_key(&0));
6445        assert!(!s.client.streams.contains_key(&4));
6446
6447        // Subsequent request should use stream ID 4.
6448        let stream_id2 = s.client.send_request(&mut s.pipe.client, &req, true);
6449        assert_eq!(stream_id2, Ok(4));
6450        assert!(s.client.streams.contains_key(&0));
6451        assert!(s.client.streams.contains_key(&4));
6452
6453        s.advance().ok();
6454    }
6455
6456    #[test]
6457    /// Ensure STREAM_DATA_BLOCKED is not emitted multiple times with the same
6458    /// offset when trying to send large bodies.
6459    fn send_body_truncation_stream_blocked() {
6460        use crate::test_utils::decode_pkt;
6461
6462        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6463        config
6464            .load_cert_chain_from_pem_file("examples/cert.crt")
6465            .unwrap();
6466        config
6467            .load_priv_key_from_pem_file("examples/cert.key")
6468            .unwrap();
6469        config.set_application_protos(&[b"h3"]).unwrap();
6470        // Use generous connection-level flow control.
6471        config.set_initial_max_data(10000);
6472        config.set_initial_max_stream_data_bidi_local(80);
6473        config.set_initial_max_stream_data_bidi_remote(80);
6474        config.set_initial_max_stream_data_uni(150);
6475        config.set_initial_max_streams_bidi(100);
6476        config.set_initial_max_streams_uni(5);
6477        config.verify_peer(false);
6478
6479        let h3_config = Config::new().unwrap();
6480
6481        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6482
6483        s.handshake().unwrap();
6484
6485        let (stream, req) = s.send_request(true).unwrap();
6486
6487        let ev_headers = Event::Headers {
6488            list: req,
6489            more_frames: false,
6490        };
6491
6492        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
6493        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
6494
6495        let _ = s.send_response(stream, false).unwrap();
6496
6497        assert_eq!(s.pipe.server.streams.blocked().len(), 0);
6498
6499        // The body must be larger than the stream window would allow
6500        let d = [42; 500];
6501        let mut off = 0;
6502
6503        let sent = s
6504            .server
6505            .send_body(&mut s.pipe.server, stream, &d, true)
6506            .unwrap();
6507        assert_eq!(sent, 25);
6508        off += sent;
6509
6510        // send_body wrote as much as it could (sent < size of buff).
6511        assert_eq!(s.pipe.server.streams.blocked().len(), 1);
6512        assert_eq!(
6513            s.server
6514                .send_body(&mut s.pipe.server, stream, &d[off..], true),
6515            Err(Error::Done)
6516        );
6517        assert_eq!(s.pipe.server.streams.blocked().len(), 1);
6518
6519        // Now read raw frames to see what the QUIC layer did
6520        let mut buf = [0; 65535];
6521        let (len, _) = s.pipe.server.send(&mut buf).unwrap();
6522
6523        let frames = decode_pkt(&mut s.pipe.client, &mut buf[..len]).unwrap();
6524
6525        let mut iter = frames.iter();
6526
6527        assert_eq!(
6528            iter.next(),
6529            Some(&crate::frame::Frame::StreamDataBlocked {
6530                stream_id: 0,
6531                limit: 80,
6532            })
6533        );
6534
6535        // At the server, after sending the STREAM_DATA_BLOCKED frame, we clear
6536        // the mark.
6537        assert_eq!(s.pipe.server.streams.blocked().len(), 0);
6538
6539        // Don't read any data from the client, so stream flow control is never
6540        // given back in the form of changing the stream's max offset.
6541        // Subsequent body send operations will still fail but no more
6542        // STREAM_DATA_BLOCKED frames should be submitted since the limit didn't
6543        // change. No frames means no packet to send.
6544        assert_eq!(
6545            s.server
6546                .send_body(&mut s.pipe.server, stream, &d[off..], true),
6547            Err(Error::Done)
6548        );
6549        assert_eq!(s.pipe.server.streams.blocked().len(), 0);
6550        assert_eq!(s.pipe.server.send(&mut buf), Err(crate::Error::Done));
6551
6552        // Now update the client's max offset manually.
6553        let frames = [crate::frame::Frame::MaxStreamData {
6554            stream_id: 0,
6555            max: 100,
6556        }];
6557
6558        let pkt_type = crate::packet::Type::Short;
6559        s.pipe
6560            .send_pkt_to_server(pkt_type, &frames, &mut buf)
6561            .unwrap();
6562
6563        let sent = s
6564            .server
6565            .send_body(&mut s.pipe.server, stream, &d[off..], true)
6566            .unwrap();
6567        assert_eq!(sent, 18);
6568
6569        // Same thing here...
6570        assert_eq!(s.pipe.server.streams.blocked().len(), 1);
6571        assert_eq!(
6572            s.server
6573                .send_body(&mut s.pipe.server, stream, &d[off..], true),
6574            Err(Error::Done)
6575        );
6576        assert_eq!(s.pipe.server.streams.blocked().len(), 1);
6577
6578        let (len, _) = s.pipe.server.send(&mut buf).unwrap();
6579
6580        let frames = decode_pkt(&mut s.pipe.client, &mut buf[..len]).unwrap();
6581
6582        let mut iter = frames.iter();
6583
6584        assert_eq!(
6585            iter.next(),
6586            Some(&crate::frame::Frame::StreamDataBlocked {
6587                stream_id: 0,
6588                limit: 100,
6589            })
6590        );
6591    }
6592
6593    #[test]
6594    /// Ensure stream doesn't hang due to small cwnd.
6595    fn send_body_stream_blocked_by_small_cwnd() {
6596        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6597        config
6598            .load_cert_chain_from_pem_file("examples/cert.crt")
6599            .unwrap();
6600        config
6601            .load_priv_key_from_pem_file("examples/cert.key")
6602            .unwrap();
6603        config.set_application_protos(&[b"h3"]).unwrap();
6604        // Use generous connection-level flow control.
6605        config.set_initial_max_data(100000);
6606        config.set_initial_max_stream_data_bidi_local(100000);
6607        config.set_initial_max_stream_data_bidi_remote(50000);
6608        config.set_initial_max_stream_data_uni(150);
6609        config.set_initial_max_streams_bidi(100);
6610        config.set_initial_max_streams_uni(5);
6611        config.verify_peer(false);
6612
6613        let h3_config = Config::new().unwrap();
6614
6615        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6616
6617        s.handshake().unwrap();
6618
6619        let (stream, req) = s.send_request(true).unwrap();
6620
6621        let ev_headers = Event::Headers {
6622            list: req,
6623            more_frames: false,
6624        };
6625
6626        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
6627        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
6628
6629        let _ = s.send_response(stream, false).unwrap();
6630
6631        // Clear the writable stream queue.
6632        assert_eq!(s.pipe.server.stream_writable_next(), Some(3));
6633        assert_eq!(s.pipe.server.stream_writable_next(), Some(7));
6634        assert_eq!(s.pipe.server.stream_writable_next(), Some(11));
6635        assert_eq!(s.pipe.server.stream_writable_next(), Some(stream));
6636        assert_eq!(s.pipe.server.stream_writable_next(), None);
6637
6638        // The body must be larger than the cwnd would allow.
6639        let send_buf = [42; 80000];
6640
6641        let sent = s
6642            .server
6643            .send_body(&mut s.pipe.server, stream, &send_buf, true)
6644            .unwrap();
6645
6646        // send_body wrote as much as it could (sent < size of buff).
6647        assert_eq!(sent, 11995);
6648
6649        s.advance().ok();
6650
6651        // Client reads received headers and body.
6652        let mut recv_buf = [42; 80000];
6653        assert!(s.poll_client().is_ok());
6654        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
6655        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(11995));
6656
6657        s.advance().ok();
6658
6659        // Server send cap is smaller than remaining body buffer.
6660        assert!(s.pipe.server.tx_cap < send_buf.len() - sent);
6661
6662        // Once the server cwnd opens up, we can send more body.
6663        assert_eq!(s.pipe.server.stream_writable_next(), Some(0));
6664    }
6665
6666    #[test]
6667    /// Ensure stream doesn't hang due to small cwnd.
6668    fn send_body_stream_blocked_zero_length() {
6669        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6670        config
6671            .load_cert_chain_from_pem_file("examples/cert.crt")
6672            .unwrap();
6673        config
6674            .load_priv_key_from_pem_file("examples/cert.key")
6675            .unwrap();
6676        config.set_application_protos(&[b"h3"]).unwrap();
6677        // Use generous connection-level flow control.
6678        config.set_initial_max_data(100000);
6679        config.set_initial_max_stream_data_bidi_local(100000);
6680        config.set_initial_max_stream_data_bidi_remote(50000);
6681        config.set_initial_max_stream_data_uni(150);
6682        config.set_initial_max_streams_bidi(100);
6683        config.set_initial_max_streams_uni(5);
6684        config.verify_peer(false);
6685
6686        let h3_config = Config::new().unwrap();
6687
6688        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6689
6690        s.handshake().unwrap();
6691
6692        let (stream, req) = s.send_request(true).unwrap();
6693
6694        let ev_headers = Event::Headers {
6695            list: req,
6696            more_frames: false,
6697        };
6698
6699        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
6700        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
6701
6702        let _ = s.send_response(stream, false).unwrap();
6703
6704        // Clear the writable stream queue.
6705        assert_eq!(s.pipe.server.stream_writable_next(), Some(3));
6706        assert_eq!(s.pipe.server.stream_writable_next(), Some(7));
6707        assert_eq!(s.pipe.server.stream_writable_next(), Some(11));
6708        assert_eq!(s.pipe.server.stream_writable_next(), Some(stream));
6709        assert_eq!(s.pipe.server.stream_writable_next(), None);
6710
6711        // The body is large enough to fill the cwnd, except for enough bytes
6712        // for another DATA frame header (but no payload).
6713        let send_buf = [42; 11994];
6714
6715        let sent = s
6716            .server
6717            .send_body(&mut s.pipe.server, stream, &send_buf, false)
6718            .unwrap();
6719
6720        assert_eq!(sent, 11994);
6721
6722        // There is only enough capacity left for the DATA frame header, but
6723        // no payload.
6724        assert_eq!(s.pipe.server.stream_capacity(stream).unwrap(), 3);
6725        assert_eq!(
6726            s.server
6727                .send_body(&mut s.pipe.server, stream, &send_buf, false),
6728            Err(Error::Done)
6729        );
6730
6731        s.advance().ok();
6732
6733        // Client reads received headers and body.
6734        let mut recv_buf = [42; 80000];
6735        assert!(s.poll_client().is_ok());
6736        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
6737        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(11994));
6738
6739        s.advance().ok();
6740
6741        // Once the server cwnd opens up, we can send more body.
6742        assert_eq!(s.pipe.server.stream_writable_next(), Some(0));
6743    }
6744
6745    #[test]
6746    /// Test handling of 0-length DATA writes with and without fin.
6747    fn zero_length_data() {
6748        let mut s = Session::new().unwrap();
6749        s.handshake().unwrap();
6750
6751        let (stream, req) = s.send_request(false).unwrap();
6752
6753        assert_eq!(
6754            s.client.send_body(&mut s.pipe.client, 0, b"", false),
6755            Err(Error::Done)
6756        );
6757        assert_eq!(s.client.send_body(&mut s.pipe.client, 0, b"", true), Ok(0));
6758
6759        s.advance().ok();
6760
6761        let mut recv_buf = vec![0; 100];
6762
6763        let ev_headers = Event::Headers {
6764            list: req,
6765            more_frames: true,
6766        };
6767
6768        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
6769
6770        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
6771        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Err(Error::Done));
6772
6773        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
6774        assert_eq!(s.poll_server(), Err(Error::Done));
6775
6776        let resp = s.send_response(stream, false).unwrap();
6777
6778        assert_eq!(
6779            s.server.send_body(&mut s.pipe.server, 0, b"", false),
6780            Err(Error::Done)
6781        );
6782        assert_eq!(s.server.send_body(&mut s.pipe.server, 0, b"", true), Ok(0));
6783
6784        s.advance().ok();
6785
6786        let ev_headers = Event::Headers {
6787            list: resp,
6788            more_frames: true,
6789        };
6790
6791        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
6792
6793        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
6794        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Err(Error::Done));
6795
6796        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
6797        assert_eq!(s.poll_client(), Err(Error::Done));
6798    }
6799
6800    #[test]
6801    /// Tests that blocked 0-length DATA writes are reported correctly.
6802    fn zero_length_data_blocked() {
6803        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6804        config
6805            .load_cert_chain_from_pem_file("examples/cert.crt")
6806            .unwrap();
6807        config
6808            .load_priv_key_from_pem_file("examples/cert.key")
6809            .unwrap();
6810        config.set_application_protos(&[b"h3"]).unwrap();
6811        config.set_initial_max_data(74);
6812        config.set_initial_max_stream_data_bidi_local(150);
6813        config.set_initial_max_stream_data_bidi_remote(150);
6814        config.set_initial_max_stream_data_uni(150);
6815        config.set_initial_max_streams_bidi(100);
6816        config.set_initial_max_streams_uni(5);
6817        config.verify_peer(false);
6818
6819        let h3_config = Config::new().unwrap();
6820
6821        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6822
6823        s.handshake().unwrap();
6824
6825        let req = vec![
6826            Header::new(b":method", b"GET"),
6827            Header::new(b":scheme", b"https"),
6828            Header::new(b":authority", b"quic.tech"),
6829            Header::new(b":path", b"/test"),
6830        ];
6831
6832        assert_eq!(
6833            s.client.send_request(&mut s.pipe.client, &req, false),
6834            Ok(0)
6835        );
6836
6837        assert_eq!(
6838            s.client.send_body(&mut s.pipe.client, 0, b"", true),
6839            Err(Error::Done)
6840        );
6841
6842        // Clear the writable stream queue.
6843        assert_eq!(s.pipe.client.stream_writable_next(), Some(2));
6844        assert_eq!(s.pipe.client.stream_writable_next(), Some(6));
6845        assert_eq!(s.pipe.client.stream_writable_next(), Some(10));
6846        assert_eq!(s.pipe.client.stream_writable_next(), None);
6847
6848        s.advance().ok();
6849
6850        // Flow-control credit from the server allows the body to be sent.
6851        assert_eq!(s.pipe.client.stream_writable_next(), Some(0));
6852        assert_eq!(s.client.send_body(&mut s.pipe.client, 0, b"", true), Ok(0));
6853    }
6854
6855    #[test]
6856    /// Tests that receiving an empty SETTINGS frame is handled and reported.
6857    fn empty_settings() {
6858        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6859        config
6860            .load_cert_chain_from_pem_file("examples/cert.crt")
6861            .unwrap();
6862        config
6863            .load_priv_key_from_pem_file("examples/cert.key")
6864            .unwrap();
6865        config.set_application_protos(&[b"h3"]).unwrap();
6866        config.set_initial_max_data(1500);
6867        config.set_initial_max_stream_data_bidi_local(150);
6868        config.set_initial_max_stream_data_bidi_remote(150);
6869        config.set_initial_max_stream_data_uni(150);
6870        config.set_initial_max_streams_bidi(5);
6871        config.set_initial_max_streams_uni(5);
6872        config.verify_peer(false);
6873        config.set_ack_delay_exponent(8);
6874        config.grease(false);
6875
6876        let h3_config = Config::new().unwrap();
6877        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6878
6879        s.handshake().unwrap();
6880
6881        assert!(s.client.peer_settings_raw().is_some());
6882        assert!(s.server.peer_settings_raw().is_some());
6883    }
6884
6885    #[test]
6886    /// Tests that receiving a H3_DATAGRAM setting is ok.
6887    fn dgram_setting() {
6888        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6889        config
6890            .load_cert_chain_from_pem_file("examples/cert.crt")
6891            .unwrap();
6892        config
6893            .load_priv_key_from_pem_file("examples/cert.key")
6894            .unwrap();
6895        config.set_application_protos(&[b"h3"]).unwrap();
6896        config.set_initial_max_data(70);
6897        config.set_initial_max_stream_data_bidi_local(150);
6898        config.set_initial_max_stream_data_bidi_remote(150);
6899        config.set_initial_max_stream_data_uni(150);
6900        config.set_initial_max_streams_bidi(100);
6901        config.set_initial_max_streams_uni(5);
6902        config.enable_dgram(true, 1000, 1000);
6903        config.verify_peer(false);
6904
6905        let h3_config = Config::new().unwrap();
6906
6907        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6908        assert_eq!(s.pipe.handshake(), Ok(()));
6909
6910        s.client.send_settings(&mut s.pipe.client).unwrap();
6911        assert_eq!(s.pipe.advance(), Ok(()));
6912
6913        // Before processing SETTINGS (via poll), HTTP/3 DATAGRAMS are not
6914        // enabled.
6915        assert!(!s.server.dgram_enabled_by_peer(&s.pipe.server));
6916
6917        // When everything is ok, poll returns Done and DATAGRAM is enabled.
6918        assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::Done));
6919        assert!(s.server.dgram_enabled_by_peer(&s.pipe.server));
6920
6921        // Now detect things on the client
6922        s.server.send_settings(&mut s.pipe.server).unwrap();
6923        assert_eq!(s.pipe.advance(), Ok(()));
6924        assert!(!s.client.dgram_enabled_by_peer(&s.pipe.client));
6925        assert_eq!(s.client.poll(&mut s.pipe.client), Err(Error::Done));
6926        assert!(s.client.dgram_enabled_by_peer(&s.pipe.client));
6927    }
6928
6929    #[test]
6930    /// Tests that receiving a H3_DATAGRAM setting when no TP is set generates
6931    /// an error.
6932    fn dgram_setting_no_tp() {
6933        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6934        config
6935            .load_cert_chain_from_pem_file("examples/cert.crt")
6936            .unwrap();
6937        config
6938            .load_priv_key_from_pem_file("examples/cert.key")
6939            .unwrap();
6940        config.set_application_protos(&[b"h3"]).unwrap();
6941        config.set_initial_max_data(70);
6942        config.set_initial_max_stream_data_bidi_local(150);
6943        config.set_initial_max_stream_data_bidi_remote(150);
6944        config.set_initial_max_stream_data_uni(150);
6945        config.set_initial_max_streams_bidi(100);
6946        config.set_initial_max_streams_uni(5);
6947        config.verify_peer(false);
6948
6949        let h3_config = Config::new().unwrap();
6950
6951        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
6952        assert_eq!(s.pipe.handshake(), Ok(()));
6953
6954        s.client.control_stream_id = Some(
6955            s.client
6956                .open_uni_stream(
6957                    &mut s.pipe.client,
6958                    stream::HTTP3_CONTROL_STREAM_TYPE_ID,
6959                )
6960                .unwrap(),
6961        );
6962
6963        let settings = frame::Frame::Settings {
6964            max_field_section_size: None,
6965            qpack_max_table_capacity: None,
6966            qpack_blocked_streams: None,
6967            connect_protocol_enabled: None,
6968            h3_datagram: Some(1),
6969            grease: None,
6970            additional_settings: Default::default(),
6971            raw: Default::default(),
6972        };
6973
6974        s.send_frame_client(settings, s.client.control_stream_id.unwrap(), false)
6975            .unwrap();
6976
6977        assert_eq!(s.pipe.advance(), Ok(()));
6978
6979        assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::SettingsError));
6980    }
6981
6982    #[test]
6983    /// Tests that receiving SETTINGS with prohibited values generates an error.
6984    fn settings_h2_prohibited() {
6985        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
6986        config
6987            .load_cert_chain_from_pem_file("examples/cert.crt")
6988            .unwrap();
6989        config
6990            .load_priv_key_from_pem_file("examples/cert.key")
6991            .unwrap();
6992        config.set_application_protos(&[b"h3"]).unwrap();
6993        config.set_initial_max_data(70);
6994        config.set_initial_max_stream_data_bidi_local(150);
6995        config.set_initial_max_stream_data_bidi_remote(150);
6996        config.set_initial_max_stream_data_uni(150);
6997        config.set_initial_max_streams_bidi(100);
6998        config.set_initial_max_streams_uni(5);
6999        config.verify_peer(false);
7000
7001        let h3_config = Config::new().unwrap();
7002
7003        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7004        assert_eq!(s.pipe.handshake(), Ok(()));
7005
7006        s.client.control_stream_id = Some(
7007            s.client
7008                .open_uni_stream(
7009                    &mut s.pipe.client,
7010                    stream::HTTP3_CONTROL_STREAM_TYPE_ID,
7011                )
7012                .unwrap(),
7013        );
7014
7015        s.server.control_stream_id = Some(
7016            s.server
7017                .open_uni_stream(
7018                    &mut s.pipe.server,
7019                    stream::HTTP3_CONTROL_STREAM_TYPE_ID,
7020                )
7021                .unwrap(),
7022        );
7023
7024        let frame_payload_len = 2u64;
7025        let settings = [
7026            frame::SETTINGS_FRAME_TYPE_ID as u8,
7027            frame_payload_len as u8,
7028            0x2, // 0x2 is a reserved setting type
7029            1,
7030        ];
7031
7032        s.send_arbitrary_stream_data_client(
7033            &settings,
7034            s.client.control_stream_id.unwrap(),
7035            false,
7036        )
7037        .unwrap();
7038
7039        s.send_arbitrary_stream_data_server(
7040            &settings,
7041            s.server.control_stream_id.unwrap(),
7042            false,
7043        )
7044        .unwrap();
7045
7046        assert_eq!(s.pipe.advance(), Ok(()));
7047
7048        assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::SettingsError));
7049
7050        assert_eq!(s.client.poll(&mut s.pipe.client), Err(Error::SettingsError));
7051    }
7052
7053    #[test]
7054    /// Tests that setting SETTINGS with prohibited values generates an error.
7055    fn set_prohibited_additional_settings() {
7056        let mut h3_config = Config::new().unwrap();
7057        assert_eq!(
7058            h3_config.set_additional_settings(vec![(
7059                frame::SETTINGS_QPACK_MAX_TABLE_CAPACITY,
7060                43
7061            )]),
7062            Err(Error::SettingsError)
7063        );
7064        assert_eq!(
7065            h3_config.set_additional_settings(vec![(
7066                frame::SETTINGS_MAX_FIELD_SECTION_SIZE,
7067                43
7068            )]),
7069            Err(Error::SettingsError)
7070        );
7071        assert_eq!(
7072            h3_config.set_additional_settings(vec![(
7073                frame::SETTINGS_QPACK_BLOCKED_STREAMS,
7074                43
7075            )]),
7076            Err(Error::SettingsError)
7077        );
7078        assert_eq!(
7079            h3_config.set_additional_settings(vec![(
7080                frame::SETTINGS_ENABLE_CONNECT_PROTOCOL,
7081                43
7082            )]),
7083            Err(Error::SettingsError)
7084        );
7085        assert_eq!(
7086            h3_config
7087                .set_additional_settings(vec![(frame::SETTINGS_H3_DATAGRAM, 43)]),
7088            Err(Error::SettingsError)
7089        );
7090    }
7091
7092    #[test]
7093    /// Tests that a client rejects a SETTINGS frame received on a request
7094    /// stream.
7095    fn settings_on_request_stream_client() {
7096        let mut s = Session::new().unwrap();
7097        s.handshake().unwrap();
7098
7099        let (stream, _req) = s.send_request(true).unwrap();
7100
7101        let settings = frame::Frame::Settings {
7102            max_field_section_size: None,
7103            qpack_max_table_capacity: None,
7104            qpack_blocked_streams: None,
7105            connect_protocol_enabled: None,
7106            h3_datagram: None,
7107            grease: None,
7108            additional_settings: Default::default(),
7109            raw: Default::default(),
7110        };
7111
7112        s.send_frame_server(settings, stream, false).unwrap();
7113
7114        // The client MUST treat this as H3_FRAME_UNEXPECTED.
7115        assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
7116        assert_eq!(
7117            s.pipe.client.local_error(),
7118            Some(&crate::ConnectionError {
7119                is_app: true,
7120                error_code: WireErrorCode::FrameUnexpected as u64,
7121                reason: format!(
7122                    "Unexpected frame type {}",
7123                    frame::SETTINGS_FRAME_TYPE_ID
7124                )
7125                .into_bytes(),
7126            })
7127        );
7128    }
7129
7130    #[test]
7131    /// Tests that a client rejects a CANCEL_PUSH frame received on a request
7132    /// stream.
7133    fn cancel_push_on_request_stream_client() {
7134        let mut s = Session::new().unwrap();
7135        s.handshake().unwrap();
7136
7137        let (stream, _req) = s.send_request(true).unwrap();
7138        let cancel_push = frame::Frame::CancelPush { push_id: 0 };
7139        s.send_frame_server(cancel_push, stream, false).unwrap();
7140
7141        // The client MUST treat this as H3_FRAME_UNEXPECTED.
7142        assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
7143        assert_eq!(
7144            s.pipe.client.local_error(),
7145            Some(&crate::ConnectionError {
7146                is_app: true,
7147                error_code: WireErrorCode::FrameUnexpected as u64,
7148                reason: format!(
7149                    "Unexpected frame type {}",
7150                    frame::CANCEL_PUSH_FRAME_TYPE_ID
7151                )
7152                .into_bytes(),
7153            })
7154        );
7155    }
7156
7157    #[test]
7158    /// Tests that a client rejects a GOAWAY frame received on a request
7159    /// stream.
7160    fn goaway_on_request_stream_client() {
7161        let mut s = Session::new().unwrap();
7162        s.handshake().unwrap();
7163
7164        let (stream, _req) = s.send_request(true).unwrap();
7165        let goaway = frame::Frame::GoAway { id: 0 };
7166
7167        s.send_frame_server(goaway, stream, false).unwrap();
7168
7169        // The client MUST treat this as H3_FRAME_UNEXPECTED.
7170        assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
7171        assert_eq!(
7172            s.pipe.client.local_error(),
7173            Some(&crate::ConnectionError {
7174                is_app: true,
7175                error_code: WireErrorCode::FrameUnexpected as u64,
7176                reason: format!(
7177                    "Unexpected frame type {}",
7178                    frame::GOAWAY_FRAME_TYPE_ID
7179                )
7180                .into_bytes(),
7181            })
7182        );
7183    }
7184
7185    #[test]
7186    /// Tests that a client rejects a MAX_PUSH_ID frame received on a request
7187    /// stream.
7188    fn max_push_id_on_request_stream_client() {
7189        let mut s = Session::new().unwrap();
7190        s.handshake().unwrap();
7191
7192        let (stream, _req) = s.send_request(true).unwrap();
7193        let max_push_id = frame::Frame::MaxPushId { push_id: 0 };
7194
7195        s.send_frame_server(max_push_id, stream, false).unwrap();
7196
7197        // The client MUST treat this as H3_FRAME_UNEXPECTED.
7198        assert_eq!(s.poll_client(), Err(Error::FrameUnexpected));
7199        assert_eq!(
7200            s.pipe.client.local_error(),
7201            Some(&crate::ConnectionError {
7202                is_app: true,
7203                error_code: WireErrorCode::FrameUnexpected as u64,
7204                reason: format!(
7205                    "Unexpected frame type {}",
7206                    frame::MAX_PUSH_FRAME_TYPE_ID
7207                )
7208                .into_bytes(),
7209            })
7210        );
7211    }
7212
7213    #[test]
7214    /// Tests additional settings are actually exchanged by the peers.
7215    fn set_additional_settings() {
7216        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
7217        config
7218            .load_cert_chain_from_pem_file("examples/cert.crt")
7219            .unwrap();
7220        config
7221            .load_priv_key_from_pem_file("examples/cert.key")
7222            .unwrap();
7223        config.set_application_protos(&[b"h3"]).unwrap();
7224        config.set_initial_max_data(70);
7225        config.set_initial_max_stream_data_bidi_local(150);
7226        config.set_initial_max_stream_data_bidi_remote(150);
7227        config.set_initial_max_stream_data_uni(150);
7228        config.set_initial_max_streams_bidi(100);
7229        config.set_initial_max_streams_uni(5);
7230        config.verify_peer(false);
7231        config.grease(false);
7232
7233        let mut h3_config = Config::new().unwrap();
7234        h3_config
7235            .set_additional_settings(vec![(42, 43), (44, 45)])
7236            .unwrap();
7237
7238        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7239        assert_eq!(s.pipe.handshake(), Ok(()));
7240
7241        assert_eq!(s.pipe.advance(), Ok(()));
7242
7243        s.client.send_settings(&mut s.pipe.client).unwrap();
7244        assert_eq!(s.pipe.advance(), Ok(()));
7245        assert_eq!(s.server.poll(&mut s.pipe.server), Err(Error::Done));
7246
7247        s.server.send_settings(&mut s.pipe.server).unwrap();
7248        assert_eq!(s.pipe.advance(), Ok(()));
7249        assert_eq!(s.client.poll(&mut s.pipe.client), Err(Error::Done));
7250
7251        assert_eq!(
7252            s.server.peer_settings_raw(),
7253            Some(&[(6, 32_768), (42, 43), (44, 45)][..])
7254        );
7255        assert_eq!(
7256            s.client.peer_settings_raw(),
7257            Some(&[(6, 32_768), (42, 43), (44, 45)][..])
7258        );
7259    }
7260
7261    #[test]
7262    /// Send a single DATAGRAM.
7263    fn single_dgram() {
7264        let mut buf = [0; 65535];
7265        let mut s = Session::new().unwrap();
7266        s.handshake().unwrap();
7267
7268        // We'll send default data of 10 bytes on flow ID 0.
7269        let result = (11, 0, 1);
7270
7271        s.send_dgram_client(0).unwrap();
7272
7273        assert_eq!(s.poll_server(), Err(Error::Done));
7274        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7275
7276        s.send_dgram_server(0).unwrap();
7277        assert_eq!(s.poll_client(), Err(Error::Done));
7278        assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
7279    }
7280
7281    #[test]
7282    /// Send multiple DATAGRAMs.
7283    fn multiple_dgram() {
7284        let mut buf = [0; 65535];
7285        let mut s = Session::new().unwrap();
7286        s.handshake().unwrap();
7287
7288        // We'll send default data of 10 bytes on flow ID 0.
7289        let result = (11, 0, 1);
7290
7291        s.send_dgram_client(0).unwrap();
7292        s.send_dgram_client(0).unwrap();
7293        s.send_dgram_client(0).unwrap();
7294
7295        assert_eq!(s.poll_server(), Err(Error::Done));
7296        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7297        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7298        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7299        assert_eq!(s.recv_dgram_server(&mut buf), Err(Error::Done));
7300
7301        s.send_dgram_server(0).unwrap();
7302        s.send_dgram_server(0).unwrap();
7303        s.send_dgram_server(0).unwrap();
7304
7305        assert_eq!(s.poll_client(), Err(Error::Done));
7306        assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
7307        assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
7308        assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
7309        assert_eq!(s.recv_dgram_client(&mut buf), Err(Error::Done));
7310    }
7311
7312    #[test]
7313    /// Send more DATAGRAMs than the send queue allows.
7314    fn multiple_dgram_overflow() {
7315        let mut buf = [0; 65535];
7316        let mut s = Session::new().unwrap();
7317        s.handshake().unwrap();
7318
7319        // We'll send default data of 10 bytes on flow ID 0.
7320        let result = (11, 0, 1);
7321
7322        // Five DATAGRAMs
7323        s.send_dgram_client(0).unwrap();
7324        s.send_dgram_client(0).unwrap();
7325        s.send_dgram_client(0).unwrap();
7326        s.send_dgram_client(0).unwrap();
7327        s.send_dgram_client(0).unwrap();
7328
7329        // Only 3 independent DATAGRAMs to read events will fire.
7330        assert_eq!(s.poll_server(), Err(Error::Done));
7331        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7332        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7333        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7334        assert_eq!(s.recv_dgram_server(&mut buf), Err(Error::Done));
7335    }
7336
7337    #[test]
7338    /// Send a single DATAGRAM and request.
7339    fn poll_datagram_cycling_no_read() {
7340        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
7341        config
7342            .load_cert_chain_from_pem_file("examples/cert.crt")
7343            .unwrap();
7344        config
7345            .load_priv_key_from_pem_file("examples/cert.key")
7346            .unwrap();
7347        config.set_application_protos(&[b"h3"]).unwrap();
7348        config.set_initial_max_data(1500);
7349        config.set_initial_max_stream_data_bidi_local(150);
7350        config.set_initial_max_stream_data_bidi_remote(150);
7351        config.set_initial_max_stream_data_uni(150);
7352        config.set_initial_max_streams_bidi(100);
7353        config.set_initial_max_streams_uni(5);
7354        config.verify_peer(false);
7355        config.enable_dgram(true, 100, 100);
7356
7357        let h3_config = Config::new().unwrap();
7358        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7359        s.handshake().unwrap();
7360
7361        // Send request followed by DATAGRAM on client side.
7362        let (stream, req) = s.send_request(false).unwrap();
7363
7364        s.send_body_client(stream, true).unwrap();
7365
7366        let ev_headers = Event::Headers {
7367            list: req,
7368            more_frames: true,
7369        };
7370
7371        s.send_dgram_client(0).unwrap();
7372
7373        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
7374        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
7375
7376        assert_eq!(s.poll_server(), Err(Error::Done));
7377    }
7378
7379    #[test]
7380    /// Send a single DATAGRAM and request.
7381    fn poll_datagram_single_read() {
7382        let mut buf = [0; 65535];
7383
7384        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
7385        config
7386            .load_cert_chain_from_pem_file("examples/cert.crt")
7387            .unwrap();
7388        config
7389            .load_priv_key_from_pem_file("examples/cert.key")
7390            .unwrap();
7391        config.set_application_protos(&[b"h3"]).unwrap();
7392        config.set_initial_max_data(1500);
7393        config.set_initial_max_stream_data_bidi_local(150);
7394        config.set_initial_max_stream_data_bidi_remote(150);
7395        config.set_initial_max_stream_data_uni(150);
7396        config.set_initial_max_streams_bidi(100);
7397        config.set_initial_max_streams_uni(5);
7398        config.verify_peer(false);
7399        config.enable_dgram(true, 100, 100);
7400
7401        let h3_config = Config::new().unwrap();
7402        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7403        s.handshake().unwrap();
7404
7405        // We'll send default data of 10 bytes on flow ID 0.
7406        let result = (11, 0, 1);
7407
7408        // Send request followed by DATAGRAM on client side.
7409        let (stream, req) = s.send_request(false).unwrap();
7410
7411        let body = s.send_body_client(stream, true).unwrap();
7412
7413        let mut recv_buf = vec![0; body.len()];
7414
7415        let ev_headers = Event::Headers {
7416            list: req,
7417            more_frames: true,
7418        };
7419
7420        s.send_dgram_client(0).unwrap();
7421
7422        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
7423        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
7424
7425        assert_eq!(s.poll_server(), Err(Error::Done));
7426
7427        assert_eq!(s.recv_dgram_server(&mut buf), Ok(result));
7428
7429        assert_eq!(s.poll_server(), Err(Error::Done));
7430
7431        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
7432        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
7433        assert_eq!(s.poll_server(), Err(Error::Done));
7434
7435        // Send response followed by DATAGRAM on server side
7436        let resp = s.send_response(stream, false).unwrap();
7437
7438        let body = s.send_body_server(stream, true).unwrap();
7439
7440        let mut recv_buf = vec![0; body.len()];
7441
7442        let ev_headers = Event::Headers {
7443            list: resp,
7444            more_frames: true,
7445        };
7446
7447        s.send_dgram_server(0).unwrap();
7448
7449        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
7450        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
7451
7452        assert_eq!(s.poll_client(), Err(Error::Done));
7453
7454        assert_eq!(s.recv_dgram_client(&mut buf), Ok(result));
7455
7456        assert_eq!(s.poll_client(), Err(Error::Done));
7457
7458        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
7459
7460        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
7461        assert_eq!(s.poll_client(), Err(Error::Done));
7462    }
7463
7464    #[test]
7465    /// Send multiple DATAGRAMs and requests.
7466    fn poll_datagram_multi_read() {
7467        let mut buf = [0; 65535];
7468
7469        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
7470        config
7471            .load_cert_chain_from_pem_file("examples/cert.crt")
7472            .unwrap();
7473        config
7474            .load_priv_key_from_pem_file("examples/cert.key")
7475            .unwrap();
7476        config.set_application_protos(&[b"h3"]).unwrap();
7477        config.set_initial_max_data(1500);
7478        config.set_initial_max_stream_data_bidi_local(150);
7479        config.set_initial_max_stream_data_bidi_remote(150);
7480        config.set_initial_max_stream_data_uni(150);
7481        config.set_initial_max_streams_bidi(100);
7482        config.set_initial_max_streams_uni(5);
7483        config.verify_peer(false);
7484        config.enable_dgram(true, 100, 100);
7485
7486        let h3_config = Config::new().unwrap();
7487        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7488        s.handshake().unwrap();
7489
7490        // 10 bytes on flow ID 0 and 2.
7491        let flow_0_result = (11, 0, 1);
7492        let flow_2_result = (11, 2, 1);
7493
7494        // Send requests followed by DATAGRAMs on client side.
7495        let (stream, req) = s.send_request(false).unwrap();
7496
7497        let body = s.send_body_client(stream, true).unwrap();
7498
7499        let mut recv_buf = vec![0; body.len()];
7500
7501        let ev_headers = Event::Headers {
7502            list: req,
7503            more_frames: true,
7504        };
7505
7506        s.send_dgram_client(0).unwrap();
7507        s.send_dgram_client(0).unwrap();
7508        s.send_dgram_client(0).unwrap();
7509        s.send_dgram_client(0).unwrap();
7510        s.send_dgram_client(0).unwrap();
7511        s.send_dgram_client(2).unwrap();
7512        s.send_dgram_client(2).unwrap();
7513        s.send_dgram_client(2).unwrap();
7514        s.send_dgram_client(2).unwrap();
7515        s.send_dgram_client(2).unwrap();
7516
7517        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
7518        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
7519
7520        assert_eq!(s.poll_server(), Err(Error::Done));
7521
7522        // Second cycle, start to read
7523        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
7524        assert_eq!(s.poll_server(), Err(Error::Done));
7525        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
7526        assert_eq!(s.poll_server(), Err(Error::Done));
7527        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
7528        assert_eq!(s.poll_server(), Err(Error::Done));
7529
7530        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
7531        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
7532
7533        assert_eq!(s.poll_server(), Err(Error::Done));
7534
7535        // Third cycle.
7536        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
7537        assert_eq!(s.poll_server(), Err(Error::Done));
7538        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
7539        assert_eq!(s.poll_server(), Err(Error::Done));
7540        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
7541        assert_eq!(s.poll_server(), Err(Error::Done));
7542        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
7543        assert_eq!(s.poll_server(), Err(Error::Done));
7544        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
7545        assert_eq!(s.poll_server(), Err(Error::Done));
7546        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
7547        assert_eq!(s.poll_server(), Err(Error::Done));
7548        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
7549        assert_eq!(s.poll_server(), Err(Error::Done));
7550
7551        // Send response followed by DATAGRAM on server side
7552        let resp = s.send_response(stream, false).unwrap();
7553
7554        let body = s.send_body_server(stream, true).unwrap();
7555
7556        let mut recv_buf = vec![0; body.len()];
7557
7558        let ev_headers = Event::Headers {
7559            list: resp,
7560            more_frames: true,
7561        };
7562
7563        s.send_dgram_server(0).unwrap();
7564        s.send_dgram_server(0).unwrap();
7565        s.send_dgram_server(0).unwrap();
7566        s.send_dgram_server(0).unwrap();
7567        s.send_dgram_server(0).unwrap();
7568        s.send_dgram_server(2).unwrap();
7569        s.send_dgram_server(2).unwrap();
7570        s.send_dgram_server(2).unwrap();
7571        s.send_dgram_server(2).unwrap();
7572        s.send_dgram_server(2).unwrap();
7573
7574        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
7575        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
7576
7577        assert_eq!(s.poll_client(), Err(Error::Done));
7578
7579        // Second cycle, start to read
7580        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
7581        assert_eq!(s.poll_client(), Err(Error::Done));
7582        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
7583        assert_eq!(s.poll_client(), Err(Error::Done));
7584        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
7585        assert_eq!(s.poll_client(), Err(Error::Done));
7586
7587        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
7588        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
7589
7590        assert_eq!(s.poll_client(), Err(Error::Done));
7591
7592        // Third cycle.
7593        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
7594        assert_eq!(s.poll_client(), Err(Error::Done));
7595        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_0_result));
7596        assert_eq!(s.poll_client(), Err(Error::Done));
7597        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
7598        assert_eq!(s.poll_client(), Err(Error::Done));
7599        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
7600        assert_eq!(s.poll_client(), Err(Error::Done));
7601        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
7602        assert_eq!(s.poll_client(), Err(Error::Done));
7603        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
7604        assert_eq!(s.poll_client(), Err(Error::Done));
7605        assert_eq!(s.recv_dgram_client(&mut buf), Ok(flow_2_result));
7606        assert_eq!(s.poll_client(), Err(Error::Done));
7607    }
7608
7609    #[test]
7610    /// Tests that the Finished event is not issued for streams of unknown type
7611    /// (e.g. GREASE).
7612    fn finished_is_for_requests() {
7613        let mut s = Session::new().unwrap();
7614        s.handshake().unwrap();
7615
7616        assert_eq!(s.poll_client(), Err(Error::Done));
7617        assert_eq!(s.poll_server(), Err(Error::Done));
7618
7619        assert_eq!(s.client.open_grease_stream(&mut s.pipe.client), Ok(()));
7620        assert_eq!(s.pipe.advance(), Ok(()));
7621
7622        assert_eq!(s.poll_client(), Err(Error::Done));
7623        assert_eq!(s.poll_server(), Err(Error::Done));
7624    }
7625
7626    #[test]
7627    fn unknown_uni_stream_leaks_past_max_streams_uni() {
7628        let (mut config, h3_config) = Session::default_configs().unwrap();
7629        config.set_initial_max_data(100_000);
7630        config.set_initial_max_stream_data_uni(100_000);
7631        config.set_initial_max_streams_uni(5);
7632        config.grease(false);
7633
7634        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7635        s.handshake().unwrap();
7636
7637        let baseline = s.server.streams.len();
7638        let mut leaked_streams = Vec::new();
7639        let mut id = 14;
7640
7641        let n = 500;
7642        for i in 0..n {
7643            s.pipe
7644                .client
7645                .stream_send(id, &[0x21], true)
7646                .unwrap_or_else(|e| {
7647                    panic!(
7648                        "stream credit was not re-issued after {} streams: {:?}",
7649                        i, e
7650                    )
7651                });
7652
7653            s.pipe.advance().unwrap();
7654            assert_eq!(s.poll_server(), Err(Error::Done));
7655            assert!(s.pipe.server.streams.is_collected(id));
7656            s.pipe.advance().unwrap();
7657
7658            leaked_streams.push(id);
7659            id += 4;
7660        }
7661
7662        for id in leaked_streams {
7663            assert!(s.pipe.server.streams.is_collected(id));
7664        }
7665
7666        assert_eq!(
7667            s.server.streams.len(),
7668            baseline,
7669            "expected {} allocated streams in stream map after {} streams with unknown type",
7670            baseline,
7671            n,
7672        );
7673    }
7674
7675    #[test]
7676    fn empty_uni_stream_leaks_past_max_streams_uni() {
7677        let (mut config, h3_config) = Session::default_configs().unwrap();
7678        config.set_initial_max_data(100_000);
7679        config.set_initial_max_stream_data_uni(100_000);
7680        config.set_initial_max_streams_uni(5);
7681        config.grease(false);
7682
7683        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7684        s.handshake().unwrap();
7685
7686        let baseline = s.server.streams.len();
7687        let mut leaked_streams = Vec::new();
7688        let mut id = 14;
7689
7690        let n = 500;
7691        for i in 0..n {
7692            s.pipe
7693                .client
7694                .stream_send(id, &[], true)
7695                .unwrap_or_else(|e| {
7696                    panic!(
7697                        "stream credit was not re-issued after {} streams: {:?}",
7698                        i, e
7699                    )
7700                });
7701
7702            s.pipe.advance().unwrap();
7703            assert_eq!(s.poll_server(), Err(Error::Done));
7704            assert!(s.pipe.server.streams.is_collected(id));
7705            s.pipe.advance().unwrap();
7706
7707            leaked_streams.push(id);
7708            id += 4;
7709        }
7710
7711        for id in leaked_streams {
7712            assert!(s.pipe.server.streams.is_collected(id));
7713        }
7714
7715        assert_eq!(
7716            s.server.streams.len(),
7717            baseline,
7718            "expected {} allocated streams in stream map after {} streams without stream type",
7719            baseline,
7720            n,
7721        );
7722    }
7723
7724    #[test]
7725    /// Tests that streams are marked as finished only once.
7726    fn finished_once() {
7727        let mut s = Session::new().unwrap();
7728        s.handshake().unwrap();
7729
7730        let (stream, req) = s.send_request(false).unwrap();
7731        let body = s.send_body_client(stream, true).unwrap();
7732
7733        let mut recv_buf = vec![0; body.len()];
7734
7735        let ev_headers = Event::Headers {
7736            list: req,
7737            more_frames: true,
7738        };
7739
7740        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
7741        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
7742
7743        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
7744        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
7745
7746        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Err(Error::Done));
7747        assert_eq!(s.poll_server(), Err(Error::Done));
7748    }
7749
7750    #[test]
7751    /// Tests that the Data event is properly re-armed.
7752    fn data_event_rearm() {
7753        let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
7754
7755        let mut s = Session::new().unwrap();
7756        s.handshake().unwrap();
7757
7758        let (r1_id, r1_hdrs) = s.send_request(false).unwrap();
7759
7760        let mut recv_buf = vec![0; bytes.len()];
7761
7762        let r1_ev_headers = Event::Headers {
7763            list: r1_hdrs,
7764            more_frames: true,
7765        };
7766
7767        // Manually send an incomplete DATA frame (i.e. the frame size is longer
7768        // than the actual data sent).
7769        {
7770            let mut d = [42; 10];
7771            let mut b = octets::OctetsMut::with_slice(&mut d);
7772
7773            b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
7774            b.put_varint(bytes.len() as u64).unwrap();
7775            let off = b.off();
7776            s.pipe.client.stream_send(r1_id, &d[..off], false).unwrap();
7777
7778            assert_eq!(
7779                s.pipe.client.stream_send(r1_id, &bytes[..5], false),
7780                Ok(5)
7781            );
7782
7783            s.advance().ok();
7784        }
7785
7786        assert_eq!(s.poll_server(), Ok((r1_id, r1_ev_headers)));
7787        assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
7788        assert_eq!(s.poll_server(), Err(Error::Done));
7789
7790        // Read the available body data.
7791        assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(5));
7792
7793        // Send the remaining DATA payload.
7794        assert_eq!(s.pipe.client.stream_send(r1_id, &bytes[5..], false), Ok(5));
7795        s.advance().ok();
7796
7797        assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
7798        assert_eq!(s.poll_server(), Err(Error::Done));
7799
7800        // Read the rest of the body data.
7801        assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(5));
7802        assert_eq!(s.poll_server(), Err(Error::Done));
7803
7804        // Send more data.
7805        let r1_body = s.send_body_client(r1_id, false).unwrap();
7806
7807        assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
7808        assert_eq!(s.poll_server(), Err(Error::Done));
7809
7810        assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(r1_body.len()));
7811
7812        // Send a new request to test cross-stream event rearming.
7813        let (r2_id, r2_hdrs) = s.send_request(false).unwrap();
7814        let r2_ev_headers = Event::Headers {
7815            list: r2_hdrs,
7816            more_frames: true,
7817        };
7818        let r2_body = s.send_body_client(r2_id, false).unwrap();
7819
7820        s.advance().ok();
7821
7822        assert_eq!(s.poll_server(), Ok((r2_id, r2_ev_headers)));
7823        assert_eq!(s.poll_server(), Ok((r2_id, Event::Data)));
7824        assert_eq!(s.recv_body_server(r2_id, &mut recv_buf), Ok(r2_body.len()));
7825        assert_eq!(s.poll_server(), Err(Error::Done));
7826
7827        // Send more data on request 1, then trailing HEADERS.
7828        let r1_body = s.send_body_client(r1_id, false).unwrap();
7829
7830        let trailers = vec![Header::new(b"hello", b"world")];
7831
7832        s.client
7833            .send_headers(&mut s.pipe.client, r1_id, &trailers, true)
7834            .unwrap();
7835
7836        let r1_ev_trailers = Event::Headers {
7837            list: trailers.clone(),
7838            more_frames: false,
7839        };
7840
7841        s.advance().ok();
7842
7843        assert_eq!(s.poll_server(), Ok((r1_id, Event::Data)));
7844        assert_eq!(s.recv_body_server(r1_id, &mut recv_buf), Ok(r1_body.len()));
7845
7846        assert_eq!(s.poll_server(), Ok((r1_id, r1_ev_trailers)));
7847        assert_eq!(s.poll_server(), Ok((r1_id, Event::Finished)));
7848        assert_eq!(s.poll_server(), Err(Error::Done));
7849
7850        // Send more data on request 2, then trailing HEADERS.
7851        let r2_body = s.send_body_client(r2_id, false).unwrap();
7852
7853        s.client
7854            .send_headers(&mut s.pipe.client, r2_id, &trailers, false)
7855            .unwrap();
7856
7857        let r2_ev_trailers = Event::Headers {
7858            list: trailers,
7859            more_frames: true,
7860        };
7861
7862        s.advance().ok();
7863
7864        assert_eq!(s.poll_server(), Ok((r2_id, Event::Data)));
7865        assert_eq!(s.recv_body_server(r2_id, &mut recv_buf), Ok(r2_body.len()));
7866        assert_eq!(s.poll_server(), Ok((r2_id, r2_ev_trailers)));
7867        assert_eq!(s.poll_server(), Err(Error::Done));
7868
7869        let (r3_id, r3_hdrs) = s.send_request(false).unwrap();
7870
7871        let r3_ev_headers = Event::Headers {
7872            list: r3_hdrs,
7873            more_frames: true,
7874        };
7875
7876        // Manually send an incomplete DATA frame containing only its header.
7877        {
7878            let mut d = [42; 10];
7879            let mut b = octets::OctetsMut::with_slice(&mut d);
7880
7881            b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
7882            b.put_varint(bytes.len() as u64).unwrap();
7883            let off = b.off();
7884            s.pipe.client.stream_send(r3_id, &d[..off], false).unwrap();
7885
7886            s.advance().ok();
7887        }
7888
7889        assert_eq!(s.poll_server(), Ok((r3_id, r3_ev_headers)));
7890        assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
7891        assert_eq!(s.poll_server(), Err(Error::Done));
7892
7893        assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Err(Error::Done));
7894
7895        assert_eq!(s.pipe.client.stream_send(r3_id, &bytes[..5], false), Ok(5));
7896
7897        s.advance().ok();
7898
7899        assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
7900        assert_eq!(s.poll_server(), Err(Error::Done));
7901
7902        assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Ok(5));
7903
7904        assert_eq!(s.pipe.client.stream_send(r3_id, &bytes[5..], false), Ok(5));
7905        s.advance().ok();
7906
7907        assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
7908        assert_eq!(s.poll_server(), Err(Error::Done));
7909
7910        assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Ok(5));
7911
7912        // Buffer multiple data frames.
7913        let body = s.send_body_client(r3_id, false).unwrap();
7914        s.send_body_client(r3_id, false).unwrap();
7915        s.send_body_client(r3_id, false).unwrap();
7916
7917        assert_eq!(s.poll_server(), Ok((r3_id, Event::Data)));
7918        assert_eq!(s.poll_server(), Err(Error::Done));
7919
7920        {
7921            let mut d = [42; 10];
7922            let mut b = octets::OctetsMut::with_slice(&mut d);
7923
7924            b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
7925            b.put_varint(0).unwrap();
7926            let off = b.off();
7927            s.pipe.client.stream_send(r3_id, &d[..off], true).unwrap();
7928
7929            s.advance().ok();
7930        }
7931
7932        let mut recv_buf = vec![0; bytes.len() * 3];
7933
7934        assert_eq!(s.recv_body_server(r3_id, &mut recv_buf), Ok(body.len() * 3));
7935    }
7936
7937    #[test]
7938    /// Tests that the Datagram event is properly re-armed.
7939    fn dgram_event_rearm() {
7940        let mut buf = [0; 65535];
7941
7942        let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
7943        config
7944            .load_cert_chain_from_pem_file("examples/cert.crt")
7945            .unwrap();
7946        config
7947            .load_priv_key_from_pem_file("examples/cert.key")
7948            .unwrap();
7949        config.set_application_protos(&[b"h3"]).unwrap();
7950        config.set_initial_max_data(1500);
7951        config.set_initial_max_stream_data_bidi_local(150);
7952        config.set_initial_max_stream_data_bidi_remote(150);
7953        config.set_initial_max_stream_data_uni(150);
7954        config.set_initial_max_streams_bidi(100);
7955        config.set_initial_max_streams_uni(5);
7956        config.verify_peer(false);
7957        config.enable_dgram(true, 100, 100);
7958
7959        let h3_config = Config::new().unwrap();
7960        let mut s = Session::with_configs(&mut config, &h3_config).unwrap();
7961        s.handshake().unwrap();
7962
7963        // 10 bytes on flow ID 0 and 2.
7964        let flow_0_result = (11, 0, 1);
7965        let flow_2_result = (11, 2, 1);
7966
7967        // Send requests followed by DATAGRAMs on client side.
7968        let (stream, req) = s.send_request(false).unwrap();
7969
7970        let body = s.send_body_client(stream, true).unwrap();
7971
7972        let mut recv_buf = vec![0; body.len()];
7973
7974        let ev_headers = Event::Headers {
7975            list: req,
7976            more_frames: true,
7977        };
7978
7979        s.send_dgram_client(0).unwrap();
7980        s.send_dgram_client(0).unwrap();
7981        s.send_dgram_client(2).unwrap();
7982        s.send_dgram_client(2).unwrap();
7983
7984        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
7985        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
7986
7987        assert_eq!(s.poll_server(), Err(Error::Done));
7988        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
7989
7990        assert_eq!(s.poll_server(), Err(Error::Done));
7991        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
7992
7993        assert_eq!(s.poll_server(), Err(Error::Done));
7994        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
7995
7996        assert_eq!(s.poll_server(), Err(Error::Done));
7997        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
7998
7999        assert_eq!(s.poll_server(), Err(Error::Done));
8000
8001        s.send_dgram_client(0).unwrap();
8002        s.send_dgram_client(2).unwrap();
8003
8004        assert_eq!(s.poll_server(), Err(Error::Done));
8005
8006        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_0_result));
8007        assert_eq!(s.poll_server(), Err(Error::Done));
8008
8009        assert_eq!(s.recv_dgram_server(&mut buf), Ok(flow_2_result));
8010        assert_eq!(s.poll_server(), Err(Error::Done));
8011
8012        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
8013        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
8014
8015        // Verify that dgram counts are incremented.
8016        assert_eq!(s.pipe.client.dgram_sent_count, 6);
8017        assert_eq!(s.pipe.client.dgram_recv_count, 0);
8018        assert_eq!(s.pipe.server.dgram_sent_count, 0);
8019        assert_eq!(s.pipe.server.dgram_recv_count, 6);
8020
8021        let server_path = s.pipe.server.paths.get_active().expect("no active");
8022        let client_path = s.pipe.client.paths.get_active().expect("no active");
8023        assert_eq!(client_path.dgram_sent_count, 6);
8024        assert_eq!(client_path.dgram_recv_count, 0);
8025        assert_eq!(server_path.dgram_sent_count, 0);
8026        assert_eq!(server_path.dgram_recv_count, 6);
8027    }
8028
8029    #[test]
8030    fn reset_stream() {
8031        let mut buf = [0; 65535];
8032
8033        let mut s = Session::new().unwrap();
8034        s.handshake().unwrap();
8035
8036        // Client sends request.
8037        let (stream, req) = s.send_request(false).unwrap();
8038
8039        let ev_headers = Event::Headers {
8040            list: req,
8041            more_frames: true,
8042        };
8043
8044        // Server sends response and closes stream.
8045        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8046        assert_eq!(s.poll_server(), Err(Error::Done));
8047
8048        let resp = s.send_response(stream, true).unwrap();
8049
8050        let ev_headers = Event::Headers {
8051            list: resp,
8052            more_frames: false,
8053        };
8054
8055        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8056        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
8057        assert_eq!(s.poll_client(), Err(Error::Done));
8058
8059        // Client sends RESET_STREAM, closing stream.
8060        let frames = [crate::frame::Frame::ResetStream {
8061            stream_id: stream,
8062            error_code: 42,
8063            final_size: 68,
8064        }];
8065
8066        let pkt_type = crate::packet::Type::Short;
8067        assert_eq!(
8068            s.pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
8069            Ok(39)
8070        );
8071
8072        // Server issues Reset event for the stream.
8073        assert_eq!(s.poll_server(), Ok((stream, Event::Reset(42))));
8074        assert_eq!(s.poll_server(), Err(Error::Done));
8075
8076        // Sending RESET_STREAM again shouldn't trigger another Reset event.
8077        assert_eq!(
8078            s.pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
8079            Ok(39)
8080        );
8081
8082        assert_eq!(s.poll_server(), Err(Error::Done));
8083    }
8084
8085    #[test]
8086    fn reset_mid_data_frame() {
8087        let mut s = Session::new().unwrap();
8088        s.handshake().unwrap();
8089
8090        // Client sends request.
8091        let (stream, req) = s.send_request(false).unwrap();
8092
8093        let ev_headers = Event::Headers {
8094            list: req,
8095            more_frames: true,
8096        };
8097
8098        // Server sends response
8099        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8100        assert_eq!(s.poll_server(), Err(Error::Done));
8101
8102        let resp = s.send_response(stream, false).unwrap();
8103
8104        let ev_headers = Event::Headers {
8105            list: resp,
8106            more_frames: true,
8107        };
8108
8109        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8110        assert_eq!(s.poll_client(), Err(Error::Done));
8111
8112        // We want to indicate a larger DATA frame than we will send, so
8113        // sidestep quiche's h3 API and write H3 frame bytes directly to QUIC
8114        // stream. Imagine a response body of 200 bytes, that would be sent
8115        // across two DATA frames of 100 bytes, but quiche's stream write is
8116        // limited to only emitting 95 bytes of the DATA frame before the stream
8117        // is reset.
8118        let mut d = [42; 10];
8119        let mut b = octets::OctetsMut::with_slice(&mut d);
8120        b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
8121        b.put_varint(100).unwrap();
8122        let off = b.off();
8123        s.pipe.server.stream_send(0, &d[..off], false).unwrap();
8124        let body = [42; 200];
8125        let written = s.pipe.server.stream_send(0, &body[..200], false).unwrap();
8126
8127        assert_eq!(written, 95);
8128
8129        s.advance().ok();
8130
8131        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
8132        assert_eq!(s.poll_client(), Err(Error::Done));
8133
8134        let mut read_buf = [0; 65535];
8135        let read = s
8136            .client
8137            .recv_body(&mut s.pipe.client, 0, &mut read_buf)
8138            .unwrap();
8139        assert_eq!(read, 95);
8140
8141        s.pipe
8142            .server
8143            .stream_shutdown(0, crate::Shutdown::Write, 42)
8144            .unwrap();
8145
8146        s.advance().ok();
8147
8148        assert_eq!(s.poll_client(), Ok((stream, Event::Reset(42))));
8149
8150        // Reading the body after the reset does not queue a Finished event.
8151        assert_eq!(
8152            s.client.recv_body(&mut s.pipe.client, 0, &mut read_buf),
8153            Err(Error::Done)
8154        );
8155        assert_eq!(s.poll_client(), Err(Error::Done));
8156    }
8157
8158    #[test]
8159    fn fin_mid_data_frame() {
8160        let mut s = Session::new().unwrap();
8161        s.handshake().unwrap();
8162
8163        // Client sends request.
8164        let (stream, req) = s.send_request(false).unwrap();
8165
8166        let ev_headers = Event::Headers {
8167            list: req,
8168            more_frames: true,
8169        };
8170
8171        // Server sends response
8172        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8173        assert_eq!(s.poll_server(), Err(Error::Done));
8174
8175        let resp = s.send_response(stream, false).unwrap();
8176
8177        let ev_headers = Event::Headers {
8178            list: resp,
8179            more_frames: true,
8180        };
8181
8182        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8183        assert_eq!(s.poll_client(), Err(Error::Done));
8184
8185        // We want to indicate a larger DATA frame than we will send, so
8186        // sidestep quiche's h3 API and write H3 frame bytes directly to QUIC
8187        // stream. Imagine a response body of 200 bytes, that would be sent
8188        // across two DATA frames of 100 bytes, but quiche's stream write is
8189        // limited to only emitting 95 bytes of the DATA frame before the stream
8190        // is Fin'd.
8191        let mut d = [42; 10];
8192        let mut b = octets::OctetsMut::with_slice(&mut d);
8193        b.put_varint(frame::DATA_FRAME_TYPE_ID).unwrap();
8194        b.put_varint(100).unwrap();
8195        let off = b.off();
8196        s.pipe.server.stream_send(0, &d[..off], false).unwrap();
8197        let body = [42; 200];
8198        let written = s.pipe.server.stream_send(0, &body[..200], false).unwrap();
8199
8200        assert_eq!(written, 95);
8201
8202        s.advance().ok();
8203
8204        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
8205        assert_eq!(s.poll_client(), Err(Error::Done));
8206
8207        let mut read_buf = [0; 65535];
8208        let read = s
8209            .client
8210            .recv_body(&mut s.pipe.client, 0, &mut read_buf)
8211            .unwrap();
8212        assert_eq!(read, 95);
8213
8214        let written = s.pipe.server.stream_send(0, &[], true).unwrap();
8215
8216        assert_eq!(written, 0);
8217
8218        s.advance().ok();
8219
8220        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
8221        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
8222        assert_eq!(s.poll_client(), Err(Error::Done));
8223    }
8224
8225    /// The client shuts down the stream's write direction, the server
8226    /// shuts down its side with fin
8227    #[test]
8228    fn client_shutdown_write_server_fin() {
8229        let mut buf = [0; 65535];
8230        let mut s = Session::new().unwrap();
8231        s.handshake().unwrap();
8232
8233        // Client sends request.
8234        let (stream, req) = s.send_request(false).unwrap();
8235
8236        let ev_headers = Event::Headers {
8237            list: req,
8238            more_frames: true,
8239        };
8240
8241        // Server sends response and closes stream.
8242        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8243        assert_eq!(s.poll_server(), Err(Error::Done));
8244
8245        let resp = s.send_response(stream, true).unwrap();
8246
8247        let ev_headers = Event::Headers {
8248            list: resp,
8249            more_frames: false,
8250        };
8251
8252        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8253        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
8254        assert_eq!(s.poll_client(), Err(Error::Done));
8255
8256        // Client shuts down stream ==> sends RESET_STREAM
8257        assert_eq!(
8258            s.pipe
8259                .client
8260                .stream_shutdown(stream, crate::Shutdown::Write, 42),
8261            Ok(())
8262        );
8263        assert_eq!(s.advance(), Ok(()));
8264
8265        // Server sees the Reset event for the stream.
8266        assert_eq!(s.poll_server(), Ok((stream, Event::Reset(42))));
8267        assert_eq!(s.poll_server(), Err(Error::Done));
8268
8269        // Streams have been collected by quiche
8270        assert!(s.pipe.server.streams.is_collected(stream));
8271        assert!(s.pipe.client.streams.is_collected(stream));
8272
8273        // Client sends another request, server sends response without fin
8274        //
8275        let (stream, req) = s.send_request(false).unwrap();
8276
8277        let ev_headers = Event::Headers {
8278            list: req,
8279            more_frames: true,
8280        };
8281
8282        // Check that server has received the request.
8283        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8284        assert_eq!(s.poll_server(), Err(Error::Done));
8285
8286        // Server sends reponse without closing the stream.
8287        let resp = s.send_response(stream, false).unwrap();
8288
8289        let ev_headers = Event::Headers {
8290            list: resp,
8291            more_frames: true,
8292        };
8293
8294        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8295        assert_eq!(s.poll_client(), Err(Error::Done));
8296
8297        // Client shuts down stream ==> sends RESET_STREAM
8298        assert_eq!(
8299            s.pipe
8300                .client
8301                .stream_shutdown(stream, crate::Shutdown::Write, 42),
8302            Ok(())
8303        );
8304        assert_eq!(s.advance(), Ok(()));
8305
8306        // Server sees the Reset event for the stream.
8307        assert_eq!(s.poll_server(), Ok((stream, Event::Reset(42))));
8308        assert_eq!(s.poll_server(), Err(Error::Done));
8309
8310        // Server sends body and closes the stream.
8311        s.send_body_server(stream, true).unwrap();
8312
8313        // Stream has been collected on server by quiche
8314        assert!(s.pipe.server.streams.is_collected(stream));
8315        // Client stream has not been collected, the client needs to
8316        // read the fin from the stream first.
8317        assert!(!s.pipe.client.streams.is_collected(stream));
8318        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
8319        s.recv_body_client(stream, &mut buf).unwrap();
8320        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
8321        assert_eq!(s.poll_client(), Err(Error::Done));
8322        assert!(s.pipe.client.streams.is_collected(stream));
8323    }
8324
8325    #[test]
8326    fn client_shutdown_read() {
8327        let mut buf = [0; 65535];
8328        let mut s = Session::new().unwrap();
8329        s.handshake().unwrap();
8330
8331        // Client sends request and leaves stream open.
8332        let (stream, req) = s.send_request(false).unwrap();
8333
8334        let ev_headers = Event::Headers {
8335            list: req,
8336            more_frames: true,
8337        };
8338
8339        // Server sends response and leaves stream open.
8340        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8341        assert_eq!(s.poll_server(), Err(Error::Done));
8342
8343        let resp = s.send_response(stream, false).unwrap();
8344
8345        let ev_headers = Event::Headers {
8346            list: resp,
8347            more_frames: true,
8348        };
8349
8350        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8351        assert_eq!(s.poll_client(), Err(Error::Done));
8352        // Client shuts down read
8353        assert_eq!(
8354            s.pipe
8355                .client
8356                .stream_shutdown(stream, crate::Shutdown::Read, 42),
8357            Ok(())
8358        );
8359        assert_eq!(s.advance(), Ok(()));
8360
8361        // Stream is writable on server side, but returns StreamStopped
8362        assert_eq!(s.poll_server(), Err(Error::Done));
8363        let writables: Vec<u64> = s.pipe.server.writable().collect();
8364        assert!(writables.contains(&stream));
8365        assert_eq!(
8366            s.send_body_server(stream, false),
8367            Err(Error::TransportError(crate::Error::StreamStopped(42)))
8368        );
8369
8370        // Client needs to finish its side by sending a fin
8371        assert_eq!(
8372            s.client.send_body(&mut s.pipe.client, stream, &[], true),
8373            Ok(0)
8374        );
8375        assert_eq!(s.advance(), Ok(()));
8376        // Note, we get an Event::Data for an empty buffer today. But it
8377        // would also be fine to not get it.
8378        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
8379        assert_eq!(s.recv_body_server(stream, &mut buf), Err(Error::Done));
8380        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
8381        assert_eq!(s.poll_server(), Err(Error::Done));
8382
8383        // Since the client has already send a fin, the stream is collected
8384        // on both client and server
8385        assert!(s.pipe.client.streams.is_collected(stream));
8386        assert!(s.pipe.server.streams.is_collected(stream));
8387    }
8388
8389    #[test]
8390    fn reset_finished_at_server() {
8391        let mut s = Session::new().unwrap();
8392        s.handshake().unwrap();
8393
8394        // Client sends HEADERS and doesn't fin
8395        let (stream, _req) = s.send_request(false).unwrap();
8396
8397        // ..then Client sends RESET_STREAM
8398        assert_eq!(
8399            s.pipe.client.stream_shutdown(0, crate::Shutdown::Write, 0),
8400            Ok(())
8401        );
8402
8403        assert_eq!(s.pipe.advance(), Ok(()));
8404
8405        // Server receives just a reset
8406        assert_eq!(s.poll_server(), Ok((stream, Event::Reset(0))));
8407        assert_eq!(s.poll_server(), Err(Error::Done));
8408
8409        // Client sends HEADERS and fin
8410        let (stream, req) = s.send_request(true).unwrap();
8411
8412        // ..then Client sends RESET_STREAM
8413        assert_eq!(
8414            s.pipe.client.stream_shutdown(4, crate::Shutdown::Write, 0),
8415            Ok(())
8416        );
8417
8418        let ev_headers = Event::Headers {
8419            list: req,
8420            more_frames: false,
8421        };
8422
8423        // Server receives headers and fin.
8424        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8425        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
8426        assert_eq!(s.poll_server(), Err(Error::Done));
8427    }
8428
8429    #[test]
8430    fn reset_finished_at_server_with_data_pending() {
8431        let mut s = Session::new().unwrap();
8432        s.handshake().unwrap();
8433
8434        // Client sends HEADERS and doesn't fin.
8435        let (stream, req) = s.send_request(false).unwrap();
8436
8437        assert!(s.send_body_client(stream, false).is_ok());
8438
8439        assert_eq!(s.pipe.advance(), Ok(()));
8440
8441        let ev_headers = Event::Headers {
8442            list: req,
8443            more_frames: true,
8444        };
8445
8446        // Server receives headers and data...
8447        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8448        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
8449
8450        // ..then Client sends RESET_STREAM.
8451        assert_eq!(
8452            s.pipe
8453                .client
8454                .stream_shutdown(stream, crate::Shutdown::Write, 0),
8455            Ok(())
8456        );
8457
8458        assert_eq!(s.pipe.advance(), Ok(()));
8459
8460        // The server does *not* attempt to read from the stream,
8461        // but polls and receives the reset and there are no more
8462        // readable streams.
8463        assert_eq!(s.poll_server(), Ok((stream, Event::Reset(0))));
8464        assert_eq!(s.poll_server(), Err(Error::Done));
8465        assert_eq!(s.pipe.server.readable().len(), 0);
8466    }
8467
8468    #[test]
8469    fn reset_finished_at_server_with_data_pending_2() {
8470        let mut s = Session::new().unwrap();
8471        s.handshake().unwrap();
8472
8473        // Client sends HEADERS and doesn't fin.
8474        let (stream, req) = s.send_request(false).unwrap();
8475
8476        assert!(s.send_body_client(stream, false).is_ok());
8477
8478        assert_eq!(s.pipe.advance(), Ok(()));
8479
8480        let ev_headers = Event::Headers {
8481            list: req,
8482            more_frames: true,
8483        };
8484
8485        // Server receives headers and data...
8486        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8487        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
8488
8489        // ..then Client sends RESET_STREAM.
8490        assert_eq!(
8491            s.pipe
8492                .client
8493                .stream_shutdown(stream, crate::Shutdown::Write, 0),
8494            Ok(())
8495        );
8496
8497        assert_eq!(s.pipe.advance(), Ok(()));
8498
8499        // Server reads from the stream and receives the reset while
8500        // attempting to read.
8501        assert_eq!(
8502            s.recv_body_server(stream, &mut [0; 100]),
8503            Err(Error::TransportError(crate::Error::StreamReset(0)))
8504        );
8505
8506        // No more events and there are no more readable streams.
8507        assert_eq!(s.poll_server(), Err(Error::Done));
8508        assert_eq!(s.pipe.server.readable().len(), 0);
8509    }
8510
8511    #[test]
8512    fn reset_finished_at_client() {
8513        let mut buf = [0; 65535];
8514        let mut s = Session::new().unwrap();
8515        s.handshake().unwrap();
8516
8517        // Client sends HEADERS and doesn't fin
8518        let (stream, req) = s.send_request(false).unwrap();
8519
8520        let ev_headers = Event::Headers {
8521            list: req,
8522            more_frames: true,
8523        };
8524
8525        // Server receives headers.
8526        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8527        assert_eq!(s.poll_server(), Err(Error::Done));
8528
8529        // Server sends response and doesn't fin
8530        s.send_response(stream, false).unwrap();
8531
8532        assert_eq!(s.pipe.advance(), Ok(()));
8533
8534        // .. then Server sends RESET_STREAM
8535        assert_eq!(
8536            s.pipe
8537                .server
8538                .stream_shutdown(stream, crate::Shutdown::Write, 0),
8539            Ok(())
8540        );
8541
8542        assert_eq!(s.pipe.advance(), Ok(()));
8543
8544        // Client receives Reset only
8545        assert_eq!(s.poll_client(), Ok((stream, Event::Reset(0))));
8546        assert_eq!(s.poll_server(), Err(Error::Done));
8547
8548        // Client sends headers and fin.
8549        let (stream, req) = s.send_request(true).unwrap();
8550
8551        let ev_headers = Event::Headers {
8552            list: req,
8553            more_frames: false,
8554        };
8555
8556        // Server receives headers and fin.
8557        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8558        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
8559        assert_eq!(s.poll_server(), Err(Error::Done));
8560
8561        // Server sends response and fin
8562        let resp = s.send_response(stream, true).unwrap();
8563
8564        assert_eq!(s.pipe.advance(), Ok(()));
8565
8566        // ..then Server sends RESET_STREAM
8567        let frames = [crate::frame::Frame::ResetStream {
8568            stream_id: stream,
8569            error_code: 42,
8570            final_size: 68,
8571        }];
8572
8573        let pkt_type = crate::packet::Type::Short;
8574        assert_eq!(
8575            s.pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
8576            Ok(39)
8577        );
8578
8579        assert_eq!(s.pipe.advance(), Ok(()));
8580
8581        let ev_headers = Event::Headers {
8582            list: resp,
8583            more_frames: false,
8584        };
8585
8586        // Client receives headers and fin.
8587        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8588        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
8589        assert_eq!(s.poll_client(), Err(Error::Done));
8590    }
8591
8592    #[test]
8593    fn collect_completed_streams() {
8594        let mut s = Session::new().unwrap();
8595        s.handshake().unwrap();
8596
8597        let init_streams_client = s.client.streams.len();
8598        let init_streams_server = s.server.streams.len();
8599
8600        // Client sends HEADERS and doesn't fin
8601        let (stream, req) = s.send_request(false).unwrap();
8602
8603        let ev_headers = Event::Headers {
8604            list: req,
8605            more_frames: true,
8606        };
8607
8608        // Server receives headers.
8609        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8610        assert_eq!(s.poll_server(), Err(Error::Done));
8611
8612        assert_eq!(s.client.streams.len(), init_streams_client + 1);
8613        assert_eq!(s.server.streams.len(), init_streams_server + 1);
8614
8615        // Client sends body and fin
8616        let body = s.send_body_client(stream, true).unwrap();
8617
8618        let mut recv_buf = vec![0; body.len()];
8619
8620        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
8621        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
8622
8623        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
8624
8625        assert_eq!(s.client.streams.len(), init_streams_client + 1);
8626        assert_eq!(s.server.streams.len(), init_streams_server + 1);
8627
8628        // Server sends response and finishes the stream
8629        let resp_headers = s.send_response(stream, false).unwrap();
8630        s.send_body_server(stream, true).unwrap();
8631
8632        let ev_headers = Event::Headers {
8633            list: resp_headers,
8634            more_frames: true,
8635        };
8636
8637        assert_eq!(s.poll_client(), Ok((stream, ev_headers)));
8638        assert_eq!(s.poll_client(), Ok((stream, Event::Data)));
8639        assert_eq!(s.recv_body_client(stream, &mut recv_buf), Ok(body.len()));
8640
8641        // The server stream should be gone now
8642        assert_eq!(s.client.streams.len(), init_streams_client + 1);
8643        assert_eq!(s.server.streams.len(), init_streams_server);
8644
8645        // Polling again should clean up the client
8646        assert_eq!(s.poll_client(), Ok((stream, Event::Finished)));
8647        assert_eq!(s.poll_client(), Err(Error::Done));
8648
8649        assert_eq!(s.client.streams.len(), init_streams_client);
8650    }
8651
8652    #[test]
8653    fn collect_reset_streams() {
8654        let mut s = Session::new().unwrap();
8655        s.handshake().unwrap();
8656
8657        let init_streams_client = s.client.streams.len();
8658        let init_streams_server = s.server.streams.len();
8659
8660        // Client sends HEADERS and doesn't fin
8661        let (stream, req) = s.send_request(false).unwrap();
8662
8663        let ev_headers = Event::Headers {
8664            list: req,
8665            more_frames: true,
8666        };
8667
8668        // Server receives headers.
8669        assert_eq!(s.poll_server(), Ok((stream, ev_headers)));
8670        assert_eq!(s.poll_server(), Err(Error::Done));
8671
8672        assert_eq!(s.client.streams.len(), init_streams_client + 1);
8673        assert_eq!(s.server.streams.len(), init_streams_server + 1);
8674
8675        // Client sends body and fin
8676        let body = s.send_body_client(stream, true).unwrap();
8677
8678        let mut recv_buf = vec![0; body.len()];
8679
8680        assert_eq!(s.poll_server(), Ok((stream, Event::Data)));
8681        assert_eq!(s.recv_body_server(stream, &mut recv_buf), Ok(body.len()));
8682
8683        assert_eq!(s.poll_server(), Ok((stream, Event::Finished)));
8684
8685        assert_eq!(s.client.streams.len(), init_streams_client + 1);
8686        assert_eq!(s.server.streams.len(), init_streams_server + 1);
8687
8688        // Server sends response and resets the stream.
8689        s.send_response(stream, false).unwrap();
8690        s.pipe
8691            .server
8692            .stream_shutdown(stream, crate::Shutdown::Write, 0)
8693            .unwrap();
8694
8695        s.advance().ok();
8696
8697        // TODO: need to notify resets better.
8698        //
8699        // This will trigger the h3 layer to check for the stream resets,
8700        // otherwise it wouldn't know that a reset happened.
8701        //
8702        // We will need to figure out a way to do this automatically to avoid
8703        // requiring applications to do this manually. For now just keep this
8704        // for testing purposes.
8705        let _ = s.send_body_server(stream, true);
8706
8707        assert_eq!(s.poll_server(), Err(Error::Done));
8708
8709        assert_eq!(s.poll_client(), Ok((stream, Event::Reset(0))));
8710        assert_eq!(s.poll_client(), Err(Error::Done));
8711
8712        // The server stream should be gone now
8713        assert_eq!(s.client.streams.len(), init_streams_client);
8714        assert_eq!(s.server.streams.len(), init_streams_server);
8715    }
8716}
8717
8718#[cfg(feature = "ffi")]
8719mod ffi;
8720#[cfg(feature = "internal")]
8721#[doc(hidden)]
8722pub mod frame;
8723#[cfg(not(feature = "internal"))]
8724mod frame;
8725#[doc(hidden)]
8726pub mod qpack;
8727mod stream;