crafter 0.3.2

Packet-level network interaction for Rust tools and agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
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
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
//! Explicit protocol binding and decode dispatch.

use std::sync::OnceLock;

use crate::endian::read_u32_be;
use crate::error::Result;
use crate::packet::{LinkType, NetworkLayer, Packet, Raw};
use crate::protocols::bgp::{decode::append_bgp_packet_with_registry, BGP_PORT};
use crate::protocols::dhcp::{
    append_dhcpv4_packet, append_dhcpv6_packet, is_dhcpv4_port_pair, looks_like_dhcpv4_payload,
    looks_like_dhcpv6_payload,
};
use crate::protocols::dns::{append_dns_packet, DNS_PORT};
use crate::protocols::eapol::append_eapol_packet;
use crate::protocols::icmp::{
    append_icmp_packet, append_icmp_packet_with_checksum_validation, append_icmpv6_packet,
};
use crate::protocols::igmp::append_igmp_packet;
use crate::protocols::ip::shared::IPPROTO_IGMP;
use crate::protocols::ipsec::ah::decode::append_ah_packet_with_registry_sa;
use crate::protocols::ipsec::esp::decode::append_esp_packet_with_registry_sa;
use crate::protocols::ipsec::esp::header::ESP_HEADER_LEN;
use crate::protocols::ipsec::ikev2::decode::append_ikev2_packet_with_registry;
use crate::protocols::ipsec::natt::{is_non_esp_marker, NatTraversal, NON_ESP_MARKER_LEN};
use crate::protocols::ipsec::sa::SecurityAssociation;
use crate::protocols::ipv4::{
    append_ipv4_packet_with_registry, IPPROTO_AH, IPPROTO_ESP, IPPROTO_ICMP, IPPROTO_ICMPV6,
    IPPROTO_OSPF, IPPROTO_TCP, IPPROTO_UDP,
};
use crate::protocols::ipv6::{append_ipv6_packet_with_registry, IPPROTO_IPV6_AH, IPPROTO_IPV6_ESP};
use crate::protocols::mqtt::{decode::append_mqtt_packet_with_registry, MQTT_PORT};
use crate::protocols::ospf::decode::append_ospf_packet_with_checksum_validation;
use crate::protocols::ospf::v3::append_ospfv3_packet_with_checksum_validation;
// Re-export the checksum-agnostic OSPF entrypoint alongside the registry so
// callers wiring custom dispatch can decode an OSPF payload without opting into
// decode-time checksum validation (RFC 2328 §A.3.1).
use crate::protocols::link::{
    append_arp_packet, append_vlan_packet_with_registry, decode_ble_ll_with_registry,
    decode_dot11_with_registry, decode_dot15d4_with_registry, decode_ethernet_with_registry,
    decode_linux_sll_with_registry, decode_null_loopback_with_registry,
    decode_radiotap_with_registry, ETHERTYPE_ARP, ETHERTYPE_EAPOL, ETHERTYPE_IPV4, ETHERTYPE_IPV6,
    ETHERTYPE_VLAN,
};
#[allow(unused_imports)]
pub(crate) use crate::protocols::ospf::decode::append_ospf_packet;
use crate::protocols::quic::decode::{append_quic_packet, looks_like_quic_udp_payload};
use crate::protocols::rip::ripng::{append_ripng_packet, looks_like_ripng_payload, RIPNG_UDP_PORT};
use crate::protocols::rip::{append_rip_packet, looks_like_rip_payload, RIP_UDP_PORT};
use crate::protocols::snmp::{
    decode::{append_snmp_packet, looks_like_snmp_payload},
    SNMP_PORT, SNMP_TRAP_PORT,
};
use crate::protocols::transport::{
    append_tcp_packet_with_registry, append_udp_packet_with_registry,
};

/// UDP port for IKEv2 (RFC 7296 §2; IANA "isakmp" 500). An IKE message on this
/// port is the 28-octet header plus its payload chain; the registry routes it to
/// the IKEv2 decoder.
const IKEV2_UDP_PORT: u16 = 500;

/// UDP port for IPSec NAT traversal (RFC 3948 §2; IANA "ipsec-nat-t" 4500). This
/// port carries both UDP-encapsulated ESP and IKE; the registry disambiguates
/// them by the RFC 3948 non-ESP marker (the leading four octets).
const NATT_UDP_PORT: u16 = 4500;

const fn is_snmp_udp_port(port: u16) -> bool {
    matches!(port, SNMP_PORT | SNMP_TRAP_PORT)
}

/// Common QUIC-over-UDP HTTPS port used by default registry recognition.
const QUIC_HTTPS_UDP_PORT: u16 = 443;

/// Documentation/example QUIC UDP port used by RFC-backed local fixtures.
const QUIC_EXAMPLE_UDP_PORT: u16 = 4433;

type ProtocolDecoder = dyn for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
    + Send
    + Sync
    + 'static;

/// Context passed to Ethernet-type binding predicates.
#[derive(Debug, Clone, Copy)]
pub struct EthertypeBindingContext<'a> {
    /// Ethernet type being dispatched.
    pub ethertype: u16,
    /// Payload bytes after the link header.
    pub payload: &'a [u8],
}

/// Context passed to IPv4 protocol binding predicates.
#[derive(Debug, Clone, Copy)]
pub struct Ipv4ProtocolBindingContext<'a> {
    /// IPv4 protocol number being dispatched.
    pub protocol: u8,
    /// Payload bytes after the IPv4 header.
    pub payload: &'a [u8],
}

/// Context passed to IPv6 next-header binding predicates.
#[derive(Debug, Clone, Copy)]
pub struct Ipv6NextHeaderBindingContext<'a> {
    /// IPv6 next-header value being dispatched.
    pub next_header: u8,
    /// Payload bytes after the IPv6 base header or extension stack.
    pub payload: &'a [u8],
}

/// Context passed to UDP application binding predicates.
#[derive(Debug, Clone, Copy)]
pub struct UdpBindingContext<'a> {
    /// UDP source port.
    pub source_port: u16,
    /// UDP destination port.
    pub destination_port: u16,
    /// UDP payload bytes.
    pub payload: &'a [u8],
}

/// Context passed to TCP application binding predicates.
#[derive(Debug, Clone, Copy)]
pub struct TcpBindingContext<'a> {
    /// TCP source port.
    pub source_port: u16,
    /// TCP destination port.
    pub destination_port: u16,
    /// TCP payload bytes.
    pub payload: &'a [u8],
}

struct EthertypeBinding {
    predicate: Box<dyn for<'a> Fn(EthertypeBindingContext<'a>) -> bool + Send + Sync + 'static>,
    decoder: Box<ProtocolDecoder>,
}

struct Ipv4ProtocolBinding {
    predicate: Box<dyn for<'a> Fn(Ipv4ProtocolBindingContext<'a>) -> bool + Send + Sync + 'static>,
    decoder: Box<ProtocolDecoder>,
}

struct Ipv6NextHeaderBinding {
    predicate:
        Box<dyn for<'a> Fn(Ipv6NextHeaderBindingContext<'a>) -> bool + Send + Sync + 'static>,
    decoder: Box<ProtocolDecoder>,
}

struct UdpBinding {
    predicate: Box<dyn for<'a> Fn(UdpBindingContext<'a>) -> bool + Send + Sync + 'static>,
    decoder: Box<ProtocolDecoder>,
}

struct TcpBinding {
    predicate: Box<dyn for<'a> Fn(TcpBindingContext<'a>) -> bool + Send + Sync + 'static>,
    decoder: Box<ProtocolDecoder>,
}

/// Immutable protocol dispatch table used while decoding packets.
///
/// The registry is an owned value. Built-ins are installed by [`Default`] and
/// [`ProtocolRegistry::new`], while custom bindings are explicit additions on
/// that value. There is no mutable global registry.
pub struct ProtocolRegistry {
    ethertype_bindings: Vec<EthertypeBinding>,
    builtin_ethertype_dispatch: bool,
    ipv4_bindings: Vec<Ipv4ProtocolBinding>,
    builtin_ipv4_protocol_dispatch: bool,
    ipv6_bindings: Vec<Ipv6NextHeaderBinding>,
    builtin_ipv6_next_header_dispatch: bool,
    udp_bindings: Vec<UdpBinding>,
    builtin_udp_application_dispatch: bool,
    tcp_bindings: Vec<TcpBinding>,
    security_associations: Vec<SecurityAssociation>,
    validate_checksums: bool,
    decode_applications: bool,
}

impl ProtocolRegistry {
    /// Create a registry with the built-in protocol bindings installed.
    pub fn new() -> Self {
        Self::with_builtin_bindings()
    }

