zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
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
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Building a packet field by field
//!
//! The other half of this module. [`tcp::build_probe`](super::tcp::build_probe)
//! and its neighbours build the handful of packets a scan needs, correctly and
//! with nothing to decide. This is for everything else: a packet described a
//! layer at a time, including one that is wrong on purpose.
//!
//! ```
//! use zond_engine::protocols::craft::{Ipv4, Packet, Tcp, tcp_flags};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let bytes = Packet::new()
//!     .push(Ipv4::new("192.0.2.1".parse()?, "192.0.2.9".parse()?))
//!     .push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
//!     .build()?;
//! # assert_eq!(bytes.len(), 40);
//! # Ok(())
//! # }
//! ```
//!
//! ## One rule: [`Field`]
//!
//! A header has two kinds of field. Most are the caller's outright: a port, a
//! TTL, a flag. A few are derived, such as a length that counts what is inside, a
//! checksum computed over it, or a protocol number naming the layer below. Those
//! are the interesting ones, since a scanner wants them right and somebody
//! probing a
//! stack's error handling wants them wrong.
//!
//! Every derived field is a [`Field<T>`](Field), [`Computed`] by default and
//! [`Exact`] when the caller says otherwise:
//!
//! ```
//! use zond_engine::protocols::craft::{Field, Ipv4};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let src = "192.0.2.1".parse()?;
//! let dst = "192.0.2.9".parse()?;
//!
//! // The header a stack would accept.
//! let correct = Ipv4::new(src, dst);
//!
//! // The same header claiming to be shorter than it is, with a checksum that
//! // was never computed.
//! let wrong = Ipv4 {
//!     total_length: Field::Exact(4),
//!     checksum: Field::Exact(0),
//!     ..Ipv4::new(src, dst)
//! };
//! # let _ = (correct, wrong);
//! # Ok(())
//! # }
//! ```
//!
//! That is the whole of the malformed-packet story. There is no separate
//! "corrupt" API and no flag that turns validation off, because a packet with
//! one wrong field and nineteen right ones is what actually finds bugs in a
//! stack, and an all-or-nothing switch cannot express it.
//!
//! ## Why the fields are public
//!
//! Everywhere else in this crate a type hides its fields, because it has an
//! invariant worth protecting: a [`Host`](crate::model::host::Host)'s status
//! only ever climbs, a [`PortSet`](crate::model::port::PortSet) is always
//! canonical. A header has no such invariant. Being able to write a value that
//! is wrong *is the feature*, so there is nothing for an accessor to defend and
//! a great deal for it to get in the way of.
//!
//! So these are plain data: public fields, [`Default`], and functional update
//! syntax for the common case of changing one thing. The `with_*` methods are
//! there for chaining and do nothing a struct literal could not.
//!
//! ## What it costs
//!
//! Nothing the scanner pays. The presets are written in terms of these types,
//! so there is one implementation rather than two, but a preset knows its own
//! sizes and builds into an exact buffer; a [`Packet`] allocates per layer
//! because it cannot know what it is holding until it is asked to build.
//!
//! [`Computed`]: Field::Computed
//! [`Exact`]: Field::Exact

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use crate::model::mac::MacAddr;
use crate::protocols::mac::IntoPnetMac;
use pnet_packet::arp::{ArpHardwareTypes, ArpOperation, MutableArpPacket};
use pnet_packet::ethernet::{EtherType, EtherTypes, MutableEthernetPacket};
use pnet_packet::icmp::IcmpPacket;
use pnet_packet::icmpv6::Icmpv6Packet;
use pnet_packet::ip::{IpNextHeaderProtocol, IpNextHeaderProtocols};
use pnet_packet::ipv4::{MutableIpv4Packet, checksum as ipv4_checksum};
use pnet_packet::ipv6::MutableIpv6Packet;
use pnet_packet::tcp::{MutableTcpPacket, TcpPacket};
use pnet_packet::udp::{MutableUdpPacket, UdpPacket};

use crate::protocols::error::{PacketError, Result};
use crate::protocols::sizes::{
    ARP_LEN, ETH_HDR_LEN, ICMP_HDR_LEN, IP_V4_HDR_LEN, IP_V6_HDR_LEN, SCTP_COMMON_HDR_LEN,
    TCP_HDR_LEN, UDP_HDR_LEN,
};

/// TCP header flag bits, re-exported so a caller building a [`Tcp`] header does
/// not have to reach into the probe builders for them.
pub use crate::protocols::tcp::flags as tcp_flags;

/// A header field the builder can work out for itself, unless the caller says
/// otherwise.
///
/// See the [module documentation](self) for what this is for. In short:
/// [`Computed`](Self::Computed) writes the value a conformant stack expects, and
/// [`Exact`](Self::Exact) writes what it is given, wrong or not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Field<T> {
    /// Work it out from the packet being built. The correct value.
    #[default]
    Computed,
    /// Write exactly this, whether or not it is correct.
    Exact(T),
}

impl<T> Field<T> {
    /// The value to write, given what the builder worked out.
    ///
    /// `computed` is evaluated only when it is needed, so a caller overriding a
    /// checksum does not pay for computing the one it is discarding.
    fn resolve(self, computed: impl FnOnce() -> T) -> T {
        match self {
            Self::Computed => computed(),
            Self::Exact(value) => value,
        }
    }

    /// Whether this field was given a value rather than left to the builder.
    pub const fn is_exact(&self) -> bool {
        matches!(self, Self::Exact(_))
    }

    /// The value, if one was given.
    pub fn exact(self) -> Option<T> {
        match self {
            Self::Computed => None,
            Self::Exact(value) => Some(value),
        }
    }
}

impl<T> From<T> for Field<T> {
    /// So `checksum: 0.into()` reads as well as `Field::Exact(0)`.
    fn from(value: T) -> Self {
        Self::Exact(value)
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Headers
// ══════════════════════════════════════════════════════════════════════════════

/// An Ethernet II header.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Ethernet {
    /// The address the frame claims to come from.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::mac"))]
    pub source: MacAddr,
    /// The address it is aimed at.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::mac"))]
    pub destination: MacAddr,
    /// What the frame carries. Computed from the layer inside it.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed",
            with = "document::number"
        )
    )]
    pub ethertype: Field<u16>,
}

impl Ethernet {
    /// A frame from `source` to `destination`, carrying whatever is pushed
    /// after it.
    pub fn new(source: MacAddr, destination: MacAddr) -> Self {
        Self {
            source,
            destination,
            ethertype: Field::Computed,
        }
    }

    /// Declares an ethertype rather than taking it from the layer inside.
    #[must_use]
    pub fn with_ethertype(mut self, ethertype: u16) -> Self {
        self.ethertype = Field::Exact(ethertype);
        self
    }

    /// This header alone. A caller that does not declare an
    /// [`ethertype`](Self::ethertype) and pushes nothing after it gets IPv4,
    /// since there is nothing to read one from.
    pub fn header_bytes(&self) -> Vec<u8> {
        write_ethernet(self, Vec::new(), None).expect("nothing here can overflow")
    }
}

/// An IPv4 header.
///
/// Twenty bytes plus whatever [`options`](Self::options) holds. The default
/// matches what this engine's own probes send: don't-fragment set, a random
/// identification, and a TTL of [`HOP_LIMIT_ROUTED`](super::ip::HOP_LIMIT_ROUTED).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Ipv4 {
    /// Where the packet claims to come from.
    pub source: Ipv4Addr,
    /// Where it is going.
    pub destination: Ipv4Addr,
    /// Differentiated services, six bits.
    pub dscp: u8,
    /// Explicit congestion notification, two bits.
    pub ecn: u8,
    /// The fragment identifier. Computed at random, which is what a stack does.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub identification: Field<u16>,
    /// The three-bit flags field. See [`ipv4_flags`].
    pub flags: u8,
    /// Where this fragment sits in the original datagram, in eight-byte units.
    pub fragment_offset: u16,
    /// How many hops the packet may cross.
    pub ttl: u8,
    /// What the packet carries. Computed from the layer pushed inside this one,
    /// and TCP where there is none: see [`header_bytes`](Self::header_bytes).
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed",
            with = "document::number"
        )
    )]
    pub protocol: Field<u8>,
    /// Header and payload together. Computed from the packet being built.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub total_length: Field<u16>,
    /// The header checksum. Computed over the finished header.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub checksum: Field<u16>,
    /// Header options, at most forty bytes and a whole number of four-byte
    /// words.
    ///
    /// Both bounds come from the header-length field, which is four bits
    /// counting words: fifteen of them, five of which the fixed header already
    /// takes. [`Packet::build`] refuses a run that breaks either, because the
    /// field wraps rather than saturating and a header that misdescribes itself
    /// is read as something else by every receiver.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    pub options: Vec<u8>,
}

/// IPv4 fragmentation flags, in the three-bit field
/// [`Ipv4::flags`] carries.
pub mod ipv4_flags {
    /// The packet may not be fragmented in transit.
    pub const DONT_FRAGMENT: u8 = 0b010;
    /// More fragments follow this one.
    pub const MORE_FRAGMENTS: u8 = 0b001;
}

impl Ipv4 {
    /// A header from `source` to `destination`, with every derived field left
    /// for the builder and the defaults this engine's probes use.
    pub fn new(source: Ipv4Addr, destination: Ipv4Addr) -> Self {
        Self {
            source,
            destination,
            dscp: 0,
            ecn: 0,
            identification: Field::Computed,
            flags: ipv4_flags::DONT_FRAGMENT,
            fragment_offset: 0,
            ttl: super::ip::HOP_LIMIT_ROUTED,
            protocol: Field::Computed,
            total_length: Field::Computed,
            checksum: Field::Computed,
            options: Vec::new(),
        }
    }

    /// Sets how many hops the packet may cross.
    #[must_use]
    pub fn with_ttl(mut self, ttl: u8) -> Self {
        self.ttl = ttl;
        self
    }

    /// Writes `checksum` instead of computing one.
    #[must_use]
    pub fn with_checksum(mut self, checksum: u16) -> Self {
        self.checksum = Field::Exact(checksum);
        self
    }

    /// Writes `total_length` instead of measuring the packet.
    #[must_use]
    pub fn with_total_length(mut self, total_length: u16) -> Self {
        self.total_length = Field::Exact(total_length);
        self
    }

    /// How long this header is once its options are counted.
    fn header_len(&self) -> usize {
        IP_V4_HDR_LEN + self.options.len()
    }

