beeper 0.1.0

Application-Layer Parsing in eBPF
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
use std::{net::SocketAddr, time::Duration};

use ::h2::{RecvStream, client};
use beeper::{h1, h2};
use bytes::Bytes;
use httlib_huffman as huffman;
use http::{HeaderName, HeaderValue, Request, Response, header};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    net::TcpStream,
};
use utils::{
    server,
    test::{Direction, TestProgram},
};
use xbpf::OpenObject;

const TEST_HEADER: HeaderName = HeaderName::from_static("testheader");
const METHOD_HEADER: HeaderName = HeaderName::from_static("method");
const AUTHORITY_HEADER: HeaderName = HeaderName::from_static("authority");
const PATH_HEADER: HeaderName = HeaderName::from_static("path");

fn huffman_decode(val: &[u8]) -> String {
    let mut res = Vec::new();
    huffman::decode(val, &mut res, huffman::DecoderSpeed::OneBit).unwrap();
    String::from_utf8(res).unwrap()
}

fn dynamic_table_size_for_headers(headers: &[(HeaderName, HeaderValue)]) -> u32 {
    headers.iter().fold(0, |acc, (k, v)| {
        acc + (k.as_str().len() + v.len() + 32) as u32
    })
}

fn assert_match_eq(prog: &TestProgram, idx: usize, expected: Option<&HeaderValue>) {
    let actual_hf = prog.get_match(idx).expect("get_match");
    let actual = actual_hf.map(|val| huffman_decode(&val));

    if expected.is_none() {
        assert!(
            actual.is_none(),
            "get_match({idx}): {}, expected: none",
            actual.unwrap()
        );
    } else {
        let expected = expected.unwrap().to_str().unwrap();
        assert!(
            actual.is_some(),
            "get_match({idx}): none, expected: {expected}"
        );
        assert_eq!(actual.unwrap().as_str(), expected);
    }
}

struct Client {
    send_request: client::SendRequest<Bytes>,
    local_addr: SocketAddr,
    remote_addr: SocketAddr,
}

impl Client {
    async fn connect(addr: SocketAddr, header_table_size: Option<u32>) -> Self {
        let stream = TcpStream::connect(addr).await.expect("connect");
        let local_addr = stream.local_addr().expect("local_addr");
        let remote_addr = stream.peer_addr().expect("peer_addr");

        let mut builder = client::Builder::new();
        if let Some(size) = header_table_size {
            builder.header_table_size(size);
        }

        let (send_request, connection) = builder
            .handshake::<_, Bytes>(stream)
            .await
            .expect("handshake");

        tokio::spawn(async move {
            connection.await.expect("connection");
        });

        Self {
            send_request,
            local_addr,
            remote_addr,
        }
    }

    #[allow(unused_results)]
    async fn get(
        &self,
        uri: String,
        headers: &[(header::HeaderName, HeaderValue)],
    ) -> Response<RecvStream> {
        let mut req = Request::builder().method("GET").uri(uri);
        for (name, value) in headers {
            req = req.header(name, value);
        }
        let request = req.body(()).expect("build request");

        let mut send_request = self.send_request.clone().ready().await.expect("ready");
        let (response, _) = send_request
            .send_request(request, true)
            .expect("send_request");
        let response = response.await.expect("response");

        assert!(response.status().is_success());

        response
    }
}

/// The HTTP/2 connection preface, see section 3.5 of RFC 7540.
const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";

/// The first index of the dynamic table, the static one taking up everything
/// below it.
const FIRST_DYNAMIC_INDEX: u8 = 62;

/// Renders an HTTP/2 frame.
fn frame(kind: u8, flags: u8, stream: u32, payload: &[u8]) -> Vec<u8> {
    let mut f = Vec::new();
    f.extend_from_slice(&(payload.len() as u32).to_be_bytes()[1..]);
    f.push(kind);
    f.push(flags);
    f.extend_from_slice(&stream.to_be_bytes());
    f.extend_from_slice(payload);
    f
}

/// Renders an HPACK string, spelled out rather than Huffman coded. Only short
/// strings are handled, which is all these tests send.
fn raw_str(s: &str) -> Vec<u8> {
    assert!(s.len() < 127, "raw_str only encodes a one byte length");

    let mut out = vec![s.len() as u8];
    out.extend_from_slice(s.as_bytes());

    out
}

/// A client that writes its own HPACK, which is the only way to send a header
/// that is not Huffman coded: `h2`'s encoder always codes. Real clients do send
/// them, curl among them.
struct RawClient {
    stream: TcpStream,
    local_addr: SocketAddr,
    remote_addr: SocketAddr,
    next_stream_id: u32,
}

