sec-http3 0.1.2

An async HTTP/3 implementation that supports web transport.
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use bytes::{Buf, BufMut};

use super::{parse_error::ParseError, prefix_int, prefix_string};

// 4.5. Field Line Representations
// Single header field line. These representations reference the static table or
// the dynamic table in a particular state, but do not modify that state.
pub enum HeaderBlockField {
    // 4.5.2. Indexed Field Line
    // Entry in the static table, or in the dynamic table with an absolute index
    // less than the value of the Base.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 1 | T |      Index (6+)       |
    // +---+---+-----------------------+
    Indexed,
    // 4.5.3. Indexed Field Line With Post-Base Index
    // Entry in the dynamic table with an absolute index greater than or equal
    // to the value of the Base.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 0 | 0 | 1 |  Index (4+)   |
    // +---+---+---+---+---------------+
    IndexedWithPostBase,
    // 4.5.4. Literal Field Line With Name Reference
    // Entry in the dynamic table with an absolute index greater than or equal
    // to the value of the Base.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 1 | N | T |Name Index (4+)|
    // +---+---+---+---+---------------+
    // | H |     Value Length (7+)     |
    // +---+---------------------------+
    // |  Value String (Length bytes)  |
    // +-------------------------------+
    LiteralWithNameRef,
    // 4.5.5. Literal Field Line With Post-Base Name Reference
    // The field name matches a name of an entry in the static table, or in the
    // dynamic table with an absolute index less than the value of the Base.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 0 | 0 | 0 | N |NameIdx(3+)|
    // +---+---+---+---+---+-----------+
    // | H |     Value Length (7+)     |
    // +---+---------------------------+
    // |  Value String (Length bytes)  |
    // +-------------------------------+
    LiteralWithPostBaseNameRef,
    // 4.5.6. Literal Field Line With Literal Name
    // Field name and field value are encoded as string literals.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 0 | 1 | N | H |NameLen(3+)|
    // +---+---+---+---+---+-----------+
    // |  Name String (Length bytes)   |
    // +---+---------------------------+
    // | H |     Value Length (7+)     |
    // +---+---------------------------+
    // |  Value String (Length bytes)  |
    // +-------------------------------+
    Literal,
    Unknown,
}

impl HeaderBlockField {
    // Check how the next field is encoded according its first byte
    pub fn decode(first: u8) -> Self {
        if first & 0b1000_0000 != 0 {
            HeaderBlockField::Indexed
        } else if first & 0b1111_0000 == 0b0001_0000 {
            HeaderBlockField::IndexedWithPostBase
        } else if first & 0b1100_0000 == 0b0100_0000 {
            HeaderBlockField::LiteralWithNameRef
        } else if first & 0b1111_0000 == 0 {
            HeaderBlockField::LiteralWithPostBaseNameRef
        } else if first & 0b1110_0000 == 0b0010_0000 {
            HeaderBlockField::Literal
        } else {
            HeaderBlockField::Unknown
        }
    }
}

// 4.5.1. Encoded Field Section Prefix
#[derive(Debug, PartialEq)]
pub struct HeaderPrefix {
    encoded_insert_count: usize,
    sign_negative: bool,
    delta_base: usize,
}

impl HeaderPrefix {
    pub fn new(required: usize, base: usize, total_inserted: usize, max_table_size: usize) -> Self {
        if max_table_size == 0 {
            return Self {
                encoded_insert_count: 0,
                sign_negative: false,
                delta_base: 0,
            };
        }

        if required == 0 {
            return Self {
                encoded_insert_count: 0,
                delta_base: 0,
                sign_negative: false,
            };
        }

        assert!(required <= total_inserted);
        let (sign_negative, delta_base) = if required > base {
            (true, required - base - 1)
        } else {
            (false, base - required)
        };

        let max_entries = max_table_size / 32;

        Self {
            encoded_insert_count: required % (2 * max_entries) + 1,
            sign_negative,
            delta_base,
        }
    }

