zenith-net 0.1.0

Zenith 网络地址与传输层抽象:L2-L4 协议解析、TCP/UDP/QUIC 状态机、来源准入引擎、单队列 Worker 数据面循环
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
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
//! L2/L3/L4 数据包解析
//!
//! 零拷贝、步数预算的协议解析实现:
//! - 使用 `#[repr(C, packed)]` 结构体直接映射字节流
//! - 每级解析有步数预算,超出直接丢弃
//! - 编译期确定最小包长,运行期零堆分配
//! - 所有解析通过借用原始数据,零拷贝
//! - 支持 ARP、ICMP/ICMPv6 完整解析
//! - 支持 IP/TCP/UDP 校验和验证与增量更新

use crate::error::{NetError, Result};

/// 最小以太网头长度
pub const ETH_HEADER_LEN: usize = 14;
/// 以太网 VLAN 标签长度
pub const VLAN_TAG_LEN: usize = 4;
/// 最小 IPv4 头长度
pub const IPV4_MIN_HEADER_LEN: usize = 20;
/// 最大 IPv4 头长度(IHL 4 位字段,最大 15 * 4 = 60 字节)
pub const IPV4_MAX_HEADER_LEN: usize = 60;
/// IPv6 头长度
pub const IPV6_HEADER_LEN: usize = 40;
/// 最小 TCP 头长度
pub const TCP_MIN_HEADER_LEN: usize = 20;
/// UDP 头长度
pub const UDP_HEADER_LEN: usize = 8;
/// ARP 包长度
pub const ARP_PACKET_LEN: usize = 28;
/// ICMP 最小头长度
pub const ICMP_MIN_HEADER_LEN: usize = 8;
/// ICMPv6 最小头长度
pub const ICMPV6_MIN_HEADER_LEN: usize = 4;

/// 最大解析步数预算(防止畸形包消耗过多 CPU)
pub const MAX_PARSE_STEPS: u32 = 20;

/// 安全零拷贝类型转换模块
///
/// 本模块集中管理所有 `#[repr(C, packed)]` 结构体与字节切片间的零拷贝转换。
/// 通过将 unsafe 边界收敛到本模块内的单一实现点,使全项目仅 1 处可审计的
/// unsafe 块,而非散落在 11+ 处。
///
/// # 安全不变量(Safety Invariants)
///
/// 1. 所有通过本模块解析的类型 T 必须标注 `#[repr(C, packed)]`
///    - packed 意味着无对齐要求,可从任意字节地址读取
///    - repr(C) 保证字段顺序与内存布局稳定,匹配协议帧格式
/// 2. 输入字节切片长度必须 >= `size_of::<T>()`
///    - 调用方必须在调用前完成长度校验
/// 3. 返回的引用生命周期与输入切片绑定
///    - 防止悬垂引用
/// 4. 解析后不得修改字节切片(写路径一律走 `build_reply_frame` 等构造器)
#[allow(unsafe_code)]
pub(crate) mod cast {
    use crate::error::{NetError, Result};

    /// 标记 trait:所有可零拷贝解析的协议头类型均实现此 trait。
    ///
    /// # 编译器约束
    /// - 实现类型必须为 `#[repr(C, packed)]`
    /// - `MIN_LEN` 必须等于或大于 `size_of::<Self>()`
    pub trait PacketHeader: Sized {
        /// 该头类型的最小字节长度(编译期常量)
        const MIN_LEN: usize;
    }

    /// 安全地从字节切片零拷贝解析为 `#[repr(C, packed)]` 结构体引用。
    ///
    /// # 运行期校验
    /// - 检查 `data.len() >= T::MIN_LEN`
    /// - 不足则返回 `NetError::PacketTooShort`
    ///
    /// # 安全说明
    /// 本函数内的 `unsafe` 块是协议解析路径仅有的 2 处裸指针转换点之一:
    /// - T: `#[repr(C, packed)]` → 无对齐要求,任意字节地址合法
    /// - 长度已校验 ≥ MIN_LEN ≥ size_of::<T>() → 不会越界
    /// - 返回引用生命周期绑定 data → 无悬垂风险
    #[inline]
    pub fn from_bytes<T: PacketHeader>(data: &[u8]) -> Result<&T> {
        if data.len() < T::MIN_LEN {
            return Err(NetError::PacketTooShort {
                need: T::MIN_LEN,
                got: data.len(),
            });
        }
        // SAFETY: 唯一裸指针转换点。安全不变量见模块级文档:
        // (1) T: #[repr(C, packed)] 无对齐要求
        // (2) data.len() >= T::MIN_LEN >= size_of::<T>() 保证足够字节
        // (3) 返回引用生命周期绑定 data
        Ok(unsafe { &*(data.as_ptr() as *const T) })
    }

    // 注:原 `header_bytes`(自结构体指针以 `from_raw_parts` 取 `len` 字节)
    // 已删除——IHL>5 场景会读超出 `size_of::<T>()` 的内存(形式上出 provance 界)。
    // 校验和计算统一走 [`crate::packet::verify_ipv4_checksum`] /
    // [`crate::packet::recompute_ipv4_checksum`](原数据切片取样,无裸指针转换)。
}

// === PacketHeader trait implementations for all #[repr(C, packed)] protocol headers ===
//
// 集中在一处便于审计:所有协议头的 MIN_LEN 常量在此统一定义,
// 确保与 `size_of::<T>()` 和协议规范保持一致。

impl cast::PacketHeader for EthHeader {
    const MIN_LEN: usize = ETH_HEADER_LEN;
}

impl cast::PacketHeader for VlanTag {
    const MIN_LEN: usize = VLAN_TAG_LEN;
}

impl cast::PacketHeader for Ipv4Header {
    const MIN_LEN: usize = IPV4_MIN_HEADER_LEN;
}

impl cast::PacketHeader for Ipv6Header {
    const MIN_LEN: usize = IPV6_HEADER_LEN;
}

impl cast::PacketHeader for TcpHeader {
    const MIN_LEN: usize = TCP_MIN_HEADER_LEN;
}

impl cast::PacketHeader for UdpHeader {
    const MIN_LEN: usize = UDP_HEADER_LEN;
}

impl cast::PacketHeader for ArpPacket {
    const MIN_LEN: usize = ARP_PACKET_LEN;
}

impl cast::PacketHeader for IcmpHeader {
    const MIN_LEN: usize = ICMP_MIN_HEADER_LEN;
}

impl cast::PacketHeader for IcmpV6Header {
    const MIN_LEN: usize = ICMPV6_MIN_HEADER_LEN;
}

/// 以太网类型常量
pub mod ethertype {
    /// IPv4
    pub const IPV4: u16 = 0x0800;
    /// ARP
    pub const ARP: u16 = 0x0806;
    /// IPv6
    pub const IPV6: u16 = 0x86DD;
    /// VLAN 标签
    pub const VLAN: u16 = 0x8100;
}

/// IP 协议号常量
pub mod ip_proto {
    /// ICMP
    pub const ICMP: u8 = 1;
    /// TCP
    pub const TCP: u8 = 6;
    /// UDP
    pub const UDP: u8 = 17;
    /// ICMPv6
    pub const ICMPV6: u8 = 58;
}

/// ICMP 类型常量
pub mod icmp_type {
    /// Echo Reply
    pub const ECHO_REPLY: u8 = 0;
    /// Destination Unreachable
    pub const DEST_UNREACH: u8 = 3;
    /// Redirect
    pub const REDIRECT: u8 = 5;
    /// Echo Request
    pub const ECHO_REQUEST: u8 = 8;
    /// Router Advertisement
    pub const ROUTER_ADV: u8 = 9;
    /// Router Solicitation
    pub const ROUTER_SOL: u8 = 10;
    /// Time Exceeded
    pub const TIME_EXCEEDED: u8 = 11;
    /// Parameter Problem
    pub const PARAM_PROBLEM: u8 = 12;
    /// Timestamp Request
    pub const TIMESTAMP_REQUEST: u8 = 13;
    /// Timestamp Reply
    pub const TIMESTAMP_REPLY: u8 = 14;
}

/// ICMPv6 类型常量
pub mod icmpv6_type {
    /// Destination Unreachable
    pub const DEST_UNREACH: u8 = 1;
    /// Packet Too Big
    pub const PKT_TOO_BIG: u8 = 2;
    /// Time Exceeded
    pub const TIME_EXCEEDED: u8 = 3;
    /// Parameter Problem
    pub const PARAM_PROBLEM: u8 = 4;
    /// Echo Request (Ping)
    pub const ECHO_REQUEST: u8 = 128;
    /// Echo Reply
    pub const ECHO_REPLY: u8 = 129;
    /// Router Solicitation
    pub const ROUTER_SOL: u8 = 133;
    /// Router Advertisement
    pub const ROUTER_ADV: u8 = 134;
    /// Neighbor Solicitation
    pub const NEIGHBOR_SOL: u8 = 135;
    /// Neighbor Advertisement
    pub const NEIGHBOR_ADV: u8 = 136;
    /// Redirect Message
    pub const REDIRECT: u8 = 137;
}

/// 以太网头(14 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct EthHeader {
    /// 目标 MAC 地址
    pub(crate) dst_mac: [u8; 6],
    /// 源 MAC 地址
    pub(crate) src_mac: [u8; 6],
    /// 以太网类型(网络字节序)
    pub(crate) ethertype: u16,
}

impl EthHeader {
    /// 从字节切片解析以太网头
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        cast::from_bytes(data)
    }

    /// 获取以太网类型(字节序转换)
    #[inline]
    pub fn ethertype(&self) -> u16 {
        u16::from_be(self.ethertype)
    }

    /// 获取源 MAC
    #[inline]
    pub fn src_mac(&self) -> [u8; 6] {
        self.src_mac
    }

    /// 获取目标 MAC
    #[inline]
    pub fn dst_mac(&self) -> [u8; 6] {
        self.dst_mac
    }
}

/// VLAN 标签(4 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct VlanTag {
    /// TCI(网络字节序)
    pub(crate) tci: u16,
    /// 以太网类型(网络字节序)
    pub(crate) ethertype: u16,
}

impl VlanTag {
    /// 从字节切片解析 VLAN 标签
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        cast::from_bytes(data)
    }

    /// 获取以太网类型(字节序转换)
    #[inline]
    pub fn ethertype(&self) -> u16 {
        u16::from_be(self.ethertype)
    }

    /// 获取 VLAN ID
    #[inline]
    pub fn vlan_id(&self) -> u16 {
        u16::from_be(self.tci) & 0x0FFF
    }

    /// 获取优先级码点(PCP)
    #[inline]
    pub fn pcp(&self) -> u8 {
        (u16::from_be(self.tci) >> 13) as u8
    }
}

/// IPv4 头(最小 20 字节)
#[repr(C, packed)]
#[derive(Debug, Clone)]
pub struct Ipv4Header {
    /// 版本 + IHL
    pub(crate) version_ihl: u8,
    /// TOS / DSCP + ECN
    pub(crate) tos: u8,
    /// 总长度(网络字节序)
    pub(crate) total_length: u16,
    /// 标识符(网络字节序)
    pub(crate) identification: u16,
    /// 标志 + 分片偏移(网络字节序)
    pub(crate) flags_fragment: u16,
    /// TTL
    pub(crate) ttl: u8,
    /// 协议号
    pub(crate) protocol: u8,
    /// 头校验和(网络字节序)
    pub(crate) checksum: u16,
    /// 源 IP 地址
    pub(crate) src_ip: [u8; 4],
    /// 目标 IP 地址
    pub(crate) dst_ip: [u8; 4],
}

