Skip to main content

weida_http_codec/
h3.rs

1//! HTTP/3 frames and stream types (RFC 9114 §6, §7).
2//!
3//! Every HTTP/3 frame is a type and a length, both QUIC variable-length
4//! integers, then the payload. [`decode_frame_header`] reads the two; the
5//! connection then decides from the type how much of the payload it is
6//! willing to hold (DATA is streamed, HEADERS is bounded by
7//! [`Limits::max_head_bytes`], everything else by [`Limits::max_frame_size`])
8//! before reading it.
9
10use crate::error::{DecodeError, EncodeError};
11use crate::limits::Limits;
12use crate::varint;
13
14/// Frame types (RFC 9114 §7.2).
15pub mod frame {
16    /// DATA.
17    pub const DATA: u64 = 0x0;
18    /// HEADERS.
19    pub const HEADERS: u64 = 0x1;
20    /// CANCEL_PUSH.
21    pub const CANCEL_PUSH: u64 = 0x3;
22    /// SETTINGS.
23    pub const SETTINGS: u64 = 0x4;
24    /// PUSH_PROMISE.
25    pub const PUSH_PROMISE: u64 = 0x5;
26    /// GOAWAY.
27    pub const GOAWAY: u64 = 0x7;
28    /// MAX_PUSH_ID.
29    pub const MAX_PUSH_ID: u64 = 0xd;
30}
31
32/// Whether `kind` is an HTTP/2 frame type HTTP/3 reserves (PRIORITY, PING,
33/// WINDOW_UPDATE, CONTINUATION): receiving one is `H3_FRAME_UNEXPECTED`
34/// (RFC 9114 §7.2.8).
35#[must_use]
36pub const fn is_http2_reserved(kind: u64) -> bool {
37    matches!(kind, 0x2 | 0x6 | 0x8 | 0x9)
38}
39
40/// Unidirectional stream types (RFC 9114 §6.2, RFC 9204 §4.2).
41pub mod stream {
42    /// The control stream.
43    pub const CONTROL: u64 = 0x0;
44    /// A push stream.
45    pub const PUSH: u64 = 0x1;
46    /// The QPACK encoder stream.
47    pub const QPACK_ENCODER: u64 = 0x2;
48    /// The QPACK decoder stream.
49    pub const QPACK_DECODER: u64 = 0x3;
50}
51
52/// Setting identifiers (RFC 9114 §7.2.4.1, RFC 9204 §5).
53pub mod setting {
54    /// `SETTINGS_QPACK_MAX_TABLE_CAPACITY`.
55    pub const QPACK_MAX_TABLE_CAPACITY: u64 = 0x1;
56    /// `SETTINGS_MAX_FIELD_SECTION_SIZE`.
57    pub const MAX_FIELD_SECTION_SIZE: u64 = 0x6;
58    /// `SETTINGS_QPACK_BLOCKED_STREAMS`.
59    pub const QPACK_BLOCKED_STREAMS: u64 = 0x7;
60}
61
62/// Error codes (RFC 9114 §8.1, RFC 9204 §6).
63pub mod code {
64    /// No error.
65    pub const H3_NO_ERROR: u64 = 0x100;
66    /// General protocol error.
67    pub const H3_GENERAL_PROTOCOL_ERROR: u64 = 0x101;
68    /// Internal error.
69    pub const H3_INTERNAL_ERROR: u64 = 0x102;
70    /// Stream creation error.
71    pub const H3_STREAM_CREATION_ERROR: u64 = 0x103;
72    /// Critical stream was closed.
73    pub const H3_CLOSED_CRITICAL_STREAM: u64 = 0x104;
74    /// Frame not permitted in the current state.
75    pub const H3_FRAME_UNEXPECTED: u64 = 0x105;
76    /// Frame violated layout or size rules.
77    pub const H3_FRAME_ERROR: u64 = 0x106;
78    /// Peer generating excessive load.
79    pub const H3_EXCESSIVE_LOAD: u64 = 0x107;
80    /// An identifier was used incorrectly.
81    pub const H3_ID_ERROR: u64 = 0x108;
82    /// SETTINGS frame contained invalid values.
83    pub const H3_SETTINGS_ERROR: u64 = 0x109;
84    /// No SETTINGS frame received.
85    pub const H3_MISSING_SETTINGS: u64 = 0x10a;
86    /// Request not processed.
87    pub const H3_REQUEST_REJECTED: u64 = 0x10b;
88    /// Data no longer needed.
89    pub const H3_REQUEST_CANCELLED: u64 = 0x10c;
90    /// Stream terminated early.
91    pub const H3_REQUEST_INCOMPLETE: u64 = 0x10d;
92    /// Malformed message.
93    pub const H3_MESSAGE_ERROR: u64 = 0x10e;
94    /// TCP reset or error on CONNECT request.
95    pub const H3_CONNECT_ERROR: u64 = 0x10f;
96    /// Retry over HTTP/1.1.
97    pub const H3_VERSION_FALLBACK: u64 = 0x110;
98    /// The decoder failed to interpret an encoded field section.
99    pub const QPACK_DECOMPRESSION_FAILED: u64 = 0x200;
100    /// The decoder failed to interpret an encoder instruction.
101    pub const QPACK_ENCODER_STREAM_ERROR: u64 = 0x201;
102    /// The encoder failed to interpret a decoder instruction.
103    pub const QPACK_DECODER_STREAM_ERROR: u64 = 0x202;
104}
105
106/// A frame's type and payload length.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct FrameHeader {
109    /// The frame type.
110    pub kind: u64,
111    /// The payload length.
112    pub len: u64,
113}
114
115/// Decodes a frame header. Returns it and the octets used.
116///
117/// # Errors
118///
119/// `Incomplete`.
120pub fn decode_frame_header(input: &[u8]) -> Result<(FrameHeader, usize), DecodeError> {
121    let (kind, a) = varint::decode(input)?;
122    let (len, b) = varint::decode(&input[a..])?;
123    Ok((FrameHeader { kind, len }, a + b))
124}
125
126const fn malformed(what: &'static str) -> DecodeError {
127    DecodeError::Malformed { what }
128}
129
130/// Decodes a SETTINGS payload into `(identifier, value)` pairs.
131///
132/// # Errors
133///
134/// `TooLarge` `"frame"` for a payload above [`Limits::max_frame_size`],
135/// checked before parsing; `Malformed` `"SETTINGS"` for a truncated pair,
136/// `"duplicate setting"`, or `"HTTP/2 setting in HTTP/3"` for identifiers
137/// 0x2 to 0x5 (RFC 9114 §7.2.4.1), all `H3_SETTINGS_ERROR`.
138pub fn decode_settings(payload: &[u8], limits: Limits) -> Result<Vec<(u64, u64)>, DecodeError> {
139    if payload.len() as u64 > u64::from(limits.max_frame_size) {
140        return Err(DecodeError::TooLarge {
141            what: "frame",
142            declared: payload.len() as u64,
143            cap: u64::from(limits.max_frame_size),
144        });
145    }
146    let mut out: Vec<(u64, u64)> = Vec::new();
147    let mut pos = 0;
148    while pos < payload.len() {
149        let (id, a) = varint::decode(&payload[pos..]).map_err(|_| malformed("SETTINGS"))?;
150        pos += a;
151        let (value, b) = varint::decode(&payload[pos..]).map_err(|_| malformed("SETTINGS"))?;
152        pos += b;
153        if (0x2..=0x5).contains(&id) {
154            return Err(malformed("HTTP/2 setting in HTTP/3"));
155        }
156        if out.iter().any(|&(seen, _)| seen == id) {
157            return Err(malformed("duplicate setting"));
158        }
159        out.push((id, value));
160    }
161    Ok(out)
162}
163
164/// Decodes a GOAWAY payload: one stream or push identifier.
165///
166/// # Errors
167///
168/// `Malformed` `"GOAWAY"` unless the payload is exactly one integer.
169pub fn decode_goaway(payload: &[u8]) -> Result<u64, DecodeError> {
170    match varint::decode(payload) {
171        Ok((id, used)) if used == payload.len() => Ok(id),
172        _ => Err(malformed("GOAWAY")),
173    }
174}
175
176fn header(kind: u64, len: u64, out: &mut Vec<u8>) -> Result<(), EncodeError> {
177    varint::encode(kind, out)?;
178    varint::encode(len, out)
179}
180
181/// Appends a SETTINGS frame.
182///
183/// # Errors
184///
185/// `TooLarge` `"varint"` for a value above 2^62 - 1. Nothing is written on
186/// error.
187pub fn encode_settings(settings: &[(u64, u64)], out: &mut Vec<u8>) -> Result<(), EncodeError> {
188    let mut payload = Vec::new();
189    for &(id, value) in settings {
190        varint::encode(id, &mut payload)?;
191        varint::encode(value, &mut payload)?;
192    }
193    header(frame::SETTINGS, payload.len() as u64, out)?;
194    out.extend_from_slice(&payload);
195    Ok(())
196}
197
198/// Appends the header of a DATA frame whose payload of `len` octets the
199/// caller writes next.
200///
201/// # Errors
202///
203/// `TooLarge` `"varint"` above 2^62 - 1.
204pub fn encode_data_header(len: u64, out: &mut Vec<u8>) -> Result<(), EncodeError> {
205    header(frame::DATA, len, out)
206}
207
208/// Appends a HEADERS frame carrying `block`, an encoded field section.
209pub fn encode_headers(block: &[u8], out: &mut Vec<u8>) {
210    header(frame::HEADERS, block.len() as u64, out).expect("a slice length fits a varint");
211    out.extend_from_slice(block);
212}
213
214/// Appends a GOAWAY frame naming `id`.
215///
216/// # Errors
217///
218/// `TooLarge` `"varint"` above 2^62 - 1. Nothing is written on error.
219pub fn encode_goaway(id: u64, out: &mut Vec<u8>) -> Result<(), EncodeError> {
220    if id > varint::MAX {
221        return Err(EncodeError::TooLarge {
222            what: "varint",
223            len: id,
224            cap: varint::MAX,
225        });
226    }
227    header(frame::GOAWAY, varint::len(id) as u64, out)?;
228    varint::encode(id, out)
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn settings_round_trip_and_refuse_by_name() {
237        let mut out = Vec::new();
238        encode_settings(
239            &[(setting::MAX_FIELD_SECTION_SIZE, 65_536), (0x21, 0)],
240            &mut out,
241        )
242        .unwrap();
243        let (head, used) = decode_frame_header(&out).unwrap();
244        assert_eq!(
245            head,
246            FrameHeader {
247                kind: frame::SETTINGS,
248                len: (out.len() - used) as u64
249            }
250        );
251        assert_eq!(
252            decode_settings(&out[used..], Limits::DEFAULT),
253            Ok(vec![(6, 65_536), (0x21, 0)])
254        );
255        let refuse = |p: &[u8]| match decode_settings(p, Limits::DEFAULT) {
256            Err(DecodeError::Malformed { what }) => what,
257            other => panic!("{other:?}"),
258        };
259        assert_eq!(refuse(&[0x06, 0x01, 0x06, 0x02]), "duplicate setting");
260        assert_eq!(refuse(&[0x04, 0x00]), "HTTP/2 setting in HTTP/3");
261        assert_eq!(refuse(&[0x06]), "SETTINGS");
262        let small = Limits {
263            max_frame_size: 1,
264            ..Limits::DEFAULT
265        };
266        assert!(matches!(
267            decode_settings(&[0x06, 0x01], small),
268            Err(DecodeError::TooLarge { what: "frame", .. })
269        ));
270    }
271
272    #[test]
273    fn goaway_is_one_integer() {
274        let mut out = Vec::new();
275        encode_goaway(400, &mut out).unwrap();
276        let (head, used) = decode_frame_header(&out).unwrap();
277        assert_eq!(head.kind, frame::GOAWAY);
278        assert_eq!(decode_goaway(&out[used..]), Ok(400));
279        assert_eq!(decode_goaway(&[0x01, 0x02]), Err(malformed("GOAWAY")));
280    }
281
282    #[test]
283    fn the_reserved_http2_types() {
284        assert!([0x2, 0x6, 0x8, 0x9].into_iter().all(is_http2_reserved));
285        assert!(!is_http2_reserved(frame::DATA));
286        assert!(!is_http2_reserved(frame::GOAWAY));
287    }
288}