Skip to main content

h3i/
lib.rs

1// Copyright (C) 2024, 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//! h3i - low-level HTTP/3 debug and testing
28//!
29//! HTTP/3 ([RFC 9114]) is the wire format for HTTP semantics ([RFC 9110]). The
30//! RFCs contain a range of requirements about how Request or Response messages
31//! are generated, serialized, sent, received, parsed, and consumed. QUIC ([RFC
32//! 9000]) streams are used for these messages along with other control and
33//! QPACK ([RFC 9204]) header compression instructions.
34//!
35//! h3i provides a highly configurable HTTP/3 client that can bend RFC rules in
36//! order to test the behavior of servers. QUIC streams can be opened, fin'd,
37//! stopped or reset at any point in time. HTTP/3 frames can be sent on any
38//! stream, in any order, containing user-controlled content (both legal and
39//! illegal).
40//!
41//! # Example
42//!
43//! The following example sends a request with its Content-Length header set to
44//! 5, but with its body only consisting of 4 bytes. This is classified as a
45//! [malformed request], and the server should respond with a 400 Bad Request
46//! response. Once h3i receives the response, it will close the connection.
47//!
48//! ```no_run
49//! use h3i::actions::h3::Action;
50//! use h3i::actions::h3::StreamEvent;
51//! use h3i::actions::h3::StreamEventType;
52//! use h3i::actions::h3::WaitType;
53//! use h3i::client::sync_client;
54//! use h3i::config::Config;
55//! use quiche::h3::frame::Frame;
56//! use quiche::h3::Header;
57//! use quiche::h3::NameValue;
58//!
59//! fn main() {
60//!    /// The QUIC stream to send the frames on. See
61//!    /// https://datatracker.ietf.org/doc/html/rfc9000#name-streams and
62//!    /// https://datatracker.ietf.org/doc/html/rfc9114#request-streams for more.
63//!    const STREAM_ID: u64 = 0;
64//!
65//!    let config = Config::new()
66//!        .with_host_port("blog.cloudflare.com".to_string())
67//!        .with_idle_timeout(2000)
68//!        .build()
69//!        .unwrap();
70//!
71//!    let headers = vec![
72//!        Header::new(b":method", b"POST"),
73//!        Header::new(b":scheme", b"https"),
74//!        Header::new(b":authority", b"blog.cloudflare.com"),
75//!        Header::new(b":path", b"/"),
76//!        // We say that we're going to send a body with 5 bytes...
77//!        Header::new(b"content-length", b"5"),
78//!    ];
79//!
80//!    let header_block = encode_header_block(&headers).unwrap();
81//!
82//!    let actions = vec![
83//!        Action::SendHeadersFrame {
84//!            stream_id: STREAM_ID,
85//!            fin_stream: false,
86//!            headers,
87//!            frame: Frame::Headers { header_block },
88//!            literal_headers: false,
89//!            expected_result: Default::default(),
90//!        },
91//!        Action::SendFrame {
92//!            stream_id: STREAM_ID,
93//!            fin_stream: true,
94//!            frame: Frame::Data {
95//!                // ...but, in actuality, we only send 4 bytes. This should yield a
96//!                // 400 Bad Request response from an RFC-compliant
97//!                // server: https://datatracker.ietf.org/doc/html/rfc9114#section-4.1.2-3
98//!                payload: b"test".to_vec(),
99//!            },
100//!            expected_result: Default::default(),
101//!        },
102//!        Action::Wait {
103//!            wait_type: WaitType::StreamEvent(StreamEvent {
104//!                stream_id: STREAM_ID,
105//!                event_type: StreamEventType::Headers,
106//!            }),
107//!        },
108//!        Action::ConnectionClose {
109//!            error: quiche::ConnectionError {
110//!                is_app: true,
111//!                error_code: quiche::h3::WireErrorCode::NoError as u64,
112//!                reason: vec![],
113//!            },
114//!        },
115//!    ];
116//!
117//!    // This example doesn't use close trigger frames, since we manually close the connection upon
118//!    // receiving a HEADERS frame on stream 0.
119//!    let close_trigger_frames = None;
120//!    let summary = sync_client::connect(config, actions, close_trigger_frames);
121//!
122//!    println!(
123//!        "=== received connection summary! ===\n\n{}",
124//!        serde_json::to_string_pretty(&summary).unwrap_or_else(|e| e.to_string())
125//!    );
126//! }
127//!
128//! // SendHeadersFrame requires a QPACK-encoded header block. h3i provides a
129//! // `send_headers_frame` helper function to abstract this, but for clarity, we do
130//! // it here.
131//! fn encode_header_block(
132//!     headers: &[quiche::h3::Header],
133//! ) -> std::result::Result<Vec<u8>, String> {
134//!     let mut encoder = quiche::h3::qpack::Encoder::new();
135//!
136//!     let headers_len = headers
137//!         .iter()
138//!         .fold(0, |acc, h| acc + h.value().len() + h.name().len() + 32);
139//!
140//!     let mut header_block = vec![0; headers_len];
141//!     let len = encoder
142//!         .encode(headers, &mut header_block)
143//!         .map_err(|_| "Internal Error")?;
144//!
145//!     header_block.truncate(len);
146//!
147//!     Ok(header_block)
148//! }
149//! ```
150
151//! [RFC 9000]: https://www.rfc-editor.org/rfc/rfc9000.html
152//! [RFC 9110]: https://www.rfc-editor.org/rfc/rfc9110.html
153//! [RFC 9114]: https://www.rfc-editor.org/rfc/rfc9114.html
154//! [RFC 9204]: https://www.rfc-editor.org/rfc/rfc9204.html
155//! [malformed request]: https://datatracker.ietf.org/doc/html/rfc9114#section-4.1.2-3
156
157use qlog::events::quic::PacketHeader;
158use qlog::events::quic::PacketSent;
159use qlog::events::quic::PacketType;
160use qlog::events::quic::QuicFrame;
161use qlog::events::EventData;
162use quiche::h3::qpack::encode_int;
163use quiche::h3::qpack::encode_str;
164use quiche::h3::qpack::LITERAL;
165use quiche::h3::NameValue;
166use smallvec::SmallVec;
167
168#[cfg(not(feature = "async"))]
169pub use quiche;
170#[cfg(feature = "async")]
171pub use tokio_quiche::quiche;
172
173/// The ID for an HTTP/3 control stream type.
174///
175/// See <https://datatracker.ietf.org/doc/html/rfc9114#name-control-streams>.
176pub const HTTP3_CONTROL_STREAM_TYPE_ID: u64 = 0x0;
177
178/// The ID for an HTTP/3 push stream type.
179///
180/// See <https://datatracker.ietf.org/doc/html/rfc9114#name-push-streams>.
181pub const HTTP3_PUSH_STREAM_TYPE_ID: u64 = 0x1;
182
183/// The ID for a QPACK encoder stream type.
184///
185/// See <https://datatracker.ietf.org/doc/html/rfc9204#section-4.2-2.1>.
186pub const QPACK_ENCODER_STREAM_TYPE_ID: u64 = 0x2;
187
188/// The ID for a QPACK decoder stream type.
189///
190/// See <https://datatracker.ietf.org/doc/html/rfc9204#section-4.2-2.2>.
191pub const QPACK_DECODER_STREAM_TYPE_ID: u64 = 0x3;
192
193#[derive(Default)]
194struct StreamIdAllocator {
195    id: u64,
196}
197
198impl StreamIdAllocator {
199    pub fn take_next_id(&mut self) -> u64 {
200        let old = self.id;
201        self.id += 4;
202
203        old
204    }
205
206    pub fn peek_next_id(&mut self) -> u64 {
207        self.id
208    }
209}
210
211/// Encodes a header block literally. Unlike [`encode_header_block`],
212/// this function encodes all the headers exactly as provided. This
213/// means it does not use the huffman lookup table, nor does it convert
214/// the header names to lowercase before encoding.
215fn encode_header_block_literal(
216    headers: &[quiche::h3::Header],
217) -> std::result::Result<Vec<u8>, String> {
218    // This is a combination of a modified `quiche::h3::qpack::Encoder::encode`
219    // and the [`encode_header_block`] function.
220    let headers_len = headers
221        .iter()
222        .fold(0, |acc, h| acc + h.value().len() + h.name().len() + 32);
223
224    let mut header_block = vec![0; headers_len];
225
226    let mut b = octets::OctetsMut::with_slice(&mut header_block);
227
228    // Required Insert Count.
229    encode_int(0, 0, 8, &mut b).map_err(|e| format!("{e:?}"))?;
230
231    // Base.
232    encode_int(0, 0, 7, &mut b).map_err(|e| format!("{e:?}"))?;
233
234    for h in headers {
235        encode_str::<false>(h.name(), LITERAL, 3, &mut b)
236            .map_err(|e| format!("{e:?}"))?;
237        encode_str::<false>(h.value(), 0, 7, &mut b)
238            .map_err(|e| format!("{e:?}"))?;
239    }
240
241    let len = b.off();
242
243    header_block.truncate(len);
244    Ok(header_block)
245}
246
247fn encode_header_block(
248    headers: &[quiche::h3::Header],
249) -> std::result::Result<Vec<u8>, String> {
250    let mut encoder = quiche::h3::qpack::Encoder::new();
251
252    let headers_len = headers
253        .iter()
254        .fold(0, |acc, h| acc + h.value().len() + h.name().len() + 32);
255
256    let mut header_block = vec![0; headers_len];
257    let len = encoder
258        .encode(headers, &mut header_block)
259        .map_err(|_| "Internal Error")?;
260
261    header_block.truncate(len);
262
263    Ok(header_block)
264}
265
266fn fake_packet_header() -> PacketHeader {
267    PacketHeader {
268        packet_type: PacketType::OneRtt,
269        ..Default::default()
270    }
271}
272
273fn fake_packet_sent(frames: Option<SmallVec<[QuicFrame; 1]>>) -> EventData {
274    EventData::QuicPacketSent(PacketSent {
275        header: fake_packet_header(),
276        frames,
277        ..Default::default()
278    })
279}
280
281pub mod actions;
282pub mod client;
283pub mod config;
284pub mod frame;
285pub mod frame_parser;
286pub mod prompts;
287pub mod recordreplay;