    /// Shared built-in registry used by default decode entrypoints.
    pub(crate) fn builtin() -> &'static Self {
        static BUILTIN_REGISTRY: OnceLock<ProtocolRegistry> = OnceLock::new();
        BUILTIN_REGISTRY.get_or_init(Self::with_builtin_bindings)
    }

    /// Shared transport-only registry used by shallow ICMP quoted-datagram
    /// decode.
    pub(crate) fn transport_only_builtin() -> &'static Self {
        static TRANSPORT_ONLY_REGISTRY: OnceLock<ProtocolRegistry> = OnceLock::new();
        TRANSPORT_ONLY_REGISTRY.get_or_init(Self::transport_only)
    }

    /// Create a registry with no bindings.
    pub fn empty() -> Self {
        Self {
            ethertype_bindings: Vec::new(),
            builtin_ethertype_dispatch: false,
            ipv4_bindings: Vec::new(),
            builtin_ipv4_protocol_dispatch: false,
            ipv6_bindings: Vec::new(),
            builtin_ipv6_next_header_dispatch: false,
            udp_bindings: Vec::new(),
            builtin_udp_application_dispatch: false,
            tcp_bindings: Vec::new(),
            security_associations: Vec::new(),
            validate_checksums: true,
            decode_applications: true,
        }
    }

    /// Create a registry containing libcrafter-compatible built-in dispatch.
    pub fn with_builtin_bindings() -> Self {
        let mut registry = Self::empty();

        registry.bind_ethertype_with_registry(ETHERTYPE_ARP, |_registry, packet, payload| {
            append_arp_packet(packet, payload)
        });
        registry.bind_ethertype_with_registry(ETHERTYPE_VLAN, |registry, packet, payload| {
            append_vlan_packet_with_registry(registry, packet, payload)
        });
        registry.bind_ethertype_with_registry(ETHERTYPE_IPV4, |registry, packet, payload| {
            append_ipv4_packet_with_registry(registry, packet, payload)
        });
        registry.bind_ethertype_with_registry(ETHERTYPE_IPV6, |registry, packet, payload| {
            append_ipv6_packet_with_registry(registry, packet, payload)
        });
        registry.bind_ethertype_with_registry(ETHERTYPE_EAPOL, |_registry, packet, payload| {
            append_eapol_packet(packet, payload)
        });
        registry.builtin_ethertype_dispatch = true;

        registry.bind_ipv4_protocol_with_registry(IPPROTO_ICMP, |registry, packet, payload| {
            append_icmp_packet_with_checksum_validation(
                packet,
                payload,
                registry.validates_checksums(),
            )
        });
        registry.bind_ipv4_protocol_with_registry(IPPROTO_TCP, |registry, packet, payload| {
            append_tcp_packet_with_registry(registry, packet, payload)
        });
        registry.bind_ipv4_protocol_with_registry(IPPROTO_UDP, |registry, packet, payload| {
            append_udp_packet_with_registry(registry, packet, payload)
        });
        registry.bind_ipv4_protocol_with_registry(IPPROTO_IGMP, |_registry, packet, payload| {
            append_igmp_packet(packet, payload)
        });
        // ESP (IP protocol 50, RFC 4303). The decoder looks up a registered SA by
        // the on-wire SPI: when one is found it drives the SA-aware path (verify
        // the ICV, decrypt, strip padding, dispatch the inner protocol/IP); when
        // none is found — as in the default SA-less registry — it falls back to
        // the opaque path (SPI/Sequence exposed, encrypted body preserved
        // verbatim). Callers register SAs with
        // [`ProtocolRegistry::register_security_association`].
        registry.bind_ipv4_protocol_with_registry(IPPROTO_ESP, |registry, packet, payload| {
            decode_esp_with_registry_sa(registry, packet, payload)
        });
        // AH (IP protocol 51, RFC 4302). AH only authenticates, so the protected
        // upper-layer data — and, in tunnel mode, the inner IP datagram — is
        // always in the clear: the typed `Ah` header and its variable-length ICV
        // decode without keys, and the inner protocol dispatches by Next Header.
        // When a registered SA matches the on-wire SPI the decoder also verifies
        // the ICV and records the verified status; otherwise — as in the default
        // SA-less registry — the ICV is preserved verbatim rather than verified.
        registry.bind_ipv4_protocol_with_registry(IPPROTO_AH, |registry, packet, payload| {
            decode_ah_with_registry_sa(registry, packet, payload)
        });
        // OSPFv2 (IP protocol 89, RFC 2328). OSPF runs directly over IP, so the
        // IPv4 payload is the OSPF common header plus its body; the decoder is
        // handed the registry checksum policy for decode-time checksum status.
        registry.bind_ipv4_protocol_with_registry(IPPROTO_OSPF, |registry, packet, payload| {
            append_ospf_packet_with_checksum_validation(
                packet,
                payload,
                registry.validates_checksums(),
            )
        });

        registry
            .bind_ipv6_next_header_with_registry(IPPROTO_ICMPV6, |_registry, packet, payload| {
                append_icmpv6_packet(packet, payload)
            });
        registry.bind_ipv6_next_header_with_registry(IPPROTO_TCP, |registry, packet, payload| {
            append_tcp_packet_with_registry(registry, packet, payload)
        });
        registry.bind_ipv6_next_header_with_registry(IPPROTO_UDP, |registry, packet, payload| {
            append_udp_packet_with_registry(registry, packet, payload)
        });
        // ESP as an IPv6 next-header (RFC 4303); same SA-lookup behavior as IPv4.
        registry
            .bind_ipv6_next_header_with_registry(IPPROTO_IPV6_ESP, |registry, packet, payload| {
                decode_esp_with_registry_sa(registry, packet, payload)
            });
        // AH as an IPv6 next-header (RFC 4302). AH can appear in the IPv6
        // extension-header chain, so once the chain walk reaches next-header 51
        // it dispatches here; the cleartext upper-layer data (transport mode) or
        // inner IP datagram (tunnel mode) decodes without keys, and a registered
        // SA matching the SPI additionally verifies the ICV, same as IPv4.
        registry
            .bind_ipv6_next_header_with_registry(IPPROTO_IPV6_AH, |registry, packet, payload| {
                decode_ah_with_registry_sa(registry, packet, payload)
            });
        // OSPFv3 as an IPv6 next-header (RFC 5340 §2.5): next-header 89 carries
        // the 16-octet OSPFv3 common header and its body. The decoder parses the
        // header into a typed `Ospfv3` layer, dispatches the body by packet type
        // and the v3 LSAs, and is handed the registry checksum policy for the
        // decode-time IPv6 upper-layer checksum status (RFC 5340 §2.7).
        registry.bind_ipv6_next_header_with_registry(IPPROTO_OSPF, |registry, packet, payload| {
            append_ospfv3_packet_with_checksum_validation(
                packet,
                payload,
                registry.validates_checksums(),
            )
        });

        registry.bind_udp_port_with_registry(DNS_PORT, |_registry, packet, payload| {
            append_dns_packet(packet, payload)
        });
        // IKEv2 over UDP/500 (RFC 7296 §2). The UDP application dispatch passes the
        // UDP payload, which for port 500 is a complete IKE message (28-octet
        // header + payload chain); the decoder walks it into typed payload layers
        // (Raw for an unmodeled type). UDP/500 carries IKE only and never the
        // non-ESP marker (RFC 3948 §2.2), so no disambiguation is needed here.
        registry.bind_udp_port_with_registry(IKEV2_UDP_PORT, |registry, packet, payload| {
            append_ikev2_packet_with_registry(registry, packet, payload)
        });
        // IPSec NAT traversal over UDP/4500 (RFC 3948). The same flow carries both
        // UDP-encapsulated ESP and IKE, so the registry inspects the leading four
        // octets to disambiguate (RFC 3948 §2.1–§2.2):
        //
        // - **non-ESP marker** (four zero octets): an IKE message. The marker is
        //   pushed as a typed `NatTraversal` layer so it round-trips byte-exact,
        //   then the remaining bytes decode as an IKEv2 message.
        // - **a nonzero leading word**: a UDP-encapsulated ESP datagram whose
        //   leading word is a real ESP SPI (SPI 0 is reserved, RFC 4303 §2.1), so
        //   it decodes through the ESP decoder (opaque in the built-in registry).
        //
        // The binding is deliberately conservative to avoid claiming unrelated
        // traffic that merely uses port 4500: it matches only when the payload is
        // at least the ESP fixed-header length (8 octets, RFC 4303 §2). A shorter
        // payload — the RFC 3948 §4 single-octet NAT keepalive, or any short non-
        // IPSec datagram — cannot be a UDP-encapsulated ESP datagram or a
        // marker+IKE message, so it falls through to the default Raw payload.
        registry.bind_udp_with_registry(
            |ctx| {
                (ctx.source_port == NATT_UDP_PORT || ctx.destination_port == NATT_UDP_PORT)
                    && ctx.payload.len() >= ESP_HEADER_LEN
            },
            |registry, packet, payload| {
                if is_non_esp_marker(payload) {
                    // Strip the four-octet marker, preserving it as a typed layer,
                    // then decode the IKE message that follows it.
                    let marker =
                        NatTraversal::marker().bytes(payload[..NON_ESP_MARKER_LEN].to_vec());
                    let packet = packet.push(marker);
                    append_ikev2_packet_with_registry(
                        registry,
                        packet,
                        &payload[NON_ESP_MARKER_LEN..],
                    )
                } else {
                    decode_esp_with_registry_sa(registry, packet, payload)
                }
            },
        );
        // DHCPv4 decode stays deliberately conservative to avoid false
        // positives: it binds only when the UDP pair is the standard client/
        // server port pair (67/68, in either direction) AND the payload carries
        // enough BOOTP structure with the valid magic cookie. The magic-cookie
        // check is what keeps unrelated traffic that merely happens to use a
        // DHCP port from misdecoding as `Dhcpv4`.
        //
        // Intentionally unsupported port inference: RFC 8357 lets a relay agent
        // advertise a non-67 UDP source port through the relay source-port
        // sub-option (option 82, sub-option 19), and the server then directs the
        // relayed reply to that port. Inferring DHCP from such non-standard
        // ports would require trusting in-payload option data to widen the port
        // match, which would reintroduce exactly the false-positive surface the
        // magic-cookie gate exists to remove. `crafter` therefore does not infer
        // DHCP on non-67/68 port pairs; callers that need to decode those frames
        // bind the port explicitly via `bind_udp`/`bind_udp_port`.
        registry.bind_udp_with_registry(
            |ctx| {
                is_dhcpv4_port_pair(ctx.source_port, ctx.destination_port)
                    && looks_like_dhcpv4_payload(ctx.payload)
            },
            |_registry, packet, payload| append_dhcpv4_packet(packet, payload),
        );
        registry.bind_udp_with_registry(
            |ctx| looks_like_dhcpv6_payload(ctx.source_port, ctx.destination_port, ctx.payload),
            |_registry, packet, payload| append_dhcpv6_packet(packet, payload),
        );

        // RIP (RFC 1058 / RFC 2453) decode binds on UDP/520, kept conservative
        // by the `looks_like_rip_payload` shape gate (known command, version 1/2,
        // and a whole number of 20-octet entries) so unrelated traffic that
        // merely uses port 520 falls through to `Raw` rather than misdecoding as
        // `Rip`.
        registry.bind_udp_with_registry(
            |ctx| {
                (ctx.source_port == RIP_UDP_PORT || ctx.destination_port == RIP_UDP_PORT)
                    && looks_like_rip_payload(ctx.payload)
            },
            |_registry, packet, payload| append_rip_packet(packet, payload),
        );

        // RIPng (RFC 2080) decode binds on UDP/521, kept conservative by the
        // `looks_like_ripng_payload` shape gate (known command, version 1, and a
        // whole number of 20-octet RTEs) so unrelated traffic that merely uses
        // port 521 falls through to `Raw` rather than misdecoding as `Ripng`.
        registry.bind_udp_with_registry(
            |ctx| {
                (ctx.source_port == RIPNG_UDP_PORT || ctx.destination_port == RIPNG_UDP_PORT)
                    && looks_like_ripng_payload(ctx.payload)
            },
            |_registry, packet, payload| append_ripng_packet(packet, payload),
        );

        // SNMP message and notification decode binds on the source-backed
        // UDP/161 and UDP/162 ports. Port use alone is not sufficient: the BER
        // payload must pass the conservative SNMP wrapper shape check so
        // unrelated traffic on these well-known ports remains `Raw`.
        registry.bind_udp_with_registry(
            |ctx| {
                (is_snmp_udp_port(ctx.source_port) || is_snmp_udp_port(ctx.destination_port))
                    && looks_like_snmp_payload(ctx.payload)
            },
            |_registry, packet, payload| append_snmp_packet(packet, payload),
        );

        registry.bind_tcp_port_with_registry(BGP_PORT, |registry, packet, payload| {
            append_bgp_packet_with_registry(registry, packet, payload)
        });
        registry.bind_tcp_port_with_registry(MQTT_PORT, |registry, packet, payload| {
            append_mqtt_packet_with_registry(registry, packet, payload)
        });

        registry.builtin_ipv4_protocol_dispatch = true;
        registry.builtin_ipv6_next_header_dispatch = true;
        registry.builtin_udp_application_dispatch = true;

        registry
    }

    /// Create a registry that types transport headers but stops before any
    /// application-layer dispatch.
    ///
    /// Quoted original datagrams inside ICMPv4 error messages are usually only
    /// the IP header plus the first eight bytes of payload (RFC 792), so a full
    /// recursive decode would fail or drop the typed transport header the moment
    /// an application decoder (DNS, DHCP) sees a truncated prefix. This shallow
    /// registry keeps the IPv4 and transport (UDP/TCP/ICMP) headers typed while
    /// leaving their payloads raw-compatible.
    pub(crate) fn transport_only() -> Self {
        let mut registry = Self::empty();

        registry.bind_ipv4_protocol_with_registry(IPPROTO_ICMP, |_registry, packet, payload| {
            append_icmp_packet(packet, payload)
        });
        registry.bind_ipv4_protocol_with_registry(IPPROTO_TCP, |registry, packet, payload| {
            append_tcp_packet_with_registry(registry, packet, payload)
        });
        registry.bind_ipv4_protocol_with_registry(IPPROTO_UDP, |registry, packet, payload| {
            append_udp_packet_with_registry(registry, packet, payload)
        });

        registry
    }

    /// Enable or disable decode-time checksum validation for this registry.
    ///
    /// The default registry validates inspectable checksums while decoding, so
    /// decoded IPv4 and UDP layers report `Valid` or `Invalid` when enough
    /// context is present. Benchmark and header-classification workflows can
    /// opt out when they need to compare only parsing/materialization cost
    /// against decoders that do not validate checksums during parse.
    #[must_use]
    pub fn checksum_validation(mut self, enabled: bool) -> Self {
        self.validate_checksums = enabled;
        self
    }

    /// Mutably enable or disable decode-time checksum validation.
    pub fn set_checksum_validation(&mut self, enabled: bool) -> &mut Self {
        self.validate_checksums = enabled;
        self
    }

    pub(crate) const fn validates_checksums(&self) -> bool {
        self.validate_checksums
    }

    /// Enable or disable UDP/TCP application-layer decoding.
    ///
    /// When disabled, transport headers still decode normally but application
    /// payload bytes are preserved as `Raw`, bypassing built-in and custom
    /// application decoders.
    #[must_use]
    pub fn application_decoding(mut self, enabled: bool) -> Self {
        self.decode_applications = enabled;
        self
    }

    /// Mutably enable or disable UDP/TCP application-layer decoding.
    pub fn set_application_decoding(&mut self, enabled: bool) -> &mut Self {
        self.decode_applications = enabled;
        self
    }

    pub(crate) const fn decodes_applications(&self) -> bool {
        self.decode_applications
    }

    pub(crate) const fn uses_builtin_ethertype_dispatch(&self) -> bool {
        self.builtin_ethertype_dispatch
    }

    /// Decode bytes from a link-layer entrypoint.
    pub fn decode_from_link(&self, link_type: LinkType, bytes: impl AsRef<[u8]>) -> Result<Packet> {
        let bytes = bytes.as_ref();
        match link_type {
            LinkType::Raw => Packet::decode_raw(bytes),
            LinkType::Ethernet => self.decode_ethernet(bytes),
            LinkType::Ieee80211 => decode_dot11_with_registry(self, bytes),
            LinkType::Radiotap => decode_radiotap_with_registry(self, bytes),
            LinkType::BluetoothLeLl => decode_ble_ll_with_registry(self, bytes),
            // Bare 802.15.4 captures (DLT 195/230) start at the MAC frame; the
            // TAP form (DLT 283) prefixes a Dot15d4Radio pseudo-header, selected
            // by `tap`.
            LinkType::Ieee802154 => decode_dot15d4_with_registry(self, bytes, false),
            LinkType::Ieee802154Tap => decode_dot15d4_with_registry(self, bytes, true),
            LinkType::LinuxCooked | LinkType::LinuxSll => self.decode_linux_sll(bytes),
            LinkType::NullLoopback => decode_null_loopback_with_registry(self, bytes),
        }
    }

    /// Decode bytes as an Ethernet frame.
    pub fn decode_ethernet(&self, bytes: impl AsRef<[u8]>) -> Result<Packet> {
        decode_ethernet_with_registry(self, bytes.as_ref())
    }

    /// Decode bytes as a Linux cooked capture v1 frame.
    pub fn decode_linux_sll(&self, bytes: impl AsRef<[u8]>) -> Result<Packet> {
        decode_linux_sll_with_registry(self, bytes.as_ref())
    }

    /// Decode bytes from a network-layer entrypoint.
    pub fn decode_from_l3(
        &self,
        network_layer: NetworkLayer,
        bytes: impl AsRef<[u8]>,
    ) -> Result<Packet> {
        let bytes = bytes.as_ref();
        match network_layer {
            NetworkLayer::Raw => Packet::decode_raw(bytes),
            NetworkLayer::Ipv4 => self.decode_ipv4(bytes),
            NetworkLayer::Ipv6 => self.decode_ipv6(bytes),
        }
    }

    /// Decode bytes as an IPv4 packet.
    pub fn decode_ipv4(&self, bytes: impl AsRef<[u8]>) -> Result<Packet> {
        append_ipv4_packet_with_registry(self, Packet::new(), bytes.as_ref())
    }

    /// Decode bytes as an IPv6 packet.
    pub fn decode_ipv6(&self, bytes: impl AsRef<[u8]>) -> Result<Packet> {
        append_ipv6_packet_with_registry(self, Packet::new(), bytes.as_ref())
    }

    /// Register a [`SecurityAssociation`] so the ESP and AH decoders can verify
    /// and decrypt (ESP) or verify (AH) datagrams whose on-wire SPI matches it
    /// (RFC 4303 §3.4, RFC 4302 §3.4).
    ///
    /// The default built-in registry carries no SA, so ESP/AH decode opaquely:
    /// the SPI/Sequence are exposed and the encrypted body (ESP) or ICV (AH) is
    /// preserved verbatim. A caller that holds keys registers the matching SA on
    /// its own registry; the ESP/AH bindings then look the SA up by the SPI read
    /// from the wire and drive the SA-aware decode path
    /// ([`Packet::decode_from_l3_with_registry`] with this registry decrypts ESP
    /// and verifies AH). An SA is keyed by its [`SecurityAssociation::spi`]; a
    /// later registration for the same SPI takes precedence (it is matched
    /// first), mirroring how a later binding overrides an earlier one.
    ///
    /// [`Packet::decode_from_l3_with_registry`]: crate::packet::Packet::decode_from_l3_with_registry
    pub fn register_security_association(&mut self, sa: SecurityAssociation) -> &mut Self {
        self.security_associations.push(sa);
        self
    }

    /// Register a [`SecurityAssociation`] and return the owned registry, for
    /// fluent one-expression construction.
    ///
    /// This is the consuming counterpart to
    /// [`ProtocolRegistry::register_security_association`]:
    ///
    /// ```
    /// use crafter::{ProtocolRegistry, SecurityAssociation};
    /// use crafter::protocols::ipsec::sa::EncryptionAlgorithm;
    ///
    /// let registry = ProtocolRegistry::new().with_security_association(
    ///     SecurityAssociation::new(0x0000_2000)
    ///         .encryption(EncryptionAlgorithm::AesGcm16, vec![0u8; 16])
    ///         .salt(vec![0u8; 4]),
    /// );
    /// let _ = registry;
    /// ```
    #[must_use]
    pub fn with_security_association(mut self, sa: SecurityAssociation) -> Self {
        self.security_associations.push(sa);
        self
    }

    /// Find a registered [`SecurityAssociation`] by its SPI, most-recently
    /// registered first (so a later registration overrides an earlier one).
    pub(crate) fn security_association_for_spi(&self, spi: u32) -> Option<&SecurityAssociation> {
        self.security_associations
            .iter()
            .rev()
            .find(|sa| sa.spi == spi)
    }

    /// Bind an exact Ethernet type to a decoder.
    pub fn bind_ethertype<D>(&mut self, ethertype: u16, decoder: D) -> &mut Self
    where
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_ethertype_if(move |ctx| ctx.ethertype == ethertype, decoder)
    }

    /// Bind an Ethernet-type predicate to a decoder.
    pub fn bind_ethertype_if<P, D>(&mut self, predicate: P, decoder: D) -> &mut Self
    where
        P: for<'a> Fn(EthertypeBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_ethertype_if_with_registry(predicate, move |_registry, packet, payload| {
            decoder(packet, payload)
        })
    }

    /// Bind an IPv4 protocol number to a decoder.
    pub fn bind_ipv4_protocol<D>(&mut self, protocol: u8, decoder: D) -> &mut Self
    where
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_ipv4_protocol_if(move |ctx| ctx.protocol == protocol, decoder)
    }

    /// Bind an IPv4 protocol predicate to a decoder.
    pub fn bind_ipv4_protocol_if<P, D>(&mut self, predicate: P, decoder: D) -> &mut Self
    where
        P: for<'a> Fn(Ipv4ProtocolBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_ipv4_protocol_if_with_registry(predicate, move |_registry, packet, payload| {
            decoder(packet, payload)
        })
    }

    /// Bind an IPv6 next-header value to a decoder.
    pub fn bind_ipv6_next_header<D>(&mut self, next_header: u8, decoder: D) -> &mut Self
    where
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_ipv6_next_header_if(move |ctx| ctx.next_header == next_header, decoder)
    }

    /// Bind an IPv6 next-header predicate to a decoder.
    pub fn bind_ipv6_next_header_if<P, D>(&mut self, predicate: P, decoder: D) -> &mut Self
    where
        P: for<'a> Fn(Ipv6NextHeaderBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_ipv6_next_header_if_with_registry(predicate, move |_registry, packet, payload| {
            decoder(packet, payload)
        })
    }

    /// Bind a UDP source or destination port to an application decoder.
    pub fn bind_udp_port<D>(&mut self, port: u16, decoder: D) -> &mut Self
    where
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_udp(
            move |ctx| ctx.source_port == port || ctx.destination_port == port,
            decoder,
        )
    }

    /// Bind a UDP predicate to an application decoder.
    pub fn bind_udp<P, D>(&mut self, predicate: P, decoder: D) -> &mut Self
    where
        P: for<'a> Fn(UdpBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_udp_with_registry(predicate, move |_registry, packet, payload| {
            decoder(packet, payload)
        })
    }

    /// Bind a TCP source or destination port to an application decoder.
    pub fn bind_tcp_port<D>(&mut self, port: u16, decoder: D) -> &mut Self
    where
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_tcp(
            move |ctx| ctx.source_port == port || ctx.destination_port == port,
            decoder,
        )
    }

    /// Bind a TCP predicate to an application decoder.
    pub fn bind_tcp<P, D>(&mut self, predicate: P, decoder: D) -> &mut Self
    where
        P: for<'a> Fn(TcpBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(Packet, &'a [u8]) -> Result<Packet> + Send + Sync + 'static,
    {
        self.bind_tcp_with_registry(predicate, move |_registry, packet, payload| {
            decoder(packet, payload)
        })
    }

    pub(crate) fn decode_ethertype(
        &self,
        packet: Packet,
        ethertype: u16,
        payload: &[u8],
    ) -> Result<Packet> {
        if self.builtin_ethertype_dispatch {
            return match ethertype {
                ETHERTYPE_ARP => append_arp_packet(packet, payload),
                ETHERTYPE_VLAN => append_vlan_packet_with_registry(self, packet, payload),
                ETHERTYPE_IPV4 => append_ipv4_packet_with_registry(self, packet, payload),
                ETHERTYPE_IPV6 => append_ipv6_packet_with_registry(self, packet, payload),
                ETHERTYPE_EAPOL => append_eapol_packet(packet, payload),
                _ => Ok(packet.push_raw(Raw::from_bytes(payload))),
            };
        }

        let ctx = EthertypeBindingContext { ethertype, payload };
        if let Some(binding) = self
            .ethertype_bindings
            .iter()
            .rev()
            .find(|binding| (binding.predicate)(ctx))
        {
            return (binding.decoder)(self, packet, payload);
        }
        Ok(packet.push_raw(Raw::from_bytes(payload)))
    }

    pub(crate) fn decode_ipv4_protocol(
        &self,
        packet: Packet,
        protocol: u8,
        payload: &[u8],
    ) -> Result<Packet> {
        if self.builtin_ipv4_protocol_dispatch {
            return match protocol {
                IPPROTO_ICMP => append_icmp_packet_with_checksum_validation(
                    packet,
                    payload,
                    self.validates_checksums(),
                ),
                IPPROTO_TCP => append_tcp_packet_with_registry(self, packet, payload),
                IPPROTO_UDP => append_udp_packet_with_registry(self, packet, payload),
                IPPROTO_IGMP => append_igmp_packet(packet, payload),
                IPPROTO_ESP => decode_esp_with_registry_sa(self, packet, payload),
                IPPROTO_AH => decode_ah_with_registry_sa(self, packet, payload),
                IPPROTO_OSPF => append_ospf_packet_with_checksum_validation(
                    packet,
                    payload,
                    self.validates_checksums(),
                ),
                _ => append_raw_if_needed(packet, payload),
            };
        }

        let ctx = Ipv4ProtocolBindingContext { protocol, payload };
        if let Some(binding) = self
            .ipv4_bindings
            .iter()
            .rev()
            .find(|binding| (binding.predicate)(ctx))
        {
            return (binding.decoder)(self, packet, payload);
        }
        append_raw_if_needed(packet, payload)
    }

    pub(crate) fn decode_ipv6_next_header(
        &self,
        packet: Packet,
        next_header: u8,
        payload: &[u8],
    ) -> Result<Packet> {
        if self.builtin_ipv6_next_header_dispatch {
            return match next_header {
                IPPROTO_ICMPV6 => append_icmpv6_packet(packet, payload),
                IPPROTO_TCP => append_tcp_packet_with_registry(self, packet, payload),
                IPPROTO_UDP => append_udp_packet_with_registry(self, packet, payload),
                IPPROTO_IPV6_ESP => decode_esp_with_registry_sa(self, packet, payload),
                IPPROTO_IPV6_AH => decode_ah_with_registry_sa(self, packet, payload),
                IPPROTO_OSPF => append_ospfv3_packet_with_checksum_validation(
                    packet,
                    payload,
                    self.validates_checksums(),
                ),
                _ => append_raw_if_needed(packet, payload),
            };
        }

        let ctx = Ipv6NextHeaderBindingContext {
            next_header,
            payload,
        };
        if let Some(binding) = self
            .ipv6_bindings
            .iter()
            .rev()
            .find(|binding| (binding.predicate)(ctx))
        {
            return (binding.decoder)(self, packet, payload);
        }
        append_raw_if_needed(packet, payload)
    }

    pub(crate) fn decode_udp_application(
        &self,
        packet: Packet,
        source_port: u16,
        destination_port: u16,
        payload: &[u8],
    ) -> Result<Packet> {
        if !self.decode_applications {
            return append_raw_if_needed(packet, payload);
        }

        if self.builtin_udp_application_dispatch {
            if is_dhcpv4_port_pair(source_port, destination_port)
                && looks_like_dhcpv4_payload(payload)
            {
                return append_dhcpv4_packet(packet, payload);
            }

            if looks_like_dhcpv6_payload(source_port, destination_port, payload) {
                return append_dhcpv6_packet(packet, payload);
            }

            if (source_port == RIP_UDP_PORT || destination_port == RIP_UDP_PORT)
                && looks_like_rip_payload(payload)
            {
                return append_rip_packet(packet, payload);
            }

            if (source_port == RIPNG_UDP_PORT || destination_port == RIPNG_UDP_PORT)
                && looks_like_ripng_payload(payload)
            {
                return append_ripng_packet(packet, payload);
            }

            if (is_snmp_udp_port(source_port) || is_snmp_udp_port(destination_port))
                && looks_like_snmp_payload(payload)
            {
                return append_snmp_packet(packet, payload);
            }

            if (source_port == NATT_UDP_PORT || destination_port == NATT_UDP_PORT)
                && payload.len() >= ESP_HEADER_LEN
            {
                if is_non_esp_marker(payload) {
                    let marker =
                        NatTraversal::marker().bytes(payload[..NON_ESP_MARKER_LEN].to_vec());
                    let packet = packet.push(marker);
                    return append_ikev2_packet_with_registry(
                        self,
                        packet,
                        &payload[NON_ESP_MARKER_LEN..],
                    );
                }
                return decode_esp_with_registry_sa(self, packet, payload);
            }

            if source_port == IKEV2_UDP_PORT || destination_port == IKEV2_UDP_PORT {
                return append_ikev2_packet_with_registry(self, packet, payload);
            }

            if source_port == DNS_PORT || destination_port == DNS_PORT {
                return append_dns_packet(packet, payload);
            }

            if is_quic_default_port_pair(source_port, destination_port)
                && looks_like_quic_udp_payload(payload)
            {
                return append_quic_packet(packet, payload);
            }

            return append_raw_if_needed(packet, payload);
        }

        let ctx = UdpBindingContext {
            source_port,
            destination_port,
            payload,
        };
        if let Some(binding) = self
            .udp_bindings
            .iter()
            .rev()
            .find(|binding| (binding.predicate)(ctx))
        {
            return (binding.decoder)(self, packet, payload);
        }
        append_raw_if_needed(packet, payload)
    }

    pub(crate) fn decode_tcp_application(
        &self,
        packet: Packet,
        source_port: u16,
        destination_port: u16,
        payload: &[u8],
    ) -> Result<Packet> {
        if !self.decode_applications {
            return append_raw_if_needed(packet, payload);
        }

        let ctx = TcpBindingContext {
            source_port,
            destination_port,
            payload,
        };
        if let Some(binding) = self
            .tcp_bindings
            .iter()
            .rev()
            .find(|binding| (binding.predicate)(ctx))
        {
            return (binding.decoder)(self, packet, payload);
        }
        append_raw_if_needed(packet, payload)
    }

    pub(crate) fn bind_ethertype_with_registry<D>(
        &mut self,
        ethertype: u16,
        decoder: D,
    ) -> &mut Self
    where
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.bind_ethertype_if_with_registry(move |ctx| ctx.ethertype == ethertype, decoder)
    }

    pub(crate) fn bind_ethertype_if_with_registry<P, D>(
        &mut self,
        predicate: P,
        decoder: D,
    ) -> &mut Self
    where
        P: for<'a> Fn(EthertypeBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.builtin_ethertype_dispatch = false;
        self.ethertype_bindings.push(EthertypeBinding {
            predicate: Box::new(predicate),
            decoder: Box::new(decoder),
        });
        self
    }

    pub(crate) fn bind_ipv4_protocol_with_registry<D>(
        &mut self,
        protocol: u8,
        decoder: D,
    ) -> &mut Self
    where
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.bind_ipv4_protocol_if_with_registry(move |ctx| ctx.protocol == protocol, decoder)
    }

    pub(crate) fn bind_ipv4_protocol_if_with_registry<P, D>(
        &mut self,
        predicate: P,
        decoder: D,
    ) -> &mut Self
    where
        P: for<'a> Fn(Ipv4ProtocolBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.ipv4_bindings.push(Ipv4ProtocolBinding {
            predicate: Box::new(predicate),
            decoder: Box::new(decoder),
        });
        self.builtin_ipv4_protocol_dispatch = false;
        self
    }

    pub(crate) fn bind_ipv6_next_header_with_registry<D>(
        &mut self,
        next_header: u8,
        decoder: D,
    ) -> &mut Self
    where
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.bind_ipv6_next_header_if_with_registry(
            move |ctx| ctx.next_header == next_header,
            decoder,
        )
    }

    pub(crate) fn bind_ipv6_next_header_if_with_registry<P, D>(
        &mut self,
        predicate: P,
        decoder: D,
    ) -> &mut Self
    where
        P: for<'a> Fn(Ipv6NextHeaderBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.ipv6_bindings.push(Ipv6NextHeaderBinding {
            predicate: Box::new(predicate),
            decoder: Box::new(decoder),
        });
        self.builtin_ipv6_next_header_dispatch = false;
        self
    }

    pub(crate) fn bind_udp_port_with_registry<D>(&mut self, port: u16, decoder: D) -> &mut Self
    where
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.bind_udp_with_registry(
            move |ctx| ctx.source_port == port || ctx.destination_port == port,
            decoder,
        )
    }

    pub(crate) fn bind_udp_with_registry<P, D>(&mut self, predicate: P, decoder: D) -> &mut Self
    where
        P: for<'a> Fn(UdpBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.udp_bindings.push(UdpBinding {
            predicate: Box::new(predicate),
            decoder: Box::new(decoder),
        });
        self.builtin_udp_application_dispatch = false;
        self
    }

    pub(crate) fn bind_tcp_port_with_registry<D>(&mut self, port: u16, decoder: D) -> &mut Self
    where
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.bind_tcp_with_registry(
            move |ctx| ctx.source_port == port || ctx.destination_port == port,
            decoder,
        )
    }

    pub(crate) fn bind_tcp_with_registry<P, D>(&mut self, predicate: P, decoder: D) -> &mut Self
    where
        P: for<'a> Fn(TcpBindingContext<'a>) -> bool + Send + Sync + 'static,
        D: for<'a> Fn(&'a ProtocolRegistry, Packet, &'a [u8]) -> Result<Packet>
            + Send
            + Sync
            + 'static,
    {
        self.tcp_bindings.push(TcpBinding {
            predicate: Box::new(predicate),
            decoder: Box::new(decoder),
        });
        self
    }
}