impl RawClient {
    /// Connects and completes the handshake.
    async fn connect(addr: SocketAddr) -> Self {
        let mut stream = TcpStream::connect(addr).await.expect("connect");
        let local_addr = stream.local_addr().expect("local_addr");
        let remote_addr = stream.peer_addr().expect("peer_addr");

        stream.write_all(PREFACE).await.expect("preface");
        // empty, so every parameter keeps its default
        stream
            .write_all(&frame(0x04, 0, 0, &[]))
            .await
            .expect("settings");
        stream.flush().await.expect("flush");

        let mut client = Self {
            stream,
            local_addr,
            remote_addr,
            next_stream_id: 1,
        };

        client.read_frame(0x04).await;
        client
            .stream
            .write_all(&frame(0x04, 0x01, 0, &[]))
            .await
            .expect("settings ack");
        client.stream.flush().await.expect("flush");

        client
    }

    /// Reads frames until one of type `kind` arrives, and returns its payload.
    async fn read_frame(&mut self, kind: u8) -> Vec<u8> {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);

        loop {
            let mut head = [0; 9];
            tokio::time::timeout_at(deadline, self.stream.read_exact(&mut head))
                .await
                .expect("timed out waiting for a frame")
                .expect("read frame header");

            let len = u32::from_be_bytes([0, head[0], head[1], head[2]]) as usize;
            let mut payload = vec![0; len];
            tokio::time::timeout_at(deadline, self.stream.read_exact(&mut payload))
                .await
                .expect("timed out reading a frame")
                .expect("read frame payload");

            if head[3] == kind {
                return payload;
            }
        }
    }

    /// Sends a request carrying `block` and waits for its response, so that the
    /// parser has seen it by the time this returns.
    async fn request(&mut self, block: Vec<u8>) {
        let id = self.next_stream_id;
        self.next_stream_id += 2;

        // END_STREAM | END_HEADERS
        self.stream
            .write_all(&frame(0x01, 0x05, id, &block))
            .await
            .expect("request");
        self.stream.flush().await.expect("flush");

        self.read_frame(0x01).await;
    }

    /// Writes `bytes` as they are, without expecting an answer.
    ///
    /// A malformed frame is answered with a GOAWAY at best, so there is nothing
    /// to wait for, and nothing is read back: a read of whatever happens to
    /// have arrived can stop in the middle of a frame and leave the stream out
    /// of step for the next one. The parser runs on the way out of `write_all`,
    /// which is what makes that safe -- an `sk_msg` program runs as part of the
    /// send, so it has seen these bytes by the time this returns.
    async fn send_raw(&mut self, bytes: &[u8]) {
        self.stream.write_all(bytes).await.expect("write");
        self.stream.flush().await.expect("flush");
    }
}

fn attach_preface_parser(prog_fd: i32) -> h1::AttachedParser {
    h1::Parser::new()
        .match_h2_preface()
        .replace_parse_msg("parse_h1")
        .replace_matched("matched_h1")
        .replace_extract("extract_h1_match")
        .attach(prog_fd)
        .expect("attach parser")
}

fn attach_h2_parser(prog_fd: i32, hdrs: &[HeaderName]) -> h2::AttachedParser {
    let mut h2 = h2::Parser::new();
    for hdr in hdrs {
        h2 = h2.capture_hdr(hdr).expect(&format!("capture {:?}", hdr));
    }

    h2.replace_parse_msg("parse_h2")
        .replace_extract("extract_h2_match")
        .attach(prog_fd)
        .expect("attach parser")
}

#[tokio::test]
async fn parse_header_field_indexed_in_static_table() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog = TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[METHOD_HEADER]);

    let client = Client::connect(addr, None).await;
    client.get(format!("http://{}", addr), &[]).await;

    let method_val = HeaderValue::from_static("GET");
    assert_match_eq(&prog, 0, Some(&method_val));
}

#[tokio::test]
async fn parse_header_field_no_indexing_name_indexed_in_static_table() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[header::AUTHORIZATION]);

    let auth_val = HeaderValue::from_static("Basic YmVlbGluZTpiZWVsaW5l"); // beeper:beeper in base64

    let client = Client::connect(addr, None).await;
    client
        .get(
            format!("http://{}", addr),
            &[(header::AUTHORIZATION, auth_val.clone())],
        )
        .await;

    assert_match_eq(&prog, 0, Some(&auth_val));
}