    pub fn get(
        self,
        total_inserted: usize,
        max_table_size: usize,
    ) -> Result<(usize, usize), ParseError> {
        if max_table_size == 0 {
            return Ok((0, 0));
        }

        // 4.5.1.1. Required Insert Count
        let required = if self.encoded_insert_count == 0 {
            0
        } else {
            let mut insert_count = self.encoded_insert_count - 1;
            let max_entries = max_table_size / 32;
            let mut wrapped = total_inserted % (2 * max_entries);

            if wrapped >= insert_count + max_entries {
                insert_count += 2 * max_entries;
            } else if wrapped + max_entries < insert_count {
                wrapped += 2 * max_entries;
            }

            insert_count + total_inserted - wrapped
        };

        let base = if required == 0 {
            0
        } else if !self.sign_negative {
            required + self.delta_base
        } else {
            if self.delta_base + 1 > required {
                return Err(ParseError::InvalidBase(
                    required as isize - self.delta_base as isize - 1,
                ));
            }
            required - self.delta_base - 1
        };

        Ok((required, base))
    }

    // 4.5.1. Encoded Field Section Prefix
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // |   Required Insert Count (8+)  |
    // +---+---------------------------+
    // | S |      Delta Base (7+)      |
    // +---+---------------------------+
    // |      Encoded Field Lines    ...
    // +-------------------------------+
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Self, ParseError> {
        let (_, encoded_insert_count) = prefix_int::decode(8, buf)?;
        let (sign_negative, delta_base) = prefix_int::decode(7, buf)?;
        Ok(Self {
            encoded_insert_count,
            delta_base,
            sign_negative: sign_negative == 1,
        })
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        let sign_bit = if self.sign_negative { 1 } else { 0 };
        prefix_int::encode(8, 0, self.encoded_insert_count, buf);
        prefix_int::encode(7, sign_bit, self.delta_base, buf);
    }
}

#[derive(Debug, PartialEq)]
pub enum Indexed {
    Static(usize),
    Dynamic(usize),
}