fn is_quic_default_port_pair(source_port: u16, destination_port: u16) -> bool {
    matches!(source_port, QUIC_HTTPS_UDP_PORT | QUIC_EXAMPLE_UDP_PORT)
        || matches!(
            destination_port,
            QUIC_HTTPS_UDP_PORT | QUIC_EXAMPLE_UDP_PORT
        )
}

impl Default for ProtocolRegistry {
    fn default() -> Self {
        Self::with_builtin_bindings()
    }
}

fn append_raw_if_needed(packet: Packet, payload: &[u8]) -> Result<Packet> {
    if payload.is_empty() {
        Ok(packet)
    } else {
        Ok(packet.push_raw(Raw::from_bytes(payload)))
    }
}

/// Decode an ESP datagram, consulting the registry's registered SAs (RFC 4303).
///
/// The ESP Security Parameters Index is the leading four octets of the datagram
/// (RFC 4303 §2.1). When a [`SecurityAssociation`] registered with
/// [`ProtocolRegistry::register_security_association`] matches that SPI, the
/// SA-aware path verifies the ICV, decrypts, strips the RFC 4303 §2.4 padding,
/// and dispatches the inner protocol (transport) or inner IP (tunnel); an
/// integrity failure surfaces a structured error and the decode fails closed.
/// When no SA matches — the default SA-less registry — the opaque path runs:
/// the SPI/Sequence are exposed and the encrypted body is preserved verbatim.
/// A buffer too short to even hold the SPI falls through to the opaque decode,
/// which reports the structured truncation error.
fn decode_esp_with_registry_sa(
    registry: &ProtocolRegistry,
    packet: Packet,
    payload: &[u8],
) -> Result<Packet> {
    let sa = read_u32_be(payload.get(0..4).unwrap_or(payload))
        .ok()
        .and_then(|spi| registry.security_association_for_spi(spi));
    append_esp_packet_with_registry_sa(registry, packet, payload, sa)
}