#[tokio::test]
async fn parse_header_field_never_indexing_name_indexed_in_static_table() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[TEST_HEADER]);

    let mut test_header_val = HeaderValue::from_static("my secret");
    test_header_val.set_sensitive(true);

    let client = Client::connect(addr, None).await;
    client
        .get(
            format!("http://{}", addr),
            &[(TEST_HEADER, test_header_val.clone())],
        )
        .await;

    assert_match_eq(&prog, 0, Some(&test_header_val));
}

#[tokio::test]
async fn parse_header_field_never_indexing_new_name() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[TEST_HEADER]);

    let mut test_header_val = HeaderValue::from_static("my secret");
    test_header_val.set_sensitive(true);

    let client = Client::connect(addr, None).await;
    client
        .get(
            format!("http://{}", addr),
            &[(TEST_HEADER, test_header_val.clone())],
        )
        .await;

    assert_match_eq(&prog, 0, Some(&test_header_val));
}

#[tokio::test]
async fn parse_header_field_incremental_indexing_name_indexed_in_static_table() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[header::USER_AGENT, PATH_HEADER]);

    let user_agent_val = HeaderValue::from_static("beeper");
    let path = "/bee/1234";
    let path_val = HeaderValue::from_static(path);

    let client = Client::connect(addr, None).await;
    client
        .get(
            format!("http://{}{}", addr, path),
            &[(header::USER_AGENT, user_agent_val.clone())],
        )
        .await;
    assert_match_eq(&prog, 0, Some(&user_agent_val));
    assert_match_eq(&prog, 1, Some(&path_val));
}

// #[tokio::test]
// async fn parse_header_field_incremental_indexing_name_indexed_in_dynamic_table() {
//     todo!();
// }

#[tokio::test]
async fn parse_header_field_incremental_indexing_new_name() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[TEST_HEADER, PATH_HEADER]);

    let test_header_val = HeaderValue::from_static("beeper");
    let path = "/bee/1234";
    let path_val = HeaderValue::from_static(&path);

    let client = Client::connect(addr, None).await;
    client
        .get(
            format!("http://{}{}", addr, path),
            &[(TEST_HEADER, test_header_val.clone())],
        )
        .await;
    assert_match_eq(&prog, 0, Some(&test_header_val));
    assert_match_eq(&prog, 1, Some(&path_val));
}

#[tokio::test]
async fn parse_header_field_incremental_indexing_indexed_in_dynamic_table() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(
        prog.prog_fd(),
        &[header::USER_AGENT, header::ACCEPT_LANGUAGE],
    );

    let user_agent_val = HeaderValue::from_static("beeper");
    let lang_val = HeaderValue::from_static("sumsum");

    let client = Client::connect(addr, None).await;
    client
        .get(
            format!("http://{}", addr),
            &[
                (header::USER_AGENT, user_agent_val.clone()),
                (header::ACCEPT_LANGUAGE, lang_val.clone()),
            ],
        )
        .await;
    assert_match_eq(&prog, 0, Some(&user_agent_val));
    assert_match_eq(&prog, 1, Some(&lang_val));

    // repeat the request with other headers
    // this will check if it indexes the dynamic table correctly
    client
        .get(
            format!("http://{}", addr),
            &[(header::VIA, HeaderValue::from_static("the hive"))],
        )
        .await;
    assert_match_eq(&prog, 0, None);
    assert_match_eq(&prog, 1, None);

    // we repeat this request to check if the header has been added to the dynamic table
    client
        .get(
            format!("http://{}", addr),
            &[
                (header::ACCEPT_LANGUAGE, lang_val.clone()),
                (header::USER_AGENT, user_agent_val.clone()),
            ],
        )
        .await;
    assert_match_eq(&prog, 0, Some(&user_agent_val));
    assert_match_eq(&prog, 1, Some(&lang_val));
}

/// Builds the header block of a request whose fields are spelled out rather
/// than Huffman coded.
///
/// The only entries it adds to the dynamic table are the ones in `indexed`,
/// whose name is either taken from the static table or, for `None`, spelled
/// out.
fn raw_request_block(authority: &str, indexed: &[(Option<u8>, &str, &str)]) -> Vec<u8> {
    // :method: GET, :scheme: http and :path: /
    let mut block = vec![0x82, 0x86, 0x84];

    // :authority, without indexing so that it stays out of the dynamic table
    block.push(0x01);
    block.extend_from_slice(&raw_str(authority));

    for (name_idx, name, value) in indexed {
        match name_idx {
            Some(idx) => block.push(0x40 | idx),
            None => {
                block.push(0x40);
                block.extend_from_slice(&raw_str(name));
            }
        }
        block.extend_from_slice(&raw_str(value));
    }

    block
}

