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;
166
167#[cfg(not(feature = "async"))]
168pub use quiche;
169#[cfg(feature = "async")]
170pub use tokio_quiche::quiche;
171
172/// The ID for an HTTP/3 control stream type.
173///
174/// See <https://datatracker.ietf.org/doc/html/rfc9114#name-control-streams>.
175pub const HTTP3_CONTROL_STREAM_TYPE_ID: u64 = 0x0;
176
177/// The ID for an HTTP/3 push stream type.
178///
179/// See <https://datatracker.ietf.org/doc/html/rfc9114#name-push-streams>.
180pub const HTTP3_PUSH_STREAM_TYPE_ID: u64 = 0x1;
181
182/// The ID for a QPACK encoder stream type.
183///
184/// See <https://datatracker.ietf.org/doc/html/rfc9204#section-4.2-2.1>.
185pub const QPACK_ENCODER_STREAM_TYPE_ID: u64 = 0x2;
186
187/// The ID for a QPACK decoder stream type.
188///
189/// See <https://datatracker.ietf.org/doc/html/rfc9204#section-4.2-2.2>.
190pub const QPACK_DECODER_STREAM_TYPE_ID: u64 = 0x3;
191
192#[derive(Default)]
193struct StreamIdAllocator {
194 id: u64,
195}
196
197impl StreamIdAllocator {
198 pub fn take_next_id(&mut self) -> u64 {
199 let old = self.id;
200 self.id += 4;
201
202 old
203 }
204
205 pub fn peek_next_id(&mut self) -> u64 {
206 self.id
207 }
208}
209
210/// Encodes a header block literally. Unlike [`encode_header_block`],
211/// this function encodes all the headers exactly as provided. This
212/// means it does not use the huffman lookup table, nor does it convert
213/// the header names to lowercase before encoding.
214fn encode_header_block_literal(
215 headers: &[quiche::h3::Header],
216) -> std::result::Result<Vec<u8>, String> {
217 // This is a combination of a modified `quiche::h3::qpack::Encoder::encode`
218 // and the [`encode_header_block`] function.
219 let headers_len = headers
220 .iter()
221 .fold(0, |acc, h| acc + h.value().len() + h.name().len() + 32);
222
223 let mut header_block = vec![0; headers_len];
224
225 let mut b = octets::OctetsMut::with_slice(&mut header_block);
226
227 // Required Insert Count.
228 encode_int(0, 0, 8, &mut b).map_err(|e| format!("{e:?}"))?;
229
230 // Base.
231 encode_int(0, 0, 7, &mut b).map_err(|e| format!("{e:?}"))?;
232
233 for h in headers {
234 encode_str::<false>(h.name(), LITERAL, 3, &mut b)
235 .map_err(|e| format!("{e:?}"))?;
236 encode_str::<false>(h.value(), 0, 7, &mut b)
237 .map_err(|e| format!("{e:?}"))?;
238 }
239
240 let len = b.off();
241
242 header_block.truncate(len);
243 Ok(header_block)
244}
245
246fn encode_header_block(
247 headers: &[quiche::h3::Header],
248) -> std::result::Result<Vec<u8>, String> {
249 let mut encoder = quiche::h3::qpack::Encoder::new();
250
251 let headers_len = headers
252 .iter()
253 .fold(0, |acc, h| acc + h.value().len() + h.name().len() + 32);
254
255 let mut header_block = vec![0; headers_len];
256 let len = encoder
257 .encode(headers, &mut header_block)
258 .map_err(|_| "Internal Error")?;
259
260 header_block.truncate(len);
261
262 Ok(header_block)
263}
264
265fn fake_packet_header() -> PacketHeader {
266 PacketHeader {
267 packet_type: PacketType::OneRtt,
268 ..Default::default()
269 }
270}
271
272fn fake_packet_sent(frames: Option<Vec<QuicFrame>>) -> EventData {
273 EventData::QuicPacketSent(PacketSent {
274 header: fake_packet_header(),
275 frames,
276 ..Default::default()
277 })
278}
279
280pub mod actions;
281pub mod client;
282pub mod config;
283pub mod frame;
284pub mod frame_parser;
285pub mod prompts;
286pub mod recordreplay;