/// Decode an AH datagram, consulting the registry's registered SAs (RFC 4302).
///
/// The AH Security Parameters Index follows the Next Header, Payload Len, and
/// Reserved fields, occupying octets 4..8 of the datagram (RFC 4302 §2.4). When
/// a [`SecurityAssociation`] registered with
/// [`ProtocolRegistry::register_security_association`] matches that SPI, the
/// SA-aware path verifies the ICV over the canonicalized immutable IP fields,
/// the ICV-zeroed AH header, and the cleartext upper-layer data, recording the
/// verified status on the recovered [`Ah`] layer; a mismatch fails closed with a
/// structured error. When no SA matches — the default SA-less registry — the
/// opaque path recovers the typed header and inner protocol without verifying.
/// AH never encrypts, so the inner layers are recovered the same either way.
///
/// [`Ah`]: crate::protocols::ipsec::ah::Ah
fn decode_ah_with_registry_sa(
    registry: &ProtocolRegistry,
    packet: Packet,
    payload: &[u8],
) -> Result<Packet> {
    let sa = payload
        .get(4..8)
        .and_then(|spi_bytes| read_u32_be(spi_bytes).ok())
        .and_then(|spi| registry.security_association_for_spi(spi));
    append_ah_packet_with_registry_sa(registry, packet, payload, sa)
}