    /// This header alone, sized and checksummed for a packet carrying
    /// `payload_length` bytes after it.
    ///
    /// For a caller assembling the layers itself, which is what the transport
    /// does when it already holds a finished segment. [`Packet::build`] is the
    /// easier road when the payload is to hand.
    ///
    /// Set [`protocol`](Self::protocol) before calling this. There is no
    /// layer inside a header built on its own, so a `Computed` protocol has
    /// nothing to read and falls back to TCP. A caller holding a finished UDP
    /// segment and taking the default gets a header naming the wrong protocol,
    /// and the packet is dropped by the receiver rather than refused here.
    ///
    /// # Errors
    ///
    /// [`PacketError::TooLong`] when header and payload together exceed what
    /// the total-length field can describe.
    pub fn header_bytes(&self, payload_length: u16) -> Result<Vec<u8>> {
        let mut bytes = write_ipv4(self, Vec::new(), None)?;
        let total_length = match self.total_length {
            Field::Exact(value) => value,
            Field::Computed => (self.header_len() as u32 + u32::from(payload_length))
                .try_into()
                .map_err(|_| {
                    PacketError::too_long(
                        "the IPv4 total length",
                        self.header_len(),
                        payload_length as usize,
                    )
                })?,
        };

        // Rewritten and re-checksummed, because the length the header claims is
        // part of what the checksum covers.
        let mut ipv4 =
            MutableIpv4Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
        ipv4.set_total_length(total_length);
        ipv4.set_checksum(0);
        let sum = self
            .checksum
            .resolve(|| ipv4_checksum(&ipv4.to_immutable()));
        ipv4.set_checksum(sum);
        Ok(bytes)
    }
}

/// An IPv6 header.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Ipv6 {
    /// Where the packet claims to come from.
    pub source: Ipv6Addr,
    /// Where it is going.
    pub destination: Ipv6Addr,
    /// Traffic class, eight bits.
    pub traffic_class: u8,
    /// The flow label, twenty bits. Computed at random.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub flow_label: Field<u32>,
    /// What follows this header. Computed from the layer pushed inside this one,
    /// and TCP where there is none: see [`header_bytes`](Self::header_bytes).
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed",
            with = "document::number"
        )
    )]
    pub next_header: Field<u8>,
    /// Everything after this header. Computed from the packet being built.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub payload_length: Field<u16>,
    /// How many hops the packet may cross. See
    /// [`HOP_LIMIT_ON_LINK`](super::ip::HOP_LIMIT_ON_LINK) and its neighbours
    /// for the three values that matter and why.
    pub hop_limit: u8,
}

impl Ipv6 {
    /// A header from `source` to `destination`, with the routed hop limit.
    pub fn new(source: Ipv6Addr, destination: Ipv6Addr) -> Self {
        Self {
            source,
            destination,
            traffic_class: 0,
            flow_label: Field::Computed,
            next_header: Field::Computed,
            payload_length: Field::Computed,
            hop_limit: super::ip::HOP_LIMIT_ROUTED,
        }
    }

    /// Sets how many hops the packet may cross.
    #[must_use]
    pub fn with_hop_limit(mut self, hop_limit: u8) -> Self {
        self.hop_limit = hop_limit;
        self
    }

    /// Writes `payload_length` instead of measuring the packet.
    #[must_use]
    pub fn with_payload_length(mut self, payload_length: u16) -> Self {
        self.payload_length = Field::Exact(payload_length);
        self
    }

    /// This header alone, declaring `payload_length` bytes after it. The IPv6
    /// counterpart of [`Ipv4::header_bytes`], and infallible for the reason
    /// that one is not: the field counts the payload rather than the total.
    ///
    /// Set [`next_header`](Self::next_header) before calling this, for the
    /// reason [`Ipv4::header_bytes`] gives about its own protocol field. A
    /// header built alone has no layer inside it to name.
    pub fn header_bytes(&self, payload_length: u16) -> Vec<u8> {
        let declared = Ipv6 {
            payload_length: Field::Exact(self.payload_length.resolve(|| payload_length)),
            ..self.clone()
        };
        write_ipv6(&declared, Vec::new(), None).expect("nothing here can overflow")
    }
}

/// A TCP header and whatever it carries.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Tcp {
    /// The port the segment claims to come from.
    pub source_port: u16,
    /// The port it is aimed at.
    pub destination_port: u16,
    /// The sequence number.
    pub sequence: u32,
    /// The acknowledgement number, meaningful only with
    /// [`ACK`](tcp_flags::ACK) set.
    pub acknowledgement: u32,
    /// The flag bits. See [`tcp_flags`].
    pub flags: u8,
    /// The receive window advertised.
    ///
    /// Defaults to 1024, which is what every probe this engine sends carries, so
    /// a hand-built segment is unremarkable beside them without having to say
    /// so. Read from `tcp`'s own constant rather than written twice.
    pub window: u16,
    /// The urgent pointer, meaningful only with [`URG`](tcp_flags::URG) set.
    pub urgent_pointer: u16,
    /// How long the header is, in four-byte words. Computed from the options.
    ///
    /// The field a stack uses to find the payload, so an exact value smaller
    /// than the real header makes the receiver read option bytes as data, and a
    /// larger one makes it read data as options.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub data_offset: Field<u8>,
    /// The checksum, over the segment and an IP pseudo-header. Computed.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub checksum: Field<u16>,
    /// Header options, as raw bytes: at most forty, and a whole number of
    /// four-byte words.
    ///
    /// The data offset is the same shape of field as IPv4's header length and
    /// carries the same bounds; see [`Ipv4::options`]. [`Packet::build`] refuses
    /// a run that breaks either.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    pub options: Vec<u8>,
    /// The segment's payload.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    pub payload: Vec<u8>,
}

impl Tcp {
    /// A bare segment from `source_port` to `destination_port`, with no flags
    /// set and every derived field left for the builder.
    pub fn new(source_port: u16, destination_port: u16) -> Self {
        Self {
            source_port,
            destination_port,
            sequence: 0,
            acknowledgement: 0,
            flags: 0,
            window: super::tcp::PROBE_WINDOW,
            urgent_pointer: 0,
            data_offset: Field::Computed,
            checksum: Field::Computed,
            options: Vec::new(),
            payload: Vec::new(),
        }
    }

    /// Sets the flag bits, replacing any already set. See [`tcp_flags`].
    #[must_use]
    pub fn with_flags(mut self, flags: u8) -> Self {
        self.flags = flags;
        self
    }

    /// Sets the sequence number.
    #[must_use]
    pub fn with_sequence(mut self, sequence: u32) -> Self {
        self.sequence = sequence;
        self
    }

    /// Sets the acknowledgement number.
    #[must_use]
    pub fn with_acknowledgement(mut self, acknowledgement: u32) -> Self {
        self.acknowledgement = acknowledgement;
        self
    }

    /// Sets the receive window advertised.
    #[must_use]
    pub fn with_window(mut self, window: u16) -> Self {
        self.window = window;
        self
    }

    /// Writes `checksum` instead of computing one.
    #[must_use]
    pub fn with_checksum(mut self, checksum: u16) -> Self {
        self.checksum = Field::Exact(checksum);
        self
    }

    /// Attaches a payload.
    #[must_use]
    pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
        self.payload = payload.into();
        self
    }

    /// How long this header is once its options are counted.
    fn header_len(&self) -> usize {
        TCP_HDR_LEN + self.options.len()
    }

    /// This segment's bytes, checksummed against `addresses`.
    ///
    /// The addresses are a parameter because a TCP checksum covers a
    /// pseudo-header built from them, and a segment does not carry them. Pass
    /// `None` to leave the checksum zero, which is what a caller assembling a
    /// fragment to embed elsewhere wants.
    ///
    /// [`Packet::build`] calls this with the addresses of the IP layer it
    /// found. A preset that already knows them calls it directly and skips
    /// building a header it would only throw away.
    ///
    /// # Errors
    ///
    /// [`PacketError::FamilyMismatch`] when the two addresses are of different
    /// families.
    pub fn to_bytes(&self, addresses: Option<(IpAddr, IpAddr)>) -> Result<Vec<u8>> {
        write_tcp(self, Vec::new(), addresses)
    }

    /// The checksum this segment should carry against `addresses`, perturbed to
    /// one that is definitely wrong and never zero.
    ///
    /// Computes the correct checksum through the ordinary build, then corrupts
    /// it with [`corrupt_internet_checksum`]. Set the result on
    /// [`checksum`](Self::checksum) with [`Field::Exact`] to emit a segment a
    /// conformant host drops, so a reply to it came from something in the path
    /// rather than from the host. Computing the correct value first and
    /// perturbing it is what makes the result certainly wrong, where an arbitrary
    /// number might once in 2^16 be the checksum the segment needs.
    ///
    /// # Errors
    ///
    /// [`PacketError::FamilyMismatch`] when the two addresses are of different
    /// families, exactly as [`to_bytes`](Self::to_bytes) reports it.
    pub fn corrupt_checksum(&self, addresses: Option<(IpAddr, IpAddr)>) -> Result<u16> {
        let bytes = Tcp {
            checksum: Field::Computed,
            ..self.clone()
        }
        .to_bytes(addresses)?;
        let correct = TcpPacket::new(&bytes)
            .expect("a segment just built parses")
            .get_checksum();
        Ok(corrupt_internet_checksum(correct))
    }
}

/// A UDP header and whatever it carries.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Udp {
    /// The port the datagram claims to come from.
    pub source_port: u16,
    /// The port it is aimed at.
    pub destination_port: u16,
    /// Header and payload together. Computed from the packet being built.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub length: Field<u16>,
    /// The checksum, over the datagram and an IP pseudo-header. Computed.
    ///
    /// Optional over IPv4 and mandatory over IPv6: RFC 8200 §8.1 requires a
    /// receiver to discard a zero-checksum datagram, so
    /// `Field::Exact(0)` over IPv6 builds something that never arrives.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub checksum: Field<u16>,
    /// The datagram's payload.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    pub payload: Vec<u8>,
}

impl Udp {
    /// A bare datagram from `source_port` to `destination_port`.
    pub fn new(source_port: u16, destination_port: u16) -> Self {
        Self {
            source_port,
            destination_port,
            length: Field::Computed,
            checksum: Field::Computed,
            payload: Vec::new(),
        }
    }

    /// Attaches a payload.
    #[must_use]
    pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
        self.payload = payload.into();
        self
    }

    /// Writes `checksum` instead of computing one.
    #[must_use]
    pub fn with_checksum(mut self, checksum: u16) -> Self {
        self.checksum = Field::Exact(checksum);
        self
    }

    /// This datagram's bytes, checksummed against `addresses`. The UDP
    /// counterpart of [`Tcp::to_bytes`], and the same rules apply.
    ///
    /// # Errors
    ///
    /// [`PacketError::FamilyMismatch`] when the two addresses are of different
    /// families, and [`PacketError::TooLong`] for a payload the length field
    /// cannot describe.
    pub fn to_bytes(&self, addresses: Option<(IpAddr, IpAddr)>) -> Result<Vec<u8>> {
        write_udp(self, Vec::new(), addresses)
    }
}

