beeper 0.1.3

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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
use ::h2::{RecvStream, client};
use beeper::{MatchId, h1, h2, pseudo_header};
use bytes::Bytes;
use httlib_huffman as huffman;
use http::{HeaderName, HeaderValue, Request, Response, header};
use std::{net::SocketAddr, time::Duration};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    net::TcpStream,
};
use utils::{
    server,
    test::{Direction, Hook, TestProgram},
};
use xbpf::OpenObject;

const TEST_HEADER_NAME: &str = "testheader";
const TEST_HEADER: HeaderName = HeaderName::from_static(TEST_HEADER_NAME);

fn huffman_encode(s: &str) -> Vec<u8> {
    let mut coded = Vec::new();
    huffman::encode(s.as_bytes(), &mut coded).expect("encode");
    assert!(
        coded.len() < 127,
        "huffman_encode only encodes a one byte length"
    );

    let mut out = vec![0x80 | coded.len() as u8];
    out.extend_from_slice(&coded);

    out
}

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: &[(&str, HeaderValue)]) -> u32 {
    headers
        .iter()
        .fold(0, |acc, (k, v)| acc + (k.len() + v.len() + 32) as u32)
}

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

    if expected.is_none() {
        assert!(
            actual.is_none(),
            "get_match({mid:?}): {}, expected: none",
            actual.unwrap()
        );
    } else {
        let expected = expected.unwrap().to_str().unwrap();
        assert!(
            actual.is_some(),
            "get_match({mid:?}): 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 response = self.send(uri, headers).await;
        assert!(
            response.status().is_success(),
            "status: {}",
            response.status()
        );

        response
    }

    /// Same as [`Client::get`], but does not expect the server to have accepted
    /// the request. A header list the server turns down still reaches the
    /// parser, which is all some tests need of it.
    #[allow(unused_results)]
    async fn send(
        &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");
        response.await.expect("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
}

/// Renders an HPACK string of any length, spelled out rather than Huffman
/// coded. The length is written as the two byte integer of section 5.1 of RFC
/// 7541 whenever it does not fit into the seven bit prefix.
fn long_raw_str(s: &str) -> Vec<u8> {
    let mut out = Vec::new();
    if s.len() < 0x7F {
        out.push(s.len() as u8);
    } else {
        assert!(s.len() < 0x7F + 128, "long_raw_str only encodes two bytes");
        out.push(0x7F);
        out.push((s.len() - 0x7F) 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>) {
        self.request_all(&[(0, block)]).await;
    }

    /// Sends a request whose header block is split at `split`, the first half
    /// going out in the HEADERS frame and the second in a CONTINUATION frame,
    /// see section 6.10 of RFC 9113.
    async fn request_continued(&mut self, block: Vec<u8>, split: usize) {
        let id = self.next_stream_id;
        self.next_stream_id += 2;

        let mut out = Vec::new();
        // END_STREAM, but the block carries on
        out.extend_from_slice(&frame(0x01, 0x01, id, &block[..split]));
        // CONTINUATION | END_HEADERS
        out.extend_from_slice(&frame(0x09, 0x04, id, &block[split..]));

        self.stream.write_all(&out).await.expect("request");
        self.stream.flush().await.expect("flush");

        self.read_frame(0x01).await;
    }

    /// Sends every request in `reqs` in a single write, so that the parser has
    /// to find each frame by the length of the one before it. Each of them is
    /// the flags its HEADERS frame carries on top of END_STREAM and
    /// END_HEADERS, and the payload of that frame, which the caller lays out
    /// itself rather than handing over a bare block.
    async fn request_all(&mut self, reqs: &[(u8, Vec<u8>)]) {
        let mut out = Vec::new();
        for (flags, payload) in reqs {
            let id = self.next_stream_id;
            self.next_stream_id += 2;

            out.extend_from_slice(&frame(0x01, 0x05 | flags, id, payload));
        }

        self.stream.write_all(&out).await.expect("request");
        self.stream.flush().await.expect("flush");

        for _ in reqs {
            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_h1_parser(prog_fd: i32, hook: Hook) -> h1::AttachedParser {
    let mut h1 = h1::Parser::new();
    h1.match_h2_preface().expect("match preface");

    let suffix = hook.to_string();
    h1.matched_fn("matched_h1")
        .parse_fn(format!("parse_h1_{suffix}"), hook.into())
        .extract_fn(format!("extract_h1_match_{suffix}"), hook.into())
        .attach(prog_fd)
        .expect("attach parser")
}

/// Attaches a parser capturing `hdrs` and returns it along with the match id
/// of each of them, in the order they were configured in.
fn attach_h2_parser(prog_fd: i32, hook: Hook, hdrs: &[&str]) -> (h2::AttachedParser, Vec<MatchId>) {
    let mut h2 = h2::Parser::new();

    let mut mids = Vec::new();
    for hdr in hdrs {
        mids.push(
            h2.capture_hdr(hdr)
                .unwrap_or_else(|e| panic!("capture {hdr:?}: {e}")),
        );
    }

    let suffix = hook.to_string();
    let h2 = h2
        .parse_fn(format!("parse_h2_{suffix}"), hook.into())
        .extract_fn(format!("extract_h2_match_{suffix}"), hook.into())
        .attach(prog_fd)
        .expect("attach parser");

    (h2, mids)
}

/// Attaches the test program at `hook` along with the parsers that go with it.
fn attach_at<'obj>(
    addr: SocketAddr,
    open_obj: &'obj mut OpenObject,
    hook: Hook,
    hdrs: &[&str],
) -> (
    TestProgram<'obj>,
    h1::AttachedParser,
    h2::AttachedParser,
    Vec<MatchId>,
) {
    let prog = TestProgram::attach_to(addr, open_obj, Direction::Downstream, hook)
        .expect("attach program");

    let h1 = attach_h1_parser(prog.prog_fd(), hook);
    let (h2, mids) = attach_h2_parser(prog.prog_fd(), hook, hdrs);

    (prog, h1, h2, mids)
}

/// The addresses the parser at `hook` keys the connection of `client` with:
/// `sk_msg` runs on the client's socket, `sk_skb` on the server's.
fn conn_at(
    hook: Hook,
    local_addr: SocketAddr,
    remote_addr: SocketAddr,
) -> (SocketAddr, SocketAddr) {
    match hook {
        Hook::Msg => (local_addr, remote_addr),
        Hook::Skb => (remote_addr, local_addr),
    }
}

#[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_h1_parser(prog.prog_fd(), Hook::Msg);
    let (_h2, mids) =
        attach_h2_parser(prog.prog_fd(), Hook::Msg, &[pseudo_header::METHOD.as_str()]);

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

    let method_val = HeaderValue::from_static("GET");
    assert_match_eq(&prog, mids[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, _h1, _h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Msg,
        &[header::AUTHORIZATION.as_str()],
    );

    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, mids[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, _h1, _h2, mids) = attach_at(addr, &mut open_obj, Hook::Msg, &[TEST_HEADER_NAME]);

    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, mids[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, _h1, _h2, mids) = attach_at(addr, &mut open_obj, Hook::Msg, &[TEST_HEADER_NAME]);

    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, mids[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, _h1, _h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Msg,
        &[header::USER_AGENT.as_str(), pseudo_header::PATH.as_str()],
    );

    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, mids[0], Some(&user_agent_val));
    assert_match_eq(&prog, mids[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, _h1, _h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Msg,
        &[TEST_HEADER_NAME, pseudo_header::PATH.as_str()],
    );

    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, mids[0], Some(&test_header_val));
    assert_match_eq(&prog, mids[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, _h1, _h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Msg,
        &[
            header::USER_AGENT.as_str(),
            header::ACCEPT_LANGUAGE.as_str(),
        ],
    );

    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, mids[0], Some(&user_agent_val));
    assert_match_eq(&prog, mids[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, mids[0], None);
    assert_match_eq(&prog, mids[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, mids[0], Some(&user_agent_val));
    assert_match_eq(&prog, mids[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, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    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_NAME, "in-the-hive"),
                (Some(19), "accept", "*/*"),
            ],
        ))
        .await;

    assert_eq!(
        prog.get_match(mids[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_NAME, test_header_val.clone()),
        (header::ACCEPT.as_str(), accept_val.clone()),
    ];
    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("connection is known")
        .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, _h1, _h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    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(mids[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(mids[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, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    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("connection is known")
        .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(mids[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("connection is known")
        .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, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    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(mids[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("connection is known")
        .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, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    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(mids[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("connection is known")
        .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, _h1, _h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    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(mids[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, _h1, h2, _mids) = attach_at(addr, &mut open_obj, Hook::Msg, &[]);

    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("connection is known")
        .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, _h1, h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Msg,
        &[TEST_HEADER_NAME, header::USER_AGENT.as_str()],
    );

    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("connection is known")
        .expect("dynamic_table_info");

    let authority = addr.to_string();
    let expected_dt = &[
        (TEST_HEADER_NAME, test_header_val.clone()),
        (
            pseudo_header::AUTHORITY.as_str(),
            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, mids[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("connection is known")
        .expect("dynamic_table_info");
    let expected_dt = &[
        (TEST_HEADER_NAME, test_header_val.clone()),
        (
            pseudo_header::AUTHORITY.as_str(),
            HeaderValue::from_str(&authority.as_str()).unwrap(),
        ),
        (header::USER_AGENT.as_str(), 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, mids[1], Some(&user_agent_val));

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

    // this should evict the authority, the oldest entry, and nothing more
    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("connection is known")
        .expect("dynamic_table_info");
    let expected_dt = &[
        (TEST_HEADER_NAME, test_header_val.clone()),
        (header::USER_AGENT.as_str(), user_agent_val.clone()),
        (header::USER_AGENT.as_str(), 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_eq!(info.deleted, 1);
    assert_match_eq(&prog, mids[1], Some(&test_header_val));
}

/// The flag of a HEADERS frame saying that its block is padded, see section 6.2
/// of RFC 9113.
const PADDED_FLAG: u8 = 0x08;

/// The flag saying that a priority comes in front of its block.
const PRIORITY_FLAG: u8 = 0x20;

/// Renders the payload of a HEADERS frame that pads `block` with `pad`, see
/// section 6.2 of RFC 9113: the length of the padding, the block, and the
/// padding itself.
fn padded(block: Vec<u8>, pad: &[u8]) -> Vec<u8> {
    let mut payload = vec![pad.len() as u8];
    payload.extend_from_slice(&block);
    payload.extend_from_slice(pad);

    payload
}

/// Renders the payload of a HEADERS frame that puts a priority in front of
/// `block`, see section 6.3 of RFC 9113: a stream dependency and a weight.
fn prioritised(block: Vec<u8>) -> Vec<u8> {
    let mut payload = vec![0x00, 0x00, 0x00, 0x00, 0x10];
    payload.extend_from_slice(&block);

    payload
}

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let padded_val = HeaderValue::from_static("padded");
    let next_val = HeaderValue::from_static("after-the-padding");

    // the padding is a field that would be added to the dynamic table if it
    // were read as one, which is how the test tells that it was skipped
    let pad = [0x40, 0x00, 0x00];

    // both requests go out in a single write, so the second is only found if
    // the padded frame reported its own length correctly
    let mut client = RawClient::connect(addr).await;
    client
        .request_all(&[
            (
                PADDED_FLAG,
                padded(
                    raw_request_block(&authority, &[(Some(19), "accept", "padded")]),
                    &pad,
                ),
            ),
            (
                0,
                raw_request_block(&authority, &[(Some(19), "accept", "after-the-padding")]),
            ),
        ])
        .await;

    assert_eq!(
        prog.get_match(mids[0]).expect("get_match").as_deref(),
        Some(next_val.as_bytes()),
        "the frame after the padded one was not found"
    );

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

    let expected_dt = &[
        (header::ACCEPT.as_str(), padded_val.clone()),
        (header::ACCEPT.as_str(), next_val.clone()),
    ];
    assert_eq!(
        info.count,
        expected_dt.len() as u32,
        "the padding was read as a header field"
    );
    assert_eq!(info.size, dynamic_table_size_for_headers(expected_dt));
}

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let accept_val = HeaderValue::from_static("after-the-priority");

    let mut client = RawClient::connect(addr).await;
    client
        .request_all(&[(
            PRIORITY_FLAG,
            prioritised(raw_request_block(
                &authority,
                &[(Some(19), "accept", "after-the-priority")],
            )),
        )])
        .await;

    assert_eq!(
        prog.get_match(mids[0]).expect("get_match").as_deref(),
        Some(accept_val.as_bytes()),
        "the block was not read from behind the priority"
    );

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

    let expected_dt = &[(header::ACCEPT.as_str(), accept_val.clone())];
    assert_eq!(
        info.count,
        expected_dt.len() as u32,
        "the priority was read as a header field"
    );
    assert_eq!(info.size, dynamic_table_size_for_headers(expected_dt));
}

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Msg,
        &[TEST_HEADER_NAME, header::USER_AGENT.as_str()],
    );

    let long_val = HeaderValue::from_static("asdfqwerasdfqwerasdfqwerasdfqwer");
    let agent_val = HeaderValue::from_static("test-agent");
    let other_agent_val = HeaderValue::from_static("other-agent");
    let url = format!("http://{}", addr);

    // a table this small fills up over the three requests below, the last of
    // which evicts the authority the connection opened with
    let client = Client::connect(addr, Some(254)).await;
    client
        .get(url.clone(), &[(TEST_HEADER, long_val.clone())])
        .await;
    client
        .get(url.clone(), &[(header::USER_AGENT, agent_val.clone())])
        .await;
    client
        .get(url.clone(), &[(header::USER_AGENT, long_val.clone())])
        .await;

    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("connection is known")
        .expect("dynamic_table_info");
    assert_eq!(
        info.deleted, 1,
        "nothing was evicted, so the entries below are stored where they would be anyway"
    );

    // this one is added to a table that has already evicted, which is what
    // decides whether the entries added before it keep the index they were
    // stored under
    client
        .get(
            url.clone(),
            &[(header::USER_AGENT, other_agent_val.clone())],
        )
        .await;
    assert_match_eq(&prog, mids[1], Some(&other_agent_val));

    // the client still holds the long user agent, so it sends it as nothing but
    // the index of the entry it was added under before the eviction
    client
        .get(url.clone(), &[(header::USER_AGENT, long_val.clone())])
        .await;

    assert_match_eq(&prog, mids[1], Some(&long_val));
}
#[tokio::test]
async fn parse_header_block_split_over_a_continuation_frame() {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let (prog, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let accept_val = HeaderValue::from_static("in-the-continuation");
    let block = raw_request_block(&authority, &[(Some(19), "accept", "in-the-continuation")]);

    // the block breaks right after the three indexed pseudo headers it opens
    // with, so every field of it is whole in the frame that carries it
    let mut client = RawClient::connect(addr).await;
    client.request_continued(block, 3).await;

    assert_eq!(
        prog.get_match(mids[0]).expect("get_match").as_deref(),
        Some(accept_val.as_bytes()),
        "the field in the continuation frame was not read"
    );

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

    let expected_dt = &[(header::ACCEPT.as_str(), accept_val.clone())];
    assert_eq!(info.count, expected_dt.len() as u32);
    assert_eq!(info.size, dynamic_table_size_for_headers(expected_dt));
    assert_eq!(
        info.dirty, 0,
        "a block that breaks between fields left the table looking untrustworthy"
    );
}

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let accept_val = HeaderValue::from_static("across-the-break");
    let block = raw_request_block(&authority, &[(Some(19), "accept", "across-the-break")]);

    // the block breaks two bytes into the authority, whose first half is in a
    // frame the parser cannot address once the second one arrives
    let mut client = RawClient::connect(addr).await;
    client.request_continued(block, 3 + 1 + 1 + 2).await;

    // the fields behind the break are still read, the parser only loses the one
    // the break falls inside of
    assert_eq!(
        prog.get_match(mids[0]).expect("get_match").as_deref(),
        Some(accept_val.as_bytes()),
        "the field behind the break was not read"
    );

    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("connection is known")
        .expect("dynamic_table_info");
    assert_eq!(
        info.dirty, 1,
        "a block that breaks inside a field left the table looking trustworthy"
    );
}

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

    let mut open_obj = OpenObject::new();
    let (_prog, _h1, h2, _mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    // SETTINGS_HEADER_TABLE_SIZE is a 32 bit parameter, and a size above 64KiB
    // is one browsers do announce
    let client = Client::connect(addr, Some(65536)).await;
    client.get(format!("http://{}", addr), &[]).await;

    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("connection is known")
        .expect("dynamic_table_info");
    assert_eq!(info.max_size, 65536);
}

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, _h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let first = HeaderValue::from_static("first");

    // the first request puts `accept: first` into the dynamic table, where it
    // is the entry the next block can address with the first dynamic index
    let mut client = RawClient::connect(addr).await;
    client
        .request(raw_request_block(
            &authority,
            &[(Some(19), "accept", "first")],
        ))
        .await;
    assert_eq!(
        prog.get_match(mids[0]).expect("get_match").as_deref(),
        Some(first.as_bytes())
    );

    // the next block reads that entry by index and then adds one of its own,
    // which pushes everything below it down by one. The field it adds is a
    // `user-agent`, which matches no pattern, so nothing of it is captured and
    // the `accept` read above is still the only capture of the block
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&authority));
    block.push(0x80 | FIRST_DYNAMIC_INDEX);
    block.push(0x40 | 58);
    block.extend_from_slice(&raw_str("junk"));

    client.request(block).await;

    assert_eq!(
        prog.get_match(mids[0]).expect("get_match").as_deref(),
        Some(first.as_bytes()),
        "the capture followed the index into the entry that took its place"
    );
}

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

    let mut open_obj = OpenObject::new();
    let (_prog, _h1, h2, _mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

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

    // the same lie as in `ignore_header_field_whose_value_runs_past_the_frame`,
    // except that a second frame follows in the same write, so the bytes the
    // value claims are bytes the parser can read -- they just belong to the
    // frame behind it
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&authority));
    block.push(0x40 | 19);
    block.push(100);
    block.extend_from_slice(b"ab");

    let mut out = frame(0x01, 0x05, 1, &block);
    out.extend_from_slice(&frame(0x01, 0x05, 3, &raw_request_block(&authority, &[])));

    client.send_raw(&out).await;

    // a field is only ever made of the bytes of its own block
    let info = h2
        .dynamic_table_info(client.local_addr, client.remote_addr)
        .expect("connection is known")
        .expect("dynamic_table_info");
    assert_eq!(
        info.count, 0,
        "a value reaching into the next frame was added to the table"
    );
    assert_eq!(info.size, 0);
}

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

    let mut open_obj = OpenObject::new();
    let (_prog, _h1, h2, _mids) =
        attach_at(addr, &mut open_obj, Hook::Msg, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let long = "a".repeat(130);
    let long_val = HeaderValue::from_str(&long).expect("header value");

    // the entry does not fit into the 128 bytes the mirrored table keeps of a
    // field, but the peer sizes it by everything it sent, and it is that size
    // that decides when the two tables evict
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&authority));
    block.push(0x40 | 19);
    block.extend_from_slice(&long_raw_str(&long));

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

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

    let expected_dt = &[(header::ACCEPT.as_str(), long_val.clone())];
    assert_eq!(info.count, expected_dt.len() as u32);
    assert_eq!(
        info.size,
        dynamic_table_size_for_headers(expected_dt),
        "a field longer than an entry holds was sized by what was kept of it"
    );
}

#[tokio::test]
async fn ignore_an_index_that_only_wraps_into_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_h1_parser(prog.prog_fd(), Hook::Msg);
    let (_h2, mids) = attach_h2_parser(prog.prog_fd(), Hook::Msg, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let secret = HeaderValue::from_static("secret");

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

    // 32830 is the first dynamic index with the sixteenth bit set. No entry
    // sits there, and an index that far past the end of the table is one a
    // peer answers with a connection error
    let idx: u32 = 0x8000 + FIRST_DYNAMIC_INDEX as u32;
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&authority));
    block.push(0xFF);
    let mut rest = idx - 0x7F;
    while rest >= 0x80 {
        block.push(0x80 | (rest & 0x7F) as u8);
        rest >>= 7;
    }
    block.push(rest as u8);

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

    assert_eq!(
        prog.get_match(mids[0]).expect("get_match"),
        None,
        "an index past the end of the table resolved to an entry inside it"
    );
}

#[tokio::test]
async fn match_a_field_name_by_the_whole_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");

    // `a&b` is a legal field name whose Huffman code starts with the code of
    // `a`, padding and all: the shorter name is a byte prefix of the longer one
    let short = HeaderName::from_static("a");
    let mut coded_short = Vec::new();
    huffman::encode(short.as_str().as_bytes(), &mut coded_short).expect("encode");
    let mut coded_long = Vec::new();
    huffman::encode(b"a&b", &mut coded_long).expect("encode");
    assert!(coded_long.starts_with(&coded_short));

    let _h1 = attach_h1_parser(prog.prog_fd(), Hook::Msg);
    let (_h2, mids) = attach_h2_parser(prog.prog_fd(), Hook::Msg, &[short.as_str()]);

    let authority = addr.to_string();
    let mut block = vec![0x82, 0x86, 0x84];
    block.push(0x01);
    block.extend_from_slice(&raw_str(&authority));
    block.push(0x40);
    block.extend_from_slice(&huffman_encode("a&b"));
    block.extend_from_slice(&raw_str("not-the-one"));

    let mut client = RawClient::connect(addr).await;
    client.send_raw(&frame(0x01, 0x05, 1, &block)).await;

    assert_eq!(
        prog.get_match(mids[0]).expect("get_match"),
        None,
        "a field whose name only starts like the pattern was captured"
    );
}

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, _h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Skb,
        &[pseudo_header::METHOD.as_str()],
    );

    // the preface and the client's SETTINGS usually arrive together, so the
    // frames behind the preface start in the middle of an sk_buff
    let client = Client::connect(addr, None).await;
    client.get(format!("http://{}", addr), &[]).await;

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

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, _h2, mids) = attach_at(
        addr,
        &mut open_obj,
        Hook::Skb,
        &[
            header::USER_AGENT.as_str(),
            header::ACCEPT_LANGUAGE.as_str(),
        ],
    );

    let user_agent_val = HeaderValue::from_static("beeper");
    let lang_val = HeaderValue::from_static("sumsum");
    let hdrs = [
        (header::USER_AGENT, user_agent_val.clone()),
        (header::ACCEPT_LANGUAGE, lang_val.clone()),
    ];

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

    // the second time around both are sent as indices into the dynamic table
    client.get(format!("http://{}", addr), &hdrs).await;
    assert_match_eq(&prog, mids[0], Some(&user_agent_val));
    assert_match_eq(&prog, mids[1], Some(&lang_val));
}

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

    let mut open_obj = OpenObject::new();
    let (_prog, _h1, h2, _mids) = attach_at(addr, &mut open_obj, Hook::Skb, &[]);

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

    let (local, remote) = conn_at(Hook::Skb, client.local_addr, client.remote_addr);
    let max_size = h2
        .dynamic_table_info(local, remote)
        .expect("connection is known")
        .expect("dynamic_table_info")
        .max_size;
    assert_eq!(max_size, 1234);
}

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

    let mut open_obj = OpenObject::new();
    let (prog, _h1, h2, mids) =
        attach_at(addr, &mut open_obj, Hook::Skb, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let mut client = RawClient::connect(addr).await;
    client
        .request_all(&[
            (
                0,
                raw_request_block(&authority, &[(Some(19), "accept", "text/plain")]),
            ),
            (
                0,
                raw_request_block(&authority, &[(Some(19), "accept", "text/html")]),
            ),
        ])
        .await;

    assert_eq!(
        prog.get_match(mids[0]).expect("get_match").as_deref(),
        Some(b"text/html".as_slice()),
        "the second frame of the sk_buff was not parsed where it starts"
    );

    // both add their field to the table, so both have to have been parsed
    let (local, remote) = conn_at(Hook::Skb, client.local_addr, client.remote_addr);
    let info = h2
        .dynamic_table_info(local, remote)
        .expect("connection is known")
        .expect("dynamic_table_info");
    assert_eq!(info.count, 2);
}

/// Adds a field to the dynamic table, then sends a frame the parser skips and
/// checks that the frame still reports the table it found.
async fn report_the_dynamic_table_on_a_skipped_frame(hook: Hook) {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let (prog, _h1, _h2, _mids) = attach_at(addr, &mut open_obj, hook, &[header::ACCEPT.as_str()]);

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

    // PING, which the server answers, so that the parser has seen it by the
    // time the answer is in
    client.send_raw(&frame(0x06, 0, 0, &[0; 8])).await;
    client.read_frame(0x06).await;

    assert_eq!(prog.last_dt_counts(), (1, 1));
}

#[tokio::test]
async fn report_the_dynamic_table_on_a_skipped_frame_in_msg() {
    report_the_dynamic_table_on_a_skipped_frame(Hook::Msg).await;
}

#[tokio::test]
async fn report_the_dynamic_table_on_a_skipped_frame_in_skb() {
    report_the_dynamic_table_on_a_skipped_frame(Hook::Skb).await;
}

/// Fills the dynamic table of a connection, forgets the connection and checks
/// that nothing of it is left.
async fn forget_a_connection(hook: Hook) {
    let addr = server::launch().await.expect("launch server");

    let mut open_obj = OpenObject::new();
    let (prog, _h1, h2, mids) = attach_at(addr, &mut open_obj, hook, &[header::ACCEPT.as_str()]);

    let authority = addr.to_string();
    let mut client = RawClient::connect(addr).await;
    client
        .request(raw_request_block(
            &authority,
            &[(Some(19), "accept", "*/*")],
        ))
        .await;

    let (local, remote) = conn_at(hook, client.local_addr, client.remote_addr);
    let info = h2
        .dynamic_table_info(local, remote)
        .expect("connection is known")
        .expect("dynamic_table_info");
    assert_eq!(info.count, 1);

    h2.forget_conn(local, remote).expect("forget_conn");
    assert!(
        h2.dynamic_table_info(local, remote).is_none(),
        "the dynamic table of a forgotten connection is still there"
    );

    // forgetting a connection the parser knows nothing about is not an error
    h2.forget_conn(local, remote).expect("forget_conn twice");

    // the connection starts over from an empty table, into which the entry the
    // client still references cannot be resolved
    client.request(vec![0x82, 0x86, 0x84, 0xBE]).await;
    assert_eq!(prog.get_match(mids[0]).expect("get_match"), None);

    let info = h2
        .dynamic_table_info(local, remote)
        .expect("connection is known")
        .expect("dynamic_table_info");
    assert_eq!(info.count, 0);
}

#[tokio::test]
async fn forget_a_connection_in_msg() {
    forget_a_connection(Hook::Msg).await;
}

#[tokio::test]
async fn forget_a_connection_in_skb() {
    forget_a_connection(Hook::Skb).await;
}