Skip to main content

weida_http_codec/
qpack.rs

1//! QPACK, the field compression of HTTP/3 (RFC 9204), with the static table
2//! only.
3//!
4//! An endpoint that advertises `SETTINGS_QPACK_MAX_TABLE_CAPACITY = 0` never
5//! has a dynamic table, needs neither an encoder nor a decoder stream
6//! (RFC 9204 §4.2), and every field section it receives must have a Required
7//! Insert Count of 0. So [`decode_field_section`] refuses every reference to a
8//! dynamic table as `"dynamic table reference"`, which a connection maps onto
9//! `QPACK_DECOMPRESSION_FAILED`, and [`encode_field_section`] writes only
10//! static references and literals.
11//!
12//! Strategy of the encoder, fixed:
13//!
14//! * a field found whole in the static table is an indexed field line;
15//! * a field whose name is in the static table is a literal with a name
16//!   reference;
17//! * anything else is a literal with a literal name;
18//! * a sensitive field (the flag, or [`is_sensitive`]) sets the N bit, so an
19//!   intermediary never puts it into a dynamic table (RFC 9204 §7.1.3);
20//! * a string is Huffman-coded when that is strictly shorter.
21
22use crate::error::DecodeError;
23use crate::fields::is_sensitive;
24use crate::limits::Limits;
25use crate::prefix::{decode_int, decode_string, encode_int, encode_string};
26
27/// The static table, Appendix A: index 0 is the first entry.
28pub const STATIC: [(&[u8], &[u8]); 99] = [
29    (b":authority", b""),
30    (b":path", b"/"),
31    (b"age", b"0"),
32    (b"content-disposition", b""),
33    (b"content-length", b"0"),
34    (b"cookie", b""),
35    (b"date", b""),
36    (b"etag", b""),
37    (b"if-modified-since", b""),
38    (b"if-none-match", b""),
39    (b"last-modified", b""),
40    (b"link", b""),
41    (b"location", b""),
42    (b"referer", b""),
43    (b"set-cookie", b""),
44    (b":method", b"CONNECT"),
45    (b":method", b"DELETE"),
46    (b":method", b"GET"),
47    (b":method", b"HEAD"),
48    (b":method", b"OPTIONS"),
49    (b":method", b"POST"),
50    (b":method", b"PUT"),
51    (b":scheme", b"http"),
52    (b":scheme", b"https"),
53    (b":status", b"103"),
54    (b":status", b"200"),
55    (b":status", b"304"),
56    (b":status", b"404"),
57    (b":status", b"503"),
58    (b"accept", b"*/*"),
59    (b"accept", b"application/dns-message"),
60    (b"accept-encoding", b"gzip, deflate, br"),
61    (b"accept-ranges", b"bytes"),
62    (b"access-control-allow-headers", b"cache-control"),
63    (b"access-control-allow-headers", b"content-type"),
64    (b"access-control-allow-origin", b"*"),
65    (b"cache-control", b"max-age=0"),
66    (b"cache-control", b"max-age=2592000"),
67    (b"cache-control", b"max-age=604800"),
68    (b"cache-control", b"no-cache"),
69    (b"cache-control", b"no-store"),
70    (b"cache-control", b"public, max-age=31536000"),
71    (b"content-encoding", b"br"),
72    (b"content-encoding", b"gzip"),
73    (b"content-type", b"application/dns-message"),
74    (b"content-type", b"application/javascript"),
75    (b"content-type", b"application/json"),
76    (b"content-type", b"application/x-www-form-urlencoded"),
77    (b"content-type", b"image/gif"),
78    (b"content-type", b"image/jpeg"),
79    (b"content-type", b"image/png"),
80    (b"content-type", b"text/css"),
81    (b"content-type", b"text/html; charset=utf-8"),
82    (b"content-type", b"text/plain"),
83    (b"content-type", b"text/plain;charset=utf-8"),
84    (b"range", b"bytes=0-"),
85    (b"strict-transport-security", b"max-age=31536000"),
86    (
87        b"strict-transport-security",
88        b"max-age=31536000; includesubdomains",
89    ),
90    (
91        b"strict-transport-security",
92        b"max-age=31536000; includesubdomains; preload",
93    ),
94    (b"vary", b"accept-encoding"),
95    (b"vary", b"origin"),
96    (b"x-content-type-options", b"nosniff"),
97    (b"x-xss-protection", b"1; mode=block"),
98    (b":status", b"100"),
99    (b":status", b"204"),
100    (b":status", b"206"),
101    (b":status", b"302"),
102    (b":status", b"400"),
103    (b":status", b"403"),
104    (b":status", b"421"),
105    (b":status", b"425"),
106    (b":status", b"500"),
107    (b"accept-language", b""),
108    (b"access-control-allow-credentials", b"FALSE"),
109    (b"access-control-allow-credentials", b"TRUE"),
110    (b"access-control-allow-headers", b"*"),
111    (b"access-control-allow-methods", b"get"),
112    (b"access-control-allow-methods", b"get, post, options"),
113    (b"access-control-allow-methods", b"options"),
114    (b"access-control-expose-headers", b"content-length"),
115    (b"access-control-request-headers", b"content-type"),
116    (b"access-control-request-method", b"get"),
117    (b"access-control-request-method", b"post"),
118    (b"alt-svc", b"clear"),
119    (b"authorization", b""),
120    (
121        b"content-security-policy",
122        b"script-src 'none'; object-src 'none'; base-uri 'none'",
123    ),
124    (b"early-data", b"1"),
125    (b"expect-ct", b""),
126    (b"forwarded", b""),
127    (b"if-range", b""),
128    (b"origin", b""),
129    (b"purpose", b"prefetch"),
130    (b"server", b""),
131    (b"timing-allow-origin", b"*"),
132    (b"upgrade-insecure-requests", b"1"),
133    (b"user-agent", b""),
134    (b"x-forwarded-for", b""),
135    (b"x-frame-options", b"deny"),
136    (b"x-frame-options", b"sameorigin"),
137];
138
139const fn malformed(what: &'static str) -> DecodeError {
140    DecodeError::Malformed { what }
141}
142
143const DYNAMIC: DecodeError = malformed("dynamic table reference");
144
145fn static_entry(index: u64) -> Result<(&'static [u8], &'static [u8]), DecodeError> {
146    usize::try_from(index)
147        .ok()
148        .and_then(|i| STATIC.get(i))
149        .copied()
150        .ok_or(malformed("index"))
151}
152
153/// Decodes one complete field section, appending `(name, value)` pairs to
154/// `out` in order.
155///
156/// # Errors
157///
158/// `Malformed` `"dynamic table reference"` for a Required Insert Count other
159/// than 0 or any line that refers to a dynamic table; `"index"` past the
160/// static table; `"uppercase field name"`; `"truncated field section"`;
161/// `"integer"` and the Huffman refusals. `TooLarge` `"field section"` and
162/// `"field count"` as HPACK's decoder counts them, `"string"` for one string
163/// longer than [`Limits::max_head_bytes`].
164pub fn decode_field_section(
165    block: &[u8],
166    limits: Limits,
167    out: &mut Vec<(Vec<u8>, Vec<u8>)>,
168) -> Result<(), DecodeError> {
169    let truncated = |e: DecodeError| match e {
170        DecodeError::Incomplete { .. } => malformed("truncated field section"),
171        e => e,
172    };
173    let cap = limits.max_head_bytes;
174    // Encoded Required Insert Count, then the sign bit and Delta Base.
175    let (ric, used) = decode_int(block, 8).map_err(truncated)?;
176    if ric != 0 {
177        return Err(DYNAMIC);
178    }
179    let mut pos = used;
180    let (_, used) = decode_int(&block[pos..], 7).map_err(truncated)?;
181    pos += used;
182
183    let mut counted = 0usize;
184    let mut count = 0usize;
185    while pos < block.len() {
186        let b = block[pos];
187        let rest = &block[pos..];
188        let (name, value) = if b & 0x80 != 0 {
189            // 1T: indexed field line.
190            if b & 0x40 == 0 {
191                return Err(DYNAMIC);
192            }
193            let (idx, used) = decode_int(rest, 6).map_err(truncated)?;
194            pos += used;
195            let (n, v) = static_entry(idx)?;
196            (n.to_vec(), v.to_vec())
197        } else if b & 0x40 != 0 {
198            // 01NT: literal with name reference.
199            if b & 0x10 == 0 {
200                return Err(DYNAMIC);
201            }
202            let (idx, used) = decode_int(rest, 4).map_err(truncated)?;
203            pos += used;
204            let name = static_entry(idx)?.0.to_vec();
205            let (value, used) = decode_string(&block[pos..], 0x80, 7, cap).map_err(truncated)?;
206            pos += used;
207            (name, value)
208        } else if b & 0x20 != 0 {
209            // 001NH: literal with literal name.
210            let (name, used) = decode_string(rest, 0x08, 3, cap).map_err(truncated)?;
211            pos += used;
212            let (value, used) = decode_string(&block[pos..], 0x80, 7, cap).map_err(truncated)?;
213            pos += used;
214            (name, value)
215        } else {
216            // 0001: post-base indexed; 0000N: post-base name reference.
217            return Err(DYNAMIC);
218        };
219        if name.iter().any(u8::is_ascii_uppercase) {
220            return Err(malformed("uppercase field name"));
221        }
222        count += 1;
223        if count > limits.max_fields {
224            return Err(DecodeError::TooLarge {
225                what: "field count",
226                declared: count as u64,
227                cap: limits.max_fields as u64,
228            });
229        }
230        counted += name.len() + value.len() + 32;
231        if counted > cap {
232            return Err(DecodeError::TooLarge {
233                what: "field section",
234                declared: counted as u64,
235                cap: cap as u64,
236            });
237        }
238        out.push((name, value));
239    }
240    Ok(())
241}
242
243/// Encodes one field section against the static table only. Each field is
244/// `(name, value, sensitive)`; names must already be lowercase.
245pub fn encode_field_section(fields: &[(&[u8], &[u8], bool)], out: &mut Vec<u8>) {
246    // Required Insert Count 0, Delta Base 0.
247    out.extend_from_slice(&[0x00, 0x00]);
248    for &(name, value, sensitive) in fields {
249        let n_bit = sensitive || is_sensitive(name);
250        let mut by_name = None;
251        let mut exact = None;
252        for (i, (n, v)) in STATIC.iter().enumerate() {
253            if *n == name {
254                by_name.get_or_insert(i);
255                if *v == value {
256                    exact = Some(i);
257                    break;
258                }
259            }
260        }
261        if let Some(i) = exact {
262            encode_int(i as u64, 6, 0xc0, out);
263            continue;
264        }
265        match by_name {
266            Some(i) => {
267                let first = 0x50 | if n_bit { 0x20 } else { 0 };
268                encode_int(i as u64, 4, first, out);
269            }
270            None => {
271                let first = 0x20 | if n_bit { 0x10 } else { 0 };
272                encode_string(name, first, 0x08, 3, true, out);
273            }
274        }
275        encode_string(value, 0, 0x80, 7, true, out);
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    const L: Limits = Limits::DEFAULT;
284
285    type Fields = Vec<(Vec<u8>, Vec<u8>)>;
286
287    fn decode(block: &[u8]) -> Result<Fields, DecodeError> {
288        let mut out = Vec::new();
289        decode_field_section(block, L, &mut out).map(|()| out)
290    }
291
292    #[test]
293    fn every_line_shape_round_trips() {
294        let fields: &[(&[u8], &[u8], bool)] = &[
295            (b":method", b"GET", false),
296            (b":path", b"/a/b", false),
297            (b"x-custom", b"value", false),
298            (b"authorization", b"Bearer t", false),
299            (b"x-secret", b"s", true),
300            (b"accept", b"", false),
301        ];
302        let mut block = Vec::new();
303        encode_field_section(fields, &mut block);
304        let out = decode(&block).unwrap();
305        let expect: Vec<_> = fields
306            .iter()
307            .map(|(n, v, _)| (n.to_vec(), v.to_vec()))
308            .collect();
309        assert_eq!(out, expect);
310        // `:method GET` is static index 17: 11 + 010001.
311        assert_eq!(block[2], 0xd1);
312    }
313
314    #[test]
315    fn sensitive_fields_set_the_never_indexed_bit() {
316        let mut block = Vec::new();
317        encode_field_section(&[(b"authorization", b"x", false)], &mut block);
318        // 01NT with N set: name index 84 does not fit 4 bits.
319        assert_eq!(block[2], 0x7f);
320        let mut block = Vec::new();
321        encode_field_section(&[(b"x-secret", b"s", true)], &mut block);
322        assert_eq!(block[2] & 0xf0, 0x30);
323    }
324
325    #[test]
326    fn every_dynamic_reference_is_refused() {
327        for block in [
328            &[0x01, 0x00][..],         // Required Insert Count 1
329            &[0x00, 0x00, 0x80],       // indexed, T = 0
330            &[0x00, 0x00, 0x40, 0x00], // name reference, T = 0
331            &[0x00, 0x00, 0x10],       // post-base indexed
332            &[0x00, 0x00, 0x00, 0x00], // post-base name reference
333        ] {
334            assert_eq!(decode(block), Err(DYNAMIC), "{block:02x?}");
335        }
336    }
337
338    #[test]
339    fn the_static_table_ends_at_98() {
340        let mut block = vec![0, 0];
341        encode_int(98, 6, 0xc0, &mut block);
342        assert_eq!(decode(&block).unwrap()[0].0, b"x-frame-options");
343        let mut block = vec![0, 0];
344        encode_int(99, 6, 0xc0, &mut block);
345        assert_eq!(decode(&block), Err(malformed("index")));
346    }
347
348    #[test]
349    fn a_truncated_section_is_malformed() {
350        assert_eq!(decode(&[0x00]), Err(malformed("truncated field section")));
351        assert_eq!(
352            decode(&[0x00, 0x00, 0x51, 0x05, b'a']),
353            Err(malformed("truncated field section"))
354        );
355    }
356}