1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use std::collections::HashMap;
use crate::error::Error;
use crate::huffman;
enum Representation {
/// Indexed header field representation
///
/// An indexed header field representation identifies an entry in either the
/// static table or the dynamic table (see Section 2.3).
///
/// # Header encoding
///
/// ```text
/// 0 1 2 3 4 5 6 7
/// +---+---+---+---+---+---+---+---+
/// | 1 | Index (7+) |
/// +---+---------------------------+
/// ```
Indexed,
/// Literal Header Field with Incremental Indexing
///
/// A literal header field with incremental indexing representation results
/// in appending a header field to the decoded header list and inserting it
/// as a new entry into the dynamic table.
///
/// # Header encoding
///
/// ```text
/// 0 1 2 3 4 5 6 7
/// +---+---+---+---+---+---+---+---+
/// | 0 | 1 | Index (6+) |
/// +---+---+-----------------------+
/// | H | Value Length (7+) |
/// +---+---------------------------+
/// | Value String (Length octets) |
/// +-------------------------------+
/// ```
LiteralWithIndexing,
/// Literal Header Field without Indexing
///
/// A literal header field without indexing representation results in
/// appending a header field to the decoded header list without altering the
/// dynamic table.
///
/// # Header encoding
///
/// ```text
/// 0 1 2 3 4 5 6 7
/// +---+---+---+---+---+---+---+---+
/// | 0 | 0 | 0 | 0 | Index (4+) |
/// +---+---+-----------------------+
/// | H | Value Length (7+) |
/// +---+---------------------------+
/// | Value String (Length octets) |
/// +-------------------------------+
/// ```
LiteralWithoutIndexing,
/// Literal Header Field Never Indexed
///
/// A literal header field never-indexed representation results in appending
/// a header field to the decoded header list without altering the dynamic
/// table. Intermediaries MUST use the same representation for encoding this
/// header field.
///
/// ```text
/// 0 1 2 3 4 5 6 7
/// +---+---+---+---+---+---+---+---+
/// | 0 | 0 | 0 | 1 | Index (4+) |
/// +---+---+-----------------------+
/// | H | Value Length (7+) |
/// +---+---------------------------+
/// | Value String (Length octets) |
/// +-------------------------------+
/// ```
LiteralNeverIndexed,
/// Dynamic Table Size Update
///
/// A dynamic table size update signals a change to the size of the dynamic
/// table.
///
/// # Header encoding
///
/// ```text
/// 0 1 2 3 4 5 6 7
/// +---+---+---+---+---+---+---+---+
/// | 0 | 0 | 1 | Max size (5+) |
/// +---+---------------------------+
/// ```
SizeUpdate,
}
impl Representation {
fn load(byte: u8) -> Result<Representation, Error> {
const INDEXED: u8 = 0b1000_0000;
const LITERAL_WITH_INDEXING: u8 = 0b0100_0000;
const LITERAL_WITHOUT_INDEXING: u8 = 0b1111_0000;
const LITERAL_NEVER_INDEXED: u8 = 0b0001_0000;
const SIZE_UPDATE_MASK: u8 = 0b1110_0000;
const SIZE_UPDATE: u8 = 0b0010_0000;
// TODO: What did I even write here?
if byte & INDEXED == INDEXED {
Ok(Representation::Indexed)
} else if byte & LITERAL_WITH_INDEXING == LITERAL_WITH_INDEXING {
Ok(Representation::LiteralWithIndexing)
} else if byte & LITERAL_WITHOUT_INDEXING == 0 {
Ok(Representation::LiteralWithoutIndexing)
} else if byte & LITERAL_WITHOUT_INDEXING == LITERAL_NEVER_INDEXED {
Ok(Representation::LiteralNeverIndexed)
} else if byte & SIZE_UPDATE_MASK == SIZE_UPDATE {
Ok(Representation::SizeUpdate)
} else {
Err(Error::InvalidHpack("invalid Representation"))
}
}
}
pub enum PathKind {
Cached(usize),
Plain(Vec<u8>),
}
pub struct Decoder {
next_cache_index: usize,
dynamic_table: Vec<Option<usize>>,
huffman_paths: HashMap<Vec<u8>, usize>,
plain_paths: HashMap<Vec<u8>, usize>,
}
impl Decoder {
/// Creates a new `Decoder` with all settings set to default values.
pub fn new() -> Self {
Decoder {
next_cache_index: 0,
dynamic_table: Vec::new(),
huffman_paths: HashMap::new(),
plain_paths: HashMap::new(),
}
}
pub fn find_path(&mut self, mut buf: &[u8]) -> Result<PathKind, Error> {
use self::Representation::*;
let mut find_path = Err(Error::NoPathSet);
while !buf.is_empty() {
// At this point we are always at the beginning of the next block
// within the HPACK data. The type of the block can always be
// determined from the first byte.
let adv = match Representation::load(buf[0])? {
Indexed => {
let (index, adv) = decode_int(buf, 7)?;
if index > 61 {
let table_len = self.dynamic_table.len();
if index > 61 + table_len {
return Err(Error::InvalidHpack("invalid dynamic table index"));
}
let index = 61 + table_len - index;
if let Some(cached) = &self.dynamic_table[index] {
find_path = Ok(PathKind::Cached(*cached));
}
}
adv
}
LiteralWithIndexing => {
let (path, adv) = decode_literal_path(buf, true)?;
let opt_index = match path {
Some(path) => {
let path_buf = match path {
OutStr::Plain(path) => path.to_vec(),
OutStr::Huffman(huff_path) => {
let mut path_buf = Vec::with_capacity(32);
huffman::decode(huff_path, &mut path_buf)?;
path_buf
}
};
find_path = Ok(PathKind::Plain(path_buf));
// the caller level should update the index too
self.next_cache_index += 1;
Some(self.next_cache_index - 1)
}
None => None,
};
self.dynamic_table.push(opt_index);
adv
}
LiteralWithoutIndexing | LiteralNeverIndexed => {
let (path, adv) = decode_literal_path(buf, false)?;
if let Some(path) = path {
find_path = Ok(match path {
OutStr::Plain(path) => match self.plain_paths.get(path) {
Some(cached) => PathKind::Cached(*cached),
None => {
let cached = self.next_cache_index;
self.next_cache_index += 1;
self.plain_paths.insert(path.to_vec(), cached);
PathKind::Plain(path.to_vec())
}
},
OutStr::Huffman(huff_path) => match self.huffman_paths.get(huff_path) {
Some(cached) => PathKind::Cached(*cached),
None => {
let cached = self.next_cache_index;
self.next_cache_index += 1;
self.huffman_paths.insert(huff_path.to_vec(), cached);
let mut plain = Vec::with_capacity(32);
huffman::decode(huff_path, &mut plain)?;
PathKind::Plain(plain)
}
},
});
}
adv
}
SizeUpdate => {
let (_, adv) = decode_int(buf, 7)?;
adv
}
};
buf = &buf[adv..];
}
find_path
}
}
enum OutStr<'a> {
Plain(&'a [u8]),
Huffman(&'a [u8]),
}
impl<'a> OutStr<'a> {
fn eq_str(&self, s: &str) -> bool {
match self {
Self::Plain(out) => *out == s.as_bytes(),
Self::Huffman(out) => {
if out.len() > s.len() {
return false;
}
let mut huffbuf = Vec::with_capacity(s.len());
huffman::encode(s.as_bytes(), &mut huffbuf);
out == &huffbuf
}
}
}
}
fn decode_literal_path<'a>(
mut buf: &'a [u8],
index: bool,
) -> Result<(Option<OutStr<'a>>, usize), Error> {
let prefix = if index { 6 } else { 4 };
// Extract the table index for the name, or 0 if not indexed
let (table_idx, index_adv) = decode_int(buf, prefix)?;
buf = &buf[index_adv..];
if table_idx == 0 {
// parse name and value
let (name_str, name_adv) = decode_string(buf)?;
let (value_str, value_adv) = decode_string(&buf[name_adv..])?;
let adv = index_adv + name_adv + value_adv;
if name_str.eq_str(":path") {
Ok((Some(value_str), adv))
} else {
Ok((None, adv))
}
} else {
// name is indexed, so parse value only
let (value_str, value_adv) = decode_string(buf)?;
let adv = index_adv + value_adv;
if table_idx == 4 || table_idx == 5 {
Ok((Some(value_str), adv))
} else {
Ok((None, adv))
}
}
}
fn decode_string<'a>(buf: &'a [u8]) -> Result<(OutStr<'a>, usize), Error> {
if buf.is_empty() {
return Err(Error::InvalidHpack("need more"));
}
const HUFF_FLAG: u8 = 0b1000_0000;
let huff = (buf[0] & HUFF_FLAG) == HUFF_FLAG;
// Decode the string length using 7 bit prefix
let (len, adv) = decode_int(buf, 7)?;
if len > buf.len() - adv {
return Err(Error::InvalidHpack("need more"));
}
let end = adv + len;
let msg = &buf[adv..end];
if huff {
Ok((OutStr::Huffman(msg), end))
} else {
Ok((OutStr::Plain(msg), end))
}
}
fn decode_int(buf: &[u8], prefix_size: u8) -> Result<(usize, usize), Error> {
// The octet limit is chosen such that the maximum allowed *value* can
// never overflow an unsigned 32-bit integer. The maximum value of any
// integer that can be encoded with 5 octets is ~2^28
const MAX_BYTES: usize = 5;
const VARINT_MASK: u8 = 0b0111_1111;
const VARINT_FLAG: u8 = 0b1000_0000;
if prefix_size < 1 || prefix_size > 8 {
return Err(Error::InvalidHpack("invalid integer"));
}
if buf.is_empty() {
return Err(Error::InvalidHpack("need more"));
}
let mask = if prefix_size == 8 {
0xFF
} else {
(1u8 << prefix_size).wrapping_sub(1)
};
let mut ret = (buf[0] & mask) as usize;
if ret < mask as usize {
// Value fits in the prefix bits
return Ok((ret, 1));
}
// The int did not fit in the prefix bits, so continue reading.
//
// The total number of bytes used to represent the int. The first byte was
// the prefix, so start at 1.
let mut bytes = 1;
// The rest of the int is stored as a varint -- 7 bits for the value and 1
// bit to indicate if it is the last byte.
let mut shift = 0;
while !buf.is_empty() {
let b = buf[bytes];
bytes += 1;
ret += ((b & VARINT_MASK) as usize) << shift;
shift += 7;
if b & VARINT_FLAG == 0 {
return Ok((ret, bytes));
}
if bytes == MAX_BYTES {
// The spec requires that this situation is an error
return Err(Error::InvalidHpack("integer overflow"));
}
}
Err(Error::InvalidHpack("need more"))
}