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