git clone https://garage44.eu/jeroen/pinnacle.git.. /net/src/hpack.rs
//! HPACK (RFC 7541), HTTP/2's header compression: the decoder whole (the
//! static and dynamic tables, integers, literals plain or Huffman-coded),
//! and an encoder that never adds to the server's table (the static table
//! for names, literals otherwise), so it has no table to keep.
use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// A block cut short, an index past the tables, a bad Huffman code, a
/// table larger than allowed: the connection cannot go on (its tables
/// would no longer agree).
Compression(&'static str),
}
/// The table a decoder keeps at most: SETTINGS_HEADER_TABLE_SIZE's
/// default, which this client does not change.
pub const TABLE_SIZE: usize = 4096;
/// What a header list may come to, in bytes as HPACK counts them (each
/// field 32 more than its name and value), at most.
pub const MAX_LIST: usize = 256 * 1024;
pub struct Decoder {
/// The newest first.
table: VecDeque<(String, String)>,
size: usize,
/// The size the server last set, at most [`TABLE_SIZE`].
capacity: usize,
}
impl Default for Decoder {
fn default() -> Self {
Self::new()
}
}
impl Decoder {
pub fn new() -> Decoder {
Decoder {
table: VecDeque::new(),
size: 0,
capacity: TABLE_SIZE,
}
}
/// A header block's fields, in order.
pub fn decode(&mut self, mut block: &[u8]) -> Result<Vec<(String, String)>, Error> {
let mut fields: Vec<(String, String)> = Vec::new();
let mut list = 0;
while let Some(&b) = block.first() {
if b & 0x80 != 0 {
let i = integer(&mut block, 7)?;
fields.push(self.field(i)?);
} else if b & 0xe0 == 0x20 {
// A size update, only before the block's first field.
let size = integer(&mut block, 5)?;
if !fields.is_empty() || size > TABLE_SIZE {
return Err(Error::Compression("a table size update not allowed"));
}
self.capacity = size;
self.evict(0);
continue;
} else {
// With incremental indexing (01), else without or never
// indexed (0000, 0001).
let indexing = b & 0x40 != 0;
let index = integer(&mut block, if indexing { 6 } else { 4 })?;
let name = if index == 0 {
string(&mut block)?
} else {
self.field(index)?.0
};
let value = string(&mut block)?;
if indexing {
self.insert(name.clone(), value.clone());
}
fields.push((name, value));
}
let (name, value) = fields.last().map_or((0, 0), |(n, v)| (n.len(), v.len()));
list += name + value + 32;
if list > MAX_LIST {
return Err(Error::Compression("a header list too large"));
}
}
Ok(fields)
}
fn field(&self, index: usize) -> Result<(String, String), Error> {
let missing = Error::Compression("an index past the tables");
match index {
0 => Err(missing),
1..=61 => {
let (n, v) = STATIC_FIELDS[index - 1];
Ok((n.into(), v.into()))
}
_ => self.table.get(index - 62).cloned().ok_or(missing),
}
}
fn insert(&mut self, name: String, value: String) {
let size = name.len() + value.len() + 32;
// An entry larger than the table empties it and is not kept.
if size > self.capacity {
self.table.clear();
self.size = 0;
return;
}
self.evict(size);
self.table.push_front((name, value));
self.size += size;
}
/// Drops the oldest until `room` more fits.
fn evict(&mut self, room: usize) {
while self.size + room > self.capacity {
let Some((n, v)) = self.table.pop_back() else {
self.size = 0;
return;
};
self.size -= n.len() + v.len() + 32;
}
}
}
/// An integer with an `n`-bit prefix (5.1), taken off the front.
fn integer(block: &mut &[u8], n: u32) -> Result<usize, Error> {
let short = Error::Compression("an integer cut short");
let (&first, mut rest) = block.split_first().ok_or(short)?;
let mask = (1usize << n) - 1;
let mut value = usize::from(first) & mask;
if value == mask {
let mut shift = 0;
loop {
let (&b, more) = rest.split_first().ok_or(short)?;
rest = more;
if shift > 21 {
return Err(Error::Compression("an integer too large"));
}
value += usize::from(b & 0x7f) << shift;
shift += 7;
if b & 0x80 == 0 {
break;
}
}
}
*block = rest;
Ok(value)
}
/// A string literal (5.2), plain or Huffman-coded, taken off the front.
fn string(block: &mut &[u8]) -> Result<String, Error> {
let huffman = block.first().is_some_and(|b| b & 0x80 != 0);
let len = integer(block, 7)?;
if len > block.len() {
return Err(Error::Compression("a string cut short"));
}
let (bytes, rest) = block.split_at(len);
*block = rest;
let bytes = if huffman {
huffman_decode(bytes)?
} else {
bytes.to_vec()
};
// Header values are bytes; what is not UTF-8 is read as Latin-1, so
// nothing is lost and they stay strings.
Ok(match String::from_utf8(bytes) {
Ok(s) => s,
Err(e) => e.as_bytes().iter().map(|&b| char::from(b)).collect(),
})
}
/// Decodes Huffman-coded bytes. The code is canonical: each length's
/// codes are consecutive, so a code is found from its length's first.
pub fn huffman_decode(bytes: &[u8]) -> Result<Vec<u8>, Error> {
let bad = Error::Compression("a bad Huffman code");
let (first, start) = canonical();
let mut out = Vec::with_capacity(bytes.len() * 8 / 5);
let (mut code, mut len) = (0u32, 0usize);
for byte in bytes {
for bit in (0..8).rev() {
code = (code << 1) | u32::from(byte >> bit & 1);
len += 1;
let count = start[len + 1] - start[len];
if count > 0 && code >= first[len] && code - first[len] < count as u32 {
let symbol = SORTED[start[len] + (code - first[len]) as usize].2;
if symbol == 256 {
return Err(bad); // EOS inside a string
}
out.push(symbol as u8);
(code, len) = (0, 0);
} else if len >= 30 {
return Err(bad);
}
}
}
// What is left is padding: under 8 bits, all ones (EOS's start).
if len >= 8 || code != (1 << len) - 1 {
return Err(bad);
}
Ok(out)
}
/// Per length (1–30): its first code, and where its codes start in
/// [`SORTED`] (`start[len + 1]` where they end).
fn canonical() -> ([u32; 32], [usize; 32]) {
let mut first = [0u32; 32];
let mut start = [0usize; 32];
let mut at = 0;
for len in 1..31 {
start[len] = at;
if let Some(&(code, ..)) = SORTED.get(at).filter(|e| usize::from(e.1) == len) {
first[len] = code;
}
while SORTED.get(at).is_some_and(|e| usize::from(e.1) == len) {
at += 1;
}
}
start[31] = at;
(first, start)
}
/// The Huffman code ordered by length, then code: (code, length, symbol).
static SORTED: [(u32, u8, u16); 257] = sorted();
const fn sorted() -> [(u32, u8, u16); 257] {
let mut out = [(0u32, 0u8, 0u16); 257];
let mut i = 0;
while i < 257 {
out[i] = (HUFFMAN[i].0, HUFFMAN[i].1, i as u16);
i += 1;
}
// Insertion sort, at compile time.
let mut i = 1;
while i < 257 {
let mut j = i;
while j > 0 && (out[j - 1].1 > out[j].1 || (out[j - 1].1 == out[j].1 && out[j - 1].0 > out[j].0)) {
out.swap(j - 1, j);
j -= 1;
}
i += 1;
}
out
}
/// A header block for `fields` (names already lower-case): a static
/// entry where one matches whole, else a literal not indexed, its name
/// from the static table where it is there.
pub fn encode(fields: &[(&str, &str)]) -> Vec<u8> {
let mut out = Vec::new();
for &(name, value) in fields {
if let Some(i) = STATIC_FIELDS.iter().position(|&(n, v)| n == name && v == value) {
put_integer(&mut out, 0x80, 7, i + 1);
continue;
}
match STATIC_FIELDS.iter().position(|&(n, _)| n == name) {
Some(i) => put_integer(&mut out, 0, 4, i + 1),
None => {
out.push(0);
put_string(&mut out, name);
}
}
put_string(&mut out, value);
}
out
}
fn put_integer(out: &mut Vec<u8>, flags: u8, n: u32, mut value: usize) {
let mask = (1usize << n) - 1;
if value < mask {
out.push(flags | value as u8);
return;
}
out.push(flags | mask as u8);
value -= mask;
while value >= 0x80 {
out.push((value & 0x7f) as u8 | 0x80);
value >>= 7;
}
out.push(value as u8);
}
fn put_string(out: &mut Vec<u8>, s: &str) {
put_integer(out, 0, 7, s.len());
out.extend_from_slice(s.as_bytes());
}
/// RFC 7541's static table (Appendix A), from index 1.
static STATIC_FIELDS: [(&str, &str); 61] = [
(":authority", ""),
(":method", "GET"),
(":method", "POST"),
(":path", "/"),
(":path", "/index.html"),
(":scheme", "http"),
(":scheme", "https"),
(":status", "200"),
(":status", "204"),
(":status", "206"),
(":status", "304"),
(":status", "400"),
(":status", "404"),
(":status", "500"),
("accept-charset", ""),
("accept-encoding", "gzip, deflate"),
("accept-language", ""),
("accept-ranges", ""),
("accept", ""),
("access-control-allow-origin", ""),
("age", ""),
("allow", ""),
("authorization", ""),
("cache-control", ""),
("content-disposition", ""),
("content-encoding", ""),
("content-language", ""),
("content-length", ""),
("content-location", ""),
("content-range", ""),
("content-type", ""),
("cookie", ""),
("date", ""),
("etag", ""),
("expect", ""),
("expires", ""),
("from", ""),
("host", ""),
("if-match", ""),
("if-modified-since", ""),
("if-none-match", ""),
("if-range", ""),
("if-unmodified-since", ""),
("last-modified", ""),
("link", ""),
("location", ""),
("max-forwards", ""),
("proxy-authenticate", ""),
("proxy-authorization", ""),
("range", ""),
("referer", ""),
("refresh", ""),
("retry-after", ""),
("server", ""),
("set-cookie", ""),
("strict-transport-security", ""),
("transfer-encoding", ""),
("user-agent", ""),
("vary", ""),
("via", ""),
("www-authenticate", ""),
];
/// RFC 7541's Huffman code (Appendix B): each symbol's code, aligned to
/// the least significant bit, and its length; 256 is EOS.
static HUFFMAN: [(u32, u8); 257] = [
(0x1ff8, 13),
(0x7fffd8, 23),
(0xfffffe2, 28),
(0xfffffe3, 28),
(0xfffffe4, 28),
(0xfffffe5, 28),
(0xfffffe6, 28),
(0xfffffe7, 28),
(0xfffffe8, 28),
(0xffffea, 24),
(0x3ffffffc, 30),
(0xfffffe9, 28),
(0xfffffea, 28),
(0x3ffffffd, 30),
(0xfffffeb, 28),
(0xfffffec, 28),
(0xfffffed, 28),
(0xfffffee, 28),
(0xfffffef, 28),
(0xffffff0, 28),
(0xffffff1, 28),
(0xffffff2, 28),
(0x3ffffffe, 30),
(0xffffff3, 28),
(0xffffff4, 28),
(0xffffff5, 28),
(0xffffff6, 28),
(0xffffff7, 28),
(0xffffff8, 28),
(0xffffff9, 28),
(0xffffffa, 28),
(0xffffffb, 28),
(0x14, 6),
(0x3f8, 10),
(0x3f9, 10),
(0xffa, 12),
(0x1ff9, 13),
(0x15, 6),
(0xf8, 8),
(0x7fa, 11),
(0x3fa, 10),
(0x3fb, 10),
(0xf9, 8),
(0x7fb, 11),
(0xfa, 8),
(0x16, 6),
(0x17, 6),
(0x18, 6),
(0x0, 5),
(0x1, 5),
(0x2, 5),
(0x19, 6),
(0x1a, 6),
(0x1b, 6),
(0x1c, 6),
(0x1d, 6),
(0x1e, 6),
(0x1f, 6),
(0x5c, 7),
(0xfb, 8),
(0x7ffc, 15),
(0x20, 6),
(0xffb, 12),
(0x3fc, 10),
(0x1ffa, 13),
(0x21, 6),
(0x5d, 7),
(0x5e, 7),
(0x5f, 7),
(0x60, 7),
(0x61, 7),
(0x62, 7),
(0x63, 7),
(0x64, 7),
(0x65, 7),
(0x66, 7),
(0x67, 7),
(0x68, 7),
(0x69, 7),
(0x6a, 7),
(0x6b, 7),
(0x6c, 7),
(0x6d, 7),
(0x6e, 7),
(0x6f, 7),
(0x70, 7),
(0x71, 7),
(0x72, 7),
(0xfc, 8),
(0x73, 7),
(0xfd, 8),
(0x1ffb, 13),
(0x7fff0, 19),
(0x1ffc, 13),
(0x3ffc, 14),
(0x22, 6),
(0x7ffd, 15),
(0x3, 5),
(0x23, 6),
(0x4, 5),
(0x24, 6),
(0x5, 5),
(0x25, 6),
(0x26, 6),
(0x27, 6),
(0x6, 5),
(0x74, 7),
(0x75, 7),
(0x28, 6),
(0x29, 6),
(0x2a, 6),
(0x7, 5),
(0x2b, 6),
(0x76, 7),
(0x2c, 6),
(0x8, 5),
(0x9, 5),
(0x2d, 6),
(0x77, 7),
(0x78, 7),
(0x79, 7),
(0x7a, 7),
(0x7b, 7),
(0x7ffe, 15),
(0x7fc, 11),
(0x3ffd, 14),
(0x1ffd, 13),
(0xffffffc, 28),
(0xfffe6, 20),
(0x3fffd2, 22),
(0xfffe7, 20),
(0xfffe8, 20),
(0x3fffd3, 22),
(0x3fffd4, 22),
(0x3fffd5, 22),
(0x7fffd9, 23),
(0x3fffd6, 22),
(0x7fffda, 23),
(0x7fffdb, 23),
(0x7fffdc, 23),
(0x7fffdd, 23),
(0x7fffde, 23),
(0xffffeb, 24),
(0x7fffdf, 23),
(0xffffec, 24),
(0xffffed, 24),
(0x3fffd7, 22),
(0x7fffe0, 23),
(0xffffee, 24),
(0x7fffe1, 23),
(0x7fffe2, 23),
(0x7fffe3, 23),
(0x7fffe4, 23),
(0x1fffdc, 21),
(0x3fffd8, 22),
(0x7fffe5, 23),
(0x3fffd9, 22),
(0x7fffe6, 23),
(0x7fffe7, 23),
(0xffffef, 24),
(0x3fffda, 22),
(0x1fffdd, 21),
(0xfffe9, 20),
(0x3fffdb, 22),
(0x3fffdc, 22),
(0x7fffe8, 23),
(0x7fffe9, 23),
(0x1fffde, 21),
(0x7fffea, 23),
(0x3fffdd, 22),
(0x3fffde, 22),
(0xfffff0, 24),
(0x1fffdf, 21),
(0x3fffdf, 22),
(0x7fffeb, 23),
(0x7fffec, 23),
(0x1fffe0, 21),
(0x1fffe1, 21),
(0x3fffe0, 22),
(0x1fffe2, 21),
(0x7fffed, 23),
(0x3fffe1, 22),
(0x7fffee, 23),
(0x7fffef, 23),
(0xfffea, 20),
(0x3fffe2, 22),
(0x3fffe3, 22),
(0x3fffe4, 22),
(0x7ffff0, 23),
(0x3fffe5, 22),
(0x3fffe6, 22),
(0x7ffff1, 23),
(0x3ffffe0, 26),
(0x3ffffe1, 26),
(0xfffeb, 20),
(0x7fff1, 19),
(0x3fffe7, 22),
(0x7ffff2, 23),
(0x3fffe8, 22),
(0x1ffffec, 25),
(0x3ffffe2, 26),
(0x3ffffe3, 26),
(0x3ffffe4, 26),
(0x7ffffde, 27),
(0x7ffffdf, 27),
(0x3ffffe5, 26),
(0xfffff1, 24),
(0x1ffffed, 25),
(0x7fff2, 19),
(0x1fffe3, 21),
(0x3ffffe6, 26),
(0x7ffffe0, 27),
(0x7ffffe1, 27),
(0x3ffffe7, 26),
(0x7ffffe2, 27),
(0xfffff2, 24),
(0x1fffe4, 21),
(0x1fffe5, 21),
(0x3ffffe8, 26),
(0x3ffffe9, 26),
(0xffffffd, 28),
(0x7ffffe3, 27),
(0x7ffffe4, 27),
(0x7ffffe5, 27),
(0xfffec, 20),
(0xfffff3, 24),
(0xfffed, 20),
(0x1fffe6, 21),
(0x3fffe9, 22),
(0x1fffe7, 21),
(0x1fffe8, 21),
(0x7ffff3, 23),
(0x3fffea, 22),
(0x3fffeb, 22),
(0x1ffffee, 25),
(0x1ffffef, 25),
(0xfffff4, 24),
(0xfffff5, 24),
(0x3ffffea, 26),
(0x7ffff4, 23),
(0x3ffffeb, 26),
(0x7ffffe6, 27),
(0x3ffffec, 26),
(0x3ffffed, 26),
(0x7ffffe7, 27),
(0x7ffffe8, 27),
(0x7ffffe9, 27),
(0x7ffffea, 27),
(0x7ffffeb, 27),
(0xffffffe, 28),
(0x7ffffec, 27),
(0x7ffffed, 27),
(0x7ffffee, 27),
(0x7ffffef, 27),
(0x7fffff0, 27),
(0x3ffffee, 26),
(0x3fffffff, 30),
];
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use std::vec;
fn hex(s: &str) -> Vec<u8> {
let s: String = s.split_whitespace().collect();
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect()
}
fn fields(f: &[(&str, &str)]) -> Vec<(String, String)> {
f.iter().map(|&(n, v)| (n.into(), v.into())).collect()
}
#[test]
fn each_length_s_codes_are_consecutive() {
let (first, start) = canonical();
assert_eq!(start[31], 257);
for len in 1..31 {
for (k, e) in SORTED[start[len]..start[len + 1]].iter().enumerate() {
assert_eq!(e.0, first[len] + k as u32, "length {len}");
}
}
}
#[test]
fn integers_of_rfc_7541_c_1() {
let mut out = Vec::new();
put_integer(&mut out, 0, 5, 1337);
assert_eq!(out, [0x1f, 0x9a, 0x0a]);
assert_eq!(integer(&mut &out[..], 5), Ok(1337));
assert_eq!(integer(&mut &[0x0a][..], 5), Ok(10));
assert_eq!(integer(&mut &[0x2a][..], 8), Ok(42));
assert!(integer(&mut &[0x1f, 0xff, 0xff, 0xff, 0xff, 0xff][..], 5).is_err());
}
/// C.3 then C.4: three requests on one connection, plain, then Huffman.
#[test]
fn requests_of_rfc_7541_c_3_and_c_4() {
for blocks in [
[
"8286 8441 0f77 7777 2e65 7861 6d70 6c65 2e63 6f6d",
"8286 84be 5808 6e6f 2d63 6163 6865",
"8287 85bf 400a 6375 7374 6f6d 2d6b 6579 0c63 7573 746f 6d2d 7661 6c75 65",
],
[
"8286 8441 8cf1 e3c2 e5f2 3a6b a0ab 90f4 ff",
"8286 84be 5886 a8eb 1064 9cbf",
"8287 85bf 4088 25a8 49e9 5ba9 7d7f 8925 a849 e95b b8e8 b4bf",
],
] {
let mut d = Decoder::new();
let authority = (":authority", "www.example.com");
assert_eq!(
d.decode(&hex(blocks[0])).unwrap(),
fields(&[(":method", "GET"), (":scheme", "http"), (":path", "/"), authority])
);
assert_eq!(d.size, 57);
assert_eq!(
d.decode(&hex(blocks[1])).unwrap(),
fields(&[
(":method", "GET"),
(":scheme", "http"),
(":path", "/"),
authority,
("cache-control", "no-cache")
])
);
assert_eq!(
d.decode(&hex(blocks[2])).unwrap(),
fields(&[
(":method", "GET"),
(":scheme", "https"),
(":path", "/index.html"),
authority,
("custom-key", "custom-value")
])
);
assert_eq!(d.size, 164);
}
}
/// C.6: responses with Huffman coding and a 256-byte table, entries
/// evicted as it fills.
#[test]
fn responses_of_rfc_7541_c_6() {
let mut d = Decoder::new();
d.capacity = 256;
let first = d
.decode(&hex(
"4882 6402 5885 aec3 771a 4b61 96d0 7abe 9410 54d4 44a8 2005 9504 0b81 66e0 82a6
2d1b ff6e 919d 29ad 1718 63c7 8f0b 97c8 e9ae 82ae 43d3",
))
.unwrap();
assert_eq!(
first,
fields(&[
(":status", "302"),
("cache-control", "private"),
("date", "Mon, 21 Oct 2013 20:13:21 GMT"),
("location", "https://www.example.com"),
])
);
assert_eq!(d.size, 222);
let second = d.decode(&hex("4883 640e ff c1 c0 bf")).unwrap();
assert_eq!(second[0], (":status".into(), "307".into()));
assert_eq!(d.size, 222);
let third = d
.decode(&hex(
"88c1 6196 d07a be94 1054 d444 a820 0595 040b 8166 e084 a62d 1bff c05a 839b d9ab
77ad 94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f
9587 3160 65c0 03ed 4ee5 b106 3d50 07",
))
.unwrap();
assert_eq!(
third,
fields(&[
(":status", "200"),
("cache-control", "private"),
("date", "Mon, 21 Oct 2013 20:13:22 GMT"),
("location", "https://www.example.com"),
("content-encoding", "gzip"),
(
"set-cookie",
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"
),
])
);
assert_eq!(d.size, 215);
}
#[test]
fn bad_codes_and_indexes_are_refused() {
// Padding longer than 7 bits, padding not all ones, EOS itself.
assert!(huffman_decode(&[0xff, 0xff]).is_err());
assert!(huffman_decode(&[0x00]).is_err());
assert!(huffman_decode(&[0xff, 0xff, 0xff, 0xff]).is_err());
let mut d = Decoder::new();
assert!(d.decode(&[0x80]).is_err(), "index 0");
assert!(d.decode(&[0xbe]).is_err(), "62 with an empty table");
assert!(d.decode(&[0x3f, 0xe2, 0x1f]).is_err(), "a table past 4096");
assert!(d.decode(&[0x3f, 0xe1, 0x1f]).is_ok(), "4096 itself");
}
#[test]
fn what_it_encodes_it_decodes() {
let sent = [
(":method", "GET"),
(":scheme", "https"),
(":path", "/store/catalog"),
(":authority", "pinnacle-os.eu"),
("user-agent", "Pinnacle"),
("x-thing", "a value"),
];
let block = encode(&sent);
assert_eq!(block[..2], [0x82, 0x87], "GET and https from the static table");
assert_eq!(Decoder::new().decode(&block).unwrap(), fields(&sent));
let long = "x".repeat(300);
let block = encode(&[("x-long", &long)]);
assert_eq!(
Decoder::new().decode(&block).unwrap(),
fields(&[("x-long", &long)])
);
let _ = vec![0u8];
}
}