/// An SCTP packet: the twelve-byte common header and the chunks after it.
///
/// The one transport here whose checksum is not the internet checksum. SCTP
/// carries a CRC32c (RFC 3309, RFC 4960 §6.8) over the whole packet with no
/// pseudo-header, so unlike [`Tcp`] and [`Udp`] it depends on nothing outside
/// itself and [`to_bytes`](Self::to_bytes) takes no addresses.
///
/// Chunks are carried already encoded, in [`chunks`](Self::chunks): building an
/// INIT or any other chunk is [`sctp`](super::sctp)'s job, and this type owns
/// only the common header and the one derived field worth getting wrong on
/// purpose, the [`checksum`](Self::checksum).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Sctp {
    /// The port the packet claims to come from.
    pub source_port: u16,
    /// The port it is aimed at.
    pub destination_port: u16,
    /// The association's verification tag, zero in a packet carrying an INIT
    /// (RFC 4960 §8.5.1).
    pub verification_tag: u32,
    /// The CRC32c over the whole packet. Computed, and written little-endian per
    /// RFC 4960 §6.8.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub checksum: Field<u32>,
    /// The chunks after the common header, already encoded.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    pub chunks: Vec<u8>,
}

impl Sctp {
    /// A bare packet from `source_port` to `destination_port`: verification tag
    /// zero, no chunks, checksum left for the builder.
    pub fn new(source_port: u16, destination_port: u16) -> Self {
        Self {
            source_port,
            destination_port,
            verification_tag: 0,
            checksum: Field::Computed,
            chunks: Vec::new(),
        }
    }

    /// Sets the verification tag.
    #[must_use]
    pub fn with_verification_tag(mut self, verification_tag: u32) -> Self {
        self.verification_tag = verification_tag;
        self
    }

    /// Attaches the already-encoded chunks after the common header.
    #[must_use]
    pub fn with_chunks(mut self, chunks: impl Into<Vec<u8>>) -> Self {
        self.chunks = chunks.into();
        self
    }

    /// Writes `checksum` instead of computing one.
    #[must_use]
    pub fn with_checksum(mut self, checksum: u32) -> Self {
        self.checksum = Field::Exact(checksum);
        self
    }

    /// This packet's bytes. The SCTP counterpart of [`Tcp::to_bytes`], and
    /// simpler: the CRC32c covers no pseudo-header, so there are no addresses to
    /// pass and nothing that can mismatch.
    pub fn to_bytes(&self) -> Vec<u8> {
        write_sctp(self, Vec::new())
    }
}

/// An ICMPv4 message.
///
/// The four bytes after the checksum mean different things to different message
/// types, so they are carried as [`rest_of_header`](Self::rest_of_header) rather
/// than named. [`echo_request`](Self::echo_request) fills them in for the one type
/// a scan sends, and anything else is the caller's to lay out.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Icmpv4 {
    /// The message type. 8 is an echo request, 0 an echo reply, 3 destination
    /// unreachable.
    pub icmp_type: u8,
    /// The code, whose meaning depends on the type.
    pub code: u8,
    /// The checksum, over the whole message. Computed.
    ///
    /// Unlike its IPv6 counterpart this covers the ICMP message alone, with no
    /// pseudo-header, so it does not depend on the addresses around it.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub checksum: Field<u16>,
    /// The four type-specific bytes between the checksum and the payload. An
    /// echo carries its identifier and sequence here.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex_fixed"))]
    pub rest_of_header: [u8; 4],
    /// Whatever follows the header.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    pub payload: Vec<u8>,
}

impl Icmpv4 {
    /// An echo request carrying `identifier` and `sequence`.
    ///
    /// RFC 792 requires a reply to echo both back unchanged, which is what lets
    /// a scanner tell one of its own requests from another and both from
    /// somebody else's ping.
    pub fn echo_request(identifier: u16, sequence: u16) -> Self {
        Self::echo(ECHO_REQUEST_V4, identifier, sequence)
    }

    /// An echo reply carrying `identifier` and `sequence`.
    pub fn echo_reply(identifier: u16, sequence: u16) -> Self {
        Self::echo(ECHO_REPLY_V4, identifier, sequence)
    }

    fn echo(icmp_type: u8, identifier: u16, sequence: u16) -> Self {
        let [id_hi, id_lo] = identifier.to_be_bytes();
        let [seq_hi, seq_lo] = sequence.to_be_bytes();
        Self {
            icmp_type,
            code: 0,
            checksum: Field::Computed,
            rest_of_header: [id_hi, id_lo, seq_hi, seq_lo],
            payload: Vec::new(),
        }
    }

    /// A timestamp request carrying `identifier` and `sequence`.
    ///
    /// RFC 792's type 13, whose header is an echo's exactly: the identifier and
    /// sequence sit in the same four bytes and a reply echoes both back. What
    /// differs is the twelve bytes behind them, which the caller supplies as a
    /// payload and which a conformant target fills in before replying.
    ///
    /// There is no IPv6 counterpart. RFC 4443 defines no timestamp message, so a
    /// probe of this shape is an IPv4 question and the caller has to know it.
    pub fn timestamp_request(identifier: u16, sequence: u16) -> Self {
        Self::echo(TIMESTAMP_REQUEST_V4, identifier, sequence)
    }

    /// Attaches a payload, which an echo reply is required to send back.
    #[must_use]
    pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
        self.payload = payload.into();
        self
    }

    /// Writes `checksum` instead of computing one.
    #[must_use]
    pub fn with_checksum(mut self, checksum: u16) -> Self {
        self.checksum = Field::Exact(checksum);
        self
    }

    /// Sets the code, whose meaning depends on the message type.
    ///
    /// Zero for a conformant echo, and a probe sending zero asks nothing a
    /// responder can differ about: see
    /// [`ECHO_PROBE_CODE`](super::icmp::ECHO_PROBE_CODE).
    #[must_use]
    pub fn with_code(mut self, code: u8) -> Self {
        self.code = code;
        self
    }

    /// This message's bytes.
    ///
    /// Takes no addresses, unlike [`Icmpv6::to_bytes`]: an ICMPv4 checksum
    /// covers the message alone.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = icmp_body(
            self.icmp_type,
            self.code,
            self.rest_of_header,
            &self.payload,
        );
        let sum = self.checksum.resolve(|| {
            let message = IcmpPacket::new(&bytes).expect("just written");
            pnet_packet::icmp::checksum(&message)
        });
        bytes[2..4].copy_from_slice(&sum.to_be_bytes());
        bytes
    }
}

/// An ICMPv6 message.
///
/// The IPv6 counterpart of [`Icmpv4`], with one difference that matters: its
/// checksum covers an IPv6 pseudo-header as well as the message, so it depends
/// on the addresses of the header around it. See [`to_bytes`](Self::to_bytes).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Icmpv6 {
    /// The message type. 128 is an echo request, 129 an echo reply, 135 a
    /// neighbor solicitation.
    pub icmp_type: u8,
    /// The code, whose meaning depends on the type.
    pub code: u8,
    /// The checksum, over the message and an IPv6 pseudo-header. Computed.
    #[cfg_attr(
        feature = "packet-exchange",
        serde(
            default = "document::computed",
            skip_serializing_if = "document::is_computed"
        )
    )]
    pub checksum: Field<u16>,
    /// The four type-specific bytes between the checksum and the payload.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex_fixed"))]
    pub rest_of_header: [u8; 4],
    /// Whatever follows the header.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    pub payload: Vec<u8>,
}

impl Icmpv6 {
    /// An echo request carrying `identifier` and `sequence`.
    pub fn echo_request(identifier: u16, sequence: u16) -> Self {
        Self::echo(ECHO_REQUEST_V6, identifier, sequence)
    }

    /// An echo reply carrying `identifier` and `sequence`.
    pub fn echo_reply(identifier: u16, sequence: u16) -> Self {
        Self::echo(ECHO_REPLY_V6, identifier, sequence)
    }

    fn echo(icmp_type: u8, identifier: u16, sequence: u16) -> Self {
        let [id_hi, id_lo] = identifier.to_be_bytes();
        let [seq_hi, seq_lo] = sequence.to_be_bytes();
        Self {
            icmp_type,
            code: 0,
            checksum: Field::Computed,
            rest_of_header: [id_hi, id_lo, seq_hi, seq_lo],
            payload: Vec::new(),
        }
    }

    /// Attaches a payload.
    #[must_use]
    pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
        self.payload = payload.into();
        self
    }

    /// Writes `checksum` instead of computing one.
    #[must_use]
    pub fn with_checksum(mut self, checksum: u16) -> Self {
        self.checksum = Field::Exact(checksum);
        self
    }

    /// Sets the code, whose meaning depends on the message type.
    ///
    /// Zero for a conformant echo, and a probe sending zero asks nothing a
    /// responder can differ about: see
    /// [`ECHO_PROBE_CODE`](super::icmp::ECHO_PROBE_CODE).
    #[must_use]
    pub fn with_code(mut self, code: u8) -> Self {
        self.code = code;
        self
    }

    /// This message's bytes, checksummed against `addresses`.
    ///
    /// The addresses are required for a computed checksum and ignored for an
    /// exact one. `None` leaves a computed checksum zero, which over IPv6 is
    /// not merely wrong but fatal: RFC 4443 has no "no checksum" encoding, so a
    /// receiver discards it.
    ///
    /// # Errors
    ///
    /// [`PacketError::WrongFamily`] when both addresses are IPv4, which is an
    /// ICMPv6 message inside an IPv4 header and a packet nothing can build, and
    /// [`PacketError::FamilyMismatch`] when the two do not agree with each other
    /// at all.
    pub fn to_bytes(&self, addresses: Option<(IpAddr, IpAddr)>) -> Result<Vec<u8>> {
        let mut bytes = icmp_body(
            self.icmp_type,
            self.code,
            self.rest_of_header,
            &self.payload,
        );

        let sum = match self.checksum {
            Field::Exact(value) => value,
            Field::Computed => {
                let message = Icmpv6Packet::new(&bytes).expect("just written");
                match addresses {
                    None => 0,
                    Some((IpAddr::V6(src), IpAddr::V6(dst))) => {
                        pnet_packet::icmpv6::checksum(&message, &src, &dst)
                    }
                    // Not a family mismatch: the two may agree with each other
                    // and still not be IPv6, which is what an ICMPv6 layer
                    // inside an IPv4 header looks like from here.
                    Some((IpAddr::V4(src), IpAddr::V4(_))) => {
                        return Err(PacketError::WrongFamily {
                            protocol: "ICMPv6",
                            expected: "IPv6",
                            got: IpAddr::V4(src),
                        });
                    }
                    Some((src, dst)) => return Err(PacketError::FamilyMismatch { src, dst }),
                }
            }
        };
        bytes[2..4].copy_from_slice(&sum.to_be_bytes());
        Ok(bytes)
    }
}

/// An ICMP message with its checksum left zero, for either family.
///
/// The two share a layout of type, code, checksum, four type-specific bytes and
/// payload, differing only in what the checksum covers.
fn icmp_body(icmp_type: u8, code: u8, rest_of_header: [u8; 4], payload: &[u8]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(ICMP_HDR_LEN + payload.len());
    bytes.push(icmp_type);
    bytes.push(code);
    bytes.extend_from_slice(&[0, 0]);
    bytes.extend_from_slice(&rest_of_header);
    bytes.extend_from_slice(payload);
    bytes
}