#[cfg(test)]
mod protocol_registry {
    use super::ProtocolRegistry;
    use crate::protocols::igmp::Igmp;
    use crate::protocols::ip::shared::IPPROTO_IGMP;
    use crate::{Ipv4, Ipv4ChecksumStatus, NetworkLayer, Packet, Raw, Udp, UdpChecksumStatus};

    #[test]
    fn custom_ipv4_protocol_binding_decodes_without_global_state() {
        let mut registry = ProtocolRegistry::empty();
        registry.bind_ipv4_protocol(253, |packet, payload| {
            Ok(packet.push(Raw::from_bytes(payload)))
        });

        let bytes = (Ipv4::new().protocol(253) / Raw::from("agent-proto"))
            .compile()
            .unwrap();
        let decoded = registry
            .decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .unwrap();

        assert_eq!(decoded.layer::<Raw>().unwrap().as_bytes(), b"agent-proto");
        assert!(Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .unwrap()
            .layer::<Raw>()
            .is_some());
    }

    #[test]
    fn later_bindings_override_builtins_for_that_registry_only() {
        let mut registry = ProtocolRegistry::new();
        registry.bind_udp_port(crate::DNS_PORT, |packet, payload| {
            Ok(packet.push(Raw::from_bytes(payload)))
        });

        let bytes = (Ipv4::new()
            / crate::Udp::new().sport(53001).dport(crate::DNS_PORT)
            / crate::Dns::a_query("example.com."))
        .compile()
        .unwrap();
        let custom = registry
            .decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .unwrap();
        let builtin = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();

        assert!(custom.layer::<crate::Dns>().is_none());
        assert!(custom.layer::<Raw>().is_some());
        assert!(builtin.layer::<crate::Dns>().is_some());
    }

    #[test]
    fn registry_can_skip_application_decoding() {
        let bytes = (Ipv4::new()
            / crate::Udp::new().sport(53001).dport(crate::DNS_PORT)
            / crate::Dns::a_query("example.com."))
        .compile()
        .unwrap();
        let registry = ProtocolRegistry::new().application_decoding(false);

        let decoded = registry
            .decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .unwrap();

        assert!(decoded.layer::<crate::Udp>().is_some());
        assert!(decoded.layer::<crate::Dns>().is_none());
        assert!(decoded.layer::<Raw>().is_some());
        assert!(Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .unwrap()
            .layer::<crate::Dns>()
            .is_some());
    }

    /// IP protocol 89 dispatches to the OSPF decoder through the default
    /// registry: an `Ipv4 / Ospfv2` Hello round-trips byte-for-byte and exposes
    /// a typed `Ospfv2` layer when decoded via the public `Packet` entrypoint.
    #[test]
    fn default_registry_decodes_ospf_over_ipv4() {
        use core::net::Ipv4Addr;

        use crate::protocols::ospf::decode::{
            append_ospf_packet, append_ospf_packet_with_checksum_validation,
        };
        use crate::protocols::ospf::Ospfv2;

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(192, 0, 2, 2))
            / Ospfv2::hello())
        .compile()
        .expect("Ipv4 / Ospfv2 Hello compiles");

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .expect("the default registry decodes OSPF over IPv4");
        assert!(
            decoded.layer::<Ospfv2>().is_some(),
            "the decoded packet exposes a typed Ospfv2 layer"
        );

        let recompiled = decoded.compile().expect("decoded OSPF re-compiles");
        assert_eq!(recompiled.as_bytes(), bytes.as_bytes());

        // The checksum-aware and plain decode entrypoints are both reachable
        // from the registry module: feed the OSPF payload (after the IPv4
        // header) to each and confirm both surface the typed layer.
        let ipv4_header_len = (bytes.as_bytes()[0] & 0x0f) as usize * 4;
        let ospf_payload = &bytes.as_bytes()[ipv4_header_len..];
        assert!(append_ospf_packet(Packet::new(), ospf_payload)
            .expect("append_ospf_packet decodes the payload")
            .layer::<Ospfv2>()
            .is_some());
        assert!(
            append_ospf_packet_with_checksum_validation(Packet::new(), ospf_payload, false)
                .expect("append_ospf_packet_with_checksum_validation decodes the payload")
                .layer::<Ospfv2>()
                .is_some()
        );
    }

    #[test]
    fn registry_can_skip_decode_checksum_validation() {
        let bytes = (Ipv4::new() / Udp::new().sport(53001).dport(9000) / Raw::from("payload"))
            .compile()
            .unwrap();
        let registry = ProtocolRegistry::new().checksum_validation(false);

        let decoded = registry
            .decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .unwrap();

        assert_eq!(
            decoded.layer::<Ipv4>().unwrap().checksum_status(),
            Ipv4ChecksumStatus::NotChecked
        );
        assert_eq!(
            decoded.layer::<Udp>().unwrap().checksum_status(),
            UdpChecksumStatus::NotChecked
        );
        assert_eq!(
            Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
                .unwrap()
                .layer::<Udp>()
                .unwrap()
                .checksum_status(),
            UdpChecksumStatus::Valid
        );
    }

    #[test]
    fn igmp_registry_binding_default_l3_decode_produces_ipv4_igmp() {
        let bytes = (Ipv4::new().protocol(IPPROTO_IGMP) / Igmp::membership_query())
            .compile()
            .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();

        assert_eq!(decoded.len(), 2);
        assert!(decoded
            .get(0)
            .is_some_and(|layer| layer.as_any().is::<Ipv4>()));
        assert!(decoded
            .get(1)
            .is_some_and(|layer| layer.as_any().is::<Igmp>()));
        assert!(decoded.layer::<Raw>().is_none());
    }

    #[test]
    fn igmp_registry_binding_empty_registry_preserves_payload_as_raw() {
        let bytes = (Ipv4::new().protocol(IPPROTO_IGMP) / Igmp::membership_query())
            .compile()
            .unwrap();
        let registry = ProtocolRegistry::empty();

        let decoded = registry
            .decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
            .unwrap();

        let raw = decoded
            .layer::<Raw>()
            .expect("empty registry raw IGMP payload");
        assert_eq!(decoded.len(), 2);
        assert!(decoded.layer::<Igmp>().is_none());
        assert_eq!(raw.as_bytes(), &bytes.as_bytes()[20..]);
    }
}

#[cfg(test)]
mod decode_dispatch {
    use super::ProtocolRegistry;
    use crate::{Ethernet, Ipv4, Ipv4Protocol, LinkType, NetworkLayer, Packet, Raw, Udp};