impl Indexed {
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Self, ParseError> {
        match prefix_int::decode(6, buf)? {
            (0b11, i) => Ok(Indexed::Static(i)),
            (0b10, i) => Ok(Indexed::Dynamic(i)),
            (f, _) => Err(ParseError::InvalidPrefix(f)),
        }
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        match self {
            Indexed::Static(i) => prefix_int::encode(6, 0b11, *i, buf),
            Indexed::Dynamic(i) => prefix_int::encode(6, 0b10, *i, buf),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct IndexedWithPostBase(pub usize);

impl IndexedWithPostBase {
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Self, ParseError> {
        match prefix_int::decode(4, buf)? {
            (0b0001, i) => Ok(IndexedWithPostBase(i)),
            (f, _) => Err(ParseError::InvalidPrefix(f)),
        }
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        prefix_int::encode(4, 0b0001, self.0, buf)
    }
}

#[derive(Debug, PartialEq)]
pub enum LiteralWithNameRef {
    Static { index: usize, value: Vec<u8> },
    Dynamic { index: usize, value: Vec<u8> },
}

impl LiteralWithNameRef {
    pub fn new_static<T: Into<Vec<u8>>>(index: usize, value: T) -> Self {
        LiteralWithNameRef::Static {
            index,
            value: value.into(),
        }
    }

    pub fn new_dynamic<T: Into<Vec<u8>>>(index: usize, value: T) -> Self {
        LiteralWithNameRef::Dynamic {
            index,
            value: value.into(),
        }
    }

    pub fn decode<R: Buf>(buf: &mut R) -> Result<Self, ParseError> {
        match prefix_int::decode(4, buf)? {
            (f, i) if f & 0b0101 == 0b0101 => Ok(LiteralWithNameRef::new_static(
                i,
                prefix_string::decode(8, buf)?,
            )),
            (f, i) if f & 0b0101 == 0b0100 => Ok(LiteralWithNameRef::new_dynamic(
                i,
                prefix_string::decode(8, buf)?,
            )),
            (f, _) => Err(ParseError::InvalidPrefix(f)),
        }
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) -> Result<(), prefix_string::Error> {
        match self {
            LiteralWithNameRef::Static { index, value } => {
                prefix_int::encode(4, 0b0101, *index, buf);
                prefix_string::encode(8, 0, value, buf)?;
            }
            LiteralWithNameRef::Dynamic { index, value } => {
                prefix_int::encode(4, 0b0100, *index, buf);
                prefix_string::encode(8, 0, value, buf)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, PartialEq)]
pub struct LiteralWithPostBaseNameRef {
    pub index: usize,
    pub value: Vec<u8>,
}

impl LiteralWithPostBaseNameRef {
    pub fn new<T: Into<Vec<u8>>>(index: usize, value: T) -> Self {
        LiteralWithPostBaseNameRef {
            index,
            value: value.into(),
        }
    }

    pub fn decode<R: Buf>(buf: &mut R) -> Result<Self, ParseError> {
        match prefix_int::decode(3, buf)? {
            (f, i) if f & 0b1111_0000 == 0 => Ok(LiteralWithPostBaseNameRef::new(
                i,
                prefix_string::decode(8, buf)?,
            )),
            (f, _) => Err(ParseError::InvalidPrefix(f)),
        }
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) -> Result<(), prefix_string::Error> {
        prefix_int::encode(3, 0b0000, self.index, buf);
        prefix_string::encode(8, 0, &self.value, buf)?;
        Ok(())
    }
}

#[derive(Debug, PartialEq)]
pub struct Literal {
    pub name: Vec<u8>,
    pub value: Vec<u8>,
}

impl Literal {
    pub fn new<T: Into<Vec<u8>>>(name: T, value: T) -> Self {
        Literal {
            name: name.into(),
            value: value.into(),
        }
    }

    pub fn decode<R: Buf>(buf: &mut R) -> Result<Self, ParseError> {
        if buf.remaining() < 1 {
            return Err(ParseError::Integer(prefix_int::Error::UnexpectedEnd));
        } else if buf.chunk()[0] & 0b1110_0000 != 0b0010_0000 {
            return Err(ParseError::InvalidPrefix(buf.chunk()[0]));
        }
        Ok(Literal::new(
            prefix_string::decode(4, buf)?,
            prefix_string::decode(8, buf)?,
        ))
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) -> Result<(), prefix_string::Error> {
        prefix_string::encode(4, 0b0010, &self.name, buf)?;
        prefix_string::encode(8, 0, &self.value, buf)?;
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Cursor;

    const TABLE_SIZE: usize = 4096;

    #[test]
    fn indexed_static() {
        let field = Indexed::Static(42);
        let mut buf = vec![];
        field.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(Indexed::decode(&mut read), Ok(field));
    }

    #[test]
    fn indexed_dynamic() {
        let field = Indexed::Dynamic(42);
        let mut buf = vec![];
        field.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(Indexed::decode(&mut read), Ok(field));
    }

    #[test]
    fn indexed_with_postbase() {
        let field = IndexedWithPostBase(42);
        let mut buf = vec![];
        field.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(IndexedWithPostBase::decode(&mut read), Ok(field));
    }

    #[test]
    fn literal_with_name_ref() {
        let field = LiteralWithNameRef::new_static(42, "foo");
        let mut buf = vec![];
        field.encode(&mut buf).unwrap();
        let mut read = Cursor::new(&buf);
        assert_eq!(LiteralWithNameRef::decode(&mut read), Ok(field));
    }

    #[test]
    fn literal_with_post_base_name_ref() {
        let field = LiteralWithPostBaseNameRef::new(42, "foo");
        let mut buf = vec![];
        field.encode(&mut buf).unwrap();
        let mut read = Cursor::new(&buf);
        assert_eq!(LiteralWithPostBaseNameRef::decode(&mut read), Ok(field));
    }

    #[test]
    fn literal() {
        let field = Literal::new("foo", "bar");
        let mut buf = vec![];
        field.encode(&mut buf).unwrap();
        let mut read = Cursor::new(&buf);
        assert_eq!(Literal::decode(&mut read), Ok(field));
    }

    #[test]
    fn header_prefix() {
        let prefix = HeaderPrefix::new(10, 5, 12, TABLE_SIZE);
        let mut buf = vec![];
        prefix.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        let decoded = HeaderPrefix::decode(&mut read);
        assert_eq!(decoded, Ok(prefix));
        assert_eq!(decoded.unwrap().get(13, 3332).unwrap(), (10, 5));
    }

    #[test]
    fn header_prefix_table_size_0() {
        HeaderPrefix::new(10, 5, 12, 0).get(1, 0).unwrap();
    }

    #[test]
    fn base_index_too_small() {
        let mut buf = vec![];
        let encoded_largest_ref = (2 % (2 * TABLE_SIZE / 32)) + 1;
        prefix_int::encode(8, 0, encoded_largest_ref, &mut buf);
        prefix_int::encode(7, 1, 2, &mut buf); // base index negative = 0

        let mut read = Cursor::new(&buf);
        assert_eq!(
            HeaderPrefix::decode(&mut read).unwrap().get(2, TABLE_SIZE),
            Err(ParseError::InvalidBase(-1))
        );
    }
}