impl Ipv4Header {
    /// 从字节切片解析 IPv4 头
    ///
    /// 校验项(fail-closed,遵循 RFC 791):
    /// - 数据长度 >= 20 字节(最小头长)
    /// - IP 版本 = 4
    /// - IHL >= 5(头长 >= 20 字节)
    /// - IHL 指示的头长 <= 数据长度(防止后续 payload_offset 越界)
    /// - total_length >= header_length(头内部一致性,RFC 791 §3.1)
    ///
    /// # 安全
    /// 此函数仅校验 IPv4 头自身的合法性。缓冲区与 `total_length` 的一致性
    /// (`total_length <= data.len()`)由调用方(如 `parse_ipv4`)负责,
    /// 因为该检查需要上下文(缓冲区可能大于 IP 包声明长度)。
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        let hdr = cast::from_bytes::<Self>(data)?;
        let version = hdr.version_ihl >> 4;
        if version != 4 {
            return Err(NetError::InvalidIpVersion(version));
        }
        // IHL 合法范围 [5, 15],header_length = IHL * 4
        let ihl = hdr.version_ihl & 0x0F;
        if ihl < 5 {
            return Err(NetError::InvalidPacket {
                reason: "IPv4 IHL < 5 (header too short)",
            });
        }
        // 头长不能超过可用数据(防止后续 payload_offset 越界)
        let hdr_len = (ihl as usize) << 2;
        if hdr_len > data.len() {
            return Err(NetError::InvalidPacket {
                reason: "IPv4 header length exceeds packet size",
            });
        }
        // RFC 791 §3.1: total_length 包含 IP 头 + 数据,必须 >= 头长。
        // 使用 checked 算术符合 AGENT.md §11.2.5;此处不需要 checked_sub
        // 因为 total_length (u16) 与 hdr_len (≤60) 均在 u32 范围内。
        let total_len = u16::from_be(hdr.total_length) as usize;
        if total_len < hdr_len {
            return Err(NetError::InvalidPacket {
                reason: "IPv4 total_length < header length (RFC 791 violation)",
            });
        }
        Ok(hdr)
    }

    /// IP 版本号(应为 4)
    #[inline]
    pub fn version(&self) -> u8 {
        self.version_ihl >> 4
    }

    /// Internet 头长(IHL,单位:4 字节字)
    #[inline]
    pub fn ihl(&self) -> u8 {
        self.version_ihl & 0x0F
    }

    /// 整个 IP 包总长度(IP 头 + 数据,字节)
    #[inline]
    pub fn total_length(&self) -> u16 {
        u16::from_be(self.total_length)
    }

    /// 上层协议号(如 6=TCP, 17=UDP)
    #[inline]
    pub fn protocol(&self) -> u8 {
        self.protocol
    }

    /// 生存时间(TTL,跳数限制)
    #[inline]
    pub fn ttl(&self) -> u8 {
        self.ttl
    }

    /// 源 IPv4 地址
    #[inline]
    pub fn src_ip(&self) -> [u8; 4] {
        self.src_ip
    }

    /// 目标 IPv4 地址
    #[inline]
    pub fn dst_ip(&self) -> [u8; 4] {
        self.dst_ip
    }

    /// 头校验和
    #[inline]
    pub fn checksum(&self) -> u16 {
        u16::from_be(self.checksum)
    }

    /// 标志字段(3-bit,含 DF/MF/Reserved)
    #[inline]
    pub fn flags(&self) -> u8 {
        (u16::from_be(self.flags_fragment) >> 13) as u8
    }

    /// 是否设置 Don't Fragment 标志
    #[inline]
    pub fn dont_fragment(&self) -> bool {
        self.flags() & 0x02 != 0
    }

    /// 是否设置 More Fragments 标志
    #[inline]
    pub fn more_fragments(&self) -> bool {
        self.flags() & 0x01 != 0
    }

    /// IP 头长度(字节,= IHL * 4)
    #[inline]
    pub fn header_length(&self) -> usize {
        (self.ihl() as usize) << 2
    }

    /// 负载起始偏移(= 头长度)
    #[inline]
    pub fn payload_offset(&self) -> usize {
        self.header_length()
    }

    /// IPv4 标识符(Identification 字段)
    #[inline]
    pub fn identification(&self) -> u16 {
        u16::from_be(self.identification)
    }

    /// Type of Service / DSCP + ECN 字节
    #[inline]
    pub fn tos(&self) -> u8 {
        self.tos
    }

    /// 分片偏移(Fragment Offset,低 13-bit,单位:8 字节)
    #[inline]
    pub fn fragment_offset(&self) -> u16 {
        u16::from_be(self.flags_fragment) & 0x1FFF
    }

}

/// 验证 IPv4 头校验和(RFC 1071,零拷贝,fail-closed)
///
/// `data` 必须以 IPv4 头起始(`data[0]` 为 version_ihl);读取 IHL 得到头长。
/// 校验头长:偶数、∈ [20, 60]、`data.len() >= 头长`——任一不满足返回 `None`
/// (fail-closed);否则返回 `Some(ones_complement(tmp) == data[10..12])`。
///
/// 取代原 `Ipv4Header::verify_checksum(&self)`:原实现经 `from_raw_parts` 从
/// 结构体指针读 `hdr_len` 字节,IHL>5 时出 `size_of::<Ipv4Header>`(20) 界,
/// 虽语义上读入原包缓冲但被引用 provance 只覆盖 20B——形式上不成立。
/// 现在的 free function 直接从原数据切片取样,全程无裸指针转换。
#[inline]
pub fn verify_ipv4_checksum(data: &[u8]) -> Option<bool> {
    if data.len() < IPV4_MIN_HEADER_LEN {
        return None;
    }
    let ihl = (data[0] & 0x0F) as usize;
    let hdr_len = ihl << 2;
    if !(IPV4_MIN_HEADER_LEN..=IPV4_MAX_HEADER_LEN).contains(&hdr_len)
        || !hdr_len.is_multiple_of(2)
        || data.len() < hdr_len
    {
        return None;
    }
    // 校验和字段视为 0:拷贝到栈上清零后计算(hdr_len ≤ 60 字节,零堆分配)
    let mut tmp = [0u8; IPV4_MAX_HEADER_LEN];
    tmp[..hdr_len].copy_from_slice(&data[..hdr_len]);
    tmp[10] = 0;
    tmp[11] = 0;
    let stored = u16::from_be_bytes([data[10], data[11]]);
    Some(compute_ipv4_checksum(&tmp[..hdr_len]) == stored)
}

/// 原地重算并写回 IPv4 头校验和(RFC 1071,fail-closed)
///
/// `data` 必须以 IPv4 头起始。头长校验同 [`verify_ipv4_checksum`];
/// 成功时清零 data[10..12] → 按 RFC 1071 计算 → 按大端写回;
/// 校验失败返回 `false` 且不修改 `data`。
#[inline]
pub fn recompute_ipv4_checksum(data: &mut [u8]) -> bool {
    if data.len() < IPV4_MIN_HEADER_LEN {
        return false;
    }
    let ihl = (data[0] & 0x0F) as usize;
    let hdr_len = ihl << 2;
    if !(IPV4_MIN_HEADER_LEN..=IPV4_MAX_HEADER_LEN).contains(&hdr_len)
        || !hdr_len.is_multiple_of(2)
        || data.len() < hdr_len
    {
        return false;
    }
    data[10] = 0;
    data[11] = 0;
    let computed = compute_ipv4_checksum(&data[..hdr_len]);
    data[10..12].copy_from_slice(&computed.to_be_bytes());
    true
}

/// IPv4 头校验和(RFC 1071 一反码和)
///
/// 全 workspace 唯一实现:[`verify_ipv4_checksum`] /
/// [`recompute_ipv4_checksum`] 与 worker 回包构造(build_reply_frame)
/// 共用本函数,消除重复实现。
///
/// # 参数
/// * `header` - IPv4 头字节切片(长度须为偶数;校验和字段须已置 0)
#[inline]
pub fn compute_ipv4_checksum(header: &[u8]) -> u16 {
    debug_assert!(header.len().is_multiple_of(2));
    let mut sum: u32 = 0;
    for pair in header.chunks_exact(2) {
        sum = sum.saturating_add(u32::from(u16::from_be_bytes([pair[0], pair[1]])));
    }
    // 折叠进位
    while (sum >> 16) != 0 {
        sum = (sum & 0xFFFF) + (sum >> 16);
    }
    !(sum as u16)
}

/// IPv6 头(40 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct Ipv6Header {
    /// 版本 + 流量类型 + 流标签(网络字节序)
    pub(crate) version_traffic_flow: u32,
    /// 负载长度(网络字节序)
    pub(crate) payload_length: u16,
    /// 下一头协议号
    pub(crate) next_header: u8,
    /// 跳数限制
    pub(crate) hop_limit: u8,
    /// 源 IP 地址
    pub(crate) src_ip: [u8; 16],
    /// 目标 IP 地址
    pub(crate) dst_ip: [u8; 16],
}

impl Ipv6Header {
    /// 从字节切片解析 IPv6 头
    ///
    /// 校验项(fail-closed):
    /// - 数据长度 >= 40 字节
    /// - IP 版本 = 6
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        let hdr = cast::from_bytes::<Self>(data)?;
        let version = (u32::from_be(hdr.version_traffic_flow) >> 28) as u8;
        if version != 6 {
            return Err(NetError::InvalidIpVersion(version));
        }
        Ok(hdr)
    }

    /// IP 版本号(应为 6)
    #[inline]
    pub fn version(&self) -> u8 {
        (u32::from_be(self.version_traffic_flow) >> 28) as u8
    }

    /// 流量类别(Traffic Class,8-bit)
    #[inline]
    pub fn traffic_class(&self) -> u8 {
        (u32::from_be(self.version_traffic_flow) >> 20) as u8
    }

    /// 流标签(Flow Label,20-bit)
    #[inline]
    pub fn flow_label(&self) -> u32 {
        u32::from_be(self.version_traffic_flow) & 0x000FFFFF
    }

    /// 负载长度(字节,不含 IPv6 头)
    #[inline]
    pub fn payload_length(&self) -> u16 {
        u16::from_be(self.payload_length)
    }

    /// 下一头类型(如 6=TCP, 17=UDP)
    #[inline]
    pub fn next_header(&self) -> u8 {
        self.next_header
    }

    /// 跳数限制(Hop Limit,类似 IPv4 TTL)
    #[inline]
    pub fn hop_limit(&self) -> u8 {
        self.hop_limit
    }

    /// 源 IPv6 地址
    #[inline]
    pub fn src_ip(&self) -> [u8; 16] {
        self.src_ip
    }

    /// 目标 IPv6 地址
    #[inline]
    pub fn dst_ip(&self) -> [u8; 16] {
        self.dst_ip
    }
}

/// TCP 头(最小 20 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct TcpHeader {
    /// 源端口(网络字节序)
    pub(crate) src_port: u16,
    /// 目标端口(网络字节序)
    pub(crate) dst_port: u16,
    /// 序列号(网络字节序)
    pub(crate) seq_num: u32,
    /// 确认号(网络字节序)
    pub(crate) ack_num: u32,
    /// data_offset + 标志位(网络字节序)
    pub(crate) data_offset_flags: u16,
    /// 窗口大小(网络字节序)
    pub(crate) window_size: u16,
    /// 校验和(网络字节序)
    pub(crate) checksum: u16,
    /// 紧急指针(网络字节序)
    pub(crate) urgent_ptr: u16,
}