    #[test]
    fn default_registry_dispatches_from_ethernet_to_ipv4_udp() {
        let bytes = (Ethernet::new()
            / Ipv4::new().ipv4_protocol(Ipv4Protocol::Udp)
            / Udp::new().sport(53002).dport(9999)
            / Raw::from("payload"))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_link(LinkType::Ethernet, bytes.as_bytes()).unwrap();

        assert!(decoded.layer::<Ethernet>().is_some());
        assert!(decoded.layer::<Ipv4>().is_some());
        assert!(decoded.layer::<Udp>().is_some());
        assert_eq!(decoded.layer::<Raw>().unwrap().as_bytes(), b"payload");
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes.as_bytes());
    }

    #[test]
    fn registry_ble_decode_from_link_builds_radio_and_advertising_layers() {
        let frame = [
            37, 0xc4, 0x00, 0x00, 0xd6, 0xbe, 0x89, 0x8e, 0x13, 0x0c, 0xd6, 0xbe, 0x89, 0x8e, 0x40,
            0x0f, 0x01, 0x53, 0x00, 0x5e, 0x00, 0x02, 0x02, 0x01, 0x06, 0x05, 0x09, b't', b'e',
            b's', b't',
        ];

        let decoded = ProtocolRegistry::new()
            .decode_from_link(LinkType::BluetoothLeLl, frame)
            .unwrap();

        assert_eq!(decoded.iter().count(), 2);
        let radio = decoded.get(0).unwrap();
        let adv = decoded.get(1).unwrap();
        assert_eq!(radio.name(), "BleRadio");
        assert!(radio.summary().contains("ch=37"));
        assert!(radio.summary().contains("aa=0x8e89bed6"));
        assert_eq!(adv.name(), "BleLlAdv");
        assert_eq!(
            adv.summary(),
            "BleLlAdv(ADV_IND, AdvA=02:00:5E:00:53:01, len=15)"
        );
        assert!(decoded.layer::<Raw>().is_none());
    }

    #[test]
    fn explicit_registry_decodes_ipv4_and_ipv6_custom_protocols() {
        let mut registry = ProtocolRegistry::new();
        registry.bind_ipv4_protocol(254, |packet, payload| {
            Ok(packet.push(Raw::from_bytes(payload)))
        });
        registry.bind_ipv6_next_header(253, |packet, payload| {
            Ok(packet.push(Raw::from_bytes(payload)))
        });

        let ipv4_bytes = (Ipv4::new().protocol(254) / Raw::from("v4-private"))
            .compile()
            .unwrap();
        let ipv6_bytes = (crate::Ipv6::new().nh(253) / Raw::from("v6-private"))
            .compile()
            .unwrap();

        let ipv4 = Packet::decode_from_l3_with_registry(&registry, NetworkLayer::Ipv4, ipv4_bytes)
            .unwrap();
        let ipv6 = Packet::decode_from_l3_with_registry(&registry, NetworkLayer::Ipv6, ipv6_bytes)
            .unwrap();

        assert_eq!(ipv4.layer::<Raw>().unwrap().as_bytes(), b"v4-private");
        assert_eq!(ipv6.layer::<Raw>().unwrap().as_bytes(), b"v6-private");
    }
}

#[cfg(test)]
mod registry_dot15d4 {
    use crate::protocols::link::{Dot15d4, Dot15d4Radio, ZigbeeAps, ZigbeeNwk};
    use crate::{LinkType, Packet, Raw};

    /// A full radio + MAC + Zigbee NWK + APS stack built with the builder API,
    /// using lab-safe documentation-style identifiers.
    fn full_stack_packet() -> Packet {
        Dot15d4Radio::on_channel(20).rssi(-55)
            / Dot15d4::data()
                .seq(9)
                .dest_short(0x1234, 0x0000)
                .src_short(0x1234, 0xABCD)
            / ZigbeeNwk::data().dest(0x0000).src(0xABCD).radius(30).seq(5)
            / ZigbeeAps::data()
                .cluster(0x0006)
                .profile(0x0104)
                .dest_endpoint(1)
                .src_endpoint(1)
                .counter(7)
                .payload(&[0x01, 0x02])
    }

    #[test]
    fn decode_from_link_tap_routes_to_dot15d4_entrypoint() {
        // A TAP capture (DLT 283) prefixes a Dot15d4Radio pseudo-header; the
        // public decode_from_link path must yield the radio + MAC + Zigbee
        // layers.
        let compiled = full_stack_packet()
            .compile()
            .expect("compile TAP + MAC + NWK + APS stack");

        let decoded = Packet::decode_from_link(LinkType::Ieee802154Tap, compiled.as_bytes())
            .expect("decode TAP 802.15.4 frame via decode_from_link");

        assert!(
            decoded.layer::<Dot15d4Radio>().is_some(),
            "Dot15d4Radio layer present"
        );
        assert!(
            decoded.layer::<Dot15d4>().is_some(),
            "Dot15d4 MAC layer present"
        );
        assert!(
            decoded.layer::<ZigbeeNwk>().is_some(),
            "ZigbeeNwk layer present"
        );
        assert!(
            decoded.layer::<ZigbeeAps>().is_some(),
            "ZigbeeAps layer present"
        );
        assert_eq!(
            decoded
                .layer::<Raw>()
                .expect("APS payload preserved as Raw")
                .as_bytes(),
            &[0x01, 0x02]
        );
    }

    #[test]
    fn decode_from_link_bare_mac_skips_radio_descriptor() {
        // A bare capture (DLT 195/230) starts at the MAC frame, so no radio
        // descriptor is emitted, but the MAC + Zigbee layers still decode.
        let mac_only = (Dot15d4::data()
            .seq(9)
            .dest_short(0x1234, 0x0000)
            .src_short(0x1234, 0xABCD)
            / ZigbeeNwk::data().dest(0x0000).src(0xABCD).radius(30).seq(5)
            / ZigbeeAps::data()
                .cluster(0x0006)
                .profile(0x0104)
                .dest_endpoint(1)
                .src_endpoint(1)
                .counter(7)
                .payload(&[0x01, 0x02]))
        .compile()
        .expect("compile bare MAC + NWK + APS frame");

        let decoded = Packet::decode_from_link(LinkType::Ieee802154, mac_only.as_bytes())
            .expect("decode bare 802.15.4 frame via decode_from_link");

        assert!(
            decoded.layer::<Dot15d4Radio>().is_none(),
            "no radio descriptor for bare frame"
        );
        assert!(
            decoded.layer::<Dot15d4>().is_some(),
            "Dot15d4 MAC layer present"
        );
        assert!(
            decoded.layer::<ZigbeeNwk>().is_some(),
            "ZigbeeNwk layer present"
        );
        assert!(
            decoded.layer::<ZigbeeAps>().is_some(),
            "ZigbeeAps layer present"
        );
    }

    #[test]
    fn decode_from_link_truncated_buffer_is_structured_error() {
        // A buffer too short to hold a MAC frame control field must surface as a
        // structured decode error, never a panic.
        let err = Packet::decode_from_link(LinkType::Ieee802154, [0x01u8])
            .expect_err("truncated 802.15.4 buffer must error");
        let rendered = err.to_string();
        assert!(
            !rendered.is_empty(),
            "structured error renders a non-empty message: {rendered}"
        );

        // The TAP form is equally resilient to a truncated radio pseudo-header.
        assert!(
            Packet::decode_from_link(LinkType::Ieee802154Tap, [0x00u8, 0x00]).is_err(),
            "truncated TAP pseudo-header must error",
        );
    }
}

#[cfg(test)]
mod esp_protocol_binding {
    use crate::protocols::ipsec::esp::Esp;
    use crate::protocols::ipv4::IPPROTO_ESP;
    use crate::protocols::ipv6::IPPROTO_IPV6_ESP;
    use crate::{Ipv4, Ipv6, NetworkLayer, Packet, Raw};

