Skip to main content

weida_http_codec/
hpack.rs

1//! HPACK, the field compression of HTTP/2 (RFC 7541).
2//!
3//! [`Decoder`] reads a complete field block (the payload of HEADERS plus its
4//! CONTINUATION frames) against the static table and a dynamic table bounded
5//! by the size this side advertised; [`Encoder`] writes one with a fixed,
6//! simple strategy:
7//!
8//! * a field found whole in the static or dynamic table is written as an
9//!   index;
10//! * a sensitive field (the caller's flag, or a name
11//!   [`is_sensitive`] names) is a literal
12//!   *never indexed*, so no intermediary puts it into a compression context
13//!   (RFC 7541 §7.1.3);
14//! * everything else is a literal *with incremental indexing*, its name
15//!   indexed when a table holds it;
16//! * a string is Huffman-coded when that is strictly shorter.
17//!
18//! # The Appendix C vectors
19//!
20//! `tests/golden_vectors.rs` decodes every block of RFC 7541 Appendix C and
21//! re-encodes C.3, C.4, C.5.1, C.5.2 and C.6.1 byte for byte. Three blocks
22//! are asserted decode-only, each for a stated reason of this strategy:
23//!
24//! * **C.5.3 and C.6.3** carry `set-cookie`, which the RFC's encoder indexes
25//!   and this one writes never-indexed, because it is a credential.
26//! * **C.6.2** Huffman-codes `307`, whose Huffman form is exactly as long as
27//!   its plain form; this encoder takes Huffman only when it is shorter.
28//!
29//! The C.3 and C.5 vectors are written without Huffman coding, which is what
30//! [`Encoder::set_huffman`] exists for; C.5 and C.6 start from a 256-octet
31//! table on both sides, which [`Encoder::with_table_size`] states.
32
33use std::collections::VecDeque;
34
35use crate::error::DecodeError;
36use crate::fields::is_sensitive;
37use crate::limits::Limits;
38use crate::prefix::{decode_int, decode_string, encode_int, encode_string};
39
40/// The static table, Appendix A: index 1 is the first entry.
41pub const STATIC: [(&[u8], &[u8]); 61] = [
42    (b":authority", b""),
43    (b":method", b"GET"),
44    (b":method", b"POST"),
45    (b":path", b"/"),
46    (b":path", b"/index.html"),
47    (b":scheme", b"http"),
48    (b":scheme", b"https"),
49    (b":status", b"200"),
50    (b":status", b"204"),
51    (b":status", b"206"),
52    (b":status", b"304"),
53    (b":status", b"400"),
54    (b":status", b"404"),
55    (b":status", b"500"),
56    (b"accept-charset", b""),
57    (b"accept-encoding", b"gzip, deflate"),
58    (b"accept-language", b""),
59    (b"accept-ranges", b""),
60    (b"accept", b""),
61    (b"access-control-allow-origin", b""),
62    (b"age", b""),
63    (b"allow", b""),
64    (b"authorization", b""),
65    (b"cache-control", b""),
66    (b"content-disposition", b""),
67    (b"content-encoding", b""),
68    (b"content-language", b""),
69    (b"content-length", b""),
70    (b"content-location", b""),
71    (b"content-range", b""),
72    (b"content-type", b""),
73    (b"cookie", b""),
74    (b"date", b""),
75    (b"etag", b""),
76    (b"expect", b""),
77    (b"expires", b""),
78    (b"from", b""),
79    (b"host", b""),
80    (b"if-match", b""),
81    (b"if-modified-since", b""),
82    (b"if-none-match", b""),
83    (b"if-range", b""),
84    (b"if-unmodified-since", b""),
85    (b"last-modified", b""),
86    (b"link", b""),
87    (b"location", b""),
88    (b"max-forwards", b""),
89    (b"proxy-authenticate", b""),
90    (b"proxy-authorization", b""),
91    (b"range", b""),
92    (b"referer", b""),
93    (b"refresh", b""),
94    (b"retry-after", b""),
95    (b"server", b""),
96    (b"set-cookie", b""),
97    (b"strict-transport-security", b""),
98    (b"transfer-encoding", b""),
99    (b"user-agent", b""),
100    (b"vary", b""),
101    (b"via", b""),
102    (b"www-authenticate", b""),
103];
104
105/// The default `SETTINGS_HEADER_TABLE_SIZE`, and the largest dynamic table
106/// this crate's [`Encoder`] uses: 4096 octets (RFC 9113 §6.5.2).
107pub const DEFAULT_TABLE_SIZE: u32 = 4096;
108
109/// What one entry costs in a dynamic table (RFC 7541 §4.1).
110fn entry_size(name: &[u8], value: &[u8]) -> usize {
111    name.len() + value.len() + 32
112}
113
114/// The dynamic table: newest first, so index 62 is the front.
115#[derive(Debug, Default)]
116struct Table {
117    entries: VecDeque<(Vec<u8>, Vec<u8>)>,
118    size: usize,
119    max: usize,
120}
121
122impl Table {
123    fn new(max: usize) -> Self {
124        Self {
125            entries: VecDeque::new(),
126            size: 0,
127            max,
128        }
129    }
130
131    fn evict_to(&mut self, max: usize) {
132        while self.size > max {
133            let (n, v) = self
134                .entries
135                .pop_back()
136                .expect("a table over its size has entries");
137            self.size -= entry_size(&n, &v);
138        }
139    }
140
141    fn set_max(&mut self, max: usize) {
142        self.max = max;
143        self.evict_to(max);
144    }
145
146    /// RFC 7541 §4.4: an entry larger than the table empties it and is not
147    /// added.
148    fn insert(&mut self, name: Vec<u8>, value: Vec<u8>) {
149        let size = entry_size(&name, &value);
150        if size > self.max {
151            self.entries.clear();
152            self.size = 0;
153            return;
154        }
155        self.evict_to(self.max - size);
156        self.size += size;
157        self.entries.push_front((name, value));
158    }
159
160    /// Entry `index` of the combined address space (1-based).
161    fn get(&self, index: u64) -> Option<(&[u8], &[u8])> {
162        let index = usize::try_from(index).ok()?;
163        match index {
164            0 => None,
165            1..=61 => Some(STATIC[index - 1]),
166            _ => self
167                .entries
168                .get(index - 62)
169                .map(|(n, v)| (n.as_slice(), v.as_slice())),
170        }
171    }
172
173    /// The lowest index whose entry is `(name, value)`, and the lowest whose
174    /// name is `name`.
175    fn find(&self, name: &[u8], value: &[u8]) -> (Option<usize>, Option<usize>) {
176        let mut name_only = None;
177        let all = STATIC.iter().copied().chain(
178            self.entries
179                .iter()
180                .map(|(n, v)| (n.as_slice(), v.as_slice())),
181        );
182        for (i, (n, v)) in all.enumerate() {
183            if n == name {
184                if v == value {
185                    return (Some(i + 1), name_only.or(Some(i + 1)));
186                }
187                name_only.get_or_insert(i + 1);
188            }
189        }
190        (None, name_only)
191    }
192}
193
194/// An HPACK decoder: one per connection direction.
195#[derive(Debug)]
196pub struct Decoder {
197    table: Table,
198    /// The largest size an update may set: our `SETTINGS_HEADER_TABLE_SIZE`.
199    limit: usize,
200}
201
202const fn malformed(what: &'static str) -> DecodeError {
203    DecodeError::Malformed { what }
204}
205
206impl Decoder {
207    /// A decoder whose table is bounded by `max_table_size`, the
208    /// `SETTINGS_HEADER_TABLE_SIZE` this side advertised.
209    #[must_use]
210    pub fn new(max_table_size: u32) -> Self {
211        Self {
212            table: Table::new(max_table_size as usize),
213            limit: max_table_size as usize,
214        }
215    }
216
217    /// Follows a change of our `SETTINGS_HEADER_TABLE_SIZE`: later updates
218    /// are bounded by it, and the table shrinks to it at once.
219    pub fn set_max_table_size(&mut self, max: u32) {
220        self.limit = max as usize;
221        if self.table.max > self.limit {
222            self.table.set_max(self.limit);
223        }
224    }
225
226    /// Decodes one complete field block, appending `(name, value)` pairs to
227    /// `out` in order.
228    ///
229    /// # Errors
230    ///
231    /// `TooLarge` `"field section"` when the fields, counted as name plus
232    /// value plus 32 each (RFC 9113 §6.5.2), exceed
233    /// [`Limits::max_head_bytes`], `"field count"` past
234    /// [`Limits::max_fields`], `"string"` for one string longer than
235    /// `max_head_bytes`; `Malformed` naming the rule: `"index"`, a table
236    /// size update that is `"not at the start of a block"` or
237    /// `"above the advertised table size"`, `"truncated field block"`,
238    /// `"integer"`, the Huffman refusals. After any of these the decoder must
239    /// not be used again: the dynamic table may hold half a block (RFC 7541
240    /// §2.3.3 makes this a connection error).
241    ///
242    /// `Malformed` `"uppercase field name"` is the exception: the block is
243    /// decoded to its end first, so the dynamic table stays in step with the
244    /// peer's encoder and the connection can refuse only that stream
245    /// (RFC 9113 §8.2.1). `out` then holds the block's fields.
246    pub fn decode(
247        &mut self,
248        block: &[u8],
249        limits: Limits,
250        out: &mut Vec<(Vec<u8>, Vec<u8>)>,
251    ) -> Result<(), DecodeError> {
252        let truncated = |e: DecodeError| match e {
253            DecodeError::Incomplete { .. } => malformed("truncated field block"),
254            e => e,
255        };
256        let cap = limits.max_head_bytes;
257        let mut pos = 0;
258        let mut at_start = true;
259        let mut counted = 0usize;
260        let mut count = 0usize;
261        let mut uppercase = false;
262        while pos < block.len() {
263            let b = block[pos];
264            let rest = &block[pos..];
265            let (name, value, index) = if b & 0x80 != 0 {
266                let (idx, used) = decode_int(rest, 7).map_err(truncated)?;
267                pos += used;
268                let (n, v) = self.table.get(idx).ok_or(malformed("index"))?;
269                (n.to_vec(), v.to_vec(), false)
270            } else if b & 0xe0 == 0x20 {
271                let (size, used) = decode_int(rest, 5).map_err(truncated)?;
272                pos += used;
273                if !at_start {
274                    return Err(malformed("table size update not at the start of a block"));
275                }
276                if size > self.limit as u64 {
277                    return Err(malformed(
278                        "table size update above the advertised table size",
279                    ));
280                }
281                self.table.set_max(size as usize);
282                continue;
283            } else {
284                // 01: incremental indexing, 6-bit name index; 0000 without
285                // indexing and 0001 never indexed, 4-bit name index.
286                let (prefix, index) = if b & 0x40 != 0 { (6, true) } else { (4, false) };
287                let (idx, used) = decode_int(rest, prefix).map_err(truncated)?;
288                pos += used;
289                let name = if idx == 0 {
290                    let (n, used) =
291                        decode_string(&block[pos..], 0x80, 7, cap).map_err(truncated)?;
292                    pos += used;
293                    n
294                } else {
295                    self.table.get(idx).ok_or(malformed("index"))?.0.to_vec()
296                };
297                let (value, used) =
298                    decode_string(&block[pos..], 0x80, 7, cap).map_err(truncated)?;
299                pos += used;
300                (name, value, index)
301            };
302            at_start = false;
303            uppercase |= name.iter().any(u8::is_ascii_uppercase);
304            count += 1;
305            if count > limits.max_fields {
306                return Err(DecodeError::TooLarge {
307                    what: "field count",
308                    declared: count as u64,
309                    cap: limits.max_fields as u64,
310                });
311            }
312            counted += entry_size(&name, &value);
313            if counted > cap {
314                return Err(DecodeError::TooLarge {
315                    what: "field section",
316                    declared: counted as u64,
317                    cap: cap as u64,
318                });
319            }
320            if index {
321                self.table.insert(name.clone(), value.clone());
322            }
323            out.push((name, value));
324        }
325        if uppercase {
326            return Err(malformed("uppercase field name"));
327        }
328        Ok(())
329    }
330}
331
332/// An HPACK encoder: one per connection direction.
333#[derive(Debug)]
334pub struct Encoder {
335    table: Table,
336    /// The smallest size the table passed through since the last block, and
337    /// whether it changed: a block starts with the updates the decoder needs
338    /// (RFC 7541 §4.2).
339    pending: Option<usize>,
340    huffman: bool,
341}
342
343impl Default for Encoder {
344    fn default() -> Self {
345        Self::new()
346    }
347}
348
349impl Encoder {
350    /// An encoder whose table is [`DEFAULT_TABLE_SIZE`], the size a decoder
351    /// starts with in HTTP/2.
352    #[must_use]
353    pub fn new() -> Self {
354        Self::with_table_size(DEFAULT_TABLE_SIZE)
355    }
356
357    /// An encoder whose table starts at `size` on both sides, as when the
358    /// size was agreed before the first block (RFC 7541 Appendix C.5). Sizes
359    /// above [`DEFAULT_TABLE_SIZE`] are capped to it.
360    #[must_use]
361    pub fn with_table_size(size: u32) -> Self {
362        Self {
363            table: Table::new(size.min(DEFAULT_TABLE_SIZE) as usize),
364            pending: None,
365            huffman: true,
366        }
367    }
368
369    /// Whether strings are Huffman-coded when that is shorter; on by
370    /// default.
371    pub fn set_huffman(&mut self, on: bool) {
372        self.huffman = on;
373    }
374
375    /// Follows the peer's `SETTINGS_HEADER_TABLE_SIZE`. This encoder uses at
376    /// most [`DEFAULT_TABLE_SIZE`]; a change in what it uses is announced at
377    /// the start of the next block.
378    pub fn set_peer_max_table_size(&mut self, size: u32) {
379        let size = size.min(DEFAULT_TABLE_SIZE) as usize;
380        if size == self.table.max {
381            return;
382        }
383        let low = self
384            .pending
385            .map_or(size.min(self.table.max), |p| p.min(size));
386        self.pending = Some(low);
387        self.table.set_max(size);
388    }
389
390    /// Encodes one field block. Each field is `(name, value, sensitive)`;
391    /// names must already be lowercase, which the caller checked.
392    pub fn encode(&mut self, fields: &[(&[u8], &[u8], bool)], out: &mut Vec<u8>) {
393        if let Some(low) = self.pending.take() {
394            encode_int(low as u64, 5, 0x20, out);
395            if low != self.table.max {
396                encode_int(self.table.max as u64, 5, 0x20, out);
397            }
398        }
399        for &(name, value, sensitive) in fields {
400            let sensitive = sensitive || is_sensitive(name);
401            let (exact, by_name) = self.table.find(name, value);
402            if let Some(i) = exact {
403                encode_int(i as u64, 7, 0x80, out);
404                continue;
405            }
406            let (prefix, first) = if sensitive { (4, 0x10) } else { (6, 0x40) };
407            match by_name {
408                Some(i) => encode_int(i as u64, prefix, first, out),
409                None => {
410                    out.push(first);
411                    encode_string(name, 0, 0x80, 7, self.huffman, out);
412                }
413            }
414            encode_string(value, 0, 0x80, 7, self.huffman, out);
415            if !sensitive {
416                self.table.insert(name.to_vec(), value.to_vec());
417            }
418        }
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425
426    const L: Limits = Limits::DEFAULT;
427
428    fn round_trip(
429        enc: &mut Encoder,
430        dec: &mut Decoder,
431        fields: &[(&[u8], &[u8], bool)],
432    ) -> Vec<u8> {
433        let mut block = Vec::new();
434        enc.encode(fields, &mut block);
435        let mut out = Vec::new();
436        dec.decode(&block, L, &mut out).unwrap();
437        let expect: Vec<_> = fields
438            .iter()
439            .map(|(n, v, _)| (n.to_vec(), v.to_vec()))
440            .collect();
441        assert_eq!(out, expect);
442        block
443    }
444
445    #[test]
446    fn a_sensitive_field_is_never_indexed_and_never_enters_the_table() {
447        let (mut e, mut d) = (Encoder::new(), Decoder::new(4096));
448        let block = round_trip(&mut e, &mut d, &[(b"authorization", b"Bearer x", false)]);
449        // 0001 with name index 23 (authorization) does not fit 4 bits.
450        assert_eq!(block[0], 0x1f);
451        let block = round_trip(&mut e, &mut d, &[(b"x-token", b"s", true)]);
452        assert_eq!(block[0], 0x10);
453        // Sent again, still literal: nothing was indexed.
454        let again = round_trip(&mut e, &mut d, &[(b"x-token", b"s", true)]);
455        assert_eq!(again, block);
456    }
457
458    #[test]
459    fn a_repeated_field_becomes_one_index_octet() {
460        let (mut e, mut d) = (Encoder::new(), Decoder::new(4096));
461        round_trip(&mut e, &mut d, &[(b"x-a", b"1", false)]);
462        let block = round_trip(&mut e, &mut d, &[(b"x-a", b"1", false)]);
463        assert_eq!(block, [0x80 | 62]);
464    }
465
466    #[test]
467    fn a_shrunk_peer_table_is_announced_once() {
468        let (mut e, mut d) = (Encoder::new(), Decoder::new(4096));
469        round_trip(&mut e, &mut d, &[(b"x-a", b"1", false)]);
470        e.set_peer_max_table_size(0);
471        e.set_peer_max_table_size(100);
472        d.set_max_table_size(100);
473        let block = round_trip(&mut e, &mut d, &[(b"x-a", b"1", false)]);
474        // Two updates: to the minimum (0) and then to the final size (100).
475        assert_eq!(&block[..3], [0x20, 0x3f, 100 - 31]);
476        let block = round_trip(&mut e, &mut d, &[(b"x-a", b"1", false)]);
477        assert_eq!(block, [0x80 | 62]);
478    }
479
480    #[test]
481    fn the_decoder_refuses_what_it_did_not_advertise() {
482        let mut d = Decoder::new(100);
483        let mut out = Vec::new();
484        assert_eq!(
485            d.decode(&[0x3f, 0xe1, 0x1f], L, &mut out),
486            Err(malformed(
487                "table size update above the advertised table size"
488            ))
489        );
490        let mut d = Decoder::new(4096);
491        assert_eq!(
492            d.decode(&[0x82, 0x20], L, &mut out),
493            Err(malformed("table size update not at the start of a block"))
494        );
495        assert_eq!(d.decode(&[0x80], L, &mut out), Err(malformed("index")));
496        assert_eq!(d.decode(&[0xbe], L, &mut out), Err(malformed("index")));
497        assert_eq!(
498            d.decode(&[0x40, 0x01, b'A', 0x00], L, &mut out),
499            Err(malformed("uppercase field name"))
500        );
501        assert_eq!(
502            d.decode(&[0x40, 0x05, b'a'], L, &mut out),
503            Err(malformed("truncated field block"))
504        );
505    }
506
507    #[test]
508    fn an_uppercase_name_is_refused_with_the_table_in_step() {
509        let mut d = Decoder::new(4096);
510        let mut out = Vec::new();
511        // `A: v` with incremental indexing, then `b: w` likewise.
512        let block = [0x40, 0x01, b'A', 0x01, b'v', 0x40, 0x01, b'b', 0x01, b'w'];
513        assert_eq!(
514            d.decode(&block, L, &mut out),
515            Err(malformed("uppercase field name"))
516        );
517        // Both entries went in, newest first, as the peer's encoder has them;
518        // the next block can still index them (and is refused for the same
519        // name again).
520        let mut out = Vec::new();
521        d.decode(&[0xbe], L, &mut out).unwrap();
522        assert_eq!(out, [(b"b".to_vec(), b"w".to_vec())]);
523        let mut out = Vec::new();
524        assert_eq!(
525            d.decode(&[0xbf], L, &mut out),
526            Err(malformed("uppercase field name"))
527        );
528        assert_eq!(out, [(b"A".to_vec(), b"v".to_vec())]);
529    }
530
531    #[test]
532    fn the_field_section_is_counted_as_rfc9113_counts_it() {
533        let mut block = Vec::new();
534        Encoder::new().encode(&[(b"a", b"b", false), (b"c", b"d", false)], &mut block);
535        let mut out = Vec::new();
536        let exact = Limits {
537            max_head_bytes: 68,
538            ..L
539        };
540        Decoder::new(4096).decode(&block, exact, &mut out).unwrap();
541        let short = Limits {
542            max_head_bytes: 67,
543            ..L
544        };
545        assert!(matches!(
546            Decoder::new(4096).decode(&block, short, &mut Vec::new()),
547            Err(DecodeError::TooLarge {
548                what: "field section",
549                declared: 68,
550                cap: 67
551            })
552        ));
553        let one = Limits { max_fields: 1, ..L };
554        assert!(matches!(
555            Decoder::new(4096).decode(&block, one, &mut Vec::new()),
556            Err(DecodeError::TooLarge {
557                what: "field count",
558                ..
559            })
560        ));
561    }
562
563    #[test]
564    fn an_oversized_entry_empties_the_table() {
565        let mut t = Table::new(64);
566        t.insert(b"a".to_vec(), b"b".to_vec());
567        assert_eq!(t.size, 34);
568        t.insert(b"a".to_vec(), vec![b'x'; 40]);
569        assert_eq!((t.size, t.entries.len()), (0, 0));
570    }
571}