impl TcpHeader {
    /// 从字节切片解析 TCP 头
    ///
    /// 校验项(fail-closed):
    /// - 数据长度 >= 20 字节(最小头长)
    /// - data_offset >= 5(头长 >= 20 字节)
    /// - data_offset 指示的头长 <= 数据长度(防止越界)
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        let hdr = cast::from_bytes::<Self>(data)?;
        // data_offset 合法最小值为 5(20 字节),最大值为 15(60 字节)
        let data_offset = (u16::from_be(hdr.data_offset_flags) >> 12) as u8;
        if data_offset < 5 {
            return Err(NetError::InvalidPacket {
                reason: "TCP data_offset < 5 (header too short)",
            });
        }
        let hdr_len = (data_offset as usize) << 2;
        if hdr_len > data.len() {
            return Err(NetError::InvalidPacket {
                reason: "TCP header length exceeds packet size",
            });
        }
        Ok(hdr)
    }

    /// 源端口
    #[inline]
    pub fn src_port(&self) -> u16 {
        u16::from_be(self.src_port)
    }

    /// 目标端口
    #[inline]
    pub fn dst_port(&self) -> u16 {
        u16::from_be(self.dst_port)
    }

    /// 序列号
    #[inline]
    pub fn seq_num(&self) -> u32 {
        u32::from_be(self.seq_num)
    }

    /// 确认号
    #[inline]
    pub fn ack_num(&self) -> u32 {
        u32::from_be(self.ack_num)
    }

    /// 数据偏移(单位:4 字节字)
    #[inline]
    pub fn data_offset(&self) -> u8 {
        (u16::from_be(self.data_offset_flags) >> 12) as u8
    }

    /// 标志位(9-bit,含 SYN/ACK/FIN/RST/PSH 等)
    #[inline]
    pub fn flags(&self) -> u16 {
        u16::from_be(self.data_offset_flags) & 0x01FF
    }

    /// 是否设置 SYN 标志
    #[inline]
    pub fn syn(&self) -> bool {
        self.flags() & 0x02 != 0
    }

    /// 是否设置 ACK 标志
    #[inline]
    pub fn ack(&self) -> bool {
        self.flags() & 0x10 != 0
    }

    /// 是否设置 FIN 标志
    #[inline]
    pub fn fin(&self) -> bool {
        self.flags() & 0x01 != 0
    }

    /// 是否设置 RST 标志
    #[inline]
    pub fn rst(&self) -> bool {
        self.flags() & 0x04 != 0
    }

    /// 是否设置 PSH 标志
    #[inline]
    pub fn psh(&self) -> bool {
        self.flags() & 0x08 != 0
    }

    /// 窗口大小
    #[inline]
    pub fn window_size(&self) -> u16 {
        u16::from_be(self.window_size)
    }

    /// 头校验和
    #[inline]
    pub fn checksum(&self) -> u16 {
        u16::from_be(self.checksum)
    }

    /// TCP 头长度(字节,= data_offset * 4)
    #[inline]
    pub fn header_length(&self) -> usize {
        (self.data_offset() as usize) << 2
    }

    /// 负载起始偏移(= 头长度)
    #[inline]
    pub fn payload_offset(&self) -> usize {
        self.header_length()
    }

    /// 检查 TCP 头标志是否有效(不能全为 0 或全为 1)
    #[inline]
    pub fn validate_flags(&self) -> bool {
        let flags = self.flags();
        // 全 0 或全 1 (9 bit flags) 都无效
        flags != 0 && flags != 0x1FF
    }

    /// 获取 TCP 选项字节 (data_offset > 5 时存在)
    ///
    /// `data` 必须是以 TCP 头起始的完整字节切片(含选项)。
    /// 返回 `Some(&[u8])` 为选项字节区域 `[20..data_offset*4]`,
    /// 若 data_offset == 5(无选项)或数据不足则返回 `None`。
    #[inline]
    pub fn options_bytes<'a>(&self, data: &'a [u8]) -> Option<&'a [u8]> {
        let data_offset = (self.data_offset() as usize) * 4;
        if data_offset > 20 && data.len() >= data_offset {
            Some(&data[20..data_offset])
        } else {
            None
        }
    }
}

/// TCP 选项信息
///
/// 解析 TCP 选项字节后得到的结果,包含选项类型序列和各选项的值。
#[derive(Debug, Clone)]
pub struct TcpOptionsInfo {
    /// 选项类型序列 (按出现顺序)
    pub option_types: Vec<u8>,
    /// MSS 值
    pub mss: Option<u16>,
    /// 窗口缩放因子
    pub window_scale: Option<u8>,
    /// SACK 是否允许
    pub sack_permitted: bool,
    /// TSval
    pub tsval: Option<u32>,
    /// TSecr
    pub tsecr: Option<u32>,
}

/// 解析 TCP 选项字节
///
/// TCP 选项格式: Kind(1 byte) | Length(1 byte, 0 for EOL/NOP) | Value(Length-2 bytes)
/// 常见选项:
/// - 0: EOL (End of Option List)
/// - 1: NOP (No Operation)
/// - 2: MSS (Maximum Segment Size, 4 bytes total)
/// - 3: Window Scale (3 bytes total)
/// - 4: SACK Permitted (2 bytes total, no value)
/// - 5: SACK (variable)
/// - 8: Timestamps (10 bytes total)
/// - 19: TCP MD5 Signature (18 bytes total)
pub fn parse_tcp_options(options: &[u8]) -> TcpOptionsInfo {
    let mut info = TcpOptionsInfo {
        option_types: Vec::new(),
        mss: None,
        window_scale: None,
        sack_permitted: false,
        tsval: None,
        tsecr: None,
    };

    let mut i = 0;
    while i < options.len() {
        let kind = options[i];
        match kind {
            0 => break, // EOL
            1 => { // NOP
                info.option_types.push(1);
                i += 1;
                continue;
            }
            _ => {
                info.option_types.push(kind);
                if i + 1 >= options.len() {
                    break;
                }
                let len = options[i + 1] as usize;
                if len < 2 || i + len > options.len() {
                    break;
                }
                match kind {
                    2 => { // MSS
                        if len >= 4 {
                            info.mss = Some(u16::from_be_bytes([options[i + 2], options[i + 3]]));
                        }
                    }
                    3 => { // Window Scale
                        if len >= 3 {
                            info.window_scale = Some(options[i + 2]);
                        }
                    }
                    4 => { // SACK Permitted
                        info.sack_permitted = true;
                    }
                    8 => { // Timestamps
                        if len >= 10 {
                            info.tsval = Some(u32::from_be_bytes([
                                options[i + 2], options[i + 3], options[i + 4], options[i + 5]
                            ]));
                            info.tsecr = Some(u32::from_be_bytes([
                                options[i + 6], options[i + 7], options[i + 8], options[i + 9]
                            ]));
                        }
                    }
                    _ => {}
                }
                i += len;
            }
        }
    }
    info
}

/// UDP 头(8 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct UdpHeader {
    /// 源端口(网络字节序)
    pub(crate) src_port: u16,
    /// 目标端口(网络字节序)
    pub(crate) dst_port: u16,
    /// 长度(网络字节序,含头)
    pub(crate) length: u16,
    /// 校验和(网络字节序)
    pub(crate) checksum: u16,
}

impl UdpHeader {
    /// 从字节切片解析 UDP 头
    ///
    /// 校验项(fail-closed):
    /// - 数据长度 >= 8 字节(固定头长)
    /// - length 字段 >= 8(RFC 768: 最小值为头长 8 字节)
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        let hdr = cast::from_bytes::<Self>(data)?;
        // RFC 768: length 字段包含 UDP 头(8 字节),最小值为 8
        let length = u16::from_be(hdr.length);
        if (length as usize) < UDP_HEADER_LEN {
            return Err(NetError::InvalidPacket {
                reason: "UDP length field < 8 (smaller than header)",
            });
        }
        if (length as usize) > data.len() {
            return Err(NetError::InvalidPacket {
                reason: "UDP length field exceeds buffer size",
            });
        }
        Ok(hdr)
    }

    /// 源端口
    #[inline]
    pub fn src_port(&self) -> u16 {
        u16::from_be(self.src_port)
    }

    /// 目标端口
    #[inline]
    pub fn dst_port(&self) -> u16 {
        u16::from_be(self.dst_port)
    }

    /// UDP 长度(含 UDP 头,字节)
    #[inline]
    pub fn length(&self) -> u16 {
        u16::from_be(self.length)
    }

    /// 头校验和
    #[inline]
    pub fn checksum(&self) -> u16 {
        u16::from_be(self.checksum)
    }

    /// 负载长度(= length - 8,饱和减法)
    #[inline]
    pub fn payload_len(&self) -> u16 {
        let total = self.length();
        total.saturating_sub(UDP_HEADER_LEN as u16)
    }

    /// 验证 UDP 长度字段合法性
    #[inline]
    pub fn validate_length(&self, actual_data_len: usize) -> bool {
        let declared = self.length() as usize;
        declared >= UDP_HEADER_LEN && declared <= actual_data_len
    }
}

/// ARP 包(28 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct ArpPacket {
    /// 硬件类型(网络字节序)
    pub(crate) hw_type: u16,
    /// 协议类型(网络字节序)
    pub(crate) proto_type: u16,
    /// 硬件地址长度
    pub(crate) hw_addr_len: u8,
    /// 协议地址长度
    pub(crate) proto_addr_len: u8,
    /// 操作码(网络字节序)
    pub(crate) opcode: u16,
    /// 发送方硬件地址
    pub(crate) sender_hw_addr: [u8; 6],
    /// 发送方协议地址
    pub(crate) sender_proto_addr: [u8; 4],
    /// 目标硬件地址
    pub(crate) target_hw_addr: [u8; 6],
    /// 目标协议地址
    pub(crate) target_proto_addr: [u8; 4],
}

impl ArpPacket {
    /// 从字节切片解析 ARP 包
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        cast::from_bytes(data)
    }

    /// 硬件类型(通常为 Ethernet = 1)
    #[inline]
    pub fn hw_type(&self) -> u16 {
        u16::from_be(self.hw_type)
    }

    /// 协议类型(通常为 IPv4 = 0x0800)
    #[inline]
    pub fn proto_type(&self) -> u16 {
        u16::from_be(self.proto_type)
    }

    /// 操作码(1 = 请求, 2 = 应答)
    #[inline]
    pub fn opcode(&self) -> u16 {
        u16::from_be(self.opcode)
    }

    /// 是否为 ARP 请求
    #[inline]
    pub fn is_request(&self) -> bool {
        self.opcode() == 1
    }

    /// 是否为 ARP 应答
    #[inline]
    pub fn is_reply(&self) -> bool {
        self.opcode() == 2
    }

    /// 发送方硬件地址
    #[inline]
    pub fn sender_mac(&self) -> [u8; 6] {
        self.sender_hw_addr
    }

    /// 发送方协议地址
    #[inline]
    pub fn sender_ip(&self) -> [u8; 4] {
        self.sender_proto_addr
    }

    /// 目标硬件地址
    #[inline]
    pub fn target_mac(&self) -> [u8; 6] {
        self.target_hw_addr
    }

    /// 目标协议地址
    #[inline]
    pub fn target_ip(&self) -> [u8; 4] {
        self.target_proto_addr
    }

    /// 验证 ARP 包基本合法性
    #[inline]
    pub fn validate(&self) -> bool {
        self.hw_type() == 1
            && self.proto_type() == ethertype::IPV4
            && self.hw_addr_len == 6
            && self.proto_addr_len == 4
            && (self.opcode() == 1 || self.opcode() == 2)
    }
}

/// ICMP 头(最小 8 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct IcmpHeader {
    /// ICMP 类型
    pub(crate) icmp_type: u8,
    /// 代码
    pub(crate) code: u8,
    /// 校验和(网络字节序)
    pub(crate) checksum: u16,
    /// 其余字段(类型相关,网络字节序)
    pub(crate) rest: u32,
}

impl IcmpHeader {
    /// 从字节切片解析 ICMP 头
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        cast::from_bytes(data)
    }

    /// ICMP 类型
    #[inline]
    pub fn icmp_type(&self) -> u8 {
        self.icmp_type
    }

    /// 代码
    #[inline]
    pub fn code(&self) -> u8 {
        self.code
    }

    /// 校验和
    #[inline]
    pub fn checksum(&self) -> u16 {
        u16::from_be(self.checksum)
    }

    /// 是否为 Echo Reply
    #[inline]
    pub fn is_echo_reply(&self) -> bool {
        self.icmp_type == icmp_type::ECHO_REPLY
    }

    /// 是否为 Echo Request
    #[inline]
    pub fn is_echo_request(&self) -> bool {
        self.icmp_type == icmp_type::ECHO_REQUEST
    }

    /// 是否为 Destination Unreachable
    #[inline]
    pub fn is_dest_unreachable(&self) -> bool {
        self.icmp_type == icmp_type::DEST_UNREACH
    }

    /// 是否为 Time Exceeded
    #[inline]
    pub fn is_time_exceeded(&self) -> bool {
        self.icmp_type == icmp_type::TIME_EXCEEDED
    }
}

/// ICMPv6 头(最小 4 字节)
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct IcmpV6Header {
    /// ICMPv6 类型
    pub(crate) icmp_type: u8,
    /// 代码
    pub(crate) code: u8,
    /// 校验和(网络字节序)
    pub(crate) checksum: u16,
}

