zond-engine 0.13.0

A lightweight, fast, and highly concurrent networking backend for packet crafting, protocol fingerprinting, and host discovery.
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
// 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::create_probe`](super::tcp::create_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 you describe
//! yourself, layer by layer, including one that is deliberately wrong.
//!
//! ```
//! 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 simply yours — a port, a TTL, a
//! flag. A few are *derived*: a length that counts what is inside, a checksum
//! computed over it, a protocol number naming the layer below. Those are the
//! interesting ones, because a scanner wants them right and somebody probing a
//! stack's error handling wants them wrong.
//!
//! Every derived field is a [`Field<T>`](Field), which is [`Computed`] by
//! default and [`Exact`] when you say 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 pnet::datalink::MacAddr;
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 you would rather
/// it did not.
///
/// 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 precisely what you give it, 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)]
pub struct Ethernet {
    /// The address the frame claims to come from.
    pub source: MacAddr,
    /// The address it is aimed at.
    pub destination: MacAddr,
    /// What the frame carries. Computed from the layer inside it.
    pub ethertype: Field<EtherType>,
}

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: EtherType) -> 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)]
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.
    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 inside it.
    pub protocol: Field<IpNextHeaderProtocol>,
    /// Header and payload together. Computed from the packet being built.
    pub total_length: Field<u16>,
    /// The header checksum. Computed over the finished header.
    pub checksum: Field<u16>,
    /// Header options, padded by the caller to a four-byte boundary.
    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.
    ///
    /// # 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)]
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.
    pub flow_label: Field<u32>,
    /// What follows this header. Computed from the layer inside it.
    pub next_header: Field<IpNextHeaderProtocol>,
    /// Everything after this header. Computed from the packet being built.
    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.
    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)]
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.
    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.
    pub data_offset: Field<u8>,
    /// The checksum, over the segment and an IP pseudo-header. Computed.
    pub checksum: Field<u16>,
    /// Header options, as raw bytes, padded by the caller to a four-byte
    /// boundary.
    pub options: Vec<u8>,
    /// The segment's payload.
    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: 1024,
            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
    }

    /// 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)
    }
}

/// A UDP header and whatever it carries.
#[derive(Debug, Clone, PartialEq, Eq)]
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.
    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.
    pub checksum: Field<u16>,
    /// The datagram's payload.
    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)]
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.
    pub checksum: Field<u32>,
    /// The chunks after the common header, already encoded.
    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; anything else is yours to lay out.
#[derive(Debug, Clone, PartialEq, Eq)]
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.
    pub checksum: Field<u16>,
    /// The four type-specific bytes between the checksum and the payload. An
    /// echo carries its identifier and sequence here.
    pub rest_of_header: [u8; 4],
    /// Whatever follows the header.
    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(),
        }
    }

    /// 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
    }

    /// 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)]
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.
    pub checksum: Field<u16>,
    /// The four type-specific bytes between the checksum and the payload.
    pub rest_of_header: [u8; 4],
    /// Whatever follows the header.
    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
    }

    /// 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::FamilyMismatch`] when the addresses are not both IPv6.
    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)
                    }
                    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 — type, code, checksum, four type-specific bytes,
/// payload — and differ 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;
/// 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 simply yours. It is in this module anyway, because the interesting
/// ARP packets are the ones a preset would not build: a reply nobody asked for,
/// a request claiming an address that is not yours, a hardware length that does
/// not match the addresses beside it.
#[derive(Debug, Clone, PartialEq, Eq)]
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.
    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.
    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,
        }
    }

    /// 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);
            arp.set_sender_proto_addr(self.sender_proto_addr);
            arp.set_target_hw_addr(self.target_hw_addr);
            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)]
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.
    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<IpNextHeaderProtocol> {
        match self {
            Self::Tcp(_) => Some(IpNextHeaderProtocols::Tcp),
            Self::Udp(_) => Some(IpNextHeaderProtocols::Udp),
            Self::Sctp(_) => Some(IpNextHeaderProtocols::Sctp),
            Self::Icmpv4(_) => Some(IpNextHeaderProtocols::Icmp),
            Self::Icmpv6(_) => Some(IpNextHeaderProtocols::Icmpv6),
            _ => None,
        }
    }

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

/// A packet described as a stack of headers, outermost first.
///
/// See the [module documentation](self) for the idea and an example. Push what
/// you want, in the order it appears on the wire, and call [`build`](Self::build).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
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,
        })
    }
}

/// 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()),
    }
}

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);
        eth.set_destination(header.destination);
        eth.set_ethertype(
            header
                .ethertype
                .resolve(|| inner.and_then(Layer::ethertype).unwrap_or(EtherTypes::Ipv4)),
        );
    }
    bytes.extend_from_slice(&payload);
    Ok(bytes)
}

fn write_ipv4(header: &Ipv4, payload: Vec<u8>, inner: Option<&Layer>) -> Result<Vec<u8>> {
    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(header.protocol.resolve(|| {
            inner
                .and_then(Layer::ip_protocol)
                .unwrap_or(IpNextHeaderProtocols::Tcp)
        }));
        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)
}

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(header.next_header.resolve(|| {
            inner
                .and_then(Layer::ip_protocol)
                .unwrap_or(IpNextHeaderProtocols::Tcp)
        }));
        ipv6.set_hop_limit(header.hop_limit);
        ipv6.set_source(header.source);
        ipv6.set_destination(header.destination);
    }
    bytes.extend_from_slice(&payload);
    Ok(bytes)
}

fn write_tcp(
    header: &Tcp,
    payload: Vec<u8>,
    addresses: Option<(IpAddr, IpAddr)>,
) -> Result<Vec<u8>> {
    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)
}

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 {
        Field::Exact(value) => value,
        Field::Computed => {
            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 }),
    }
}

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 single 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(test)]
mod tests {
    use super::*;
    use pnet::packet::Packet as _;
    use pnet::packet::ethernet::EthernetPacket;
    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(0x02, 0, 0, 0, 0, 1);

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

    // ── 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 = EthernetPacket::new(&over_udp).expect("a frame");
        assert_eq!(eth.get_ethertype(), EtherTypes::Ipv4);
        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 = EthernetPacket::new(&over_v6).expect("a frame");
        assert_eq!(eth.get_ethertype(), EtherTypes::Ipv6);
        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 ────────────────────────────────────────────────────────────

    /// The point of the whole design: 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 tells you 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 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, since the
    /// value is 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, not 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]);
    }
}