#[tokio::test]
async fn parse_header_field_incremental_indexing_not_huffman_encoded() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let h2 = attach_h2_parser(prog.prog_fd(), &[header::ACCEPT]);

    let accept_val = HeaderValue::from_static("*/*");
    let test_header_val = HeaderValue::from_static("in-the-hive");

    // the first spells its name out too, which the DFA cannot match, as it is
    // built from Huffman coded names. both are still added to the table.
    let mut client = RawClient::connect(addr).await;
    client
        .request(raw_request_block(
            &addr.to_string(),
            &[
                (None, TEST_HEADER.as_str(), "in-the-hive"),
                (Some(19), "accept", "*/*"),
            ],
        ))
        .await;

    assert_eq!(
        prog.get_match(0).expect("get_match").as_deref(),
        Some(accept_val.as_bytes()),
        "a value that was not Huffman coded did not come back as it was sent"
    );

    // an entry is sized by its name and value as text, whichever form they were
    // sent in
    let expected_dt = &[
        (TEST_HEADER, test_header_val.clone()),
        (header::ACCEPT, accept_val.clone()),
    ];
    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");

    assert_eq!(info.count, expected_dt.len() as u32);
    assert_eq!(info.size, dynamic_table_size_for_headers(expected_dt));
    assert_eq!(info.max_size, 4096);
}

#[tokio::test]
async fn resolve_index_of_entry_that_was_not_huffman_encoded() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[header::ACCEPT]);

    let accept_val = HeaderValue::from_static("*/*");

    let mut client = RawClient::connect(addr).await;
    client
        .request(raw_request_block(
            &addr.to_string(),
            &[(Some(19), "accept", "*/*")],
        ))
        .await;
    assert_eq!(
        prog.get_match(0).expect("get_match").as_deref(),
        Some(accept_val.as_bytes())
    );

    // the entry is now the most recent one, so a second request can refer to it
    // by index alone
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&addr.to_string()));
    block.push(0x80 | FIRST_DYNAMIC_INDEX);

    client.request(block).await;

    assert_eq!(
        prog.get_match(0).expect("get_match").as_deref(),
        Some(accept_val.as_bytes()),
        "an entry that was not Huffman coded did not resolve from the table"
    );
}

#[tokio::test]
async fn ignore_frame_that_ends_before_it_claims_to() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let h2 = attach_h2_parser(prog.prog_fd(), &[header::ACCEPT]);

    let mut client = RawClient::connect(addr).await;

    // a request the parser does get through first, so that there is something
    // for a malformed frame to damage: a capture and an entry in the table
    let accept_val = HeaderValue::from_static("*/*");
    client
        .request(raw_request_block(
            &addr.to_string(),
            &[(Some(19), "accept", "*/*")],
        ))
        .await;

    let before = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");
    assert_eq!(before.count, 1);

    // and now a HEADERS frame whose header claims a hundred bytes that were
    // never sent
    let block = raw_request_block(&addr.to_string(), &[(Some(19), "accept", "*/*")]);
    let mut truncated = frame(0x01, 0x05, 3, &block);
    truncated[0] = 0;
    truncated[1] = 0;
    truncated[2] = 100;

    client.send_raw(&truncated).await;

    // the parser gives up on a frame it cannot see the end of, leaving what it
    // had captured before it alone rather than half overwriting it
    assert_eq!(
        prog.get_match(0).expect("get_match").as_deref(),
        Some(accept_val.as_bytes()),
        "a frame that was never fully sent changed what was captured"
    );

    let after = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");
    assert_eq!(after.count, before.count);
    assert_eq!(after.size, before.size);
}

#[tokio::test]
async fn ignore_header_field_indexed_past_the_end_of_the_table() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let h2 = attach_h2_parser(prog.prog_fd(), &[header::ACCEPT]);

    let mut client = RawClient::connect(addr).await;

    // the dynamic table is empty, so nothing has that index yet
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&addr.to_string()));
    block.push(0x80 | FIRST_DYNAMIC_INDEX);

    client.send_raw(&frame(0x01, 0x05, 1, &block)).await;

    assert_eq!(
        prog.get_match(0).expect("get_match"),
        None,
        "an index no entry sits at resolved to something"
    );

    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");
    assert_eq!(info.count, 0);
}