impl IcmpV6Header {
    /// 从字节切片解析 ICMPv6 头
    #[inline]
    pub fn parse(data: &[u8]) -> Result<&Self> {
        cast::from_bytes(data)
    }

    /// ICMPv6 类型
    #[inline]
    pub fn icmp_type(&self) -> u8 {
        self.icmp_type
    }

    /// 代码
    #[inline]
    pub fn code(&self) -> u8 {
        self.code
    }

    /// 校验和
    #[inline]
    pub fn checksum(&self) -> u16 {
        u16::from_be(self.checksum)
    }

    /// 是否为 Echo Request
    #[inline]
    pub fn is_echo_request(&self) -> bool {
        self.icmp_type == icmpv6_type::ECHO_REQUEST
    }

    /// 是否为 Echo Reply
    #[inline]
    pub fn is_echo_reply(&self) -> bool {
        self.icmp_type == icmpv6_type::ECHO_REPLY
    }

    /// 是否为 Destination Unreachable
    #[inline]
    pub fn is_dest_unreachable(&self) -> bool {
        self.icmp_type == icmpv6_type::DEST_UNREACH
    }

    /// 是否为 Neighbor Solicitation
    #[inline]
    pub fn is_neighbor_sol(&self) -> bool {
        self.icmp_type == icmpv6_type::NEIGHBOR_SOL
    }

    /// 是否为 Neighbor Advertisement
    #[inline]
    pub fn is_neighbor_adv(&self) -> bool {
        self.icmp_type == icmpv6_type::NEIGHBOR_ADV
    }

    /// 是否为 Router Advertisement
    #[inline]
    pub fn is_router_adv(&self) -> bool {
        self.icmp_type == icmpv6_type::ROUTER_ADV
    }
}

/// IPv6 扩展头类型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ipv6ExtType {
    /// Hop-by-Hop Options
    HopByHop,
    /// Destination Options
    DestOptions,
    /// Routing Header
    Routing,
    /// Fragment Header
    Fragment,
    /// Authentication Header (IPSec)
    Auth,
    /// Encapsulating Security Payload (IPSec)
    Esp,
    /// Mobility Header
    Mobility,
    /// Host Identity Protocol
    Hip,
    /// Shim6 Protocol
    Shim6,
    /// No Next Header
    NoNext,
}

impl Ipv6ExtType {
    /// 从 next header 值转换
    #[inline]
    pub fn from_next_header(next: u8) -> Option<Self> {
        match next {
            0 => Some(Self::HopByHop),
            43 => Some(Self::Routing),
            44 => Some(Self::Fragment),
            50 => Some(Self::Esp),
            51 => Some(Self::Auth),
            60 => Some(Self::DestOptions),
            135 => Some(Self::Mobility),
            139 => Some(Self::Hip),
            140 => Some(Self::Shim6),
            59 => Some(Self::NoNext),
            _ => None,
        }
    }

    /// 是否为可解析的扩展头
    #[inline]
    pub fn is_parseable(next: u8) -> bool {
        Self::from_next_header(next).is_some()
    }
}

/// 解析后的完整数据包(零拷贝视图)
///
/// 所有字段均为借用引用,不持有数据。
/// 使用后必须及时释放原始帧。
#[derive(Debug, Clone, Copy)]
pub struct ParsedPacket<'a> {
    /// 以太网头
    pub eth: &'a EthHeader,
    /// VLAN 标签(如果存在)
    pub vlan: Option<&'a VlanTag>,
    /// IP 版本
    pub ip_version: IpVersion,
    /// IPv4 头(如果是 IPv4)
    pub ipv4: Option<&'a Ipv4Header>,
    /// IPv6 头(如果是 IPv6)
    pub ipv6: Option<&'a Ipv6Header>,
    /// ARP 包(如果是 ARP)
    pub arp: Option<&'a ArpPacket>,
    /// L4 协议标签
    pub l4_proto: L4Protocol,
    /// TCP 头(如果是 TCP 且解析成功)
    pub tcp: Option<&'a TcpHeader>,
    /// UDP 头(如果是 UDP 且解析成功)
    pub udp: Option<&'a UdpHeader>,
    /// ICMP 头(如果是 ICMP 且解析成功)
    pub icmp: Option<&'a IcmpHeader>,
    /// ICMPv6 头(如果是 ICMPv6 且解析成功)
    pub icmpv6: Option<&'a IcmpV6Header>,
    /// 原始数据引用
    pub raw: &'a [u8],
}

/// IP 版本
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IpVersion {
    /// IPv4
    V4,
    /// IPv6
    V6,
    /// 未知版本
    Unknown,
}

/// 解析数据包
///
/// 从零开始解析完整的 L2-L4 协议栈。
/// 有步数预算保护,超预算直接丢弃。
///
/// # 参数
/// * `data` - 原始帧数据
///
/// # 返回
/// * 解析后的数据包视图
#[inline]
pub fn parse_packet(data: &[u8]) -> Result<ParsedPacket<'_>> {
    parse_packet_with_budget(data, MAX_PARSE_STEPS)
}

/// 带可配置解析步数预算地解析数据包。
///
/// 与 [`parse_packet`] 等价,但步数预算由调用方指定(`> 0`),用于在
/// 畸形包防护粒度与极致吞吐之间自由权衡。`0` 表示使用默认
/// [`MAX_PARSE_STEPS`]。热路径仅一次计数器比较,开销可忽略。
#[inline]
pub fn parse_packet_with_budget(data: &[u8], max_steps: u32) -> Result<ParsedPacket<'_>> {
    let budget = if max_steps == 0 { MAX_PARSE_STEPS } else { max_steps };
    let steps = std::cell::Cell::new(0);
    parse_packet_with_budget_inner(data, &steps, budget)
}

#[inline]
fn parse_packet_with_budget_inner<'a>(
    data: &'a [u8],
    steps: &std::cell::Cell<u32>,
    budget: u32,
) -> Result<ParsedPacket<'a>> {
    // Step 1: Ethernet header
    steps.set(steps.get() + 1);
    if steps.get() > budget {
        return Err(NetError::InvalidPacket {
            reason: "parse step budget exceeded",
        });
    }

    let eth = EthHeader::parse(data)?;
    let mut offset = ETH_HEADER_LEN;
    let mut vlan = None;

    // Step 2: Check for VLAN
    steps.set(steps.get() + 1);
    if steps.get() > budget {
        return Err(NetError::InvalidPacket {
            reason: "parse step budget exceeded",
        });
    }

    let mut ethertype = eth.ethertype();
    if ethertype == ethertype::VLAN {
        if data.len() < offset + VLAN_TAG_LEN {
            return Err(NetError::PacketTooShort {
                need: offset + VLAN_TAG_LEN,
                got: data.len(),
            });
        }
        let vlan_tag = VlanTag::parse(&data[offset..])?;
        vlan = Some(vlan_tag);
        ethertype = vlan_tag.ethertype();
        offset += VLAN_TAG_LEN;
    }

    // Step 3: IP/ARP layer
    steps.set(steps.get() + 1);
    if steps.get() > budget {
        return Err(NetError::InvalidPacket {
            reason: "parse step budget exceeded",
        });
    }

    match ethertype {
        ethertype::IPV4 => {
            let result = parse_ipv4(&data[offset..], steps, budget)?;
            Ok(ParsedPacket {
                eth,
                vlan,
                ip_version: result.0,
                ipv4: result.1,
                ipv6: result.2,
                arp: None,
                l4_proto: result.3,
                tcp: result.4,
                udp: result.5,
                icmp: result.6,
                icmpv6: result.7,
                raw: data,
            })
        }
        ethertype::IPV6 => {
            let result = parse_ipv6(&data[offset..], steps, budget)?;
            Ok(ParsedPacket {
                eth,
                vlan,
                ip_version: result.0,
                ipv4: result.1,
                ipv6: result.2,
                arp: None,
                l4_proto: result.3,
                tcp: result.4,
                udp: result.5,
                icmp: result.6,
                icmpv6: result.7,
                raw: data,
            })
        }
        ethertype::ARP => {
            if data.len() < offset + ARP_PACKET_LEN {
                return Err(NetError::PacketTooShort {
                    need: offset + ARP_PACKET_LEN,
                    got: data.len(),
                });
            }
            let arp = ArpPacket::parse(&data[offset..])?;
            Ok(ParsedPacket {
                eth,
                vlan,
                ip_version: IpVersion::V4,
                ipv4: None,
                ipv6: None,
                arp: Some(arp),
                l4_proto: L4Protocol::Arp,
                tcp: None,
                udp: None,
                icmp: None,
                icmpv6: None,
                raw: data,
            })
        }
        other => Err(NetError::InvalidEtherType(other)),
    }
}

type L4Result<'a> = (
    IpVersion,
    Option<&'a Ipv4Header>,
    Option<&'a Ipv6Header>,
    L4Protocol,
    Option<&'a TcpHeader>,
    Option<&'a UdpHeader>,
    Option<&'a IcmpHeader>,
    Option<&'a IcmpV6Header>,
);

#[inline]
fn parse_ipv4<'a>(
    data: &'a [u8],
    steps: &std::cell::Cell<u32>,
    budget: u32,
) -> Result<L4Result<'a>> {
    steps.set(steps.get() + 1);
    if steps.get() > budget {
        return Err(NetError::InvalidPacket {
            reason: "parse step budget exceeded",
        });
    }

    let ipv4 = Ipv4Header::parse(data)?;
    let ip_hdr_len = ipv4.header_length();
    let l4_data_start = ip_hdr_len;

    if data.len() < l4_data_start {
        return Err(NetError::PacketTooShort {
            need: l4_data_start,
            got: data.len(),
        });
    }

    // RFC 791 §3.1: total_length 是 IP 头 + 数据的总长度(不含链路层头)。
    // 缓冲区必须至少包含 total_length 字节,否则视为非法包(fail-closed)。
    // 使用 checked 算术符合 AGENT.md §11.2.5(容量/地址/偏移计算必须 checked)。
    let total_len = ipv4.total_length() as usize;
    if total_len > data.len() {
        return Err(NetError::InvalidPacket {
            reason: "IPv4 total_length exceeds buffer size (RFC 791 violation)",
        });
    }

    // L4 payload 必须限定在 [l4_data_start, total_len) 区间内。
    // 此前使用 data.len() 作为上界,会读取 IP 包声明长度之外的尾部字节
    // (如 Ethernet padding 或抓包尾部填充),违反 RFC 791 语义。
    let (l4_proto, tcp_hdr, udp_hdr, icmp_hdr, icmpv6_hdr) = match ipv4.protocol() {
        ip_proto::TCP => {
            // checked_add 防止 l4_data_start + TCP_MIN_HEADER_LEN 溢出
            let need = l4_data_start.checked_add(TCP_MIN_HEADER_LEN).ok_or({
                NetError::InvalidPacket {
                    reason: "IPv4 L4 offset + TCP header length overflow",
                }
            })?;
            if total_len >= need {
                let tcp = TcpHeader::parse(&data[l4_data_start..total_len]).ok();
                (L4Protocol::Tcp, tcp, None, None, None)
            } else {
                (L4Protocol::Tcp, None, None, None, None)
            }
        }
        ip_proto::UDP => {
            let need = l4_data_start.checked_add(UDP_HEADER_LEN).ok_or({
                NetError::InvalidPacket {
                    reason: "IPv4 L4 offset + UDP header length overflow",
                }
            })?;
            if total_len >= need {
                let udp = UdpHeader::parse(&data[l4_data_start..total_len]).ok();
                (L4Protocol::Udp, None, udp, None, None)
            } else {
                (L4Protocol::Udp, None, None, None, None)
            }
        }
        ip_proto::ICMP => {
            let need = l4_data_start.checked_add(ICMP_MIN_HEADER_LEN).ok_or({
                NetError::InvalidPacket {
                    reason: "IPv4 L4 offset + ICMP header length overflow",
                }
            })?;
            if total_len >= need {
                let icmp = IcmpHeader::parse(&data[l4_data_start..total_len]).ok();
                (L4Protocol::Icmp, None, None, icmp, None)
            } else {
                (L4Protocol::Icmp, None, None, None, None)
            }
        }
        other => (L4Protocol::Other(other), None, None, None, None),
    };

    Ok((IpVersion::V4, Some(ipv4), None, l4_proto, tcp_hdr, udp_hdr, icmp_hdr, icmpv6_hdr))
}