/// ICMPv4 echo request, RFC 792.
const ECHO_REQUEST_V4: u8 = 8;
/// ICMPv4 echo reply, RFC 792.
const ECHO_REPLY_V4: u8 = 0;
/// ICMPv4 timestamp request, RFC 792. No IPv6 counterpart exists.
const TIMESTAMP_REQUEST_V4: u8 = 13;
/// ICMPv6 echo request, RFC 4443.
const ECHO_REQUEST_V6: u8 = 128;
/// ICMPv6 echo reply, RFC 4443.
const ECHO_REPLY_V6: u8 = 129;

/// An ARP packet over Ethernet and IPv4.
///
/// Twenty-eight bytes with no payload, so nothing here is derived and every field
/// is the caller's. It is in this module anyway, since the interesting ARP
/// packets are the ones a preset would not build: a reply nobody asked for, a
/// request claiming an address the sender does not hold, a hardware length that
/// does not match the addresses beside it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Arp {
    /// Request or reply. See [`arp_operations`].
    pub operation: u16,
    /// How long a hardware address is, in bytes. Six for Ethernet.
    pub hw_addr_len: u8,
    /// How long a protocol address is, in bytes. Four for IPv4.
    pub proto_addr_len: u8,
    /// The hardware address the sender claims.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::mac"))]
    pub sender_hw_addr: MacAddr,
    /// The protocol address the sender claims.
    pub sender_proto_addr: Ipv4Addr,
    /// The hardware address being asked about. Undefined in a request, which
    /// is why a request conventionally leaves it zero.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::mac"))]
    pub target_hw_addr: MacAddr,
    /// The protocol address being asked about.
    pub target_proto_addr: Ipv4Addr,
}

/// ARP operation codes, RFC 826.
pub mod arp_operations {
    /// Who holds this address?
    pub const REQUEST: u16 = 1;
    /// I do.
    pub const REPLY: u16 = 2;
}

impl Arp {
    /// A request asking who holds `target_proto_addr`.
    ///
    /// The target hardware address is left zero, which is what RFC 826 expects
    /// of a request and what every ordinary stack sends. Filling it with
    /// anything else is legal and makes the probe distinctive, which is the
    /// opposite of what a scan wants.
    pub fn request(
        sender_hw_addr: MacAddr,
        sender_proto_addr: Ipv4Addr,
        target_proto_addr: Ipv4Addr,
    ) -> Self {
        Self {
            operation: arp_operations::REQUEST,
            hw_addr_len: 6,
            proto_addr_len: 4,
            sender_hw_addr,
            sender_proto_addr,
            target_hw_addr: MacAddr::ZERO,
            target_proto_addr,
        }
    }

    /// A reply announcing that `sender_hw_addr` holds `sender_proto_addr`.
    pub fn reply(
        sender_hw_addr: MacAddr,
        sender_proto_addr: Ipv4Addr,
        target_hw_addr: MacAddr,
        target_proto_addr: Ipv4Addr,
    ) -> Self {
        Self {
            operation: arp_operations::REPLY,
            hw_addr_len: 6,
            proto_addr_len: 4,
            sender_hw_addr,
            sender_proto_addr,
            target_hw_addr,
            target_proto_addr,
        }
    }

    /// Names the hardware address being asked about.
    ///
    /// Undefined in a request, which is why [`request`](Self::request) leaves it
    /// zero. A unicast request validating a cache entry sets it, so a host that
    /// has moved answers from a different address and the mismatch is what says
    /// the entry was stale.
    #[must_use]
    pub fn with_target_hw_addr(mut self, target_hw_addr: MacAddr) -> Self {
        self.target_hw_addr = target_hw_addr;
        self
    }

    /// This packet's bytes. Nothing here is derived, so nothing can fail.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = vec![0u8; ARP_LEN];
        {
            let mut arp =
                MutableArpPacket::new(&mut bytes).expect("an ARP-sized buffer holds an ARP packet");
            arp.set_hardware_type(ArpHardwareTypes::Ethernet);
            arp.set_protocol_type(EtherTypes::Ipv4);
            arp.set_hw_addr_len(self.hw_addr_len);
            arp.set_proto_addr_len(self.proto_addr_len);
            arp.set_operation(ArpOperation(self.operation));
            arp.set_sender_hw_addr(self.sender_hw_addr.into_pnet());
            arp.set_sender_proto_addr(self.sender_proto_addr);
            arp.set_target_hw_addr(self.target_hw_addr.into_pnet());
            arp.set_target_proto_addr(self.target_proto_addr);
        }
        bytes
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Stacking
// ══════════════════════════════════════════════════════════════════════════════

/// One header in a [`Packet`], outermost first.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
#[cfg_attr(feature = "packet-exchange", serde(rename_all = "snake_case"))]
pub enum Layer {
    /// An Ethernet II header.
    Ethernet(Ethernet),
    /// An IPv4 header.
    Ipv4(Ipv4),
    /// An IPv6 header.
    Ipv6(Ipv6),
    /// A TCP header and its payload.
    Tcp(Tcp),
    /// A UDP header and its payload.
    Udp(Udp),
    /// An SCTP packet and its chunks.
    Sctp(Sctp),
    /// An ICMPv4 message.
    Icmpv4(Icmpv4),
    /// An ICMPv6 message.
    Icmpv6(Icmpv6),
    /// An ARP packet.
    Arp(Arp),
    /// Bytes written exactly as given, for a protocol nothing here models yet.
    #[cfg_attr(feature = "packet-exchange", serde(with = "document::hex"))]
    Raw(Vec<u8>),
}

macro_rules! layer_from {
    ($($variant:ident($ty:ty)),* $(,)?) => {
        $(impl From<$ty> for Layer {
            fn from(header: $ty) -> Self {
                Self::$variant(header)
            }
        })*
    };
}

layer_from!(
    Ethernet(Ethernet),
    Ipv4(Ipv4),
    Ipv6(Ipv6),
    Tcp(Tcp),
    Udp(Udp),
    Sctp(Sctp),
    Icmpv4(Icmpv4),
    Icmpv6(Icmpv6),
    Arp(Arp),
    Raw(Vec<u8>),
);

impl Layer {
    /// What an enclosing header should call this one, if it is computing its
    /// own protocol number.
    fn ip_protocol(&self) -> Option<u8> {
        let protocol = match self {
            Self::Tcp(_) => IpNextHeaderProtocols::Tcp,
            Self::Udp(_) => IpNextHeaderProtocols::Udp,
            Self::Sctp(_) => IpNextHeaderProtocols::Sctp,
            Self::Icmpv4(_) => IpNextHeaderProtocols::Icmp,
            Self::Icmpv6(_) => IpNextHeaderProtocols::Icmpv6,
            _ => return None,
        };
        Some(protocol.0)
    }

    /// What an enclosing Ethernet header should call this one.
    fn ethertype(&self) -> Option<u16> {
        let ethertype = match self {
            Self::Ipv4(_) => EtherTypes::Ipv4,
            Self::Ipv6(_) => EtherTypes::Ipv6,
            Self::Arp(_) => EtherTypes::Arp,
            _ => return None,
        };
        Some(ethertype.0)
    }
}

/// A packet described as a stack of headers, outermost first.
///
/// See the [module documentation](self) for the idea and an example. Layers are
/// pushed in the order they appear on the wire, then [`build`](Self::build)
/// assembles them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(
    feature = "packet-exchange",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Packet {
    layers: Vec<Layer>,
}

impl Packet {
    /// An empty packet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a header inside everything pushed so far.
    #[must_use]
    pub fn push(mut self, layer: impl Into<Layer>) -> Self {
        self.layers.push(layer.into());
        self
    }

    /// The layers, outermost first.
    pub fn layers(&self) -> &[Layer] {
        &self.layers
    }

    /// The layers, for a caller editing a packet it did not build.
    pub fn layers_mut(&mut self) -> &mut Vec<Layer> {
        &mut self.layers
    }

    /// Serializes the packet.
    ///
    /// Built from the inside out, because a derived length cannot be known
    /// until what it counts has been written. The one exception is a transport
    /// checksum, which needs the addresses of the IP header *outside* it, so
    /// those are found up front.
    ///
    /// # Errors
    ///
    /// [`PacketError::TooLong`] when a computed length will not fit its field,
    /// and [`PacketError::FamilyMismatch`] when a transport layer sits inside
    /// an IP header of a family its addresses do not match. A field written
    /// with [`Field::Exact`] is never checked, which is the point of it.
    pub fn build(&self) -> Result<Vec<u8>> {
        let addresses = self.enclosing_addresses();

        let mut bytes = Vec::new();
        // What the layer being written should call the one just written, when
        // it is working its own protocol or ethertype out.
        let mut inner: Option<&Layer> = None;

        for layer in self.layers.iter().rev() {
            bytes = write_layer(layer, bytes, inner, addresses)?;
            inner = Some(layer);
        }

        Ok(bytes)
    }

    /// The addresses a transport checksum's pseudo-header is built from, taken
    /// from the outermost IP layer.
    fn enclosing_addresses(&self) -> Option<(IpAddr, IpAddr)> {
        self.layers.iter().find_map(|layer| match layer {
            Layer::Ipv4(h) => Some((IpAddr::V4(h.source), IpAddr::V4(h.destination))),
            Layer::Ipv6(h) => Some((IpAddr::V6(h.source), IpAddr::V6(h.destination))),
            _ => None,
        })
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// A packet as a document
// ══════════════════════════════════════════════════════════════════════════════

/// Reading and writing a packet as a document, behind `packet-exchange`.
///
/// A header's field names are fixed by the RFCs that define them: `ttl`,
/// `checksum` and `source_port` are what RFC 791 and RFC 793 call those bytes,
/// so a derived form and the struct layout cannot drift apart the way a settings
/// file and a configuration can. That is why this is a derive where
/// [`import::settings`](crate::import::settings) is hand-written.
///
/// ```toml
/// [[layers]]
/// [layers.ipv4]
/// source = "192.0.2.1"
/// destination = "192.0.2.9"
/// ttl = 12
/// total_length = 4        # the datagram claims to be shorter than it is
///
/// [[layers]]
/// [layers.tcp]
/// source_port = 50000
/// destination_port = 80
/// flags = 2
/// payload = "48454c4c4f"
/// ```
///
/// Three conventions, each following from what the values are:
///
/// - **A derived field appears only when it was pinned.** An absent key is
///   [`Field::Computed`], which is the builder working the value out, and a
///   present one is [`Field::Exact`], which is the caller overriding it. So a
///   document says what it wants wrong and stays silent about the rest.
/// - **Bytes are lowercase hex.** Options, payloads, chunks and a raw layer, in
///   the encoding `data-encoding` already provides for the detection sandbox. An
///   array of integers would be four times the size and no clearer.
/// - **A hardware address is written the way one is read**, `aa:bb:cc:dd:ee:ff`.
///   An ethertype and a next-header protocol are written as the numbers that go
///   on the wire, since that is what a caller crafting a wrong one is choosing.
#[cfg(feature = "packet-exchange")]
mod document {
    use super::{Field, MacAddr};
    use data_encoding::HEXLOWER;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    /// What an absent key means: the builder works the value out.
    ///
    /// A function rather than [`Default`], whose derive on [`Field`] asks for a
    /// `T: Default` that a protocol number does not have.
    pub(super) fn computed<T>() -> Field<T> {
        Field::Computed
    }

    /// Whether a field is left out of a document, which every derived field is
    /// unless the caller pinned it.
    pub(super) fn is_computed<T>(field: &Field<T>) -> bool {
        !field.is_exact()
    }

    impl<T: Serialize> Serialize for Field<T> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            match self {
                Field::Computed => serializer.serialize_none(),
                Field::Exact(value) => serializer.serialize_some(value),
            }
        }
    }