    #[test]
    fn default_registry_decodes_ipv4_protocol_50_as_opaque_esp() {
        // The built-in registry has no SA, so IP protocol 50 must decode via the
        // opaque ESP path: the SPI/Sequence are exposed and the body is preserved
        // verbatim. The enclosing IPv4 protocol is pinned to 50 (auto-deriving 50
        // from an inner Esp is not wired; prior ESP tests set it explicitly too).
        let bytes = (Ipv4::new().protocol(IPPROTO_ESP)
            / Esp::new().spi(0x0000_2000).sequence(7)
            / Raw::from_bytes(vec![0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();

        // First layer is the IPv4 header; the second is the typed Esp.
        assert!(decoded.layer::<Ipv4>().is_some());
        let esp = decoded
            .get(1)
            .unwrap()
            .as_any()
            .downcast_ref::<Esp>()
            .expect("second layer is Esp");
        assert_eq!(esp.spi_value(), Some(0x0000_2000));
        assert_eq!(esp.sequence_value(), Some(7));
        // No SA in the built-in registry: the body is carried opaquely.
        assert!(esp.opaque_body().is_some());

        // The decoded packet re-compiles byte-for-byte.
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes.as_bytes());
    }

    #[test]
    fn default_registry_decodes_ipv6_next_header_50_as_opaque_esp() {
        let bytes = (Ipv6::new().nh(IPPROTO_IPV6_ESP)
            / Esp::new().spi(0x0000_3000).sequence(9)
            / Raw::from_bytes(vec![0xAA, 0xBB, 0xCC, 0xDD, 0x10, 0x20, 0x30, 0x40]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv6, bytes.as_bytes()).unwrap();

        assert!(decoded.layer::<Ipv6>().is_some());
        let esp = decoded
            .get(1)
            .unwrap()
            .as_any()
            .downcast_ref::<Esp>()
            .expect("second layer is Esp");
        assert_eq!(esp.spi_value(), Some(0x0000_3000));
        assert_eq!(esp.sequence_value(), Some(9));
        assert!(esp.opaque_body().is_some());

        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes.as_bytes());
    }
}

#[cfg(test)]
mod ah_protocol_binding {
    use crate::protocols::ipsec::ah::Ah;
    use crate::protocols::ipsec::sa::{IntegrityAlgorithm, SecurityAssociation};
    use crate::protocols::ipv4::{IPPROTO_AH, IPPROTO_TCP};
    use crate::protocols::ipv6::IPPROTO_IPV6_AH;
    use crate::{Ipv4, Ipv6, NetworkLayer, Packet, Raw, Tcp};

    /// An HMAC-SHA-256-128 (RFC 4868) integrity-only SA with a fixed
    /// documentation key. AH only authenticates, so the built-in registry can
    /// recover the inner protocol in the clear without ever holding this SA.
    fn ah_sa() -> SecurityAssociation {
        SecurityAssociation::new(0x0000_2000)
            .integrity(IntegrityAlgorithm::HmacSha2_256_128, vec![0x77u8; 32])
    }

    #[test]
    fn default_registry_decodes_ipv4_protocol_51_as_ah_with_inner_tcp() {
        // The enclosing IPv4 protocol is pinned to AH (51); the AH header is
        // sealed by the SA, but the protected Tcp / Raw travels in the clear.
        let bytes = (Ipv4::new()
            .protocol(IPPROTO_AH)
            .src("192.0.2.1".parse().unwrap())
            .dst("192.0.2.2".parse().unwrap())
            .ttl(64)
            / Ah::secured(ah_sa()).spi(0x0000_2000).sequence(1)
            / Tcp::new().sport(1234).dport(443)
            / Raw::from_bytes(vec![0xDE, 0xAD, 0xBE, 0xEF]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();

        // IPv4 header, then the typed Ah, then the cleartext inner Tcp / Raw.
        assert!(decoded.layer::<Ipv4>().is_some());
        let ah = decoded
            .get(1)
            .unwrap()
            .as_any()
            .downcast_ref::<Ah>()
            .expect("second layer is Ah");
        assert_eq!(ah.spi_value(), Some(0x0000_2000));
        assert_eq!(ah.sequence_value(), Some(1));
        assert_eq!(ah.next_header_value(), Some(IPPROTO_TCP));
        // The built-in registry has no SA, so the ICV is preserved verbatim and
        // never verified.
        assert_eq!(ah.verification_status(), None);

        let tcp = decoded
            .layer::<Tcp>()
            .expect("inner Tcp decoded in the clear");
        assert_eq!(tcp.source_port_value(), 1234);
        assert_eq!(tcp.destination_port_value(), 443);
        assert_eq!(
            decoded
                .layer::<Raw>()
                .expect("inner Raw decoded")
                .as_bytes(),
            &[0xDE, 0xAD, 0xBE, 0xEF]
        );

        // The decoded packet re-compiles byte-for-byte.
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes.as_bytes());
    }

    #[test]
    fn default_registry_decodes_ipv6_next_header_51_as_ah_with_inner_tcp() {
        let bytes = (Ipv6::new()
            .nh(IPPROTO_IPV6_AH)
            .src("2001:db8::1".parse().unwrap())
            .dst("2001:db8::2".parse().unwrap())
            .hop_limit(64)
            / Ah::secured(ah_sa()).spi(0x0000_3000).sequence(9)
            / Tcp::new().sport(2345).dport(80)
            / Raw::from_bytes(vec![0xAA, 0xBB, 0xCC, 0xDD]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv6, bytes.as_bytes()).unwrap();

        assert!(decoded.layer::<Ipv6>().is_some());
        let ah = decoded
            .get(1)
            .unwrap()
            .as_any()
            .downcast_ref::<Ah>()
            .expect("second layer is Ah");
        assert_eq!(ah.spi_value(), Some(0x0000_3000));
        assert_eq!(ah.sequence_value(), Some(9));
        assert_eq!(ah.next_header_value(), Some(IPPROTO_TCP));
        assert_eq!(ah.verification_status(), None);

        let tcp = decoded
            .layer::<Tcp>()
            .expect("inner Tcp decoded in the clear");
        assert_eq!(tcp.source_port_value(), 2345);
        assert_eq!(tcp.destination_port_value(), 80);
        assert_eq!(
            decoded
                .layer::<Raw>()
                .expect("inner Raw decoded")
                .as_bytes(),
            &[0xAA, 0xBB, 0xCC, 0xDD]
        );

        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes.as_bytes());
    }

    #[test]
    fn ah_in_ipv6_decodes_after_a_preceding_extension_header() {
        use crate::protocols::ipv6::Ipv6DestinationOptionsHeader;
        use crate::Ipv6Option;

        // AH following another IPv6 extension header: the next-header chain walk
        // must reach the AH binding. First build a real AH datagram (the AH
        // header + ICV followed by the cleartext Tcp / Raw) from a direct
        // `Ipv6(nh=AH) / Ah / Tcp / Raw` stack, then capture the bytes that
        // follow the IPv6 base header — i.e. the AH-onward wire bytes.
        let direct = (Ipv6::new()
            .nh(IPPROTO_IPV6_AH)
            .src("2001:db8::1".parse().unwrap())
            .dst("2001:db8::2".parse().unwrap())
            .hop_limit(64)
            / Ah::secured(ah_sa()).spi(0x0000_4000).sequence(3)
            / Tcp::new().sport(3456).dport(8080)
            / Raw::from_bytes(vec![0x11, 0x22, 0x33, 0x44]))
        .compile()
        .unwrap();
        // Strip the 40-octet IPv6 base header to leave the AH datagram bytes.
        let ah_datagram = direct.as_bytes()[40..].to_vec();

        // Place the AH datagram after a Destination Options extension header
        // whose own Next Header advertises AH (51). The IPv6 base header points
        // at the Destination Options header, so the registry's extension-header
        // chain walk advances base -> Destination Options -> next-header 51,
        // reaching the AH binding for the trailing bytes.
        let bytes = (Ipv6::new()
            .src("2001:db8::1".parse().unwrap())
            .dst("2001:db8::2".parse().unwrap())
            .hop_limit(64)
            / Ipv6DestinationOptionsHeader::new()
                .nh(IPPROTO_IPV6_AH)
                .option(Ipv6Option::pad1())
            / Raw::from_bytes(ah_datagram))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv6, bytes.as_bytes()).unwrap();

        // The chain walk reaches the AH binding after the Destination Options
        // header, producing a typed `Ah` (not a `Raw` tail).
        let ah = decoded
            .layer::<Ah>()
            .expect("Ah decoded after the extension header");
        assert_eq!(ah.spi_value(), Some(0x0000_4000));
        assert_eq!(ah.next_header_value(), Some(IPPROTO_TCP));

        let tcp = decoded
            .layer::<Tcp>()
            .expect("inner Tcp decoded in the clear");
        assert_eq!(tcp.source_port_value(), 3456);
        assert_eq!(tcp.destination_port_value(), 8080);

        // This case confirms the decode side: the IPv6 extension-header chain
        // walk advances past the Destination Options header and dispatches
        // next-header 51 to the AH binding. (A byte-exact re-compile is asserted
        // by the two direct `Ipv4 / Ah / Tcp` and `Ipv6 / Ah / Tcp` cases above;
        // `Ah::compile` reads only its immediately preceding layer for the IP
        // version, so re-emitting AH that sits *behind* an extension header is a
        // separate build-side concern, not part of registry dispatch.)
    }
}

#[cfg(test)]
mod dns_udp_binding {
    use super::ProtocolRegistry;
    use crate::{Dns, DnsQuestion, Ipv4, NetworkLayer, Packet, Raw, Udp, DNS_PORT, DNS_TYPE_AAAA};

    #[test]
    fn default_registry_decodes_dns_on_udp_53() {
        let bytes = (Ipv4::new()
            / Udp::new().sport(53001).dport(DNS_PORT)
            / Dns::new().question(DnsQuestion::new("example.org.", DNS_TYPE_AAAA)))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();

        assert_eq!(dns.questions()[0].name(), "example.org.");
        assert_eq!(dns.questions()[0].question_type(), DNS_TYPE_AAAA);
    }

    #[test]
    fn custom_udp_port_binding_decodes_application_payload() {
        let mut registry = ProtocolRegistry::new();
        registry.bind_udp_port(5353, |packet, payload| {
            Ok(packet.push(Raw::from_bytes(payload)))
        });

        let bytes =
            (Ipv4::new() / Udp::new().sport(5353).dport(50000) / Raw::from("custom-dns-like"))
                .compile()
                .unwrap();

        let decoded =
            Packet::decode_from_l3_with_registry(&registry, NetworkLayer::Ipv4, bytes.as_bytes())
                .unwrap();

        assert_eq!(
            decoded.layer::<Raw>().unwrap().as_bytes(),
            b"custom-dns-like"
        );
    }
}

#[cfg(test)]
mod snmp_udp_decode {
    use std::net::{Ipv4Addr, Ipv6Addr};

    use crate::{
        Ipv4, Ipv6, NetworkLayer, Packet, Raw, Snmp, SnmpOid, SnmpPdu, SnmpVarBindList,
        SnmpVersion, Udp, SNMP_PORT, SNMP_TRAP_PORT,
    };

    #[test]
    fn snmp_udp_decode_decodes_ipv4_and_ipv6_stacks() {
        let ipv4_snmp = Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 66))
            .dst(Ipv4Addr::new(198, 51, 100, 66))
            / Udp::new().sport(49_152).dport(SNMP_PORT)
            / Snmp::v1_get_request(b"public".to_vec(), 1, SnmpVarBindList::empty()).unwrap();
        let ipv4_decoded =
            Packet::decode_from_l3(NetworkLayer::Ipv4, ipv4_snmp.compile().unwrap().as_bytes())
                .unwrap();

        let snmp = ipv4_decoded.layer::<Snmp>().expect("IPv4 SNMP layer");
        assert_eq!(snmp.version(), SnmpVersion::V1);
        assert!(ipv4_decoded.layer::<Raw>().is_none());

        let ipv6_snmp = Ipv6::new()
            .src("2001:db8::66".parse::<Ipv6Addr>().unwrap())
            .dst("2001:db8::67".parse::<Ipv6Addr>().unwrap())
            / Udp::new().sport(SNMP_TRAP_PORT).dport(49_153)
            / Snmp::v2c_snmpv2_trap(b"public".to_vec(), 2, SnmpVarBindList::empty()).unwrap();
        let ipv6_decoded =
            Packet::decode_from_l3(NetworkLayer::Ipv6, ipv6_snmp.compile().unwrap().as_bytes())
                .unwrap();

        let snmp = ipv6_decoded.layer::<Snmp>().expect("IPv6 SNMP layer");
        assert_eq!(snmp.version(), SnmpVersion::V2c);
        assert_eq!(snmp.pdu().tag_number(), SnmpPdu::TAG_TRAP_V2);
        assert!(ipv6_decoded.layer::<Raw>().is_none());
    }