#[tokio::test]
async fn ignore_header_field_whose_value_runs_past_the_frame() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let h2 = attach_h2_parser(prog.prog_fd(), &[header::ACCEPT]);

    let mut client = RawClient::connect(addr).await;

    // the frame is the length it says it is, but the value inside it claims a
    // hundred bytes with two left to read
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&addr.to_string()));
    block.push(0x40 | 19);
    block.push(100);
    block.extend_from_slice(b"ab");

    client.send_raw(&frame(0x01, 0x05, 1, &block)).await;

    assert_eq!(
        prog.get_match(0).expect("get_match"),
        None,
        "a value reaching past the frame was captured"
    );

    // and it is no more welcome in the table than it is in a capture
    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");
    assert_eq!(info.count, 0);
    assert_eq!(info.size, 0);
}

#[tokio::test]
async fn parse_frame_after_an_unknown_one() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let _h2 = attach_h2_parser(prog.prog_fd(), &[header::ACCEPT]);

    let mut client = RawClient::connect(addr).await;

    // an unassigned frame type, which RFC 7540 says a peer has to discard
    // rather than choke on
    client.send_raw(&frame(0xFA, 0, 0, b"beeper")).await;

    // the parser has to pick the stream back up on the next frame
    let accept_val = HeaderValue::from_static("*/*");
    client
        .request(raw_request_block(
            &addr.to_string(),
            &[(Some(19), "accept", "*/*")],
        ))
        .await;

    assert_eq!(
        prog.get_match(0).expect("get_match").as_deref(),
        Some(accept_val.as_bytes()),
        "the parser did not recover from a frame it skipped"
    );
}

#[tokio::test]
async fn update_dynamic_table_size() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let h2 = attach_h2_parser(prog.prog_fd(), &[]);

    let client = Client::connect(addr, Some(1234)).await;
    client.get(format!("http://{}", addr), &[]).await;

    let max_size = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info")
        .max_size;
    assert_eq!(max_size, 1234);
}

#[tokio::test]
async fn evict_header_field_from_dynamic_table() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let prog =
        TestProgram::attach(addr, &mut open_obj, Direction::Downstream).expect("attach program");

    let _h1 = attach_preface_parser(prog.prog_fd());
    let h2 = attach_h2_parser(prog.prog_fd(), &[TEST_HEADER, header::USER_AGENT]);

    let test_header_val = HeaderValue::from_static("asdfqwerasdfqwerasdfqwerasdfqwer");
    let user_agent_val = HeaderValue::from_static("test-agent");

    // this request immediately exceeds the dynamic table limit
    let client = Client::connect(addr, Some(254)).await;
    client
        .get(
            format!("http://{}", addr),
            &[(TEST_HEADER, test_header_val.clone())],
        )
        .await;

    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");

    let authority = addr.to_string();
    let expected_dt = &[
        (TEST_HEADER, test_header_val.clone()),
        (
            AUTHORITY_HEADER,
            HeaderValue::from_str(&authority.as_str()).unwrap(),
        ),
    ];
    assert_eq!(info.max_size, 254);
    assert_eq!(info.count, expected_dt.len() as u32);
    assert_eq!(info.size, dynamic_table_size_for_headers(expected_dt));
    assert_match_eq(&prog, 0, Some(&test_header_val));

    client
        .get(
            format!("http://{}", addr),
            &[(header::USER_AGENT, user_agent_val.clone())],
        )
        .await;

    // this should add the user-agent to the dynamic table, but not evict TEST_HEADER
    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");
    let expected_dt = &[
        (TEST_HEADER, test_header_val.clone()),
        (
            AUTHORITY_HEADER,
            HeaderValue::from_str(&authority.as_str()).unwrap(),
        ),
        (header::USER_AGENT, user_agent_val.clone()),
    ];
    assert_eq!(info.max_size, 254);
    assert_eq!(info.count, expected_dt.len() as u32);
    assert_eq!(info.size, dynamic_table_size_for_headers(expected_dt));
    assert_match_eq(&prog, 1, Some(&user_agent_val));

    client
        .get(
            format!("http://{}", addr),
            &[(header::USER_AGENT, test_header_val.clone())],
        )
        .await;

    // this should evict all entries, and add back the user-agent
    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("dynamic_table_info");
    let expected_dt = &[(header::USER_AGENT, test_header_val.clone())];
    assert_eq!(info.max_size, 254);
    assert_eq!(info.count, expected_dt.len() as u32);
    assert_eq!(info.size, dynamic_table_size_for_headers(expected_dt));
    assert_match_eq(&prog, 1, Some(&test_header_val));
}