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