    impl<'de, T: Deserialize<'de>> Deserialize<'de> for Field<T> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            Ok(Option::<T>::deserialize(deserializer)?.map_or(Field::Computed, Field::Exact))
        }
    }

    /// Bytes, as lowercase hex.
    pub(super) mod hex {
        use super::{Deserialize, Deserializer, HEXLOWER, Serializer};

        pub(in super::super) fn serialize<S: Serializer>(
            bytes: &[u8],
            serializer: S,
        ) -> Result<S::Ok, S::Error> {
            serializer.serialize_str(&HEXLOWER.encode(bytes))
        }

        pub(in super::super) fn deserialize<'de, D: Deserializer<'de>>(
            deserializer: D,
        ) -> Result<Vec<u8>, D::Error> {
            let written = String::deserialize(deserializer)?;
            HEXLOWER
                .decode(written.as_bytes())
                .map_err(serde::de::Error::custom)
        }
    }

    /// The four type-specific bytes of an ICMP header, as hex of exactly that
    /// length.
    pub(super) mod hex_fixed {
        use super::{Deserializer, Serializer};

        pub(in super::super) fn serialize<S: Serializer>(
            bytes: &[u8; 4],
            serializer: S,
        ) -> Result<S::Ok, S::Error> {
            super::hex::serialize(bytes, serializer)
        }

        pub(in super::super) fn deserialize<'de, D: Deserializer<'de>>(
            deserializer: D,
        ) -> Result<[u8; 4], D::Error> {
            let bytes = super::hex::deserialize(deserializer)?;
            <[u8; 4]>::try_from(bytes.as_slice()).map_err(|_| {
                serde::de::Error::custom(format!(
                    "the four type-specific bytes are 8 hex characters, not {}",
                    bytes.len() * 2
                ))
            })
        }
    }

    /// A hardware address, written the way one is read.
    pub(super) mod mac {
        use super::{Deserialize, Deserializer, MacAddr, Serializer};

        pub(in super::super) fn serialize<S: Serializer>(
            mac: &MacAddr,
            serializer: S,
        ) -> Result<S::Ok, S::Error> {
            serializer.collect_str(mac)
        }

        pub(in super::super) fn deserialize<'de, D: Deserializer<'de>>(
            deserializer: D,
        ) -> Result<MacAddr, D::Error> {
            let written = String::deserialize(deserializer)?;
            written.parse().map_err(serde::de::Error::custom)
        }
    }

    /// A next-header protocol number or an ethertype: the number itself, or
    /// nothing where the builder works it out.
    pub(super) mod number {
        use super::{Deserialize, Deserializer, Field, Serialize, Serializer};

        pub(in super::super) fn serialize<S: Serializer, T: Serialize>(
            field: &Field<T>,
            serializer: S,
        ) -> Result<S::Ok, S::Error> {
            match field {
                Field::Computed => serializer.serialize_none(),
                Field::Exact(number) => serializer.serialize_some(number),
            }
        }

        pub(in super::super) fn deserialize<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
            deserializer: D,
        ) -> Result<Field<T>, D::Error> {
            Ok(Option::<T>::deserialize(deserializer)?.map_or(Field::Computed, Field::Exact))
        }
    }
}

/// Writes `layer` around `payload`, returning the two together.
fn write_layer(
    layer: &Layer,
    payload: Vec<u8>,
    inner: Option<&Layer>,
    addresses: Option<(IpAddr, IpAddr)>,
) -> Result<Vec<u8>> {
    match layer {
        Layer::Raw(bytes) => Ok([bytes.as_slice(), payload.as_slice()].concat()),
        Layer::Ethernet(header) => write_ethernet(header, payload, inner),
        Layer::Ipv4(header) => write_ipv4(header, payload, inner),
        Layer::Ipv6(header) => write_ipv6(header, payload, inner),
        Layer::Tcp(header) => write_tcp(header, payload, addresses),
        Layer::Udp(header) => write_udp(header, payload, addresses),
        Layer::Sctp(header) => Ok(write_sctp(header, payload)),
        Layer::Icmpv4(message) => Ok([message.to_bytes(), payload].concat()),
        Layer::Icmpv6(message) => Ok([message.to_bytes(addresses)?, payload].concat()),
        Layer::Arp(packet) => Ok([packet.to_bytes(), payload].concat()),
    }
}

/// Writes an Ethernet frame: the header, then whatever `inner` builds, then
/// `payload`. The outermost of the writers, and the one every framed layer
/// eventually returns to.
fn write_ethernet(header: &Ethernet, payload: Vec<u8>, inner: Option<&Layer>) -> Result<Vec<u8>> {
    let mut bytes = vec![0u8; ETH_HDR_LEN];
    {
        let mut eth =
            MutableEthernetPacket::new(&mut bytes).expect("a header-sized buffer holds a header");
        eth.set_source(header.source.into_pnet());
        eth.set_destination(header.destination.into_pnet());
        eth.set_ethertype(EtherType(header.ethertype.resolve(|| {
            inner
                .and_then(Layer::ethertype)
                .unwrap_or(EtherTypes::Ipv4.0)
        })));
    }
    bytes.extend_from_slice(&payload);
    Ok(bytes)
}

/// Writes an IPv4 datagram. Each [`Field::Computed`] header value is derived
/// from the bytes that ended up in it, and each [`Field::Exact`] is written as
/// the caller gave it, which is what lets an evasion profile put a wrong one on
/// the wire deliberately.
fn write_ipv4(header: &Ipv4, payload: Vec<u8>, inner: Option<&Layer>) -> Result<Vec<u8>> {
    PacketError::check_options("an IPv4 header", header.options.len())?;

    let header_len = header.header_len();
    let total = header_len + payload.len();
    let total_length = match header.total_length {
        Field::Exact(value) => value,
        Field::Computed => u16::try_from(total).map_err(|_| {
            PacketError::too_long("the IPv4 total length", header_len, payload.len())
        })?,
    };

    let mut bytes = vec![0u8; header_len];
    {
        let mut ipv4 =
            MutableIpv4Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
        ipv4.set_version(4);
        ipv4.set_header_length((header_len / 4) as u8);
        ipv4.set_dscp(header.dscp);
        ipv4.set_ecn(header.ecn);
        ipv4.set_total_length(total_length);
        ipv4.set_identification(header.identification.resolve(rand::random));
        ipv4.set_flags(header.flags);
        ipv4.set_fragment_offset(header.fragment_offset);
        ipv4.set_ttl(header.ttl);
        ipv4.set_next_level_protocol(IpNextHeaderProtocol(header.protocol.resolve(|| {
            inner
                .and_then(Layer::ip_protocol)
                .unwrap_or(IpNextHeaderProtocols::Tcp.0)
        })));
        ipv4.set_source(header.source);
        ipv4.set_destination(header.destination);
        if !header.options.is_empty() {
            bytes[IP_V4_HDR_LEN..header_len].copy_from_slice(&header.options);
        }
    }
    {
        let mut ipv4 =
            MutableIpv4Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
        let sum = header
            .checksum
            .resolve(|| ipv4_checksum(&ipv4.to_immutable()));
        ipv4.set_checksum(sum);
    }

    bytes.extend_from_slice(&payload);
    Ok(bytes)
}

/// [`write_ipv4`] for IPv6, which has fewer fields to compute and no checksum of
/// its own.
fn write_ipv6(header: &Ipv6, payload: Vec<u8>, inner: Option<&Layer>) -> Result<Vec<u8>> {
    let payload_length = match header.payload_length {
        Field::Exact(value) => value,
        Field::Computed => u16::try_from(payload.len())
            .map_err(|_| PacketError::too_long("the IPv6 payload length", 0, payload.len()))?,
    };

    let mut bytes = vec![0u8; IP_V6_HDR_LEN];
    {
        let mut ipv6 =
            MutableIpv6Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
        ipv6.set_version(6);
        ipv6.set_traffic_class(header.traffic_class);
        ipv6.set_flow_label(header.flow_label.resolve(rand::random));
        ipv6.set_payload_length(payload_length);
        ipv6.set_next_header(IpNextHeaderProtocol(header.next_header.resolve(|| {
            inner
                .and_then(Layer::ip_protocol)
                .unwrap_or(IpNextHeaderProtocols::Tcp.0)
        })));
        ipv6.set_hop_limit(header.hop_limit);
        ipv6.set_source(header.source);
        ipv6.set_destination(header.destination);
    }
    bytes.extend_from_slice(&payload);
    Ok(bytes)
}

/// Writes a TCP segment.
///
/// `addresses` are the enclosing IP header's, needed for the pseudo-header the
/// checksum covers; `None` leaves the checksum as the header asked for, which is
/// how a segment is built without knowing yet where it will be sent from.
fn write_tcp(
    header: &Tcp,
    payload: Vec<u8>,
    addresses: Option<(IpAddr, IpAddr)>,
) -> Result<Vec<u8>> {
    PacketError::check_options("a TCP header", header.options.len())?;

    let header_len = header.header_len();
    let mut bytes = vec![0u8; header_len];
    bytes.extend_from_slice(&header.payload);
    bytes.extend_from_slice(&payload);

    {
        let mut tcp =
            MutableTcpPacket::new(&mut bytes).expect("a header-sized buffer holds a header");
        tcp.set_source(header.source_port);
        tcp.set_destination(header.destination_port);
        tcp.set_sequence(header.sequence);
        tcp.set_acknowledgement(header.acknowledgement);
        tcp.set_data_offset(header.data_offset.resolve(|| (header_len / 4) as u8));
        tcp.set_flags(header.flags);
        tcp.set_window(header.window);
        tcp.set_urgent_ptr(header.urgent_pointer);
        tcp.set_checksum(0);
        if !header.options.is_empty() {
            bytes[TCP_HDR_LEN..header_len].copy_from_slice(&header.options);
        }
    }

    let sum = match header.checksum {
        Field::Exact(value) => value,
        Field::Computed => {
            let segment = TcpPacket::new(&bytes).expect("just written");
            transport_checksum(
                addresses,
                |src, dst| pnet_packet::tcp::ipv4_checksum(&segment, src, dst),
                |src, dst| pnet_packet::tcp::ipv6_checksum(&segment, src, dst),
            )?
        }
    };
    MutableTcpPacket::new(&mut bytes)
        .expect("a header-sized buffer holds a header")
        .set_checksum(sum);

    Ok(bytes)
}