    #[test]
    fn snmp_udp_decode_preserves_non_snmp_bytes_on_snmp_ports_as_raw() {
        let raw_payload = b"not-snmp".to_vec();
        let ipv4_raw = Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 66))
            .dst(Ipv4Addr::new(198, 51, 100, 66))
            / Udp::new().sport(49_152).dport(SNMP_PORT)
            / Raw::from_bytes(raw_payload.clone());
        let ipv4_decoded =
            Packet::decode_from_l3(NetworkLayer::Ipv4, ipv4_raw.compile().unwrap().as_bytes())
                .unwrap();

        assert!(ipv4_decoded.layer::<Snmp>().is_none());
        assert_eq!(
            ipv4_decoded
                .layer::<Raw>()
                .expect("raw IPv4 payload")
                .as_bytes(),
            raw_payload
        );

        let invalid_sequence = [0x30, 0x03, 0x02, 0x01, 0x00];
        let ipv6_raw = Ipv6::new()
            .src("2001:db8::66".parse::<Ipv6Addr>().unwrap())
            .dst("2001:db8::67".parse::<Ipv6Addr>().unwrap())
            / Udp::new().sport(SNMP_TRAP_PORT).dport(49_153)
            / Raw::from_bytes(invalid_sequence);
        let ipv6_decoded =
            Packet::decode_from_l3(NetworkLayer::Ipv6, ipv6_raw.compile().unwrap().as_bytes())
                .unwrap();

        assert!(ipv6_decoded.layer::<Snmp>().is_none());
        assert_eq!(
            ipv6_decoded
                .layer::<Raw>()
                .expect("raw IPv6 payload")
                .as_bytes(),
            invalid_sequence
        );
    }

    #[test]
    fn snmp_trap_port_decode_decodes_v1_v2_trap_and_inform_pdus() -> crate::Result<()> {
        let enterprise = SnmpOid::from_dotted("1.3.6.1.4.1")?;
        let cases = [
            (
                Snmp::v1_trap(
                    b"public".to_vec(),
                    enterprise,
                    [192, 0, 2, 1],
                    6,
                    42,
                    1234,
                    SnmpVarBindList::empty(),
                )?,
                SnmpVersion::V1,
                SnmpPdu::TAG_TRAP,
            ),
            (
                Snmp::v2c_snmpv2_trap(b"public".to_vec(), 2, SnmpVarBindList::empty())?,
                SnmpVersion::V2c,
                SnmpPdu::TAG_TRAP_V2,
            ),
            (
                Snmp::v2c_inform_request(b"public".to_vec(), 3, SnmpVarBindList::empty())?,
                SnmpVersion::V2c,
                SnmpPdu::TAG_INFORM_REQUEST,
            ),
        ];

        for (snmp, expected_version, expected_tag) in cases {
            let packet = Ipv4::new()
                .src(Ipv4Addr::new(192, 0, 2, 67))
                .dst(Ipv4Addr::new(198, 51, 100, 67))
                / Udp::new().sport(SNMP_TRAP_PORT).dport(49_154)
                / snmp;
            let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, packet.compile()?.as_bytes())?;
            let decoded_snmp = decoded.layer::<Snmp>().expect("trap-port SNMP");

            assert_eq!(decoded_snmp.version(), expected_version);
            assert_eq!(decoded_snmp.pdu().tag_number(), expected_tag);
            assert!(decoded.layer::<Raw>().is_none());
        }

        Ok(())
    }

    #[test]
    fn snmp_trap_port_decode_decodes_unknown_valid_pdu_payload() -> crate::Result<()> {
        let unknown_payload = [
            0x30, 0x0b, 0x02, 0x01, 0x01, 0x04, 0x01, b'x', 0xa9, 0x03, 0x02, 0x01, 0x05,
        ];
        let packet = Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 67))
            .dst(Ipv4Addr::new(198, 51, 100, 67))
            / Udp::new().sport(49_154).dport(SNMP_TRAP_PORT)
            / Raw::from_bytes(unknown_payload);
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, packet.compile()?.as_bytes())?;
        let snmp = decoded.layer::<Snmp>().expect("unknown PDU SNMP");

        assert_eq!(snmp.version(), SnmpVersion::V2c);
        assert_eq!(snmp.pdu().tag_number(), 9);
        assert!(snmp.pdu().as_unknown().is_some());
        assert!(decoded.layer::<Raw>().is_none());

        Ok(())
    }
}

#[cfg(test)]
mod quic_udp_dispatch {
    use super::ProtocolRegistry;
    use crate::{
        Ipv4, NetworkLayer, Packet, Quic, Raw, Udp, QUIC_VERSION_1, QUIC_VERSION_NEGOTIATION,
    };

    const QUIC_PAYLOAD: [u8; 14] = [
        0xc0, 0x00, 0x00, 0x00, 0x01, 0x04, 0x83, 0x94, 0xc8, 0xf0, 0x00, 0x00, 0x01, 0x00,
    ];

    fn udp_ipv4_packet(source_port: u16, destination_port: u16, payload: impl Into<Raw>) -> Packet {
        Ipv4::new() / Udp::new().sport(source_port).dport(destination_port) / payload.into()
    }

    fn udp_length(bytes: &[u8]) -> u16 {
        u16::from_be_bytes([bytes[24], bytes[25]])
    }

    #[test]
    fn quic_udp_dispatch_decodes_long_header_on_example_port() {
        let bytes = udp_ipv4_packet(49_152, 4433, Raw::from_bytes(QUIC_PAYLOAD))
            .compile()
            .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let quic = decoded.layer::<Quic>().expect("QUIC layer");

        assert_eq!(quic.packets().len(), 1);
        assert!(quic.packets()[0].is_long_header());
        assert_eq!(quic.len(), QUIC_PAYLOAD.len());
        assert!(decoded.layer::<Raw>().is_none());
        assert_eq!(QUIC_VERSION_1, 0x0000_0001);
    }

    #[test]
    fn quic_udp_dispatch_decodes_version_negotiation_on_https_port() {
        let payload = [
            0x80, 0x00, 0x00, 0x00, 0x00, 0x04, 0x83, 0x94, 0xc8, 0xf0, 0x00, 0x00, 0x00, 0x00,
            0x01,
        ];
        let bytes = udp_ipv4_packet(443, 49_152, Raw::from_bytes(payload))
            .compile()
            .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();

        assert!(decoded.layer::<Quic>().is_some());
        assert_eq!(QUIC_VERSION_NEGOTIATION, 0x0000_0000);
    }

    #[test]
    fn quic_udp_dispatch_preserves_non_quic_payloads_as_raw() {
        let payload = [0x16, 0xfe, 0xfd, 0x00, 0x00, 0xde, 0xad];
        let bytes = udp_ipv4_packet(49_152, 443, Raw::from_bytes(payload))
            .compile()
            .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();

        assert!(decoded.layer::<Quic>().is_none());
        assert_eq!(decoded.layer::<Raw>().unwrap().as_bytes(), payload);
    }

    #[test]
    fn quic_udp_dispatch_preserves_ambiguous_short_header_as_raw() {
        let payload = [0x43, 0x83, 0x94, 0xc8, 0xf0, 0x01, 0x02];
        let bytes = udp_ipv4_packet(49_152, 4433, Raw::from_bytes(payload))
            .compile()
            .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();

        assert!(decoded.layer::<Quic>().is_none());
        assert_eq!(decoded.layer::<Raw>().unwrap().as_bytes(), payload);
    }

    #[test]
    fn quic_multiplexing_classifier_preserves_neighbor_udp_payloads_as_raw_on_quic_ports() {
        let cases: &[(&str, &[u8])] = &[
            (
                "dtls_handshake",
                &[0x16, 0xfe, 0xfd, 0x00, 0x00, 0xde, 0xad],
            ),
            (
                "stun_binding",
                &[0x00, 0x01, 0x00, 0x00, 0x21, 0x12, 0xa4, 0x42],
            ),
            ("rtp", &[0x80, 0x60, 0x00, 0x01, 0x00, 0x00, 0xde, 0xad]),
            ("zrtp", &[0x10, 0x00, b'Z', b'R', b'T', b'P']),
            ("turn_channel_data", &[0x40, 0x00, 0x00, 0x04, 0xde, 0xad]),
        ];

        for (name, payload) in cases {
            let bytes = udp_ipv4_packet(49_152, 4433, Raw::from_bytes(payload))
                .compile()
                .unwrap();

            let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes())
                .unwrap_or_else(|err| panic!("{name} should decode as raw: {err}"));

            assert!(
                decoded.layer::<Quic>().is_none(),
                "{name} should not produce QUIC"
            );
            assert_eq!(
                decoded.layer::<Raw>().unwrap().as_bytes(),
                *payload,
                "{name} raw payload should be preserved"
            );
        }
    }

    #[test]
    fn quic_multiplexing_classifier_preserves_custom_udp_binding_precedence() {
        let mut registry = ProtocolRegistry::new();
        registry.bind_udp_port(4433, |packet, payload| {
            Ok(packet.push(Raw::from_bytes(payload)))
        });
        let bytes = udp_ipv4_packet(49_152, 4433, Raw::from_bytes(QUIC_PAYLOAD))
            .compile()
            .unwrap();

        let decoded =
            Packet::decode_from_l3_with_registry(&registry, NetworkLayer::Ipv4, bytes.as_bytes())
                .unwrap();

        assert!(decoded.layer::<Quic>().is_none());
        assert_eq!(decoded.layer::<Raw>().unwrap().as_bytes(), QUIC_PAYLOAD);
    }

    #[test]
    fn quic_udp_dispatch_custom_binding_overrides_builtin() {
        let mut registry = ProtocolRegistry::new();
        registry.bind_udp_port(4433, |packet, payload| {
            Ok(packet.push(Raw::from_bytes(payload)))
        });
        let bytes = udp_ipv4_packet(49_152, 4433, Raw::from_bytes(QUIC_PAYLOAD))
            .compile()
            .unwrap();

        let decoded =
            Packet::decode_from_l3_with_registry(&registry, NetworkLayer::Ipv4, bytes.as_bytes())
                .unwrap();

        assert!(decoded.layer::<Quic>().is_none());
        assert_eq!(decoded.layer::<Raw>().unwrap().as_bytes(), QUIC_PAYLOAD);
    }

    #[test]
    fn quic_udp_dispatch_disabled_application_decoding_preserves_raw() {
        let registry = ProtocolRegistry::new().application_decoding(false);
        let bytes = udp_ipv4_packet(49_152, 4433, Raw::from_bytes(QUIC_PAYLOAD))
            .compile()
            .unwrap();

        let decoded =
            Packet::decode_from_l3_with_registry(&registry, NetworkLayer::Ipv4, bytes.as_bytes())
                .unwrap();

        assert!(decoded.layer::<Quic>().is_none());
        assert_eq!(decoded.layer::<Raw>().unwrap().as_bytes(), QUIC_PAYLOAD);
    }

    #[test]
    fn quic_udp_dispatch_layer_length_excludes_udp_surplus_raw() {
        let packet = Ipv4::new()
            / Udp::new().sport(49_152).dport(4433)
            / Quic::from_bytes(QUIC_PAYLOAD)
            / Raw::from_bytes([0xde, 0xad, 0xbe, 0xef]);
        let compiled = packet.compile().unwrap();

        assert_eq!(
            udp_length(compiled.as_bytes()),
            (8 + QUIC_PAYLOAD.len()) as u16
        );
    }
}

#[cfg(test)]
mod bgp_tcp_binding {
    use crate::protocols::bgp::BGP_PORT;
    use crate::{Bgp, Ipv4, NetworkLayer, Packet, Raw, Tcp};

    #[test]
    fn default_registry_decodes_bgp_on_tcp_179_and_preserves_other_tcp_payloads() {
        let bgp_bytes = (Ipv4::new() / Tcp::new().sport(49_152).dport(BGP_PORT) / Bgp::keepalive())
            .compile()
            .unwrap();

        let bgp_decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bgp_bytes.as_bytes()).unwrap();

        assert!(bgp_decoded.layer::<Bgp>().is_some());
        assert!(bgp_decoded.layer::<Raw>().is_none());

        let keepalive = Packet::from_layer(Bgp::keepalive())
            .compile()
            .unwrap()
            .into_bytes();
        let raw_bytes =
            (Ipv4::new() / Tcp::new().sport(49_152).dport(80) / Raw::from_bytes(keepalive.clone()))
                .compile()
                .unwrap();

        let raw_decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, raw_bytes.as_bytes()).unwrap();

        assert!(raw_decoded.layer::<Bgp>().is_none());
        assert_eq!(raw_decoded.layer::<Raw>().unwrap().as_bytes(), keepalive);
    }
}