#[inline]
fn parse_ipv6<'a>(
    data: &'a [u8],
    steps: &std::cell::Cell<u32>,
    budget: u32,
) -> Result<L4Result<'a>> {
    steps.set(steps.get() + 1);
    if steps.get() > budget {
        return Err(NetError::InvalidPacket {
            reason: "parse step budget exceeded",
        });
    }

    let ipv6 = Ipv6Header::parse(data)?;
    let l4_data_start = IPV6_HEADER_LEN;

    if data.len() < l4_data_start {
        return Err(NetError::PacketTooShort {
            need: l4_data_start,
            got: data.len(),
        });
    }

    // RFC 8200 §3: payload_length 是 IPv6 固定头之后的字节数(含扩展头与 L4 payload)。
    // 整个 IPv6 包长度 = IPV6_HEADER_LEN + payload_length。
    // 缓冲区必须至少包含此长度,否则视为非法包(fail-closed)。
    // 使用 checked_add 防止 IPV6_HEADER_LEN + payload_length 溢出(AGENT.md §11.2.5)。
    let payload_len = ipv6.payload_length() as usize;
    let ip_total_len = IPV6_HEADER_LEN.checked_add(payload_len).ok_or({
        NetError::InvalidPacket {
            reason: "IPv6 header length + payload_length overflow",
        }
    })?;
    if ip_total_len > data.len() {
        return Err(NetError::InvalidPacket {
            reason: "IPv6 payload_length exceeds buffer size (RFC 8200 violation)",
        });
    }

    let mut next_header = ipv6.next_header();
    let mut effective_offset = l4_data_start;

    // RFC 8200 §4: 遍历完整扩展头链,逐个跳过每个扩展头。
    // 每种扩展头的长度编码不同,必须按 RFC 正确计算跳过字节数。
    // 使用 checked 算术防止溢出,步数预算防 DoS(§4.4 / §11.2.5)。
    loop {
        // 步数预算:每个扩展头消耗一步,防止超长链 DoS
        steps.set(steps.get() + 1);
        if steps.get() > budget {
            return Err(NetError::InvalidPacket {
                reason: "IPv6 extension header chain exceeds parse step budget",
            });
        }

        let ext_type = Ipv6ExtType::from_next_header(next_header);
        match ext_type {
            // NoNextHeader(59):链终止,无 L4 payload
            Some(Ipv6ExtType::NoNext) => {
                // 无 L4 协议,直接返回(l4_proto = Other(59))
                return Ok((
                    IpVersion::V6,
                    None,
                    Some(ipv6),
                    L4Protocol::Other(next_header),
                    None,
                    None,
                    None,
                    None,
                ));
            }
            // HopByHop(0) / DestOptions(60) / Routing(43):
            // 长度 = 8 * (Hdr Ext Len + 1)(RFC 8200 §4.1-4.3)
            Some(Ipv6ExtType::HopByHop) | Some(Ipv6ExtType::DestOptions) | Some(Ipv6ExtType::Routing) => {
                // 扩展头至少 8 字节:next_header(1) + len_field(1) + pad(6..)
                let need = effective_offset.checked_add(2).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 ext header: offset+2 overflow" }
                })?;
                if ip_total_len < need {
                    return Err(NetError::PacketTooShort {
                        need,
                        got: ip_total_len,
                    });
                }
                let len_field = data[effective_offset + 1] as usize;
                let ext_bytes = len_field.checked_add(1).and_then(|v| v.checked_mul(8)).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 ext header length overflow" }
                })?;
                effective_offset = effective_offset.checked_add(ext_bytes).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 ext header skip offset overflow" }
                })?;
                if ip_total_len < effective_offset {
                    return Err(NetError::InvalidPacket {
                        reason: "IPv6 ext header exceeds declared packet length",
                    });
                }
                // 推进 next_header 为当前扩展头的 next_header 字段
                next_header = data[effective_offset - ext_bytes];
            }
            // Fragment(44): 固定 8 字节头(RFC 8200 §4.5)
            Some(Ipv6ExtType::Fragment) => {
                let need = effective_offset.checked_add(8).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 Fragment header offset+8 overflow" }
                })?;
                if ip_total_len < need {
                    return Err(NetError::PacketTooShort {
                        need,
                        got: ip_total_len,
                    });
                }
                // Fragment 头的 next_header 在第 0 字节
                next_header = data[effective_offset];
                effective_offset = need;
            }
            // Auth(51): 长度 = 12 + 4 * len_field(RFC 4302 §2.2)
            Some(Ipv6ExtType::Auth) => {
                let need = effective_offset.checked_add(2).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 Auth header offset+2 overflow" }
                })?;
                if ip_total_len < need {
                    return Err(NetError::PacketTooShort {
                        need,
                        got: ip_total_len,
                    });
                }
                let len_field = data[effective_offset + 1] as usize;
                let auth_bytes = len_field.checked_mul(4).and_then(|v| v.checked_add(12)).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 Auth header length overflow" }
                })?;
                effective_offset = effective_offset.checked_add(auth_bytes).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 Auth header skip offset overflow" }
                })?;
                if ip_total_len < effective_offset {
                    return Err(NetError::InvalidPacket {
                        reason: "IPv6 Auth header exceeds declared packet length",
                    });
                }
                next_header = data[effective_offset - auth_bytes];
            }
            // ESP(50): 加密载荷,无法解析内部 next_header,链终止
            Some(Ipv6ExtType::Esp) => {
                // ESP 载荷从 effective_offset 开始加密,无法继续解析扩展头链
                // 将 L4 协议设为 ESP(50),停止遍历
                break;
            }
            // Mobility(135) / HIP(139) / Shim6(140):
            // 采用与 HopByHop 相同的 8*(len+1) 长度编码(RFC 6275 §6.1.1)
            Some(Ipv6ExtType::Mobility) | Some(Ipv6ExtType::Hip) | Some(Ipv6ExtType::Shim6) => {
                let need = effective_offset.checked_add(2).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 Mobility/HIP/Shim6 header offset+2 overflow" }
                })?;
                if ip_total_len < need {
                    return Err(NetError::PacketTooShort {
                        need,
                        got: ip_total_len,
                    });
                }
                let len_field = data[effective_offset + 1] as usize;
                let ext_bytes = len_field.checked_add(1).and_then(|v| v.checked_mul(8)).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 Mobility/HIP/Shim6 header length overflow" }
                })?;
                effective_offset = effective_offset.checked_add(ext_bytes).ok_or({
                    NetError::InvalidPacket { reason: "IPv6 Mobility/HIP/Shim6 skip offset overflow" }
                })?;
                if ip_total_len < effective_offset {
                    return Err(NetError::InvalidPacket {
                        reason: "IPv6 Mobility/HIP/Shim6 exceeds declared packet length",
                    });
                }
                next_header = data[effective_offset - ext_bytes];
            }
            // None(已识别的协议号) 或未知扩展头:非扩展头,链终止
            None => break,
        }
    }

    if ip_total_len < effective_offset {
        return Err(NetError::InvalidPacket {
            reason: "IPv6 effective offset exceeds declared packet length",
        });
    }

    // L4 payload 必须限定在 [effective_offset, ip_total_len) 区间内,
    // 不再使用 data.len() 作为上界,避免读取 IPv6 包声明长度之外的尾部字节。
    let (l4_proto, tcp_hdr, udp_hdr, icmp_hdr, icmpv6_hdr) = match next_header {
        ip_proto::TCP => {
            let need = effective_offset.checked_add(TCP_MIN_HEADER_LEN).ok_or({
                NetError::InvalidPacket {
                    reason: "IPv6 L4 offset + TCP header length overflow",
                }
            })?;
            if ip_total_len >= need {
                let tcp = TcpHeader::parse(&data[effective_offset..ip_total_len]).ok();
                (L4Protocol::Tcp, tcp, None, None, None)
            } else {
                (L4Protocol::Tcp, None, None, None, None)
            }
        }
        ip_proto::UDP => {
            let need = effective_offset.checked_add(UDP_HEADER_LEN).ok_or({
                NetError::InvalidPacket {
                    reason: "IPv6 L4 offset + UDP header length overflow",
                }
            })?;
            if ip_total_len >= need {
                let udp = UdpHeader::parse(&data[effective_offset..ip_total_len]).ok();
                (L4Protocol::Udp, None, udp, None, None)
            } else {
                (L4Protocol::Udp, None, None, None, None)
            }
        }
        ip_proto::ICMPV6 => {
            let need = effective_offset.checked_add(ICMPV6_MIN_HEADER_LEN).ok_or({
                NetError::InvalidPacket {
                    reason: "IPv6 L4 offset + ICMPv6 header length overflow",
                }
            })?;
            if ip_total_len >= need {
                let icmpv6 = IcmpV6Header::parse(&data[effective_offset..ip_total_len]).ok();
                (L4Protocol::IcmpV6, None, None, None, icmpv6)
            } else {
                (L4Protocol::IcmpV6, None, None, None, None)
            }
        }
        other => (L4Protocol::Other(other), None, None, None, None),
    };

    Ok((IpVersion::V6, None, Some(ipv6), l4_proto, tcp_hdr, udp_hdr, icmp_hdr, icmpv6_hdr))
}

/// L4 协议标签
///
/// 仅作为协议标识符,不持有数据。
/// 实际的 TCP/UDP 头数据存储在 ParsedPacket 的独立字段中。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum L4Protocol {
    /// TCP(协议号 6)
    Tcp,
    /// UDP(协议号 17)
    Udp,
    /// ICMP(协议号 1)
    Icmp,
    /// ICMPv6(协议号 58)
    IcmpV6,
    /// ARP
    Arp,
    /// 其他协议(携带原始协议号)
    Other(u8),
}

impl L4Protocol {
    /// 是否为 TCP
    #[inline]
    pub fn is_tcp(&self) -> bool {
        matches!(self, Self::Tcp)
    }

    /// 是否为 UDP
    #[inline]
    pub fn is_udp(&self) -> bool {
        matches!(self, Self::Udp)
    }

    /// 是否为 ICMP
    #[inline]
    pub fn is_icmp(&self) -> bool {
        matches!(self, Self::Icmp)
    }

    /// 是否为 ICMPv6
    #[inline]
    pub fn is_icmpv6(&self) -> bool {
        matches!(self, Self::IcmpV6)
    }

    /// 是否为 ARP
    #[inline]
    pub fn is_arp(&self) -> bool {
        matches!(self, Self::Arp)
    }