/// [`write_tcp`] for UDP, whose checksum covers the same pseudo-header and whose
/// `addresses` mean the same thing.
fn write_udp(
    header: &Udp,
    payload: Vec<u8>,
    addresses: Option<(IpAddr, IpAddr)>,
) -> Result<Vec<u8>> {
    let body_len = header.payload.len() + payload.len();
    let length = match header.length {
        Field::Exact(value) => value,
        Field::Computed => u16::try_from(UDP_HDR_LEN + body_len)
            .map_err(|_| PacketError::too_long("the UDP length", UDP_HDR_LEN, body_len))?,
    };

    let mut bytes = vec![0u8; UDP_HDR_LEN];
    bytes.extend_from_slice(&header.payload);
    bytes.extend_from_slice(&payload);

    {
        let mut udp =
            MutableUdpPacket::new(&mut bytes).expect("a header-sized buffer holds a header");
        udp.set_source(header.source_port);
        udp.set_destination(header.destination_port);
        udp.set_length(length);
        udp.set_checksum(0);
    }

    let sum = match (header.checksum, addresses) {
        (Field::Exact(value), _) => value,
        // No IP header means no pseudo-header to sum over, and the field is left
        // for whoever supplies one. The substitution below must not fire here:
        // it would answer "there was nothing to compute" with a value that says
        // "computed, and it came to zero", which nothing downstream can tell
        // from a real checksum. See `transport_checksum`.
        (Field::Computed, None) => 0,
        (Field::Computed, Some(_)) => {
            let datagram = UdpPacket::new(&bytes).expect("just written");
            let computed = transport_checksum(
                addresses,
                |src, dst| pnet_packet::udp::ipv4_checksum(&datagram, src, dst),
                |src, dst| pnet_packet::udp::ipv6_checksum(&datagram, src, dst),
            )?;
            // Zero in this field means "not computed" (RFC 768), so a genuine
            // result of zero is sent as its ones-complement equivalent.
            if computed == 0 { 0xFFFF } else { computed }
        }
    };
    MutableUdpPacket::new(&mut bytes)
        .expect("a header-sized buffer holds a header")
        .set_checksum(sum);

    Ok(bytes)
}

/// Runs whichever checksum the enclosing IP layer calls for.
///
/// A transport layer with no IP header around it has no pseudo-header to
/// checksum over, so it gets zero: the caller is building a fragment to embed
/// somewhere else, and inventing addresses for it would be worse than leaving
/// the field for them to set.
fn transport_checksum(
    addresses: Option<(IpAddr, IpAddr)>,
    v4: impl FnOnce(&Ipv4Addr, &Ipv4Addr) -> u16,
    v6: impl FnOnce(&Ipv6Addr, &Ipv6Addr) -> u16,
) -> Result<u16> {
    match addresses {
        None => Ok(0),
        Some((IpAddr::V4(src), IpAddr::V4(dst))) => Ok(v4(&src, &dst)),
        Some((IpAddr::V6(src), IpAddr::V6(dst))) => Ok(v6(&src, &dst)),
        Some((src, dst)) => Err(PacketError::FamilyMismatch { src, dst }),
    }
}

/// `len` random bytes, for padding a probe's payload out to an unusual size.
///
/// Random rather than zero, since a run of zeroes is itself a fixed pattern and
/// that is what padding exists to move a probe off. Drawn fresh on each call, so
/// two probes padded to the same length still differ in their tails.
pub fn random_padding(len: u16) -> Vec<u8> {
    std::iter::repeat_with(rand::random)
        .take(len as usize)
        .collect()
}

/// A one's-complement internet checksum (RFC 1071) made deliberately, verifiably
/// wrong.
///
/// Flipping every bit is the surest single change. A value and its complement
/// verify differently, so the result is a checksum a conformant receiver rejects,
/// and a reply to a segment that should have been dropped came from something
/// that did not check.
///
/// The one exception is a one's-complement zero, whose two encodings `0x0000`
/// and `0xFFFF` verify identically. Complementing one lands on the other, which
/// is not a different value and so not wrong, and zero is besides a checksum a
/// segment may legitimately carry. So a corruption
/// that produces either is moved to `0x0001`, which is unambiguously neither
/// encoding of zero and therefore unambiguously wrong.
pub fn corrupt_internet_checksum(correct: u16) -> u16 {
    match correct ^ 0xFFFF {
        0x0000 | 0xFFFF => 0x0001,
        flipped => flipped,
    }
}

/// Writes an SCTP packet: the common header, the caller's chunks, then the
/// CRC-32c over the whole of it, which is why the checksum field is written twice.
///
/// Infallible, unlike its neighbours: every length here is a fixed width and the
/// chunks arrive already framed.
fn write_sctp(header: &Sctp, payload: Vec<u8>) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(SCTP_COMMON_HDR_LEN + header.chunks.len() + payload.len());
    bytes.extend_from_slice(&header.source_port.to_be_bytes());
    bytes.extend_from_slice(&header.destination_port.to_be_bytes());
    bytes.extend_from_slice(&header.verification_tag.to_be_bytes());
    bytes.extend_from_slice(&[0; 4]); // checksum, filled once the packet is whole
    bytes.extend_from_slice(&header.chunks);
    bytes.extend_from_slice(&payload);

    // Computed over the packet with the field zeroed, which it is, and written
    // little-endian: the byte order RFC 4960 §6.8 puts the CRC on the wire in,
    // and the most common way an SCTP checksum comes out wrong.
    let sum = header.checksum.resolve(|| crc32c(&bytes));
    bytes[8..12].copy_from_slice(&sum.to_le_bytes());
    bytes
}

/// The CRC32c reduction table, one entry per input byte.
///
/// Built at compile time from the reflected polynomial `0x82F6_3B78`, the
/// bit-reversal of the `0x1EDC_6F41` in RFC 3309. The reflected form is what goes
/// with the reflected input and output the reduction below uses.
static CRC32C_TABLE: [u32; 256] = {
    let mut table = [0u32; 256];
    let mut byte = 0;
    while byte < 256 {
        let mut crc = byte as u32;
        let mut bit = 0;
        while bit < 8 {
            crc = if crc & 1 != 0 {
                (crc >> 1) ^ 0x82F6_3B78
            } else {
                crc >> 1
            };
            bit += 1;
        }
        table[byte] = crc;
        byte += 1;
    }
    table
};

/// The CRC32c (Castagnoli) of `data`, the checksum SCTP carries (RFC 3309).
///
/// The standard CRC-32C/iSCSI parameters, reflected in and out, initialised to
/// all-ones and finished by complementing, so this is the value that goes in the
/// SCTP checksum field, little-endian; see [`write_sctp`]. Shared with
/// [`sctp`](super::sctp) rather than reimplemented there, so a probe and a
/// hand-built packet cannot come to disagree about what the checksum is.
pub(crate) fn crc32c(data: &[u8]) -> u32 {
    let mut crc = !0u32;
    for &byte in data {
        crc = (crc >> 8) ^ CRC32C_TABLE[((crc ^ u32::from(byte)) & 0xFF) as usize];
    }
    !crc
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(all(test, feature = "packet-exchange"))]
mod document_tests {
    use super::*;

    /// Everything a packet can be made of, with a derived field pinned in each
    /// header so both halves of [`Field`] cross the document.
    fn everything() -> Packet {
        Packet::new()
            .push(Ethernet {
                ethertype: Field::Exact(0x88b5),
                ..Ethernet::new(
                    MacAddr::new(2, 0, 0, 0, 0, 1),
                    MacAddr::new(2, 0, 0, 0, 0, 2),
                )
            })
            .push(Ipv4 {
                ttl: 12,
                // Pinned, or two builds of one packet draw two identifications
                // and the comparison below is about the random number generator.
                identification: Field::Exact(0x4242),
                total_length: Field::Exact(4),
                checksum: Field::Exact(0),
                protocol: Field::Exact(IpNextHeaderProtocols::Tcp.0),
                options: vec![1, 2, 3, 4],
                ..Ipv4::new(Ipv4Addr::new(192, 0, 2, 1), Ipv4Addr::new(192, 0, 2, 9))
            })
            .push(Tcp {
                data_offset: Field::Exact(15),
                options: vec![0; 4],
                payload: b"HELLO".to_vec(),
                ..Tcp::new(50_000, 80).with_flags(tcp_flags::SYN)
            })
            .push(Layer::Raw(vec![0xde, 0xad, 0xbe, 0xef]))
    }

    /// The property a document format is for: what comes back builds the same
    /// packet the original did.
    ///
    /// Asserted on the bytes rather than on the layers, because that is what a
    /// caller gets and because it holds a field this test did not think to name.
    #[test]
    fn a_packet_written_as_a_document_reads_back_as_the_same_packet() {
        let original = everything();
        let written = toml::to_string(&original).expect("a packet is a document");
        let read: Packet = toml::from_str(&written).expect("and reads back");

        assert_eq!(
            read.build().expect("the copy builds"),
            original.build().expect("the original builds"),
            "the packet that came back is not the packet that went in:\n{written}"
        );
    }

    /// A derived field left to the builder is left out of the document, and a
    /// pinned one is written down. That is the whole encoding of [`Field`], and
    /// a document that wrote both would say a value was chosen when it was not.
    #[test]
    fn only_a_pinned_field_is_written_down() {
        let pinned = Packet::new().push(Ipv4 {
            checksum: Field::Exact(0),
            ..Ipv4::new(Ipv4Addr::LOCALHOST, Ipv4Addr::LOCALHOST)
        });
        let written = toml::to_string(&pinned).expect("a document");

        assert!(written.contains("checksum"), "{written}");
        assert!(
            !written.contains("total_length"),
            "a field left to the builder was written down as though it were chosen:\n{written}"
        );

        let read: Packet = toml::from_str(&written).expect("reads back");
        let Some(Layer::Ipv4(header)) = read.layers().first() else {
            panic!("the layer came back as something else");
        };
        assert_eq!(header.checksum, Field::Exact(0));
        assert_eq!(header.total_length, Field::Computed);
    }

    /// Bytes are hex, which is the one convention here a reader has to be told.
    #[test]
    fn bytes_are_written_as_hex() {
        let packet = Packet::new().push(Layer::Raw(vec![0xde, 0xad, 0xbe, 0xef]));
        let written = toml::to_string(&packet).expect("a document");

        assert!(written.contains("deadbeef"), "{written}");
    }

    /// Hex that is not four bytes is refused where it is read, naming what was
    /// wrong, rather than being padded or truncated into the header.
    #[test]
    fn a_rest_of_header_that_is_not_four_bytes_is_refused() {
        let error = toml::from_str::<Packet>(
            "[[layers]]\n[layers.icmpv4]\nicmp_type = 8\ncode = 0\nrest_of_header = \"dead\"\npayload = \"\"\n",
        )
        .expect_err("two bytes are not the four an ICMP header has");

        assert!(error.to_string().contains("8 hex characters"), "{error}");
    }

    /// A document is JSON as readily as TOML, since nothing here names a format.
    ///
    /// `serde_json` is here through this package's dev-dependency on itself,
    /// which carries `export-all`, so a test build always has it whatever the
    /// library was compiled with.
    #[test]
    fn the_same_packet_round_trips_through_json() {
        let original = everything();
        let written = serde_json::to_string(&original).expect("a packet is JSON too");
        let read: Packet = serde_json::from_str(&written).expect("and reads back");

        assert_eq!(
            read.build().expect("the copy builds"),
            original.build().expect("the original builds")
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pnet_packet::Packet as _;
    use pnet_packet::ipv4::Ipv4Packet;
    use pnet_packet::ipv6::Ipv6Packet;

    const V4_SRC: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 1);
    const V4_DST: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 9);
    const MAC: MacAddr = MacAddr::new(0x02, 0, 0, 0, 0, 1);

    fn v6(s: &str) -> Ipv6Addr {
        s.parse().expect("a valid address")
    }

    // ── What a layer with nothing around it gets ─────────────────────────────

    /// A transport layer with no IP header around it has no pseudo-header to
    /// checksum over, so the field is left for whoever supplies one.
    ///
    /// UDP must not answer that with `0xFFFF`, which is what the RFC 768
    /// substitution for a genuine zero would produce if it fired on the "there
    /// was nothing to sum" zero as well. `0xFFFF` is a valid checksum meaning
    /// "computed, and it came to zero", so nothing downstream could tell the two
    /// apart, and `Udp::to_bytes`'s own documentation says the rules are
    /// `Tcp::to_bytes`'s.
    #[test]
    fn a_transport_layer_with_no_addresses_leaves_its_checksum_unset() {
        let tcp = Tcp::new(50_000, 80).to_bytes(None).expect("a segment");
        let udp = Udp::new(50_000, 53).to_bytes(None).expect("a datagram");

        assert_eq!(u16::from_be_bytes([tcp[16], tcp[17]]), 0);
        assert_eq!(u16::from_be_bytes([udp[6], udp[7]]), 0);

        // The substitution still fires where there was something to compute:
        // a datagram whose checksum genuinely sums to zero goes out as 0xFFFF,
        // because zero in that field means "not computed".
        let addresses = Some((IpAddr::V4(V4_SRC), IpAddr::V4(V4_DST)));
        let summed = Udp::new(50_000, 53)
            .to_bytes(addresses)
            .expect("a datagram");
        assert_ne!(u16::from_be_bytes([summed[6], summed[7]]), 0);
    }

    /// An ICMPv6 message inside an IPv4 header is a packet nothing can build,
    /// and it is not two addresses of different families.
    ///
    /// Reported as `FamilyMismatch`, whose message reads "an IPv4 and an IPv6
    /// address", it would say so about two IPv4 ones, which sends a reader after
    /// a fault that is not there.
    #[test]
    fn an_icmpv6_message_under_an_ipv4_header_names_the_family_it_needed() {
        let refused = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Icmpv6::echo_request(1, 1))
            .build()
            .unwrap_err();

        assert!(
            matches!(
                refused,
                PacketError::WrongFamily {
                    protocol: "ICMPv6",
                    expected: "IPv6",
                    ..
                }
            ),
            "got {refused:?}"
        );
        assert!(
            !refused.to_string().contains("an IPv4 and an IPv6 address"),
            "the message still claims a mismatch that is not there: {refused}"
        );