    /// 是否为可处理的协议
    #[inline]
    pub fn is_supported(&self) -> bool {
        matches!(self, Self::Tcp | Self::Udp)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_eth_header_parse() {
        let data = [
            0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, // dst_mac
            0x11, 0x22, 0x33, 0x44, 0x55, 0x66, // src_mac
            0x08, 0x00, // ethertype = IPv4
        ];
        let eth = EthHeader::parse(&data).unwrap();
        assert_eq!(eth.ethertype(), ethertype::IPV4);
        assert_eq!(eth.dst_mac(), [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
    }

    #[test]
    fn test_eth_header_too_short() {
        let data = [0x00; 10];
        let result = EthHeader::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_ipv4_header_parse() {
        let mut data = [0u8; 20];
        data[0] = 0x45; // version=4, ihl=5
        data[1] = 0x00; // TOS
        data[2] = 0x00;
        data[3] = 0x28; // total length = 40
        data[8] = 64; // TTL
        data[9] = ip_proto::TCP; // protocol = TCP
        data[12] = 10;
        data[13] = 0;
        data[14] = 0;
        data[15] = 1; // src = 10.0.0.1
        data[16] = 10;
        data[17] = 0;
        data[18] = 0;
        data[19] = 2; // dst = 10.0.0.2

        let ipv4 = Ipv4Header::parse(&data).unwrap();
        assert_eq!(ipv4.version(), 4);
        assert_eq!(ipv4.protocol(), ip_proto::TCP);
        assert_eq!(ipv4.ttl(), 64);
        assert_eq!(ipv4.total_length(), 40);
        assert_eq!(ipv4.src_ip(), [10, 0, 0, 1]);
        assert_eq!(ipv4.dst_ip(), [10, 0, 0, 2]);
    }

    #[test]
    fn test_ipv4_checksum_verify() {
        let mut data = [0u8; 20];
        data[0] = 0x45;
        data[1] = 0x00;
        data[2] = 0x00;
        data[3] = 0x28;
        data[8] = 64;
        data[9] = ip_proto::TCP;
        data[12] = 10;
        data[13] = 0;
        data[14] = 0;
        data[15] = 1;
        data[16] = 10;
        data[17] = 0;
        data[18] = 0;
        data[19] = 2;

        // 预计算的正确 checksum(将 checksum 字段视为 0 后计算)
        let checksum_val: u16 = 0x66CE;
        data[10] = (checksum_val >> 8) as u8;
        data[11] = (checksum_val & 0xFF) as u8;

        // 校验和验证以 free function 从原数据切片取样(替代出界 struct 指针实现)
        let ipv4 = Ipv4Header::parse(&data).unwrap();
        assert!(verify_ipv4_checksum(&data).unwrap());
        assert_eq!(ipv4.ihl(), 5);
    }

    #[test]
    fn test_tcp_header_parse() {
        let mut data = [0u8; 20];
        // src_port = 12345
        data[0] = 0x30;
        data[1] = 0x39;
        // dst_port = 80
        data[2] = 0x00;
        data[3] = 0x50;
        // seq_num = 1
        data[4] = 0x00;
        data[5] = 0x00;
        data[6] = 0x00;
        data[7] = 0x01;
        // data_offset = 5 (20 bytes), flags = SYN
        data[12] = 0x50;
        data[13] = 0x02;

        let tcp = TcpHeader::parse(&data).unwrap();
        assert_eq!(tcp.src_port(), 12345);
        assert_eq!(tcp.dst_port(), 80);
        assert!(tcp.syn());
        assert!(!tcp.ack());
        assert_eq!(tcp.data_offset(), 5);
        assert!(tcp.validate_flags());
    }

    #[test]
    fn test_tcp_flags_validation() {
        let mut data = [0u8; 20];
        // 全零标志(无效)— data_offset=5 保证 parse 通过
        data[12] = 0x50;
        data[13] = 0x00;
        let tcp = TcpHeader::parse(&data).unwrap();
        assert!(!tcp.validate_flags());

        // 全 1 标志(9 bit flags 全置位 = 0x1FF)
        // data_offset=5, flags=0x1FF (bits 0-8 全 1)
        data[12] = 0x51; // data_offset=5, 保留位 0b001
        data[13] = 0xFF; // flags 0xFF + 保留位 bit0
        // u16::from_be = 0x51FF, mask 0x01FF -> 0x01FF (全 1,无效)
        let tcp = TcpHeader::parse(&data).unwrap();
        assert!(!tcp.validate_flags());

        // 正常标志(SYN+ACK=0x02|0x10=0x12)
        data[12] = 0x50;
        data[13] = 0x12;
        let tcp = TcpHeader::parse(&data).unwrap();
        assert!(tcp.validate_flags());
    }

    #[test]
    fn test_udp_header_parse() {
        let mut data = [0u8; 16];
        // src_port = 53
        data[0] = 0x00;
        data[1] = 0x35;
        // dst_port = 12345
        data[2] = 0x30;
        data[3] = 0x39;
        // length = 16
        data[4] = 0x00;
        data[5] = 0x10;

        let udp = UdpHeader::parse(&data).unwrap();
        assert_eq!(udp.src_port(), 53);
        assert_eq!(udp.dst_port(), 12345);
        assert_eq!(udp.length(), 16);
        assert_eq!(udp.payload_len(), 8);
        assert!(udp.validate_length(100));
    }

    #[test]
    fn test_arp_packet_parse() {
        let mut data = [0u8; 28];
        // Hardware type = Ethernet (1)
        data[0] = 0x00;
        data[1] = 0x01;
        // Protocol type = IPv4 (0x0800)
        data[2] = 0x08;
        data[3] = 0x00;
        // HW addr len = 6, Proto addr len = 4
        data[4] = 0x06;
        data[5] = 0x04;
        // Opcode = 1 (request)
        data[6] = 0x00;
        data[7] = 0x01;
        // Sender HW addr
        data[8..14].copy_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66]);
        // Sender IP
        data[14] = 192;
        data[15] = 168;
        data[16] = 1;
        data[17] = 1;
        // Target HW addr (zero for request)
        data[18..24].copy_from_slice(&[0x00; 6]);
        // Target IP
        data[24] = 192;
        data[25] = 168;
        data[26] = 1;
        data[27] = 2;

        let arp = ArpPacket::parse(&data).unwrap();
        assert_eq!(arp.hw_type(), 1);
        assert_eq!(arp.proto_type(), ethertype::IPV4);
        assert_eq!(arp.opcode(), 1);
        assert!(arp.is_request());
        assert!(!arp.is_reply());
        assert!(arp.validate());
    }

    #[test]
    fn test_arp_reply() {
        let mut data = [0u8; 28];
        data[0] = 0x00;
        data[1] = 0x01;
        data[2] = 0x08;
        data[3] = 0x00;
        data[4] = 0x06;
        data[5] = 0x04;
        // Opcode = 2 (reply)
        data[6] = 0x00;
        data[7] = 0x02;
        data[8..14].copy_from_slice(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66]);
        data[14] = 10;
        data[15] = 0;
        data[16] = 0;
        data[17] = 1;
        data[18..24].copy_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]);
        data[24] = 10;
        data[25] = 0;
        data[26] = 0;
        data[27] = 2;