        // Two addresses that genuinely disagree are still a mismatch.
        let mixed = Icmpv6::echo_request(1, 1)
            .to_bytes(Some((IpAddr::V4(V4_SRC), IpAddr::V6(v6("2001:db8::1")))))
            .unwrap_err();
        assert!(matches!(mixed, PacketError::FamilyMismatch { .. }));
    }

    /// A header built on its own has no layer inside it to name, so its protocol
    /// field falls back rather than being derived. That is a trap worth pinning
    /// rather than fixing: making it a refusal would turn two infallible
    /// builders fallible, and the fallback is documented at both.
    #[test]
    fn a_header_built_alone_falls_back_to_tcp_and_says_so() {
        let derived = Ipv4 {
            protocol: Field::Exact(IpNextHeaderProtocols::Udp.0),
            ..Ipv4::new(V4_SRC, V4_DST)
        }
        .header_bytes(100)
        .expect("a header");
        assert_eq!(derived[9], IpNextHeaderProtocols::Udp.0);

        let fallback = Ipv4::new(V4_SRC, V4_DST)
            .header_bytes(100)
            .expect("a header");
        assert_eq!(
            fallback[9],
            IpNextHeaderProtocols::Tcp.0,
            "the documented fallback moved; the doc on `header_bytes` moves with it"
        );
    }

    // ── The default is a correct packet ──────────────────────────────────────

    /// Left alone, every derived field is the value a conformant stack expects.
    /// That is what makes the overrides below mean something: a caller who
    /// changes one field changes only that field.
    #[test]
    fn a_packet_nobody_overrode_is_one_a_stack_would_accept() {
        let bytes = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
            .build()
            .expect("builds");

        let ip = Ipv4Packet::new(&bytes).expect("an IPv4 header");
        assert_eq!(ip.get_total_length() as usize, bytes.len());
        assert_eq!(ip.get_next_level_protocol(), IpNextHeaderProtocols::Tcp);
        assert_eq!(
            ip.get_checksum(),
            ipv4_checksum(&Ipv4Packet::new(&bytes[..20]).expect("header")),
            "the header checksums itself"
        );

        let tcp = TcpPacket::new(ip.payload()).expect("a TCP header");
        assert_eq!(tcp.get_data_offset(), 5);
        assert_eq!(tcp.get_flags(), tcp_flags::SYN);
        assert_ne!(tcp.get_checksum(), 0, "checksummed over the pseudo-header");
    }

    /// The enclosing header works out what it is carrying, so a caller who
    /// swaps the transport does not have to remember to change the protocol
    /// number alongside it.
    #[test]
    fn an_enclosing_header_names_what_is_inside_it() {
        let over_udp = Packet::new()
            .push(Ethernet::new(MAC, MacAddr::BROADCAST))
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Udp::new(50_000, 53))
            .build()
            .expect("builds");

        let eth = super::super::ethernet::parse(&over_udp).expect("a frame");
        assert_eq!(eth.ethertype(), EtherTypes::Ipv4.0);
        assert_eq!(
            Ipv4Packet::new(eth.payload())
                .expect("an IPv4 header")
                .get_next_level_protocol(),
            IpNextHeaderProtocols::Udp
        );

        let over_v6 = Packet::new()
            .push(Ethernet::new(MAC, MacAddr::BROADCAST))
            .push(Ipv6::new(v6("2001:db8::1"), v6("2001:db8::2")))
            .push(Tcp::new(50_000, 80))
            .build()
            .expect("builds");

        let eth = super::super::ethernet::parse(&over_v6).expect("a frame");
        assert_eq!(eth.ethertype(), EtherTypes::Ipv6.0);
        assert_eq!(
            Ipv6Packet::new(eth.payload())
                .expect("an IPv6 header")
                .get_next_header(),
            IpNextHeaderProtocols::Tcp
        );
    }

    /// The checksum covers a pseudo-header built from the addresses of the IP
    /// layer outside the transport, which is the one thing a layer cannot see
    /// by looking inward. Getting it from the wrong place is invisible until a
    /// real stack drops the packet.
    #[test]
    fn a_transport_checksum_covers_the_addresses_of_the_layer_around_it() {
        let checksum_with = |dst: Ipv4Addr| {
            let bytes = Packet::new()
                .push(Ipv4::new(V4_SRC, dst))
                .push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
                .build()
                .expect("builds");
            let ip = Ipv4Packet::new(&bytes).expect("header");
            TcpPacket::new(ip.payload())
                .expect("segment")
                .get_checksum()
        };

        assert_ne!(
            checksum_with(V4_DST),
            checksum_with(Ipv4Addr::new(192, 0, 2, 10)),
            "the destination is part of what is summed"
        );
    }

    // ── Overrides ────────────────────────────────────────────────────────────

    /// One wrong field, every other one still right. A packet that is wrong in
    /// nineteen ways is rejected by the first check a stack runs and says nothing
    /// about the rest.
    #[test]
    fn an_exact_field_is_written_verbatim_and_nothing_else_moves() {
        let bytes = Packet::new()
            .push(Ipv4 {
                total_length: Field::Exact(4),
                ..Ipv4::new(V4_SRC, V4_DST)
            })
            .push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
            .build()
            .expect("a wrong length is not an error, it is the request");

        let ip = Ipv4Packet::new(&bytes).expect("an IPv4 header");
        assert_eq!(ip.get_total_length(), 4, "written as asked");
        assert_eq!(bytes.len(), 40, "and the packet is its real size");
        assert_eq!(
            ip.get_next_level_protocol(),
            IpNextHeaderProtocols::Tcp,
            "the fields nobody touched are still correct"
        );

        // Read at a fixed offset rather than through `payload()`, which trusts
        // the length field and so hands back nothing. That a parser is already
        // misled by this packet is the point of building it.
        assert!(ip.payload().is_empty(), "a reader believes the header");
        let tcp = TcpPacket::new(&bytes[20..]).expect("the segment is really there");
        assert_ne!(tcp.get_checksum(), 0, "and is checksummed correctly");
        assert_eq!(tcp.get_destination(), 80);
    }

    /// A checksum of zero is a real thing to want to send and is exactly what
    /// `Computed` would never produce, so it is the clearest test that an
    /// override is honoured rather than validated away.
    #[test]
    fn a_deliberately_wrong_checksum_survives_to_the_wire() {
        let bytes = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST).with_checksum(0))
            .push(Tcp::new(50_000, 80).with_checksum(0xDEAD))
            .build()
            .expect("builds");

        let ip = Ipv4Packet::new(&bytes).expect("an IPv4 header");
        assert_eq!(ip.get_checksum(), 0);
        assert_eq!(
            TcpPacket::new(ip.payload()).expect("tcp").get_checksum(),
            0xDEAD
        );
    }

    /// A data offset larger than the header makes a receiver read payload as
    /// options, and one smaller makes it read options as payload. Both are
    /// worth being able to send and neither is something the builder should
    /// second-guess.
    #[test]
    fn a_data_offset_that_lies_about_the_header_is_written_as_given() {
        let bytes = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Tcp {
                data_offset: Field::Exact(15),
                ..Tcp::new(50_000, 80)
            })
            .build()
            .expect("builds");

        let ip = Ipv4Packet::new(&bytes).expect("header");
        assert_eq!(
            TcpPacket::new(ip.payload()).expect("tcp").get_data_offset(),
            15
        );
    }

    // ── Refusals ─────────────────────────────────────────────────────────────

    /// A *computed* length that will not fit its field is refused, because the
    /// caller asked for the correct value and there is not one. An exact one is
    /// written whatever it says, which is the previous test.
    #[test]
    fn a_computed_length_that_cannot_fit_is_refused() {
        let refused = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Udp::new(50_000, 53).with_payload(vec![0u8; u16::MAX as usize]))
            .build();

        assert!(
            matches!(refused, Err(PacketError::TooLong { .. })),
            "got {refused:?}"
        );
    }

    /// A packet may be edited after it is described, which is how a caller
    /// works from a template. Swapping the IP layer for another family has to
    /// carry the transport checksum with it rather than leaving one computed
    /// against the old pseudo-header.
    #[test]
    fn editing_the_ip_layer_moves_the_checksum_that_depends_on_it() {
        let mut packet = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN));
        let over_v4 = packet.build().expect("builds");

        packet.layers_mut()[0] = Layer::Ipv6(Ipv6::new(v6("2001:db8::1"), v6("2001:db8::2")));
        let over_v6 = packet.build().expect("builds");

        let v4_sum = TcpPacket::new(&over_v4[20..]).expect("tcp").get_checksum();
        let v6_sum = TcpPacket::new(&over_v6[40..]).expect("tcp").get_checksum();
        assert_ne!(
            v4_sum, v6_sum,
            "the pseudo-header changed, so the checksum must have"
        );
    }

    /// A transport layer with no IP header around it is a fragment the caller
    /// means to embed somewhere else, so it gets a zero checksum rather than an
    /// invented pseudo-header.
    #[test]
    fn a_bare_transport_layer_builds_without_inventing_addresses() {
        let bytes = Packet::new()
            .push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
            .build()
            .expect("builds");

        assert_eq!(bytes.len(), 20);
        assert_eq!(TcpPacket::new(&bytes).expect("tcp").get_checksum(), 0);
    }

    // ── Payloads and options ─────────────────────────────────────────────────

    #[test]
    fn a_payload_is_counted_by_every_length_above_it() {
        let bytes = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Udp::new(50_000, 53).with_payload(b"hello".to_vec()))
            .build()
            .expect("builds");

        let ip = Ipv4Packet::new(&bytes).expect("header");
        assert_eq!(ip.get_total_length() as usize, 20 + 8 + 5);
        assert_eq!(
            UdpPacket::new(ip.payload()).expect("udp").get_length(),
            8 + 5
        );
        assert_eq!(&bytes[bytes.len() - 5..], b"hello");
    }

    /// Options past what the length field measures are refused rather than
    /// wrapped into it.
    ///
    /// Both fields are four bits of four-byte words, so forty bytes of options
    /// is the most either header can describe. Wrapped silently, forty-four
    /// would produce a header declaring itself zero words long and a hundred
    /// one claiming fifty-six bytes over a buffer of a hundred and twenty, a
    /// packet every receiver reads as something other than what was built.
    #[test]
    fn options_past_what_the_length_field_measures_are_refused() {
        const LARGEST: usize = 40;

        for options in [LARGEST + 4, 100, 252] {
            let mut ip = Ipv4::new(V4_SRC, V4_DST);
            ip.options = vec![0u8; options];
            assert!(
                matches!(
                    Packet::new().push(Layer::Ipv4(ip)).build(),
                    Err(PacketError::OptionsTooLong { .. })
                ),
                "{options} bytes of IPv4 options was accepted"
            );

            let mut tcp = Tcp::new(1234, 80);
            tcp.options = vec![0u8; options];
            assert!(
                matches!(
                    Packet::new().push(Layer::Tcp(tcp)).build(),
                    Err(PacketError::OptionsTooLong { .. })
                ),
                "{options} bytes of TCP options was accepted"
            );
        }

        // And the largest that fits still builds, with the field describing it.
        let mut ip = Ipv4::new(V4_SRC, V4_DST);
        ip.options = vec![0u8; LARGEST];
        let bytes = Packet::new()
            .push(Layer::Ipv4(ip))
            .build()
            .expect("forty bytes of options is the most that fits");
        assert_eq!(usize::from(bytes[0] & 0x0F) * 4, IP_V4_HDR_LEN + LARGEST);
    }

    /// Options that are not a whole number of words are refused too.
    ///
    /// The field counts words, so the division would round down and the odd
    /// bytes become payload to whatever received the packet: six bytes of
    /// options would build a twenty-six byte header declaring twenty-four.
    #[test]
    fn options_that_are_not_a_whole_number_of_words_are_refused() {
        for options in [1usize, 2, 3, 5, 6, 7, 39] {
            let mut ip = Ipv4::new(V4_SRC, V4_DST);
            ip.options = vec![0u8; options];
            assert!(
                matches!(
                    Packet::new().push(Layer::Ipv4(ip)).build(),
                    Err(PacketError::OptionsMisaligned { .. })
                ),
                "{options} bytes of IPv4 options was accepted"
            );

            let mut tcp = Tcp::new(1234, 80);
            tcp.options = vec![0u8; options];
            assert!(
                matches!(
                    Packet::new().push(Layer::Tcp(tcp)).build(),
                    Err(PacketError::OptionsMisaligned { .. })
                ),
                "{options} bytes of TCP options was accepted"
            );
        }
    }

    /// Options lengthen the header, so the data offset that finds the payload
    /// has to move with them.
    #[test]
    fn tcp_options_move_the_data_offset_that_finds_the_payload() {
        let bytes = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Tcp {
                // One four-byte option: kind 2, length 4, MSS 1412.
                options: vec![2, 4, 0x05, 0x84],
                payload: b"body".to_vec(),
                ..Tcp::new(50_000, 80)
            })
            .build()
            .expect("builds");

        let ip = Ipv4Packet::new(&bytes).expect("header");
        let tcp = TcpPacket::new(ip.payload()).expect("tcp");
        assert_eq!(tcp.get_data_offset(), 6, "twenty bytes plus one word");
        assert_eq!(tcp.payload(), b"body");
    }

    /// Bytes nothing here models yet still go on the wire, so a protocol this
    /// module has not learned is not a wall.
    #[test]
    fn a_raw_layer_is_written_exactly_as_given() {
        let bytes = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Layer::Raw(vec![0xDE, 0xAD, 0xBE, 0xEF]))
            .build()
            .expect("builds");

        assert_eq!(&bytes[20..], &[0xDE, 0xAD, 0xBE, 0xEF]);
        assert_eq!(
            Ipv4Packet::new(&bytes).expect("header").get_total_length(),
            24
        );
    }

    // ── SCTP ─────────────────────────────────────────────────────────────────

    /// The one non-circular anchor for the whole CRC32c path: the check value
    /// RFC 3309 and the CRC-32C/iSCSI definition both publish for the ASCII
    /// digits "123456789". A wrong polynomial or a missing reflection fails
    /// here rather than by silently disagreeing with every real stack.
    #[test]
    fn crc32c_matches_the_published_check_value() {
        assert_eq!(crc32c(b"123456789"), 0xE306_9283);
    }

    /// SCTP writes its checksum little-endian (RFC 4960 §6.8), which is the
    /// classic way to get it wrong. The stored field is the CRC's little-endian
    /// bytes, computed over the packet with the field zeroed and, the value being
    /// byte-order-sensitive, demonstrably not its big-endian bytes.
    #[test]
    fn an_sctp_checksum_is_written_little_endian_over_a_zeroed_field() {
        let bytes = Sctp::new(50_000, 9)
            .with_chunks(vec![1, 0, 0, 4]) // a minimal well-formed chunk header
            .to_bytes();

        let mut zeroed = bytes.clone();
        zeroed[8..12].copy_from_slice(&[0; 4]);
        let crc = crc32c(&zeroed);

        assert_eq!(&bytes[8..12], &crc.to_le_bytes());
        assert_ne!(
            &bytes[8..12],
            &crc.to_be_bytes(),
            "little-endian rather than big; the check value makes the two differ"
        );
    }

    /// The enclosing IP header names SCTP for itself, so a caller stacking one
    /// does not have to remember protocol 132.
    #[test]
    fn an_ip_header_names_the_sctp_inside_it() {
        let bytes = Packet::new()
            .push(Ipv4::new(V4_SRC, V4_DST))
            .push(Sctp::new(50_000, 9).with_chunks(vec![1, 0, 0, 4]))
            .build()
            .expect("builds");

        assert_eq!(
            Ipv4Packet::new(&bytes)
                .expect("header")
                .get_next_level_protocol(),
            IpNextHeaderProtocols::Sctp
        );
    }

    /// The malformed-packet story reaches SCTP too: an exact checksum is written
    /// as given, which is what probing a stack's CRC validation needs.
    #[test]
    fn a_deliberately_wrong_sctp_checksum_survives_to_the_wire() {
        let bytes = Sctp::new(50_000, 9).with_checksum(0).to_bytes();
        assert_eq!(&bytes[8..12], &[0; 4]);
    }

    // ── Corrupting a checksum on purpose ─────────────────────────────────────

    /// The common case: flipping every bit lands on a value that verifies
    /// differently, so it is certainly wrong. A mutant returning the input
    /// unchanged, a corruption equal to the correct checksum, would leave a probe
    /// every host accepts.
    #[test]
    fn a_corrupt_checksum_differs_from_the_one_it_was_made_from() {
        for correct in [0x1234, 0x00FF, 0xABCD, 0x8000, 0x0001] {
            let corrupt = corrupt_internet_checksum(correct);
            assert_ne!(corrupt, correct, "{correct:#06x} was not changed");
            assert_ne!(corrupt, 0, "{correct:#06x} corrupted to a zero checksum");
        }
    }

    /// The two encodings of a one's-complement zero verify identically, so a flip
    /// between them is not wrong, and zero is a checksum a segment may
    /// legitimately carry, so it can never be the corrupt one. A mutant that only
    /// flipped the bits would return the other encoding of zero here and ship a
    /// checksum still accepted as correct.
    #[test]
    fn corrupting_a_zero_encoding_avoids_the_other_encoding_of_zero() {
        assert_eq!(corrupt_internet_checksum(0x0000), 0x0001);
        assert_eq!(corrupt_internet_checksum(0xFFFF), 0x0001);
    }

    /// A segment asked for a bad TCP checksum carries one that a real parse
    /// confirms is neither the value the segment should have nor zero, with every
    /// other byte of the header untouched.
    #[test]
    fn a_tcp_segment_can_be_built_with_a_verifiably_wrong_checksum() {
        let addresses = Some((IpAddr::V4(V4_SRC), IpAddr::V4(V4_DST)));
        let segment = Tcp::new(50_000, 80).with_flags(tcp_flags::SYN);

        let good = segment.to_bytes(addresses).expect("builds");
        let corrupt = segment.corrupt_checksum(addresses).expect("perturbs");
        let bad = Tcp {
            checksum: Field::Exact(corrupt),
            ..segment
        }
        .to_bytes(addresses)
        .expect("builds");

        let should_carry = TcpPacket::new(&good).expect("tcp").get_checksum();
        let on_the_wire = TcpPacket::new(&bad).expect("tcp").get_checksum();
        assert_ne!(on_the_wire, should_carry, "the checksum is not wrong");
        assert_ne!(on_the_wire, 0, "zero is ambiguous, not wrong");

        // Only the checksum moved: zero both copies' checksum field (bytes 16..18
        // of the TCP header) and the rest must be byte-for-byte equal.
        let (mut good, mut bad) = (good, bad);
        good[16..18].fill(0);
        bad[16..18].fill(0);
        assert_eq!(good, bad, "corrupting the checksum disturbed another field");
    }
}