        let arp = ArpPacket::parse(&data).unwrap();
        assert!(arp.is_reply());
        assert!(arp.validate());
    }

    #[test]
    fn test_icmp_header_parse() {
        let mut data = [0u8; 8];
        // Type = Echo Request (8)
        data[0] = icmp_type::ECHO_REQUEST;
        // Code = 0
        data[1] = 0;
        // Checksum = 0 (will be calculated)
        data[2] = 0;
        data[3] = 0;
        // Rest: ID=1, Seq=1
        data[4] = 0x00;
        data[5] = 0x01;
        data[6] = 0x00;
        data[7] = 0x01;

        let icmp = IcmpHeader::parse(&data).unwrap();
        assert_eq!(icmp.icmp_type(), icmp_type::ECHO_REQUEST);
        assert_eq!(icmp.code(), 0);
        assert!(icmp.is_echo_request());
        assert!(!icmp.is_echo_reply());
    }

    #[test]
    fn test_icmpv6_header_parse() {
        let mut data = [0u8; 4];
        // Type = Echo Request (128)
        data[0] = icmpv6_type::ECHO_REQUEST;
        data[1] = 0;
        data[2] = 0;
        data[3] = 0;

        let icmpv6 = IcmpV6Header::parse(&data).unwrap();
        assert_eq!(icmpv6.icmp_type(), icmpv6_type::ECHO_REQUEST);
        assert!(icmpv6.is_echo_request());
        assert!(!icmpv6.is_echo_reply());
    }

    #[test]
    fn test_vlan_detection() {
        let mut data = [0u8; 18]; // 14 + 4
        data[12] = 0x81;
        data[13] = 0x00; // VLAN ethertype
        data[14] = 0x00;
        data[15] = 0x64; // VLAN ID = 100
        data[16] = 0x08;
        data[17] = 0x00; // inner ethertype = IPv4

        let vlan = VlanTag::parse(&data[14..]).unwrap();
        assert_eq!(vlan.vlan_id(), 100);
        assert_eq!(vlan.ethertype(), ethertype::IPV4);
    }

    #[test]
    fn test_full_packet_parse_udp() {
        let mut data = vec![0u8; 14 + 20 + 8 + 16];
        // Ethernet
        data[12] = 0x08;
        data[13] = 0x00;
        // IPv4
        data[14] = 0x45; // version=4, ihl=5
        data[14 + 9] = ip_proto::UDP; // protocol = UDP
        data[14 + 2] = 0x00;
        data[14 + 3] = (20 + 8 + 16) as u8; // total length
        // UDP
        let udp_offset = 14 + 20;
        data[udp_offset] = 0x00;
        data[udp_offset + 1] = 0x35; // src_port = 53
        data[udp_offset + 2] = 0x00;
        data[udp_offset + 3] = 0x35; // dst_port = 53
        data[udp_offset + 4] = 0x00;
        data[udp_offset + 5] = 24; // length = 24

        let packet = parse_packet(&data).unwrap();
        assert_eq!(packet.ip_version, IpVersion::V4);
        assert!(packet.l4_proto.is_udp());
        assert!(packet.udp.is_some());
    }

    #[test]
    fn test_full_packet_parse_arp() {
        let mut data = vec![0u8; 14 + 28];
        // Ethernet type = ARP (0x0806)
        data[12] = 0x08;
        data[13] = 0x06;
        // ARP packet (request)
        let arp_offset = 14;
        // HW type = Ethernet (1)
        data[arp_offset] = 0x00;
        data[arp_offset + 1] = 0x01;
        // Proto = IPv4 (0x0800)
        data[arp_offset + 2] = 0x08;
        data[arp_offset + 3] = 0x00;
        // HW addr len = 6, Proto addr len = 4
        data[arp_offset + 4] = 0x06;
        data[arp_offset + 5] = 0x04;
        // Opcode = 1 (request)
        data[arp_offset + 6] = 0x00;
        data[arp_offset + 7] = 0x01;

        let packet = parse_packet(&data).unwrap();
        assert!(packet.arp.is_some());
        let arp = packet.arp.unwrap();
        assert!(arp.is_request());
        // 注意:validate() 检查 hw_addr_len==6, proto_addr_len==4
        // 由于 data 已正确设置这些字段,应通过
        assert_eq!(arp.hw_addr_len, 6);
        assert_eq!(arp.proto_addr_len, 4);
    }

    #[test]
    fn test_full_packet_parse_icmp() {
        let mut data = vec![0u8; 14 + 20 + 8];
        // Ethernet
        data[12] = 0x08;
        data[13] = 0x00;
        // IPv4
        data[14] = 0x45;
        data[14 + 9] = ip_proto::ICMP;
        data[14 + 2] = 0x00;
        data[14 + 3] = 28; // total length
        // ICMP
        let icmp_offset = 14 + 20;
        data[icmp_offset] = icmp_type::ECHO_REQUEST;
        data[icmp_offset + 1] = 0;

        let packet = parse_packet(&data).unwrap();
        assert_eq!(packet.ip_version, IpVersion::V4);
        assert!(packet.l4_proto.is_icmp());
        assert!(packet.icmp.is_some());
    }

    #[test]
    fn test_packet_too_short() {
        let data = [0u8; 5];
        let result = parse_packet(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_unknown_ethertype() {
        let mut data = [0u8; 14];
        data[12] = 0x08;
        data[13] = 0x99; // Unknown type
        let result = parse_packet(&data);
        assert!(result.is_err());
    }

    // ==================== 白盒测试:parse 校验加固 ====================

    /// IPv4 IHL < 5 应被 parse 拒绝
    #[test]
    fn test_ipv4_parse_rejects_ihl_too_small() {
        let mut data = [0u8; 20];
        data[0] = 0x43; // version=4, ihl=3 → header_length=12
        let result = Ipv4Header::parse(&data);
        assert!(result.is_err());
    }

    /// IPv4 IHL=0 应被 parse 拒绝
    #[test]
    fn test_ipv4_parse_rejects_ihl_zero() {
        let mut data = [0u8; 20];
        data[0] = 0x40; // version=4, ihl=0
        let result = Ipv4Header::parse(&data);
        assert!(result.is_err());
    }

    /// IPv4 header_length > data.len() 应被 parse 拒绝
    #[test]
    fn test_ipv4_parse_rejects_header_exceeds_data() {
        let mut data = [0u8; 30];
        data[0] = 0x4F; // version=4, ihl=15 → header_length=60 > 30
        let result = Ipv4Header::parse(&data);
        assert!(result.is_err());
    }

    /// IPv4 IHL=5 正好等于最小头长,应通过
    #[test]
    fn test_ipv4_parse_accepts_min_ihl() {
        let mut data = [0u8; 20];
        data[0] = 0x45; // version=4, ihl=5
        // RFC 791: total_length >= header_length(20 >= 20)
        data[2] = 0x00;
        data[3] = 0x14; // total_length = 20
        let result = Ipv4Header::parse(&data);
        assert!(result.is_ok());
    }

    /// IPv4 IHL=15(最大值),数据足够时应通过
    #[test]
    fn test_ipv4_parse_accepts_max_ihl() {
        let mut data = [0u8; 60];
        data[0] = 0x4F; // version=4, ihl=15 → header_length=60
        // RFC 791: total_length >= header_length(60 >= 60)
        data[2] = 0x00;
        data[3] = 0x3C; // total_length = 60
        let result = Ipv4Header::parse(&data);
        assert!(result.is_ok());
    }

    /// TCP data_offset < 5 应被 parse 拒绝
    #[test]
    fn test_tcp_parse_rejects_data_offset_too_small() {
        let mut data = [0u8; 20];
        data[12] = 0x30; // data_offset=3 → header_length=12
        let result = TcpHeader::parse(&data);
        assert!(result.is_err());
    }

    /// TCP data_offset=0 应被 parse 拒绝
    #[test]
    fn test_tcp_parse_rejects_data_offset_zero() {
        let mut data = [0u8; 20];
        data[12] = 0x00; // data_offset=0
        data[13] = 0x02; // SYN flag
        let result = TcpHeader::parse(&data);
        assert!(result.is_err());
    }

    /// TCP header_length > data.len() 应被 parse 拒绝
    #[test]
    fn test_tcp_parse_rejects_header_exceeds_data() {
        let mut data = [0u8; 20];
        data[12] = 0xF0; // data_offset=15 → header_length=60 > 20
        let result = TcpHeader::parse(&data);
        assert!(result.is_err());
    }

    /// TCP data_offset=5 正好等于最小头长,应通过
    #[test]
    fn test_tcp_parse_accepts_min_data_offset() {
        let mut data = [0u8; 20];
        data[12] = 0x50; // data_offset=5
        data[13] = 0x02; // SYN
        let result = TcpHeader::parse(&data);
        assert!(result.is_ok());
    }

    /// UDP length < 8 应被 parse 拒绝
    #[test]
    fn test_udp_parse_rejects_length_too_small() {
        let mut data = [0u8; 8];
        data[4] = 0x00;
        data[5] = 0x04; // length = 4 < 8
        let result = UdpHeader::parse(&data);
        assert!(result.is_err());
    }

    /// UDP length = 0 应被 parse 拒绝
    #[test]
    fn test_udp_parse_rejects_length_zero() {
        let mut data = [0u8; 8];
        data[4] = 0x00;
        data[5] = 0x00; // length = 0
        let result = UdpHeader::parse(&data);
        assert!(result.is_err());
    }

    /// UDP length = 8 正好等于最小值,应通过
    #[test]
    fn test_udp_parse_accepts_min_length() {
        let mut data = [0u8; 8];
        data[4] = 0x00;
        data[5] = 0x08; // length = 8
        let result = UdpHeader::parse(&data);
        assert!(result.is_ok());
    }

    // ==================== RFC 791/8200 严格校验测试 ====================
    //
    // 以下测试覆盖新加固的 length 字段校验逻辑:
    // - Ipv4Header::parse: total_length >= header_length(头内部一致性)
    // - parse_ipv4: total_length <= data.len()(缓冲区一致性)+ L4 切片边界
    // - parse_ipv6: payload_length + 40 <= data.len()(缓冲区一致性)+ L4 切片边界

    /// IPv4 total_length = 0 应被 parse 拒绝(违反 RFC 791: < header_length)
    #[test]
    fn test_ipv4_parse_rejects_total_length_zero() {
        let mut data = [0u8; 20];
        data[0] = 0x45; // version=4, ihl=5 → header_length=20
        data[2] = 0x00;
        data[3] = 0x00; // total_length = 0 < 20
        let result = Ipv4Header::parse(&data);
        assert!(result.is_err());
    }

    /// IPv4 total_length < header_length 应被 parse 拒绝
    #[test]
    fn test_ipv4_parse_rejects_total_length_less_than_header() {
        let mut data = [0u8; 20];
        data[0] = 0x45; // ihl=5 → header_length=20
        data[2] = 0x00;
        data[3] = 0x13; // total_length = 19 < 20
        let result = Ipv4Header::parse(&data);
        assert!(result.is_err());
    }

    /// IPv4 total_length = header_length(无 L4 payload)应通过头解析
    #[test]
    fn test_ipv4_parse_accepts_total_length_equals_header() {
        let mut data = [0u8; 20];
        data[0] = 0x45;
        data[2] = 0x00;
        data[3] = 0x14; // total_length = 20 = header_length
        let result = Ipv4Header::parse(&data);
        assert!(result.is_ok());
    }

    /// IPv4 IHL=15 + total_length=60(最大头长,无 payload)应通过
    #[test]
    fn test_ipv4_parse_accepts_max_ihl_with_matching_total_length() {
        let mut data = [0u8; 60];
        data[0] = 0x4F; // ihl=15 → header_length=60
        data[2] = 0x00;
        data[3] = 0x3C; // total_length = 60 = header_length
        let result = Ipv4Header::parse(&data);
        assert!(result.is_ok());
    }

    /// parse_ipv4: total_length > data.len() 应被拒绝(缓冲区一致性)
    #[test]
    fn test_parse_ipv4_rejects_total_length_exceeds_buffer() {
        // IP 层切片仅 30 字节,但 total_length 声明 100
        let mut data = [0u8; 30];
        data[0] = 0x45; // version=4, ihl=5
        data[2] = 0x00;
        data[3] = 0x64; // total_length = 100 > 30
        data[9] = ip_proto::TCP;
        let steps = std::cell::Cell::new(0);
        let result = parse_ipv4(&data, &steps, MAX_PARSE_STEPS);
        assert!(result.is_err());
    }

    /// parse_ipv4: total_length 限定 L4 切片边界,TCP 头超出 total_length 时不解析
    ///
    /// 此测试验证修复核心:此前 data.len() 用作 L4 上界,会读取 IP 包声明长度
    /// 之外的字节。修复后仅 [hdr_len, total_len) 区间内字节可用于 L4 解析。
    #[test]
    fn test_parse_ipv4_l4_bounded_by_total_length() {
        // 构造 100 字节缓冲区(IP 层切片),但 total_length 仅 30 字节
        // TCP 头需 20 字节,但 total_length - hdr_len = 30 - 20 = 10 < 20
        // 因此 TCP 头不应被解析(返回 None),但 parse_ipv4 整体应成功
        let mut data = [0u8; 100];
        data[0] = 0x45; // version=4, ihl=5 → hdr_len=20
        data[2] = 0x00;
        data[3] = 0x1E; // total_length = 30
        data[9] = ip_proto::TCP;
        // 在 offset 20 之后填充看似合法的 TCP 头数据
        data[20 + 12] = 0x50; // data_offset=5
        data[20 + 13] = 0x02; // SYN

        let steps = std::cell::Cell::new(0);
        let result = parse_ipv4(&data, &steps, MAX_PARSE_STEPS).unwrap();
        // l4_proto 仍标记为 Tcp
        assert_eq!(result.3, L4Protocol::Tcp);
        // 但 tcp_hdr 应为 None(因 total_length 不足以容纳 TCP 头)
        assert!(result.4.is_none(), "TCP header should not be parsed when total_length < hdr_len + TCP_MIN_HEADER_LEN");
    }

    /// parse_ipv4: total_length 足够容纳 TCP 头时,TCP 应被解析
    #[test]
    fn test_parse_ipv4_l4_parsed_when_total_length_sufficient() {
        // 缓冲区 100 字节,total_length = 40(精确容纳 20 IP + 20 TCP)
        let mut data = [0u8; 100];
        data[0] = 0x45;
        data[2] = 0x00;
        data[3] = 0x28; // total_length = 40
        data[9] = ip_proto::TCP;
        data[20 + 12] = 0x50; // data_offset=5
        data[20 + 13] = 0x02; // SYN

        let steps = std::cell::Cell::new(0);
        let result = parse_ipv4(&data, &steps, MAX_PARSE_STEPS).unwrap();
        assert_eq!(result.3, L4Protocol::Tcp);
        assert!(result.4.is_some(), "TCP header should be parsed when total_length is sufficient");
    }

    /// parse_ipv4: total_length < data.len() 时,TCP 仍能被正确解析(不受尾部填充影响)
    #[test]
    fn test_parse_ipv4_total_length_less_than_buffer_with_valid_tcp() {
        // 缓冲区 80 字节,total_length = 40(40 字节后是抓包尾部填充)
        let mut data = [0u8; 80];
        data[0] = 0x45;
        data[2] = 0x00;
        data[3] = 0x28; // total_length = 40
        data[9] = ip_proto::TCP;
        data[20 + 12] = 0x50;
        data[20 + 13] = 0x02;

        let steps = std::cell::Cell::new(0);
        let result = parse_ipv4(&data, &steps, MAX_PARSE_STEPS).unwrap();
        assert_eq!(result.3, L4Protocol::Tcp);
        assert!(result.4.is_some());
    }

    /// parse_ipv6: payload_length + 40 > data.len() 应被拒绝
    #[test]
    fn test_parse_ipv6_rejects_payload_length_exceeds_buffer() {
        // IP 层切片 60 字节,但 payload_length=100 → ip_total_len=140 > 60
        let mut data = [0u8; 60];
        // version=6 (top 4 bits of byte 0 in big-endian u32)
        data[0] = 0x60; // version=6, traffic_class=0, flow_label=0
        data[4] = 0x00;
        data[5] = 0x64; // payload_length = 100
        data[6] = ip_proto::TCP; // next_header
        data[7] = 64; // hop_limit

        let steps = std::cell::Cell::new(0);
        let result = parse_ipv6(&data, &steps, MAX_PARSE_STEPS);
        assert!(result.is_err());
    }

    /// parse_ipv6: payload_length = 0(无 L4 payload)应通过,L4 不解析
    #[test]
    fn test_parse_ipv6_accepts_zero_payload_length() {
        let mut data = [0u8; 40];
        data[0] = 0x60; // version=6
        data[4] = 0x00;
        data[5] = 0x00; // payload_length = 0
        data[6] = ip_proto::TCP; // next_header (但无 L4 数据)

        let steps = std::cell::Cell::new(0);
        let result = parse_ipv6(&data, &steps, MAX_PARSE_STEPS).unwrap();
        assert_eq!(result.0, IpVersion::V6);
        assert_eq!(result.3, L4Protocol::Tcp);
        // TCP 头应为 None(payload_length=0,无法容纳 TCP 头)
        assert!(result.4.is_none());
    }

    /// parse_ipv6: payload_length 限定 L4 切片边界
    #[test]
    fn test_parse_ipv6_l4_bounded_by_payload_length() {
        // 60 字节缓冲区,IPv6 头 40 + payload_length=10 → ip_total_len=50
        // TCP 头需 20 字节,但 payload_length=10 < 20 → TCP 不应被解析
        let mut data = [0u8; 60];
        data[0] = 0x60;
        data[4] = 0x00;
        data[5] = 0x0A; // payload_length = 10
        data[6] = ip_proto::TCP;
        data[7] = 64;
        // 在 offset 40 之后填充看似合法的 TCP 头数据
        data[40 + 12] = 0x50;
        data[40 + 13] = 0x02;

        let steps = std::cell::Cell::new(0);
        let result = parse_ipv6(&data, &steps, MAX_PARSE_STEPS).unwrap();
        assert_eq!(result.3, L4Protocol::Tcp);
        assert!(result.4.is_none(), "TCP header should not be parsed when payload_length < TCP_MIN_HEADER_LEN");
    }

    /// parse_ipv6: payload_length 足够时 TCP 头应被解析
    #[test]
    fn test_parse_ipv6_l4_parsed_when_payload_length_sufficient() {
        // 80 字节缓冲区,IPv6 头 40 + payload_length=20 → ip_total_len=60
        // TCP 头需 20 字节,payload_length=20 >= 20 → TCP 应被解析
        let mut data = [0u8; 80];
        data[0] = 0x60;
        data[4] = 0x00;
        data[5] = 0x14; // payload_length = 20
        data[6] = ip_proto::TCP;
        data[7] = 64;
        data[40 + 12] = 0x50;
        data[40 + 13] = 0x02;

        let steps = std::cell::Cell::new(0);
        let result = parse_ipv6(&data, &steps, MAX_PARSE_STEPS).unwrap();
        assert_eq!(result.3, L4Protocol::Tcp);
        assert!(result.4.is_some());
    }

    /// 端到端:parse_packet 修复后,含 Ethernet padding 的 IPv4 包应正确解析
    ///
    /// 真实抓包场景:Ethernet 帧最小 60 字节,短 IP 包会被 NIC padding 至 60 字节。
    /// 修复前:parse_packet 会用 data.len() 解析 L4,可能读取 padding 字节。
    /// 修复后:parse_packet 仅使用 total_length 范围内的字节解析 L4。
    #[test]
    fn test_parse_packet_with_ethernet_padding() {
        // Ethernet 14 + IPv4 20 + ICMP 8 = 42 字节,但 Ethernet 帧被 padding 至 60 字节
        let mut data = [0u8; 60];
        // Ethernet
        data[12] = 0x08;
        data[13] = 0x00; // IPv4
        // IPv4
        data[14] = 0x45; // ihl=5
        data[14 + 2] = 0x00;
        data[14 + 3] = 0x1C; // total_length = 28(20 IP + 8 ICMP),不含 18 字节 padding
        data[14 + 9] = ip_proto::ICMP;
        // ICMP Echo Request
        let icmp_offset = 14 + 20;
        data[icmp_offset] = icmp_type::ECHO_REQUEST;
        data[icmp_offset + 1] = 0;
        // 在 padding 区域填充垃圾数据(模拟 NIC padding)
        data[42] = 0xFF;
        data[43] = 0xFF;
        data[59] = 0xFF;

        let packet = parse_packet(&data).unwrap();
        assert_eq!(packet.ip_version, IpVersion::V4);
        assert!(packet.l4_proto.is_icmp());
        assert!(packet.icmp.is_some(), "ICMP header should be parsed within total_length bounds");
    }

    /// 端到端:parse_packet 拒绝 total_length 超过缓冲区的 IPv4 包
    #[test]
    fn test_parse_packet_rejects_oversized_total_length() {
        let mut data = [0u8; 50];
        data[12] = 0x08;
        data[13] = 0x00; // IPv4
        data[14] = 0x45;
        data[14 + 2] = 0x00;
        data[14 + 3] = 0x64; // total_length = 100,但 IP 层切片仅 36 字节
        data[14 + 9] = ip_proto::TCP;

        let result = parse_packet(&data);
        assert!(result.is_err(), "parse_packet should reject packet with total_length > buffer size");
    }

    /// 端到端:parse_packet 拒绝 payload_length 超过缓冲区的 IPv6 包
    #[test]
    fn test_parse_packet_rejects_oversized_ipv6_payload_length() {
        let mut data = [0u8; 60];
        data[12] = 0x86;
        data[13] = 0xDD; // IPv6
        data[14] = 0x60; // version=6
        data[14 + 4] = 0x00;
        data[14 + 5] = 0x64; // payload_length = 100,但 IP 层切片仅 46 字节
        data[14 + 6] = ip_proto::TCP;

        let result = parse_packet(&data);
        assert!(result.is_err());
    }

    /// 端到端:VLAN 标记的 IPv4 包也应受 total_length 校验
    #[test]
    fn test_parse_packet_vlan_ipv4_respects_total_length() {
        // Ethernet(14) + VLAN(4) + IPv4(20) + TCP(20) = 58 字节
        let mut data = [0u8; 80];
        // Ethernet with VLAN
        data[12] = 0x81;
        data[13] = 0x00; // VLAN ethertype
        data[14] = 0x00;
        data[15] = 0x64; // VLAN ID = 100
        data[16] = 0x08;
        data[17] = 0x00; // inner ethertype = IPv4
        // IPv4 starts at offset 18
        data[18] = 0x45;
        data[18 + 2] = 0x00;
        data[18 + 3] = 0x28; // total_length = 40 (20 IP + 20 TCP)
        data[18 + 9] = ip_proto::TCP;
        // TCP starts at offset 18 + 20 = 38
        data[38 + 12] = 0x50; // data_offset=5
        data[38 + 13] = 0x02; // SYN

        let packet = parse_packet(&data).unwrap();
        assert_eq!(packet.ip_version, IpVersion::V4);
        assert!(packet.vlan.is_some());
        assert_eq!(packet.vlan.unwrap().vlan_id(), 100);
        assert!(packet.l4_proto.is_tcp());
        assert!(packet.tcp.is_some(), "TCP header should be parsed within total_length bounds");
    }

    #[test]
    fn test_ipv4_checksum_all_zeros() {
        let mut data = [0u8; 20];
        data[0] = 0x45;
        data[2] = 0x00;
        data[3] = 0x14;
        data[8] = 64;
        data[9] = ip_proto::TCP;

        // 校验和验证以 free function 从原数据切片取样(替代出界 struct 指针实现)
        let ipv4 = Ipv4Header::parse(&data).unwrap();
        assert!(!verify_ipv4_checksum(&data).unwrap());
        assert_eq!(ipv4.ihl(), 5);
    }

    #[test]
    fn test_ipv4_checksum_all_ones() {
        let mut data = [0xFFu8; 20];
        data[0] = 0x45;
        data[10] = 0x00;
        data[11] = 0x00;

        let ipv4 = Ipv4Header::parse(&data).unwrap();
        assert!(!verify_ipv4_checksum(&data).unwrap());
        assert_eq!(ipv4.ihl(), 5);
    }

    #[test]
    fn test_ipv4_header_too_short() {
        let data = [0u8; 10];
        let result = Ipv4Header::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_ipv6_header_too_short() {
        let data = [0u8; 20];
        let result = Ipv6Header::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_tcp_header_too_short() {
        let data = [0u8; 10];
        let result = TcpHeader::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_udp_header_too_short() {
        let data = [0u8; 4];
        let result = UdpHeader::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_arp_packet_too_short() {
        let data = [0u8; 10];
        let result = ArpPacket::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_tcp_flags_all_combinations() {
        let flags_tests = vec![
            (0x02, true, false, false, false, false),  // SYN
            (0x10, false, true, false, false, false),  // ACK
            (0x01, false, false, true, false, false),  // FIN
            (0x04, false, false, false, true, false),  // RST
            (0x08, false, false, false, false, true),  // PSH
            (0x12, true, true, false, false, false),   // SYN+ACK
            (0x11, false, true, true, false, false),   // FIN+ACK
            (0x18, false, true, false, false, true),   // PSH+ACK
        ];

        for (flags_byte, syn, ack, fin, rst, psh) in flags_tests {
            let mut data = [0u8; 20];
            data[12] = 0x50;
            data[13] = flags_byte;
            let tcp = TcpHeader::parse(&data).unwrap();
            assert_eq!(tcp.syn(), syn, "SYN flag mismatch for 0x{:02x}", flags_byte);
            assert_eq!(tcp.ack(), ack, "ACK flag mismatch for 0x{:02x}", flags_byte);
            assert_eq!(tcp.fin(), fin, "FIN flag mismatch for 0x{:02x}", flags_byte);
            assert_eq!(tcp.rst(), rst, "RST flag mismatch for 0x{:02x}", flags_byte);
            assert_eq!(tcp.psh(), psh, "PSH flag mismatch for 0x{:02x}", flags_byte);
        }
    }

    #[test]
    fn test_arp_opcodes() {
        let opcodes = vec![1, 2, 3, 4];
        for opcode in opcodes {
            let mut data = [0u8; 28];
            data[0] = 0x00;
            data[1] = 0x01;
            data[2] = 0x08;
            data[3] = 0x00;
            data[4] = 0x06;
            data[5] = 0x04;
            data[6] = (opcode >> 8) as u8;
            data[7] = opcode as u8;

            let arp = ArpPacket::parse(&data).unwrap();
            assert_eq!(arp.opcode(), opcode);
            if opcode == 1 {
                assert!(arp.is_request());
                assert!(!arp.is_reply());
            } else if opcode == 2 {
                assert!(!arp.is_request());
                assert!(arp.is_reply());
            } else {
                assert!(!arp.is_request());
                assert!(!arp.is_reply());
            }
        }
    }

    #[test]
    fn test_icmp_types() {
        let types = vec![0, 3, 5, 8, 11, 13];
        for icmp_type in types {
            let mut data = [0u8; 8];
            data[0] = icmp_type;
            let icmp = IcmpHeader::parse(&data).unwrap();
            assert_eq!(icmp.icmp_type(), icmp_type);
        }
    }

    #[test]
    fn test_icmpv6_types() {
        let types = vec![1, 2, 3, 4, 128, 129, 135, 136];
        for icmp_type in types {
            let mut data = [0u8; 8];
            data[0] = icmp_type;
            let icmp = IcmpV6Header::parse(&data).unwrap();
            assert_eq!(icmp.icmp_type(), icmp_type);
        }
    }

    #[test]
    fn test_eth_header_various_ethertypes() {
        let ethertypes = vec![
            (0x0800, "IPv4"),
            (0x86DD, "IPv6"),
            (0x0806, "ARP"),
            (0x8100, "VLAN"),
            (0xFFFF, "Unknown"),
        ];

        for (ethertype, _name) in ethertypes {
            let mut data = [0u8; 14];
            data[12] = (ethertype >> 8) as u8;
            data[13] = (ethertype & 0xFF) as u8;
            let eth = EthHeader::parse(&data).unwrap();
            assert_eq!(eth.ethertype(), ethertype);
        }
    }

    #[test]
    fn test_ip_version_variants() {
        let v4 = IpVersion::V4;
        let v6 = IpVersion::V6;
        let unknown = IpVersion::Unknown;
        assert_ne!(v4, v6);
        assert_ne!(v4, unknown);
        assert_ne!(v6, unknown);
    }

    #[test]
    fn test_l4_protocol_variants() {
        let proto = L4Protocol::Tcp;
        assert!(proto.is_tcp());
        assert!(!proto.is_udp());
        assert!(!proto.is_icmp());

        let proto = L4Protocol::Udp;
        assert!(!proto.is_tcp());
        assert!(proto.is_udp());
        assert!(!proto.is_icmp());

        let proto = L4Protocol::Icmp;
        assert!(!proto.is_tcp());
        assert!(!proto.is_udp());
        assert!(proto.is_icmp());
    }

    #[test]
    fn test_udp_length_validation() {
        let mut data = [0u8; 32];
        data[4] = 0x00;
        data[5] = 0x20;

        let udp = UdpHeader::parse(&data).unwrap();
        assert_eq!(udp.length(), 32);
        assert!(udp.validate_length(100));
        assert!(!udp.validate_length(20));
    }

    #[test]
    fn test_ipv4_invalid_version() {
        let mut data = [0u8; 20];
        data[0] = 0x65;

        let result = Ipv4Header::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_ipv6_version_field() {
        let mut data = [0u8; 40];
        data[0] = 0x60;

        let ipv6 = Ipv6Header::parse(&data).unwrap();
        assert_eq!(ipv6.version(), 6);
    }

    #[test]
    fn test_truncated_ethernet_header() {
        let data = [0u8; 10];
        let result = EthHeader::parse(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_parsed_packet_debug() {
        let mut data = [0u8; 54];
        data[12] = 0x08;
        data[13] = 0x00;
        data[14] = 0x45;
        data[16] = 0x00;
        data[17] = 0x28;
        data[23] = 6;
        data[34] = 0x50;
        data[35] = 0x02;

        let packet = parse_packet(&data).unwrap();
        let debug = format!("{:?}", packet);
        assert!(debug.contains("ParsedPacket"));
    }
}