crafter 0.3.0

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

/// RFC 4884 ICMP extension header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IcmpExtension {
    version: Field<u8>,
    reserved: Field<u16>,
    checksum: Field<u16>,
}

impl IcmpExtension {
    /// Create an ICMP extension header.
    pub fn new() -> Self {
        Self {
            version: Field::defaulted(2),
            reserved: Field::defaulted(0),
            checksum: Field::unset(),
        }
    }

    /// Set the extension version.
    pub fn version(mut self, version: u8) -> Self {
        self.version.set_user(version);
        self
    }

    /// Set the 12-bit reserved field.
    pub fn reserved(mut self, reserved: u16) -> Self {
        self.reserved.set_user(reserved);
        self
    }

    /// Set the extension checksum explicitly.
    pub fn checksum(mut self, checksum: u16) -> Self {
        self.checksum.set_user(checksum);
        self
    }

    /// Version value.
    pub fn version_value(&self) -> u8 {
        value_or_copy(&self.version, 2)
    }

    /// Reserved field value.
    pub fn reserved_value(&self) -> u16 {
        value_or_copy(&self.reserved, 0)
    }

    /// Stored checksum when explicit or decoded.
    pub fn checksum_value(&self) -> Option<u16> {
        self.checksum.value().copied()
    }

    fn validate(&self) -> Result<()> {
        if self.version_value() > 0x0f {
            return Err(CrafterError::invalid_field_value(
                "icmp_extension.version",
                "version must fit in four bits",
            ));
        }
        if self.reserved_value() > 0x0fff {
            return Err(CrafterError::invalid_field_value(
                "icmp_extension.reserved",
                "reserved field must fit in 12 bits",
            ));
        }
        Ok(())
    }
}

impl Default for IcmpExtension {
    fn default() -> Self {
        Self::new()
    }
}

impl Layer for IcmpExtension {
    fn name(&self) -> &'static str {
        "IcmpExtension"
    }

    fn summary(&self) -> String {
        format!("IcmpExtension(version={})", self.version_value())
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        vec![
            ("version", self.version_value().to_string()),
            ("reserved", format!("0x{:03x}", self.reserved_value())),
            (
                "checksum",
                self.checksum_value()
                    .map(|value| format!("0x{value:04x}"))
                    .unwrap_or_else(|| "auto".to_string()),
            ),
        ]
    }

    fn encoded_len(&self) -> usize {
        ICMP_EXTENSION_HEADER_LEN
    }

    fn encoded_len_with_context(&self, ctx: &LayerContext<'_>) -> usize {
        // The RFC 4884 zero padding emitted before the extension header is part
        // of this layer's on-wire size, so enclosing length fields (the outer
        // IPv4 total length, for one) count it.
        ICMP_EXTENSION_HEADER_LEN + extension_original_datagram_padding(*ctx)
    }

    fn compile(&self, ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        self.validate()?;

        // RFC 4884: the preceding "original datagram" field is zero padded so
        // the extension structure starts at the offset the length field claims.
        // The padding belongs to the original datagram (it is not covered by the
        // extension checksum), so emit it before the extension header.
        let padding = extension_original_datagram_padding(*ctx);
        out.resize(out.len() + padding, 0);

        let mut header = Vec::with_capacity(ICMP_EXTENSION_HEADER_LEN);
        let version_reserved =
            ((self.version_value() as u16) << 12) | (self.reserved_value() & 0x0fff);
        header.extend_from_slice(&version_reserved.to_be_bytes());
        header.extend_from_slice(&0u16.to_be_bytes());
        let payload = payload_bytes_after(*ctx)?;
        let checksum = self.checksum.value().copied().unwrap_or_else(|| {
            let mut bytes = Vec::with_capacity(header.len() + payload.len());
            bytes.extend_from_slice(&header);
            bytes.extend_from_slice(&payload);
            internet_checksum(&bytes)
        });
        header[2..4].copy_from_slice(&checksum.to_be_bytes());
        out.extend_from_slice(&header);
        Ok(())
    }

    impl_layer_object!(IcmpExtension);
}

impl_layer_div!(IcmpExtension);

/// RFC 4884 ICMP extension object header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IcmpExtensionObject {
    length: Field<u16>,
    class_num: Field<u8>,
    c_type: Field<u8>,
}

impl IcmpExtensionObject {
    /// Create an extension object header.
    pub fn new() -> Self {
        Self {
            length: Field::unset(),
            class_num: Field::defaulted(0),
            c_type: Field::defaulted(0),
        }
    }

    /// Set the object length explicitly.
    pub fn length(mut self, length: u16) -> Self {
        self.length.set_user(length);
        self
    }

    /// Set the object class number.
    pub fn class_num(mut self, class_num: u8) -> Self {
        self.class_num.set_user(class_num);
        self
    }

    /// Set the object C-Type.
    pub fn c_type(mut self, c_type: u8) -> Self {
        self.c_type.set_user(c_type);
        self
    }

    /// Object length when explicit or decoded.
    pub fn length_value(&self) -> Option<u16> {
        self.length.value().copied()
    }

    /// Object class number.
    pub fn class_num_value(&self) -> u8 {
        value_or_copy(&self.class_num, 0)
    }

    /// Object C-Type.
    pub fn c_type_value(&self) -> u8 {
        value_or_copy(&self.c_type, 0)
    }

    fn effective_length(&self, ctx: LayerContext<'_>) -> Result<u16> {
        if let Some(length) = self.length.value().copied() {
            return Ok(length);
        }

        u16::try_from(ICMP_EXTENSION_OBJECT_LEN + extension_object_payload_len(ctx)).map_err(|_| {
            CrafterError::invalid_field_value(
                "icmp_extension_object.length",
                "extension object length exceeds 65535 bytes",
            )
        })
    }

    fn effective_class_num(&self, next: Option<&dyn Layer>) -> u8 {
        if self.class_num.is_user_set() {
            return self.class_num_value();
        }
        if next
            .map(|layer| layer.as_any().is::<IcmpExtensionMpls>())
            .unwrap_or(false)
        {
            ICMP_EXTENSION_CLASS_MPLS
        } else if next
            .map(|layer| layer.as_any().is::<IcmpExtensionInterfaceInfo>())
            .unwrap_or(false)
        {
            ICMP_EXTENSION_CLASS_INTERFACE_INFO
        } else if next
            .map(|layer| layer.as_any().is::<IcmpExtensionInterfaceId>())
            .unwrap_or(false)
        {
            ICMP_EXTENSION_CLASS_INTERFACE_ID
        } else {
            self.class_num_value()
        }
    }

    fn effective_c_type(&self, next: Option<&dyn Layer>) -> u8 {
        if self.c_type.is_user_set() {
            return self.c_type_value();
        }
        if next
            .map(|layer| layer.as_any().is::<IcmpExtensionMpls>())
            .unwrap_or(false)
        {
            ICMP_EXTENSION_CTYPE_MPLS_INCOMING
        } else if let Some(info) =
            next.and_then(|layer| layer.as_any().downcast_ref::<IcmpExtensionInterfaceInfo>())
        {
            info.c_type_byte()
        } else if let Some(id) =
            next.and_then(|layer| layer.as_any().downcast_ref::<IcmpExtensionInterfaceId>())
        {
            id.c_type()
        } else {
            self.c_type_value()
        }
    }
}

impl Default for IcmpExtensionObject {
    fn default() -> Self {
        Self::new()
    }
}

impl Layer for IcmpExtensionObject {
    fn name(&self) -> &'static str {
        "IcmpExtensionObject"
    }

    fn summary(&self) -> String {
        format!(
            "IcmpExtensionObject(class={}, ctype={})",
            self.class_num_value(),
            self.c_type_value()
        )
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        vec![
            (
                "length",
                self.length_value()
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "auto".to_string()),
            ),
            ("class_num", self.class_num_value().to_string()),
            ("c_type", self.c_type_value().to_string()),
        ]
    }

    fn encoded_len(&self) -> usize {
        ICMP_EXTENSION_OBJECT_LEN
    }

    fn compile(&self, ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        out.extend_from_slice(&self.effective_length(*ctx)?.to_be_bytes());
        out.push(self.effective_class_num(ctx.next()));
        out.push(self.effective_c_type(ctx.next()));
        Ok(())
    }

    impl_layer_object!(IcmpExtensionObject);
}

impl_layer_div!(IcmpExtensionObject);

/// MPLS label stack entry for ICMP extensions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IcmpExtensionMpls {
    label: Field<u32>,
    experimental: Field<u8>,
    bottom_of_stack: Field<bool>,
    ttl: Field<u8>,
}

impl IcmpExtensionMpls {
    /// Create an MPLS extension entry.
    pub fn new() -> Self {
        Self {
            label: Field::defaulted(0),
            experimental: Field::defaulted(0),
            bottom_of_stack: Field::unset(),
            ttl: Field::defaulted(0),
        }
    }

    /// Set the MPLS label.
    pub fn label(mut self, label: u32) -> Self {
        self.label.set_user(label);
        self
    }

    /// Set the experimental bits.
    pub fn experimental(mut self, experimental: u8) -> Self {
        self.experimental.set_user(experimental);
        self
    }

    /// Alias for the experimental bits.
    pub fn exp(self, experimental: u8) -> Self {
        self.experimental(experimental)
    }

    /// Set the bottom-of-stack bit explicitly.
    pub fn bottom_of_stack(mut self, bottom_of_stack: bool) -> Self {
        self.bottom_of_stack.set_user(bottom_of_stack);
        self
    }

    /// Set the MPLS TTL.
    pub fn ttl(mut self, ttl: u8) -> Self {
        self.ttl.set_user(ttl);
        self
    }

    /// MPLS label value.
    pub fn label_value(&self) -> u32 {
        value_or_copy(&self.label, 0)
    }

    /// Experimental bits value.
    pub fn experimental_value(&self) -> u8 {
        value_or_copy(&self.experimental, 0)
    }

    /// Stored bottom-of-stack bit when explicit or decoded.
    pub fn bottom_of_stack_value(&self) -> Option<bool> {
        self.bottom_of_stack.value().copied()
    }

    /// MPLS TTL value.
    pub fn ttl_value(&self) -> u8 {
        value_or_copy(&self.ttl, 0)
    }

    fn effective_bottom_of_stack(&self, next: Option<&dyn Layer>) -> bool {
        self.bottom_of_stack.value().copied().unwrap_or_else(|| {
            !next
                .map(|layer| layer.as_any().is::<IcmpExtensionMpls>())
                .unwrap_or(false)
        })
    }

    fn validate(&self) -> Result<()> {
        if self.label_value() > MPLS_MAX_LABEL {
            return Err(CrafterError::invalid_field_value(
                "icmp_extension_mpls.label",
                "MPLS label must fit in 20 bits",
            ));
        }
        if self.experimental_value() > MPLS_MAX_EXP {
            return Err(CrafterError::invalid_field_value(
                "icmp_extension_mpls.experimental",
                "MPLS experimental field must fit in three bits",
            ));
        }
        Ok(())
    }
}

impl Default for IcmpExtensionMpls {
    fn default() -> Self {
        Self::new()
    }
}

impl Layer for IcmpExtensionMpls {
    fn name(&self) -> &'static str {
        "IcmpExtensionMpls"
    }

    fn summary(&self) -> String {
        format!(
            "IcmpExtensionMpls(label={}, ttl={})",
            self.label_value(),
            self.ttl_value()
        )
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        vec![
            ("label", self.label_value().to_string()),
            ("experimental", self.experimental_value().to_string()),
            (
                "bottom_of_stack",
                self.bottom_of_stack_value()
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "auto".to_string()),
            ),
            ("ttl", self.ttl_value().to_string()),
        ]
    }

    fn encoded_len(&self) -> usize {
        ICMP_EXTENSION_MPLS_LEN
    }

    fn compile(&self, ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        self.validate()?;

        let word = (self.label_value() << 12)
            | ((self.experimental_value() as u32) << 9)
            | ((self.effective_bottom_of_stack(ctx.next()) as u32) << 8)
            | self.ttl_value() as u32;
        out.extend_from_slice(&word.to_be_bytes());
        Ok(())
    }

    impl_layer_object!(IcmpExtensionMpls);
}

impl_layer_div!(IcmpExtensionMpls);

/// RFC 5837 IP Address sub-object carried inside an interface information
/// object: a 16-bit Address Family Identifier, a 16-bit reserved field, and the
/// address bytes (4 for IPv4, 16 for IPv6). The address is kept as raw bytes so
/// unknown AFIs and non-canonical reserved values round-trip byte-for-byte.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IcmpInterfaceIpAddress {
    afi: Field<u16>,
    reserved: Field<u16>,
    address: Vec<u8>,
}

impl IcmpInterfaceIpAddress {
    /// Build an IPv4 IP Address sub-object.
    pub fn ipv4(address: Ipv4Addr) -> Self {
        Self {
            afi: Field::user(ICMP_INTERFACE_AFI_IPV4),
            reserved: Field::defaulted(0),
            address: address.octets().to_vec(),
        }
    }

    /// Build an IPv6 IP Address sub-object.
    pub fn ipv6(address: core::net::Ipv6Addr) -> Self {
        Self {
            afi: Field::user(ICMP_INTERFACE_AFI_IPV6),
            reserved: Field::defaulted(0),
            address: address.octets().to_vec(),
        }
    }

    /// Build an IP Address sub-object from a raw AFI and address bytes, the
    /// escape hatch for unknown or malformed address families.
    pub fn raw(afi: u16, address: impl Into<Vec<u8>>) -> Self {
        Self {
            afi: Field::user(afi),
            reserved: Field::defaulted(0),
            address: address.into(),
        }
    }

    /// Set the 16-bit reserved field explicitly.
    pub fn reserved(mut self, reserved: u16) -> Self {
        self.reserved.set_user(reserved);
        self
    }

    /// Address Family Identifier value.
    pub fn afi_value(&self) -> u16 {
        value_or_copy(&self.afi, 0)
    }

    /// Reserved field value.
    pub fn reserved_value(&self) -> u16 {
        value_or_copy(&self.reserved, 0)
    }

    /// Raw address bytes.
    pub fn address_bytes(&self) -> &[u8] {
        &self.address
    }

    /// Address as an [`Ipv4Addr`] when the AFI is IPv4 and four bytes follow.
    pub fn ipv4_value(&self) -> Option<Ipv4Addr> {
        if self.afi_value() == ICMP_INTERFACE_AFI_IPV4 && self.address.len() == 4 {
            Some(Ipv4Addr::new(
                self.address[0],
                self.address[1],
                self.address[2],
                self.address[3],
            ))
        } else {
            None
        }
    }

    /// Address as an [`Ipv6Addr`](core::net::Ipv6Addr) when the AFI is IPv6 and
    /// sixteen bytes follow.
    pub fn ipv6_value(&self) -> Option<core::net::Ipv6Addr> {
        if self.afi_value() == ICMP_INTERFACE_AFI_IPV6 && self.address.len() == 16 {
            let mut octets = [0u8; 16];
            octets.copy_from_slice(&self.address);
            Some(core::net::Ipv6Addr::from(octets))
        } else {
            None
        }
    }

    fn encoded_len(&self) -> usize {
        ICMP_INTERFACE_IP_ADDRESS_PREFIX_LEN + self.address.len()
    }

    fn compile(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.afi_value().to_be_bytes());
        out.extend_from_slice(&self.reserved_value().to_be_bytes());
        out.extend_from_slice(&self.address);
    }
}

/// RFC 5837 ICMP extension object carrying interface information.
///
/// The single object holds an interface role (RFC 5837 figure 1, C-Type bits
/// 0-1), a two-bit reserved field (bits 2-3), and up to four optional
/// sub-objects in their mandatory order: a 32-bit `ifIndex`, an
/// [`IcmpInterfaceIpAddress`], an interface name, and a 32-bit MTU. The C-Type
/// presence bits (4-7) are derived from which sub-objects are present, so the
/// preceding [`IcmpExtensionObject`] auto-fills class 2 and the matching C-Type
/// byte. Unknown or malformed bodies stay raw through the generic object path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IcmpExtensionInterfaceInfo {
    role: Field<u8>,
    reserved: Field<u8>,
    if_index: Option<u32>,
    ip_address: Option<IcmpInterfaceIpAddress>,
    name: Option<Vec<u8>>,
    mtu: Option<u32>,
}

impl IcmpExtensionInterfaceInfo {
    /// Create an interface information object with the incoming-interface role
    /// and no sub-objects.
    pub fn new() -> Self {
        Self {
            role: Field::defaulted(ICMP_INTERFACE_ROLE_INCOMING),
            reserved: Field::defaulted(0),
            if_index: None,
            ip_address: None,
            name: None,
            mtu: None,
        }
    }

    /// Set the two-bit interface role (RFC 5837 C-Type bits 0-1).
    pub fn role(mut self, role: u8) -> Self {
        self.role.set_user(role);
        self
    }

    /// Set the two-bit reserved field (RFC 5837 C-Type bits 2-3).
    pub fn reserved(mut self, reserved: u8) -> Self {
        self.reserved.set_user(reserved);
        self
    }

    /// Include the 32-bit ifIndex sub-object.
    pub fn if_index(mut self, if_index: u32) -> Self {
        self.if_index = Some(if_index);
        self
    }

    /// Include the IP Address sub-object.
    pub fn ip_address(mut self, ip_address: IcmpInterfaceIpAddress) -> Self {
        self.ip_address = Some(ip_address);
        self
    }

    /// Include the Interface Name sub-object from raw name octets (UTF-8 per
    /// RFC 5837, but bytes are preserved verbatim and zero padded on the wire).
    pub fn name_bytes(mut self, name: impl Into<Vec<u8>>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Include the Interface Name sub-object from a string.
    pub fn name(self, name: &str) -> Self {
        self.name_bytes(name.as_bytes().to_vec())
    }

    /// Include the 32-bit MTU sub-object.
    pub fn mtu(mut self, mtu: u32) -> Self {
        self.mtu = Some(mtu);
        self
    }

    /// Interface role value (C-Type bits 0-1).
    pub fn role_value(&self) -> u8 {
        value_or_copy(&self.role, ICMP_INTERFACE_ROLE_INCOMING)
    }

    /// Reserved field value (C-Type bits 2-3).
    pub fn reserved_value(&self) -> u8 {
        value_or_copy(&self.reserved, 0)
    }

    /// ifIndex sub-object value, if present.
    pub fn if_index_value(&self) -> Option<u32> {
        self.if_index
    }

    /// IP Address sub-object, if present.
    pub fn ip_address_value(&self) -> Option<&IcmpInterfaceIpAddress> {
        self.ip_address.as_ref()
    }

    /// Interface name octets, if present.
    pub fn name_value(&self) -> Option<&[u8]> {
        self.name.as_deref()
    }

    /// MTU sub-object value, if present.
    pub fn mtu_value(&self) -> Option<u32> {
        self.mtu
    }

    /// RFC 5837 C-Type byte: role in bits 0-1, reserved in bits 2-3, and one
    /// presence bit per included sub-object in bits 4-7.
    pub fn c_type_byte(&self) -> u8 {
        let mut byte = ((self.role_value() & 0x03) << 6) | ((self.reserved_value() & 0x03) << 4);
        if self.if_index.is_some() {
            byte |= ICMP_INTERFACE_CTYPE_IFINDEX;
        }
        if self.ip_address.is_some() {
            byte |= ICMP_INTERFACE_CTYPE_IP_ADDRESS;
        }
        if self.name.is_some() {
            byte |= ICMP_INTERFACE_CTYPE_NAME;
        }
        if self.mtu.is_some() {
            byte |= ICMP_INTERFACE_CTYPE_MTU;
        }
        byte
    }

    /// On-wire length of the interface name sub-object (length octet plus name
    /// octets, zero padded to a 4-octet boundary), when a name is present.
    fn name_encoded_len(&self) -> usize {
        self.name
            .as_ref()
            .map(|name| {
                let raw = 1 + name.len();
                raw.div_ceil(4) * 4
            })
            .unwrap_or(0)
    }

    fn validate(&self) -> Result<()> {
        if self.role_value() > 0x03 {
            return Err(CrafterError::invalid_field_value(
                "icmp_interface_info.role",
                "interface role must fit in two bits",
            ));
        }
        if self.reserved_value() > 0x03 {
            return Err(CrafterError::invalid_field_value(
                "icmp_interface_info.reserved",
                "interface reserved field must fit in two bits",
            ));
        }
        if let Some(name) = &self.name {
            if name.len() > ICMP_INTERFACE_NAME_MAX {
                return Err(CrafterError::invalid_field_value(
                    "icmp_interface_info.name",
                    "interface name must not exceed 63 octets",
                ));
            }
        }
        Ok(())
    }
}

impl Default for IcmpExtensionInterfaceInfo {
    fn default() -> Self {
        Self::new()
    }
}

impl Layer for IcmpExtensionInterfaceInfo {
    fn name(&self) -> &'static str {
        "IcmpExtensionInterfaceInfo"
    }

    fn summary(&self) -> String {
        let mut parts = vec![format!(
            "role={}",
            interface_role_summary(self.role_value())
        )];
        if let Some(if_index) = self.if_index {
            parts.push(format!("ifindex={if_index}"));
        }
        if let Some(ip) = &self.ip_address {
            let rendered = ip
                .ipv4_value()
                .map(|addr| addr.to_string())
                .or_else(|| ip.ipv6_value().map(|addr| addr.to_string()))
                .unwrap_or_else(|| {
                    format!("afi={} {}", ip.afi_value(), hex_bytes(ip.address_bytes()))
                });
            parts.push(format!("ip={rendered}"));
        }
        if let Some(name) = &self.name {
            parts.push(format!("name={}", String::from_utf8_lossy(name)));
        }
        if let Some(mtu) = self.mtu {
            parts.push(format!("mtu={mtu}"));
        }
        format!("IcmpExtensionInterfaceInfo({})", parts.join(", "))
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        vec![
            ("role", interface_role_summary(self.role_value())),
            ("reserved", self.reserved_value().to_string()),
            ("c_type", format!("0x{:02x}", self.c_type_byte())),
            (
                "if_index",
                self.if_index
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "-".to_string()),
            ),
            (
                "ip_address",
                self.ip_address
                    .as_ref()
                    .map(|ip| {
                        ip.ipv4_value()
                            .map(|addr| addr.to_string())
                            .or_else(|| ip.ipv6_value().map(|addr| addr.to_string()))
                            .unwrap_or_else(|| {
                                format!("afi={} {}", ip.afi_value(), hex_bytes(ip.address_bytes()))
                            })
                    })
                    .unwrap_or_else(|| "-".to_string()),
            ),
            (
                "name",
                self.name
                    .as_ref()
                    .map(|name| String::from_utf8_lossy(name).into_owned())
                    .unwrap_or_else(|| "-".to_string()),
            ),
            (
                "mtu",
                self.mtu
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "-".to_string()),
            ),
        ]
    }

    fn encoded_len(&self) -> usize {
        let mut len = 0;
        if self.if_index.is_some() {
            len += ICMP_INTERFACE_IFINDEX_LEN;
        }
        if let Some(ip) = &self.ip_address {
            len += ip.encoded_len();
        }
        len += self.name_encoded_len();
        if self.mtu.is_some() {
            len += ICMP_INTERFACE_MTU_LEN;
        }
        len
    }

    fn compile(&self, _ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        self.validate()?;
        if let Some(if_index) = self.if_index {
            out.extend_from_slice(&if_index.to_be_bytes());
        }
        if let Some(ip) = &self.ip_address {
            ip.compile(out);
        }
        if let Some(name) = &self.name {
            // RFC 5837: a one-octet length (covering itself plus the name) leads
            // the name, which is then zero padded to a 4-octet boundary.
            let padded = self.name_encoded_len();
            out.push((1 + name.len()) as u8);
            out.extend_from_slice(name);
            out.resize(out.len() + (padded - 1 - name.len()), 0);
        }
        if let Some(mtu) = self.mtu {
            out.extend_from_slice(&mtu.to_be_bytes());
        }
        Ok(())
    }

    impl_layer_object!(IcmpExtensionInterfaceInfo);
}

impl_layer_div!(IcmpExtensionInterfaceInfo);

/// RFC 8335 Interface Identification Object body (extension object class 3).
///
/// The object identifies the probed interface in exactly one of three ways,
/// selected by the C-Type of the preceding [`IcmpExtensionObject`]:
///
/// - C-Type 1 (by name): the interface name (RFC 7223) zero padded to a 32-bit
///   boundary.
/// - C-Type 2 (by index): a 32-bit ifIndex.
/// - C-Type 3 (by address): a 16-bit AFI, an 8-bit address length, an 8-bit
///   reserved field, and the address bytes zero padded to a 32-bit boundary.
///
/// The form is kept as a typed body so the object's C-Type auto-fills from which
/// constructor was used, and so decode can surface each form's fields. A `raw`
/// escape hatch carries an explicit C-Type and arbitrary body bytes for crafting
/// objects the typed forms do not cover.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IcmpExtensionInterfaceId {
    body: InterfaceIdBody,
}

/// The selected RFC 8335 Interface Identification Object form.
#[derive(Debug, Clone, PartialEq, Eq)]
enum InterfaceIdBody {
    /// C-Type 1: interface name, zero padded to a 32-bit boundary on the wire.
    Name(Vec<u8>),
    /// C-Type 2: a 32-bit ifIndex.
    Index(u32),
    /// C-Type 3: AFI, an explicit address length, reserved byte, and address.
    Address {
        afi: u16,
        address_length: u8,
        reserved: u8,
        address: Vec<u8>,
    },
    /// An explicit C-Type plus raw body bytes (escape hatch). The bytes are
    /// emitted verbatim without padding so deliberately malformed objects survive.
    Raw { c_type: u8, bytes: Vec<u8> },
}

impl IcmpExtensionInterfaceId {
    /// Identify the interface by name (RFC 8335 C-Type 1).
    pub fn by_name(name: &str) -> Self {
        Self::by_name_bytes(name.as_bytes().to_vec())
    }

    /// Identify the interface by raw name octets (RFC 8335 C-Type 1). The octets
    /// are zero padded to a 32-bit boundary on the wire.
    pub fn by_name_bytes(name: impl Into<Vec<u8>>) -> Self {
        Self {
            body: InterfaceIdBody::Name(name.into()),
        }
    }

    /// Identify the interface by a 32-bit ifIndex (RFC 8335 C-Type 2).
    pub fn by_index(if_index: u32) -> Self {
        Self {
            body: InterfaceIdBody::Index(if_index),
        }
    }

    /// Identify the interface by IPv4 address (RFC 8335 C-Type 3).
    pub fn by_ipv4(address: Ipv4Addr) -> Self {
        Self::by_address(ICMP_INTERFACE_AFI_IPV4, address.octets())
    }

    /// Identify the interface by IPv6 address (RFC 8335 C-Type 3).
    pub fn by_ipv6(address: core::net::Ipv6Addr) -> Self {
        Self::by_address(ICMP_INTERFACE_AFI_IPV6, address.octets())
    }

    /// Identify the interface by a raw AFI and address bytes (RFC 8335 C-Type 3).
    ///
    /// The address length defaults to the number of address bytes; the address
    /// is zero padded to a 32-bit boundary on the wire.
    pub fn by_address(afi: u16, address: impl Into<Vec<u8>>) -> Self {
        let address = address.into();
        let address_length = address.len() as u8;
        Self {
            body: InterfaceIdBody::Address {
                afi,
                address_length,
                reserved: 0,
                address,
            },
        }
    }

    /// Build an object with an explicit C-Type and raw body bytes, the escape
    /// hatch for crafting objects the typed forms do not cover. The bytes are
    /// emitted verbatim (no padding).
    pub fn raw(c_type: u8, bytes: impl Into<Vec<u8>>) -> Self {
        Self {
            body: InterfaceIdBody::Raw {
                c_type,
                bytes: bytes.into(),
            },
        }
    }

    /// Override the C-Type 3 address length field (the count of significant
    /// address bytes) explicitly, the escape hatch for deliberately mismatched
    /// lengths. Has no effect on the other forms.
    pub fn address_length(mut self, address_length: u8) -> Self {
        if let InterfaceIdBody::Address {
            address_length: slot,
            ..
        } = &mut self.body
        {
            *slot = address_length;
        }
        self
    }

    /// Override the C-Type 3 reserved byte explicitly. Has no effect on the other
    /// forms.
    pub fn reserved(mut self, reserved: u8) -> Self {
        if let InterfaceIdBody::Address { reserved: slot, .. } = &mut self.body {
            *slot = reserved;
        }
        self
    }

    /// RFC 8335 C-Type for the selected form.
    pub fn c_type(&self) -> u8 {
        match &self.body {
            InterfaceIdBody::Name(_) => ICMP_INTERFACE_ID_CTYPE_NAME,
            InterfaceIdBody::Index(_) => ICMP_INTERFACE_ID_CTYPE_INDEX,
            InterfaceIdBody::Address { .. } => ICMP_INTERFACE_ID_CTYPE_ADDRESS,
            InterfaceIdBody::Raw { c_type, .. } => *c_type,
        }
    }

    /// Interface name octets (C-Type 1), if this is a name object.
    pub fn name_value(&self) -> Option<&[u8]> {
        match &self.body {
            InterfaceIdBody::Name(name) => Some(name),
            _ => None,
        }
    }

    /// ifIndex (C-Type 2), if this is an index object.
    pub fn index_value(&self) -> Option<u32> {
        match &self.body {
            InterfaceIdBody::Index(index) => Some(*index),
            _ => None,
        }
    }

    /// Address Family Identifier (C-Type 3), if this is an address object.
    pub fn afi_value(&self) -> Option<u16> {
        match &self.body {
            InterfaceIdBody::Address { afi, .. } => Some(*afi),
            _ => None,
        }
    }

    /// Address bytes (C-Type 3), if this is an address object.
    pub fn address_bytes(&self) -> Option<&[u8]> {
        match &self.body {
            InterfaceIdBody::Address { address, .. } => Some(address),
            _ => None,
        }
    }

    /// Address length field (C-Type 3), if this is an address object.
    pub fn address_length_value(&self) -> Option<u8> {
        match &self.body {
            InterfaceIdBody::Address { address_length, .. } => Some(*address_length),
            _ => None,
        }
    }

    /// Address as an [`Ipv4Addr`] when this is an IPv4 address object.
    pub fn ipv4_value(&self) -> Option<Ipv4Addr> {
        match &self.body {
            InterfaceIdBody::Address { afi, address, .. }
                if *afi == ICMP_INTERFACE_AFI_IPV4 && address.len() == 4 =>
            {
                Some(Ipv4Addr::new(
                    address[0], address[1], address[2], address[3],
                ))
            }
            _ => None,
        }
    }

    /// Address as an [`Ipv6Addr`](core::net::Ipv6Addr) when this is an IPv6
    /// address object.
    pub fn ipv6_value(&self) -> Option<core::net::Ipv6Addr> {
        match &self.body {
            InterfaceIdBody::Address { afi, address, .. }
                if *afi == ICMP_INTERFACE_AFI_IPV6 && address.len() == 16 =>
            {
                let mut octets = [0u8; 16];
                octets.copy_from_slice(address);
                Some(core::net::Ipv6Addr::from(octets))
            }
            _ => None,
        }
    }

    /// Raw escape-hatch body bytes, if this object was built with [`Self::raw`].
    pub fn raw_bytes(&self) -> Option<&[u8]> {
        match &self.body {
            InterfaceIdBody::Raw { bytes, .. } => Some(bytes),
            _ => None,
        }
    }
}

impl Layer for IcmpExtensionInterfaceId {
    fn name(&self) -> &'static str {
        "IcmpExtensionInterfaceId"
    }

    fn summary(&self) -> String {
        let detail = match &self.body {
            InterfaceIdBody::Name(name) => {
                format!("name={}", String::from_utf8_lossy(name))
            }
            InterfaceIdBody::Index(index) => format!("ifindex={index}"),
            InterfaceIdBody::Address { afi, address, .. } => {
                if let Some(addr) = self.ipv4_value() {
                    format!("address={addr}")
                } else if let Some(addr) = self.ipv6_value() {
                    format!("address={addr}")
                } else {
                    format!("address=afi={afi} {}", hex_bytes(address))
                }
            }
            InterfaceIdBody::Raw { c_type, bytes } => {
                format!("ctype={c_type} raw={}", hex_bytes(bytes))
            }
        };
        format!("IcmpExtensionInterfaceId({detail})")
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        vec![
            ("c_type", self.c_type().to_string()),
            (
                "name",
                self.name_value()
                    .map(|name| String::from_utf8_lossy(name).into_owned())
                    .unwrap_or_else(|| "-".to_string()),
            ),
            (
                "index",
                self.index_value()
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "-".to_string()),
            ),
            (
                "afi",
                self.afi_value()
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "-".to_string()),
            ),
            (
                "address",
                self.address_bytes()
                    .map(hex_bytes)
                    .unwrap_or_else(|| "-".to_string()),
            ),
        ]
    }

    fn encoded_len(&self) -> usize {
        match &self.body {
            InterfaceIdBody::Name(name) => name.len().div_ceil(4) * 4,
            InterfaceIdBody::Index(_) => ICMP_INTERFACE_ID_INDEX_LEN,
            InterfaceIdBody::Address { address, .. } => {
                ICMP_INTERFACE_ID_ADDRESS_PREFIX_LEN + address.len().div_ceil(4) * 4
            }
            InterfaceIdBody::Raw { bytes, .. } => bytes.len(),
        }
    }

    fn compile(&self, _ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        match &self.body {
            InterfaceIdBody::Name(name) => {
                let padded = name.len().div_ceil(4) * 4;
                out.extend_from_slice(name);
                out.resize(out.len() + (padded - name.len()), 0);
            }
            InterfaceIdBody::Index(index) => {
                out.extend_from_slice(&index.to_be_bytes());
            }
            InterfaceIdBody::Address {
                afi,
                address_length,
                reserved,
                address,
            } => {
                out.extend_from_slice(&afi.to_be_bytes());
                out.push(*address_length);
                out.push(*reserved);
                let padded = address.len().div_ceil(4) * 4;
                out.extend_from_slice(address);
                out.resize(out.len() + (padded - address.len()), 0);
            }
            InterfaceIdBody::Raw { bytes, .. } => {
                out.extend_from_slice(bytes);
            }
        }
        Ok(())
    }

    impl_layer_object!(IcmpExtensionInterfaceId);
}

impl_layer_div!(IcmpExtensionInterfaceId);

/// Decode a single RFC 4950 MPLS label stack entry (4 octets) into a typed
/// [`IcmpExtensionMpls`] layer.
///
/// The 32-bit word packs a 20-bit label, a 3-bit experimental/traffic-class
/// field, a 1-bit bottom-of-stack flag, and an 8-bit TTL. Every field is set as
/// a user value — including the bottom-of-stack bit — so a re-compile reproduces
/// the exact bits even when the decoded stack is non-canonical (for example a
/// set bottom-of-stack bit that is not on the final entry).
pub(crate) fn decode_mpls_entry(chunk: &[u8]) -> IcmpExtensionMpls {
    let word = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
    let label = word >> 12;
    let experimental = ((word >> 9) & 0x07) as u8;
    let bottom_of_stack = (word >> 8) & 0x01 == 1;
    let ttl = (word & 0xff) as u8;
    IcmpExtensionMpls {
        label: Field::user(label),
        experimental: Field::user(experimental),
        bottom_of_stack: Field::user(bottom_of_stack),
        ttl: Field::user(ttl),
    }
}

/// Decode an RFC 5837 interface information object body into a typed
/// [`IcmpExtensionInterfaceInfo`] layer.
///
/// The C-Type byte drives which sub-objects are present (bits 0-1 role, bits
/// 2-3 reserved, bits 4-7 ifIndex/IP-address/name/MTU). Sub-objects are parsed
/// in their mandatory order and must consume the body exactly, with canonical
/// (zero) name padding, so a re-compile reproduces the bytes. Any short,
/// trailing, or non-canonical body returns `None` so the caller keeps the
/// region as raw bytes and decoding never panics.
pub(crate) fn decode_interface_info(
    c_type: u8,
    mut body: &[u8],
) -> Option<IcmpExtensionInterfaceInfo> {
    let role = (c_type >> 6) & 0x03;
    let reserved = (c_type >> 4) & 0x03;
    let mut info = IcmpExtensionInterfaceInfo {
        role: Field::user(role),
        reserved: Field::user(reserved),
        if_index: None,
        ip_address: None,
        name: None,
        mtu: None,
    };

    if c_type & ICMP_INTERFACE_CTYPE_IFINDEX != 0 {
        if body.len() < ICMP_INTERFACE_IFINDEX_LEN {
            return None;
        }
        info.if_index = Some(u32::from_be_bytes(copy_array_4(
            &body[..ICMP_INTERFACE_IFINDEX_LEN],
        )));
        body = &body[ICMP_INTERFACE_IFINDEX_LEN..];
    }

    if c_type & ICMP_INTERFACE_CTYPE_IP_ADDRESS != 0 {
        if body.len() < ICMP_INTERFACE_IP_ADDRESS_PREFIX_LEN {
            return None;
        }
        let afi = u16::from_be_bytes([body[0], body[1]]);
        let reserved16 = u16::from_be_bytes([body[2], body[3]]);
        // Only AFIs with a fixed address width can be split unambiguously from
        // any following name/MTU sub-objects; unknown AFIs stay raw.
        let addr_len = match afi {
            ICMP_INTERFACE_AFI_IPV4 => 4,
            ICMP_INTERFACE_AFI_IPV6 => 16,
            _ => return None,
        };
        let total = ICMP_INTERFACE_IP_ADDRESS_PREFIX_LEN + addr_len;
        if body.len() < total {
            return None;
        }
        info.ip_address = Some(IcmpInterfaceIpAddress {
            afi: Field::user(afi),
            reserved: Field::user(reserved16),
            address: body[ICMP_INTERFACE_IP_ADDRESS_PREFIX_LEN..total].to_vec(),
        });
        body = &body[total..];
    }

    if c_type & ICMP_INTERFACE_CTYPE_NAME != 0 {
        if body.is_empty() {
            return None;
        }
        let length = body[0] as usize;
        // The length octet covers itself plus the name; the name is then padded
        // to a 4-octet boundary. Reject lengths that do not fit or exceed the
        // 64-octet ceiling.
        if length < 1 || length > body.len() {
            return None;
        }
        let name_len = length - 1;
        if name_len > ICMP_INTERFACE_NAME_MAX {
            return None;
        }
        let padded = length.div_ceil(4) * 4;
        if padded > body.len() {
            return None;
        }
        // Only canonical zero padding round-trips through compile.
        if body[length..padded].iter().any(|&byte| byte != 0) {
            return None;
        }
        info.name = Some(body[1..length].to_vec());
        body = &body[padded..];
    }

    if c_type & ICMP_INTERFACE_CTYPE_MTU != 0 {
        if body.len() < ICMP_INTERFACE_MTU_LEN {
            return None;
        }
        info.mtu = Some(u32::from_be_bytes(copy_array_4(
            &body[..ICMP_INTERFACE_MTU_LEN],
        )));
        body = &body[ICMP_INTERFACE_MTU_LEN..];
    }

    // Sub-objects must consume the body exactly so the typed layer round-trips.
    if !body.is_empty() {
        return None;
    }

    Some(info)
}

/// Decode an RFC 8335 Interface Identification Object body into a typed
/// [`IcmpExtensionInterfaceId`] layer.
///
/// The object's C-Type selects the form: name (1), index (2), or address (3).
/// Each form must consume the whole body exactly with canonical (zero) padding
/// so a re-compile reproduces the bytes; anything else — an unknown C-Type, a
/// mismatched length, non-canonical padding, or an unknown-width address AFI —
/// returns `None` so the caller keeps the body as raw bytes and decoding never
/// panics.
pub(crate) fn decode_interface_id(c_type: u8, body: &[u8]) -> Option<IcmpExtensionInterfaceId> {
    match c_type {
        ICMP_INTERFACE_ID_CTYPE_NAME => {
            // The name is zero padded to a 32-bit boundary; reject a body whose
            // length is not a whole number of words or whose padding is not zero.
            if body.is_empty() || body.len() % 4 != 0 {
                return None;
            }
            // RFC 7223 names are NUL-padded; the name is the leading non-NUL run,
            // and every trailing byte after the first NUL must be NUL so the
            // padded form round-trips through compile.
            let name_len = body
                .iter()
                .position(|&byte| byte == 0)
                .unwrap_or(body.len());
            if body[name_len..].iter().any(|&byte| byte != 0) {
                return None;
            }
            // Reject names whose unpadded length would re-pad to a different size
            // (only canonical minimal padding round-trips).
            if name_len.div_ceil(4) * 4 != body.len() {
                return None;
            }
            Some(IcmpExtensionInterfaceId::by_name_bytes(
                body[..name_len].to_vec(),
            ))
        }
        ICMP_INTERFACE_ID_CTYPE_INDEX => {
            if body.len() != ICMP_INTERFACE_ID_INDEX_LEN {
                return None;
            }
            Some(IcmpExtensionInterfaceId::by_index(u32::from_be_bytes(
                copy_array_4(body),
            )))
        }
        ICMP_INTERFACE_ID_CTYPE_ADDRESS => {
            if body.len() < ICMP_INTERFACE_ID_ADDRESS_PREFIX_LEN {
                return None;
            }
            let afi = u16::from_be_bytes([body[0], body[1]]);
            let address_length = body[2];
            let reserved = body[3];
            let address = &body[ICMP_INTERFACE_ID_ADDRESS_PREFIX_LEN..];
            // The significant address length must fit the padded address region
            // and re-pad to exactly the body length so a re-compile reproduces it.
            let significant = address_length as usize;
            if significant > address.len() || significant.div_ceil(4) * 4 != address.len() {
                return None;
            }
            // Only canonical zero padding past the significant address bytes
            // round-trips through compile.
            if address[significant..].iter().any(|&byte| byte != 0) {
                return None;
            }
            Some(
                IcmpExtensionInterfaceId::by_address(afi, address[..significant].to_vec())
                    .reserved(reserved),
            )
        }
        _ => None,
    }
}

#[cfg(test)]
mod icmpv4_rfc4884_extensions {
    use super::{
        IcmpExtension, IcmpExtensionMpls, IcmpExtensionObject, Icmpv4, Icmpv4QuotedIp,
        ICMP_EXTENSION_HEADER_LEN, ICMP_PARAMETER_PROBLEM, ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM,
    };
    use crate::checksum::verify_internet_checksum;
    use crate::{Ipv4, Ipv4Protocol, NetworkLayer, Packet, Raw, Udp};
    use core::net::Ipv4Addr;

    fn src() -> Ipv4Addr {
        Ipv4Addr::new(192, 0, 2, 10)
    }

    fn dst() -> Ipv4Addr {
        Ipv4Addr::new(198, 51, 100, 20)
    }

    // The standard 32-byte quoted datagram (IPv4 + UDP + payload) an agent would
    // attach to an error message.
    fn quoted_udp() -> Packet {
        Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(198, 51, 100, 1))
            .ipv4_protocol(Ipv4Protocol::Udp)
            / Udp::new().sport(40000).dport(53)
            / Raw::from("query")
    }

    // The first byte of the ICMP body after the 20-byte IPv4 header sits at
    // offset 28; the RFC 4884 length field is the ICMP rest-of-header byte 1.
    const ICMP_BODY_START: usize = 28;
    const RFC4884_LENGTH_BYTE: usize = 25;

    // A time-exceeded message that quotes a short datagram and appends an
    // extension structure auto-fills the RFC 4884 length field, measured in
    // 32-bit words of the *padded* original datagram (128 octets minimum here).
    #[test]
    fn icmpv4_rfc4884_extensions_autofills_length_field() {
        let bytes = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(1234).ttl(64))
        .compile()
        .unwrap();

        // 128 octets / 4 = 32 words.
        assert_eq!(bytes.as_bytes()[RFC4884_LENGTH_BYTE], 32);
    }

    // A plain error message with no extension structure leaves the length field
    // zero, so a compliant receiver reads "no extensions present".
    #[test]
    fn icmpv4_rfc4884_extensions_length_is_zero_without_extensions() {
        let bytes = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp()))
        .compile()
        .unwrap();

        assert_eq!(bytes.as_bytes()[RFC4884_LENGTH_BYTE], 0);
    }

    // The original datagram is zero padded up to the RFC 4884 minimum of 128
    // octets before the extension header when the quote is shorter, and a quote
    // longer than the minimum is only padded up to the next 32-bit boundary.
    #[test]
    fn icmpv4_rfc4884_extensions_pads_minimum_original_datagram() {
        // A short quote (well under 128 octets) is padded up to the 128-octet
        // minimum.
        let quote_len = quoted_udp().encoded_len();
        assert!(quote_len < ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM);
        let short = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::destination_unreachable()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new())
        .compile()
        .unwrap();
        let ext_start = ICMP_BODY_START + ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM;
        // Everything past the quote and before the extension header is zero
        // padding making up the rest of the 128-octet original datagram.
        assert!(short.as_bytes()[ICMP_BODY_START + quote_len..ext_start]
            .iter()
            .all(|&byte| byte == 0));
        // The extension header (version 2) starts exactly at the padded boundary.
        assert_eq!(short.as_bytes()[ext_start] >> 4, 2);
        assert_eq!(short.as_bytes()[RFC4884_LENGTH_BYTE], 32);

        // A quote longer than 128 octets but not word-aligned (133 bytes) is
        // padded only up to the next 32-bit boundary (136 octets / 4 = 34 words),
        // never back down to the minimum.
        let long_quote = Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(198, 51, 100, 1))
            .ipv4_protocol(Ipv4Protocol::Udp)
            / Udp::new().sport(40000).dport(53)
            / Raw::from_bytes(vec![0xab; 105]); // 20 + 8 + 105 = 133 bytes
        let long = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(long_quote)
            / IcmpExtension::new())
        .compile()
        .unwrap();
        assert_eq!(long.as_bytes()[RFC4884_LENGTH_BYTE], 34);
        // The three padding octets that round 133 up to 136 are zero.
        let long_ext_start = ICMP_BODY_START + 136;
        assert!(long.as_bytes()[ICMP_BODY_START + 133..long_ext_start]
            .iter()
            .all(|&byte| byte == 0));
        assert_eq!(long.as_bytes()[long_ext_start] >> 4, 2);
    }

    // The extension header checksum is auto-filled over the whole extension
    // structure (header plus objects), so the structure verifies on the wire.
    #[test]
    fn icmpv4_rfc4884_extensions_autofills_extension_checksum() {
        let bytes = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(99).ttl(10))
        .compile()
        .unwrap();

        let ext_start = ICMP_BODY_START + ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM;
        // The one's-complement sum over the extension structure is zero.
        assert!(verify_internet_checksum(&bytes.as_bytes()[ext_start..]));
        // A non-zero checksum was actually emitted (not left at zero).
        assert_ne!(&bytes.as_bytes()[ext_start + 2..ext_start + 4], &[0, 0]);
    }

    // An explicit extension checksum is honored verbatim, even when it is
    // intentionally wrong, and it survives a decode round-trip.
    #[test]
    fn icmpv4_rfc4884_extensions_explicit_malformed_checksum_is_preserved() {
        let bytes = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new().checksum(0xdead)
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(7).ttl(5))
        .compile()
        .unwrap();

        let ext_start = ICMP_BODY_START + ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM;
        assert_eq!(
            &bytes.as_bytes()[ext_start + 2..ext_start + 4],
            &0xdeadu16.to_be_bytes()
        );

        // A non-zero but wrong checksum is treated as "not a real extension" on
        // decode, so the trailing bytes stay raw rather than being typed.
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        assert!(decoded.layer::<IcmpExtension>().is_none());
        assert!(decoded.layer::<Raw>().is_some());
        // The bytes round-trip unchanged regardless.
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes.as_bytes());
    }

    // A generic, unrecognized extension object retains its length, class,
    // sub-type, and raw payload across a compile/decode round-trip.
    #[test]
    fn icmpv4_rfc4884_extensions_generic_unknown_object_roundtrip() {
        let payload = [0x11u8, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];
        let packet = Ipv4::new().src(src()).dst(dst())
            / Icmpv4::new().icmp_type(ICMP_PARAMETER_PROBLEM)
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new().class_num(200).c_type(7)
            / Raw::from_bytes(payload);
        let compiled = packet.compile().unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let object = decoded.layer::<IcmpExtensionObject>().unwrap();
        // Length covers the 4-byte object header plus the 8-byte payload.
        assert_eq!(object.length_value(), Some(12));
        assert_eq!(object.class_num_value(), 200);
        assert_eq!(object.c_type_value(), 7);
        // The unknown object payload survives as raw bytes.
        let raw = decoded.layer::<Raw>().unwrap();
        assert_eq!(raw.as_bytes(), &payload);
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // A complete RFC 4884 packet decodes into typed Icmpv4, quoted datagram,
    // extension header, and extension object layers.
    #[test]
    fn icmpv4_rfc4884_extensions_decode_splits_typed_layers() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(1234).ttl(100)
            / IcmpExtensionMpls::new().label(2345).ttl(50))
        .compile()
        .unwrap();

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

        // The ICMP header and quoted datagram are typed.
        let icmp = decoded.layer::<Icmpv4>().unwrap();
        assert_eq!(icmp.length_value(), Some(32));
        let quoted = decoded.layer::<Icmpv4QuotedIp>().unwrap();
        assert_eq!(
            quoted.quoted_layer::<Ipv4>().unwrap().source(),
            Ipv4Addr::new(192, 0, 2, 1)
        );

        // The extension header and object are typed.
        let extension = decoded.layer::<IcmpExtension>().unwrap();
        assert_eq!(extension.version_value(), 2);
        assert_eq!(extension.checksum_value().map(|_| true), Some(true));
        let object = decoded.layer::<IcmpExtensionObject>().unwrap();
        // Object length covers the 4-byte object header plus the two 4-byte MPLS
        // label stack words.
        assert_eq!(object.length_value(), Some(12));
        assert_eq!(object.class_num_value(), 1);
        assert_eq!(object.c_type_value(), 1);

        // The whole structure round-trips byte-for-byte.
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // When the length field claims an extension structure but the bytes that
    // follow are not a valid one (here a corrupted version nibble), decoding
    // keeps the trailing bytes as a single Raw tail instead of fabricating typed
    // layers or panicking, and the buffer still round-trips unchanged.
    #[test]
    fn icmpv4_rfc4884_extensions_ambiguous_data_stays_raw() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(1).ttl(1))
        .compile()
        .unwrap();

        // Corrupt the extension version nibble (set it to 0xf instead of 2).
        let mut corrupt = compiled.as_bytes().to_vec();
        let ext_start = ICMP_BODY_START + ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM;
        corrupt[ext_start] = 0xf0 | (corrupt[ext_start] & 0x0f);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, &corrupt).unwrap();
        // No typed extension layers were produced.
        assert!(decoded.layer::<IcmpExtension>().is_none());
        assert!(decoded.layer::<IcmpExtensionObject>().is_none());
        // The quoted datagram is still typed and the ambiguous tail is raw.
        assert!(decoded.layer::<Icmpv4QuotedIp>().is_some());
        let raw = decoded.layer::<Raw>().unwrap();
        // The raw tail is the padding plus the unparsed extension bytes.
        assert!(raw.as_bytes().len() >= ICMP_EXTENSION_HEADER_LEN);
        // The corrupted buffer round-trips unchanged.
        assert_eq!(decoded.compile().unwrap().as_bytes(), &corrupt[..]);
    }
}

#[cfg(test)]
mod icmpv4_rfc4950_mpls {
    use super::{
        IcmpExtension, IcmpExtensionMpls, IcmpExtensionObject, Icmpv4, Icmpv4QuotedIp,
        ICMP_EXTENSION_CLASS_MPLS, ICMP_EXTENSION_CTYPE_MPLS_INCOMING,
        ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM,
    };
    use crate::{Ipv4, Ipv4Protocol, NetworkLayer, Packet, Raw, Udp};
    use core::net::Ipv4Addr;

    fn src() -> Ipv4Addr {
        Ipv4Addr::new(192, 0, 2, 10)
    }

    fn dst() -> Ipv4Addr {
        Ipv4Addr::new(198, 51, 100, 20)
    }

    // The standard short quoted datagram (IPv4 + UDP + payload) attached to an
    // error message before the extension structure.
    fn quoted_udp() -> Packet {
        Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(198, 51, 100, 1))
            .ipv4_protocol(Ipv4Protocol::Udp)
            / Udp::new().sport(40000).dport(53)
            / Raw::from("query")
    }

    // The ICMP body begins at offset 28 (20-byte IPv4 header + 8-byte ICMP
    // header). The quote is padded up to the 128-octet RFC 4884 minimum, so the
    // extension header sits at offset 28 + 128 and the first object header four
    // bytes later.
    const EXT_HEADER_START: usize = 28 + ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM;
    const OBJECT_HEADER_START: usize = EXT_HEADER_START + 4;
    const FIRST_ENTRY_START: usize = OBJECT_HEADER_START + 4;

    // A single MPLS label stack entry encodes its label, experimental bits,
    // bottom-of-stack flag, and TTL into one 4-octet word, and decodes back into
    // a typed IcmpExtensionMpls layer.
    #[test]
    fn icmpv4_rfc4950_mpls_single_label_encode_decode() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(0xabcde).exp(5).ttl(64))
        .compile()
        .unwrap();

        // Object header: length 8 (4-byte object header + one 4-byte entry),
        // class 1 (MPLS), C-Type 1 (incoming label stack).
        assert_eq!(
            &compiled.as_bytes()[OBJECT_HEADER_START..OBJECT_HEADER_START + 4],
            &[
                0x00,
                0x08,
                ICMP_EXTENSION_CLASS_MPLS,
                ICMP_EXTENSION_CTYPE_MPLS_INCOMING
            ]
        );
        // The 32-bit entry word packs label (20 bits) | exp (3) | S (1) | TTL.
        let expected = (0xabcdeu32 << 12) | (5u32 << 9) | (1u32 << 8) | 64u32;
        assert_eq!(
            &compiled.as_bytes()[FIRST_ENTRY_START..FIRST_ENTRY_START + 4],
            &expected.to_be_bytes()
        );

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let mpls = decoded.layer::<IcmpExtensionMpls>().unwrap();
        assert_eq!(mpls.label_value(), 0xabcde);
        assert_eq!(mpls.experimental_value(), 5);
        assert_eq!(mpls.ttl_value(), 64);
        // A single entry is the bottom of the stack.
        assert_eq!(mpls.bottom_of_stack_value(), Some(true));
        // The typed object header is also exposed.
        let object = decoded.layer::<IcmpExtensionObject>().unwrap();
        assert_eq!(object.length_value(), Some(8));
        assert_eq!(object.class_num_value(), ICMP_EXTENSION_CLASS_MPLS);
        assert_eq!(object.c_type_value(), ICMP_EXTENSION_CTYPE_MPLS_INCOMING);
    }

    // A multi-label stack encodes each entry as its own 4-octet word, and decode
    // exposes every entry as a separate typed layer in order, preserving each
    // entry's label, experimental bits, and TTL.
    #[test]
    fn icmpv4_rfc4950_mpls_multi_label_encode_decode() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(100).exp(1).ttl(10)
            / IcmpExtensionMpls::new().label(200).exp(2).ttl(20)
            / IcmpExtensionMpls::new().label(300).exp(3).ttl(30))
        .compile()
        .unwrap();

        // Object length covers the 4-byte header plus three 4-byte entries.
        let object = {
            let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
            decoded
                .layer::<IcmpExtensionObject>()
                .unwrap()
                .length_value()
        };
        assert_eq!(object, Some(16));

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let entries: Vec<&IcmpExtensionMpls> = decoded.layers::<IcmpExtensionMpls>().collect();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].label_value(), 100);
        assert_eq!(entries[0].experimental_value(), 1);
        assert_eq!(entries[0].ttl_value(), 10);
        assert_eq!(entries[1].label_value(), 200);
        assert_eq!(entries[2].label_value(), 300);
        // Only the final entry carries the bottom-of-stack bit.
        assert_eq!(entries[0].bottom_of_stack_value(), Some(false));
        assert_eq!(entries[1].bottom_of_stack_value(), Some(false));
        assert_eq!(entries[2].bottom_of_stack_value(), Some(true));
    }

    // With the bottom-of-stack bit left unset, compile auto-fills it: only the
    // final entry in a stack is the bottom of stack.
    #[test]
    fn icmpv4_rfc4950_mpls_bottom_of_stack_autofill() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(1).ttl(1)
            / IcmpExtensionMpls::new().label(2).ttl(2))
        .compile()
        .unwrap();

        // The bottom-of-stack S bit is bit 8 of the 32-bit entry word, which in
        // big-endian layout is the LSB of the entry's third octet (offset +2).
        // First entry: S bit clear (not the bottom of the stack).
        assert_eq!(compiled.as_bytes()[FIRST_ENTRY_START + 2] & 0x01, 0);
        // Second entry (four octets later): S bit set (bottom of the stack).
        assert_eq!(compiled.as_bytes()[FIRST_ENTRY_START + 6] & 0x01, 1);
    }

    // An explicit bottom-of-stack override is honored verbatim, even when it
    // contradicts the auto-fill rule (here a set bit on a non-final entry and a
    // clear bit on the final entry), and survives a decode round-trip.
    #[test]
    fn icmpv4_rfc4950_mpls_explicit_bottom_of_stack_override() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new()
                .label(1)
                .ttl(1)
                .bottom_of_stack(true)
            / IcmpExtensionMpls::new()
                .label(2)
                .ttl(2)
                .bottom_of_stack(false))
        .compile()
        .unwrap();

        // The S bit lives in the LSB of each entry's third octet (offset +2).
        // First entry forced to bottom-of-stack despite a following entry.
        assert_eq!(compiled.as_bytes()[FIRST_ENTRY_START + 2] & 0x01, 1);
        // Final entry forced to not-bottom-of-stack despite being last.
        assert_eq!(compiled.as_bytes()[FIRST_ENTRY_START + 6] & 0x01, 0);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let entries: Vec<&IcmpExtensionMpls> = decoded.layers::<IcmpExtensionMpls>().collect();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].bottom_of_stack_value(), Some(true));
        assert_eq!(entries[1].bottom_of_stack_value(), Some(false));
    }

    // A label that does not fit in 20 bits, and experimental bits that do not fit
    // in 3 bits, are rejected at compile time per the existing invalid-field
    // policy.
    #[test]
    fn icmpv4_rfc4950_mpls_invalid_field_bounds() {
        let too_large_label = Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(0x10_0000).ttl(1);
        assert!(too_large_label.compile().is_err());

        let too_large_exp = Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(1).exp(8).ttl(1);
        assert!(too_large_exp.compile().is_err());
    }

    // A complete MPLS-bearing error message round-trips byte-for-byte through
    // Packet::decode_from_l3 even when the entries carry maximal field values.
    #[test]
    fn icmpv4_rfc4950_mpls_byte_for_byte_roundtrip() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::destination_unreachable()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(0xfffff).exp(7).ttl(255)
            / IcmpExtensionMpls::new().label(0).exp(0).ttl(0))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        // The typed MPLS entries are present.
        assert_eq!(decoded.layers::<IcmpExtensionMpls>().count(), 2);
        // And the whole packet reproduces the original bytes exactly.
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // An MPLS object whose body is not a whole number of 4-octet entries is
    // malformed; decode keeps the body as a single Raw payload (never panicking)
    // and the buffer still round-trips unchanged.
    #[test]
    fn icmpv4_rfc4950_mpls_partial_entry_stays_raw() {
        // Build a valid two-entry MPLS object, then truncate the object so its
        // body holds one full entry plus two stray octets (a partial entry).
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionMpls::new().label(7).ttl(7)
            / IcmpExtensionMpls::new().label(8).ttl(8))
        .compile()
        .unwrap();

        let mut bytes = compiled.as_bytes().to_vec();
        // Drop the final two octets so the trailing object body is 6 bytes (one
        // 4-octet entry + a 2-octet partial entry), shrinking the object length
        // and the IPv4 total length to keep the buffer self-consistent.
        bytes.truncate(bytes.len() - 2);
        // Object length field (big-endian u16) drops from 12 to 10.
        bytes[OBJECT_HEADER_START] = 0x00;
        bytes[OBJECT_HEADER_START + 1] = 0x0a;
        // IPv4 total length (offset 2..4) drops by two as well.
        let total = u16::from_be_bytes([bytes[2], bytes[3]]) - 2;
        bytes[2..4].copy_from_slice(&total.to_be_bytes());
        // Recompute the IPv4 header checksum over the patched header.
        bytes[10] = 0;
        bytes[11] = 0;
        let mut sum = 0u32;
        for pair in bytes[0..20].chunks(2) {
            sum += u16::from_be_bytes([pair[0], pair[1]]) as u32;
        }
        while sum >> 16 != 0 {
            sum = (sum & 0xffff) + (sum >> 16);
        }
        let csum = !(sum as u16);
        bytes[10..12].copy_from_slice(&csum.to_be_bytes());

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, &bytes).unwrap();
        // The malformed MPLS body is not typed into entries.
        assert_eq!(decoded.layers::<IcmpExtensionMpls>().count(), 0);
        // It survives as a raw body and the buffer round-trips unchanged.
        assert!(decoded.layer::<Raw>().is_some());
        assert_eq!(decoded.compile().unwrap().as_bytes(), &bytes[..]);
    }
}

#[cfg(test)]
mod icmpv4_rfc5837_interface_info {
    use super::{
        IcmpExtension, IcmpExtensionInterfaceInfo, IcmpExtensionObject, IcmpInterfaceIpAddress,
        Icmpv4, Icmpv4QuotedIp, ICMP_EXTENSION_CLASS_INTERFACE_INFO, ICMP_INTERFACE_CTYPE_IFINDEX,
        ICMP_INTERFACE_CTYPE_IP_ADDRESS, ICMP_INTERFACE_CTYPE_MTU, ICMP_INTERFACE_CTYPE_NAME,
        ICMP_INTERFACE_ROLE_NEXT_HOP, ICMP_INTERFACE_ROLE_OUTGOING,
        ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM,
    };
    use crate::checksum::verify_internet_checksum;
    use crate::{Ipv4, Ipv4Protocol, NetworkLayer, Packet, Raw, Udp};
    use core::net::{Ipv4Addr, Ipv6Addr};

    fn src() -> Ipv4Addr {
        Ipv4Addr::new(192, 0, 2, 10)
    }

    fn dst() -> Ipv4Addr {
        Ipv4Addr::new(198, 51, 100, 20)
    }

    fn quoted_udp() -> Packet {
        Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 1))
            .dst(Ipv4Addr::new(198, 51, 100, 1))
            .ipv4_protocol(Ipv4Protocol::Udp)
            / Udp::new().sport(40000).dport(53)
            / Raw::from("query")
    }

    // The ICMP body begins at offset 28; the quote is padded up to the 128-octet
    // RFC 4884 minimum, so the extension header sits at offset 28 + 128 and the
    // first object header four bytes later.
    const EXT_HEADER_START: usize = 28 + ICMP_RFC4884_MIN_ORIGINAL_DATAGRAM;
    const OBJECT_HEADER_START: usize = EXT_HEADER_START + 4;
    const OBJECT_BODY_START: usize = OBJECT_HEADER_START + 4;

    // A full interface information object carrying every RFC 5837 sub-object
    // (ifIndex, IPv4 address, name, MTU) encodes its C-Type presence bits and
    // decodes back into a typed layer that exposes each field.
    #[test]
    fn icmpv4_rfc5837_interface_info_all_subobjects_encode_decode() {
        let info = IcmpExtensionInterfaceInfo::new()
            .role(ICMP_INTERFACE_ROLE_OUTGOING)
            .if_index(7)
            .ip_address(IcmpInterfaceIpAddress::ipv4(Ipv4Addr::new(192, 0, 2, 99)))
            .name("eth0")
            .mtu(1500);
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / info)
            .compile()
            .unwrap();

        // The object header auto-fills class 2 and a C-Type with role=2 and all
        // four presence bits set.
        let expected_ctype = (ICMP_INTERFACE_ROLE_OUTGOING << 6)
            | ICMP_INTERFACE_CTYPE_IFINDEX
            | ICMP_INTERFACE_CTYPE_IP_ADDRESS
            | ICMP_INTERFACE_CTYPE_NAME
            | ICMP_INTERFACE_CTYPE_MTU;
        assert_eq!(
            compiled.as_bytes()[OBJECT_HEADER_START + 2],
            ICMP_EXTENSION_CLASS_INTERFACE_INFO
        );
        assert_eq!(compiled.as_bytes()[OBJECT_HEADER_START + 3], expected_ctype);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let info = decoded.layer::<IcmpExtensionInterfaceInfo>().unwrap();
        assert_eq!(info.role_value(), ICMP_INTERFACE_ROLE_OUTGOING);
        assert_eq!(info.if_index_value(), Some(7));
        assert_eq!(
            info.ip_address_value().unwrap().ipv4_value(),
            Some(Ipv4Addr::new(192, 0, 2, 99))
        );
        assert_eq!(info.name_value(), Some(&b"eth0"[..]));
        assert_eq!(info.mtu_value(), Some(1500));
        // The whole packet reproduces its bytes exactly.
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // Each sub-object can stand alone; an ifIndex-only object sets just the
    // ifIndex presence bit and round-trips.
    #[test]
    fn icmpv4_rfc5837_interface_info_ifindex_only() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceInfo::new().if_index(0xdead_beef))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let info = decoded.layer::<IcmpExtensionInterfaceInfo>().unwrap();
        assert_eq!(info.if_index_value(), Some(0xdead_beef));
        assert_eq!(info.ip_address_value(), None);
        assert_eq!(info.name_value(), None);
        assert_eq!(info.mtu_value(), None);
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // An IPv6 IP Address sub-object carries a 16-byte address and is recognized
    // on decode by its AFI.
    #[test]
    fn icmpv4_rfc5837_interface_info_ipv6_address_subobject() {
        let addr = Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 0x1234);
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceInfo::new()
                .role(ICMP_INTERFACE_ROLE_NEXT_HOP)
                .ip_address(IcmpInterfaceIpAddress::ipv6(addr)))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let info = decoded.layer::<IcmpExtensionInterfaceInfo>().unwrap();
        assert_eq!(info.role_value(), ICMP_INTERFACE_ROLE_NEXT_HOP);
        assert_eq!(info.ip_address_value().unwrap().ipv6_value(), Some(addr));
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // The interface name sub-object emits a leading length octet covering itself
    // plus the name, then zero pads to a 4-octet boundary; decode strips both.
    #[test]
    fn icmpv4_rfc5837_interface_info_name_padding() {
        // "eth0" is 4 octets; with the length octet the sub-object is 5 octets,
        // padded up to 8.
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceInfo::new().name("eth0"))
        .compile()
        .unwrap();

        // Length octet: 1 (itself) + 4 (name) = 5.
        assert_eq!(compiled.as_bytes()[OBJECT_BODY_START], 5);
        assert_eq!(
            &compiled.as_bytes()[OBJECT_BODY_START + 1..OBJECT_BODY_START + 5],
            b"eth0"
        );
        // Three zero pad octets bring the sub-object to an 8-octet boundary.
        assert_eq!(
            &compiled.as_bytes()[OBJECT_BODY_START + 5..OBJECT_BODY_START + 8],
            &[0, 0, 0]
        );
        // Object length covers the 4-byte header plus the 8-byte name sub-object.
        let object = compiled.as_bytes()[OBJECT_HEADER_START + 1];
        assert_eq!(object, 12);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let info = decoded.layer::<IcmpExtensionInterfaceInfo>().unwrap();
        assert_eq!(info.name_value(), Some(&b"eth0"[..]));
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // The object length field auto-fills to the 4-byte object header plus the
    // sub-object body length when left unset.
    #[test]
    fn icmpv4_rfc5837_interface_info_length_autofill() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceInfo::new().if_index(1).mtu(9000))
        .compile()
        .unwrap();

        // Body: 4-byte ifIndex + 4-byte MTU = 8; object length = 4 + 8 = 12.
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let object = decoded.layer::<IcmpExtensionObject>().unwrap();
        assert_eq!(object.length_value(), Some(12));
        assert_eq!(
            object.class_num_value(),
            ICMP_EXTENSION_CLASS_INTERFACE_INFO
        );
    }

    // An explicit object length override is honored verbatim even when it does
    // not match the auto-computed body length.
    #[test]
    fn icmpv4_rfc5837_interface_info_explicit_length_override() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new().length(99)
            / IcmpExtensionInterfaceInfo::new().if_index(1))
        .compile()
        .unwrap();

        // The big-endian length field carries the override, not the computed 8.
        assert_eq!(
            u16::from_be_bytes([
                compiled.as_bytes()[OBJECT_HEADER_START],
                compiled.as_bytes()[OBJECT_HEADER_START + 1],
            ]),
            99
        );
    }

    // The RFC 4884 extension checksum is computed over the whole extension
    // structure including the interface information object and verifies on
    // decode.
    #[test]
    fn icmpv4_rfc5837_interface_info_extension_checksum() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceInfo::new()
                .if_index(5)
                .name("wlan0")
                .mtu(1280))
        .compile()
        .unwrap();

        // The extension structure (from the version/reserved/checksum header to
        // the end) carries a one's-complement checksum that verifies.
        assert!(verify_internet_checksum(
            &compiled.as_bytes()[EXT_HEADER_START..]
        ));

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        // The decoded extension header preserves the transmitted checksum.
        let extension = decoded.layer::<IcmpExtension>().unwrap();
        assert!(extension.checksum_value().is_some());
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // An unknown extension object class is not an interface information object;
    // it falls back to the generic IcmpExtensionObject + Raw body and is not
    // mistakenly typed as RFC 5837.
    #[test]
    fn icmpv4_rfc5837_interface_info_unknown_class_stays_raw() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new().class_num(200).c_type(0x0f)
            / Raw::from_bytes([1, 2, 3, 4]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        assert!(decoded.layer::<IcmpExtensionInterfaceInfo>().is_none());
        let object = decoded.layer::<IcmpExtensionObject>().unwrap();
        assert_eq!(object.class_num_value(), 200);
        assert!(decoded.layer::<Raw>().is_some());
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // An interface information object whose body is too short for the sub-objects
    // its C-Type claims cannot be parsed defensibly; decode keeps the body raw
    // and never panics, and the buffer round-trips unchanged.
    #[test]
    fn icmpv4_rfc5837_interface_info_truncated_subobject_stays_raw() {
        // Class 2, C-Type with the MTU presence bit set, but only two body octets
        // (an MTU needs four). The object is otherwise well-formed.
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::time_exceeded()
            / Icmpv4QuotedIp::new(quoted_udp())
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
                .class_num(ICMP_EXTENSION_CLASS_INTERFACE_INFO)
                .c_type(ICMP_INTERFACE_CTYPE_MTU)
            / Raw::from_bytes([0xaa, 0xbb]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        // The under-length body is not typed as an interface information object.
        assert!(decoded.layer::<IcmpExtensionInterfaceInfo>().is_none());
        assert!(decoded.layer::<Raw>().is_some());
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // The summary names the interface role and surfaces each present sub-object's
    // value without hiding the raw numbers.
    #[test]
    fn icmpv4_rfc5837_interface_info_summary() {
        let info = IcmpExtensionInterfaceInfo::new()
            .role(ICMP_INTERFACE_ROLE_OUTGOING)
            .if_index(42)
            .ip_address(IcmpInterfaceIpAddress::ipv4(Ipv4Addr::new(192, 0, 2, 1)))
            .name("eth1")
            .mtu(1500);
        let summary = crate::packet::Layer::summary(&info);
        assert!(summary.contains("outgoing"), "summary was {summary}");
        assert!(summary.contains("ifindex=42"), "summary was {summary}");
        assert!(summary.contains("192.0.2.1"), "summary was {summary}");
        assert!(summary.contains("name=eth1"), "summary was {summary}");
        assert!(summary.contains("mtu=1500"), "summary was {summary}");
    }
}

#[cfg(test)]
mod icmpv4_rfc8335_extended_echo {
    use super::{
        IcmpExtension, IcmpExtensionInterfaceId, IcmpExtensionObject, Icmpv4,
        ICMP_CODE_EXTENDED_ECHO_REPLY_MALFORMED_QUERY,
        ICMP_CODE_EXTENDED_ECHO_REPLY_MULTIPLE_INTERFACES, ICMP_CODE_EXTENDED_ECHO_REPLY_NO_ERROR,
        ICMP_CODE_EXTENDED_ECHO_REPLY_NO_SUCH_INTERFACE,
        ICMP_CODE_EXTENDED_ECHO_REPLY_NO_SUCH_TABLE_ENTRY, ICMP_EXTENDED_ECHO_REPLY,
        ICMP_EXTENDED_ECHO_REQUEST, ICMP_EXTENSION_CLASS_INTERFACE_ID,
        ICMP_INTERFACE_ID_CTYPE_ADDRESS, ICMP_INTERFACE_ID_CTYPE_INDEX,
        ICMP_INTERFACE_ID_CTYPE_NAME,
    };
    use crate::checksum::verify_internet_checksum;
    use crate::{Ipv4, NetworkLayer, Packet, Raw};
    use core::net::{Ipv4Addr, Ipv6Addr};

    fn src() -> Ipv4Addr {
        Ipv4Addr::new(192, 0, 2, 10)
    }

    fn dst() -> Ipv4Addr {
        Ipv4Addr::new(198, 51, 100, 20)
    }

    // An extended echo request carries its 16-bit identifier, 8-bit sequence
    // number, and flag byte in the fixed header, then an RFC 4884 extension
    // structure with a single Interface Identification Object directly after the
    // header (no quoted datagram, no original-datagram padding). The whole packet
    // round-trips and the typed object surfaces the ifIndex.
    #[test]
    fn icmpv4_rfc8335_extended_echo_request_compile_decode() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request().id(0x1234).seq(7)
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_index(42))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        // Fixed ICMP header at offset 20: type 42, code 0.
        assert_eq!(bytes[20], ICMP_EXTENDED_ECHO_REQUEST);
        assert_eq!(bytes[21], 0);
        // Identifier (bytes 24-25), 8-bit sequence (byte 26), flag byte (byte 27).
        assert_eq!(&bytes[24..26], &0x1234u16.to_be_bytes());
        assert_eq!(bytes[26], 7);
        assert_eq!(bytes[27], 0);
        // The extension header begins immediately after the fixed header (no
        // quote, no padding): version 2.
        assert_eq!(bytes[28] >> 4, 2);
        // The object header auto-fills class 3 and C-Type 2 (by index).
        assert_eq!(bytes[34], ICMP_EXTENSION_CLASS_INTERFACE_ID);
        assert_eq!(bytes[35], ICMP_INTERFACE_ID_CTYPE_INDEX);
        // Object length: 4-byte header + 4-byte ifIndex = 8.
        assert_eq!(u16::from_be_bytes([bytes[32], bytes[33]]), 8);
        // ifIndex value.
        assert_eq!(
            u32::from_be_bytes([bytes[36], bytes[37], bytes[38], bytes[39]]),
            42
        );

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let icmp = decoded.layer::<Icmpv4>().unwrap();
        assert_eq!(icmp.icmp_type_value(), ICMP_EXTENDED_ECHO_REQUEST);
        assert_eq!(icmp.identifier_value(), Some(0x1234));
        assert_eq!(icmp.sequence_number_value(), Some(7));
        assert_eq!(icmp.extended_l_bit_value(), Some(false));
        assert!(decoded.layer::<IcmpExtension>().is_some());
        let id = decoded.layer::<IcmpExtensionInterfaceId>().unwrap();
        assert_eq!(id.index_value(), Some(42));
        assert_eq!(id.c_type(), ICMP_INTERFACE_ID_CTYPE_INDEX);
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // The Interface Identification Object can identify by name (C-Type 1), with
    // the name zero padded to a 32-bit boundary.
    #[test]
    fn icmpv4_rfc8335_extended_echo_request_by_name() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request().id(1).seq(1)
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_name("eth0"))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        assert_eq!(bytes[35], ICMP_INTERFACE_ID_CTYPE_NAME);
        // "eth0" is 4 octets, already on a 32-bit boundary; object length 4 + 4.
        assert_eq!(u16::from_be_bytes([bytes[32], bytes[33]]), 8);
        assert_eq!(&bytes[36..40], b"eth0");

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let id = decoded.layer::<IcmpExtensionInterfaceId>().unwrap();
        assert_eq!(id.name_value(), Some(&b"eth0"[..]));
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // A short name is zero padded to a 32-bit boundary on the wire and the
    // padding is stripped on decode.
    #[test]
    fn icmpv4_rfc8335_extended_echo_request_by_name_padding() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_name("e0"))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        // "e0" (2 octets) pads to 4; object length 4 + 4 = 8.
        assert_eq!(u16::from_be_bytes([bytes[32], bytes[33]]), 8);
        assert_eq!(&bytes[36..38], b"e0");
        assert_eq!(&bytes[38..40], &[0, 0]);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let id = decoded.layer::<IcmpExtensionInterfaceId>().unwrap();
        assert_eq!(id.name_value(), Some(&b"e0"[..]));
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // The Interface Identification Object can identify by IPv4 address (C-Type 3):
    // AFI, address length, reserved, then the address padded to a 32-bit boundary.
    #[test]
    fn icmpv4_rfc8335_extended_echo_request_by_ipv4_address() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_ipv4(Ipv4Addr::new(192, 0, 2, 99)))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        assert_eq!(bytes[35], ICMP_INTERFACE_ID_CTYPE_ADDRESS);
        // AFI 1 (IPv4), address length 4, reserved 0, then the 4 address octets.
        assert_eq!(u16::from_be_bytes([bytes[36], bytes[37]]), 1);
        assert_eq!(bytes[38], 4);
        assert_eq!(bytes[39], 0);
        assert_eq!(&bytes[40..44], &[192, 0, 2, 99]);
        // Object length: 4-byte header + 4-byte prefix + 4-byte address = 12.
        assert_eq!(u16::from_be_bytes([bytes[32], bytes[33]]), 12);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let id = decoded.layer::<IcmpExtensionInterfaceId>().unwrap();
        assert_eq!(id.ipv4_value(), Some(Ipv4Addr::new(192, 0, 2, 99)));
        assert_eq!(id.address_length_value(), Some(4));
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // An IPv6 address object carries a 16-byte address (already 32-bit aligned).
    #[test]
    fn icmpv4_rfc8335_extended_echo_request_by_ipv6_address() {
        let addr = Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 0x99);
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_ipv6(addr))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        // AFI 2 (IPv6), address length 16. Object length 4 + 4 + 16 = 24.
        assert_eq!(u16::from_be_bytes([bytes[36], bytes[37]]), 2);
        assert_eq!(bytes[38], 16);
        assert_eq!(u16::from_be_bytes([bytes[32], bytes[33]]), 24);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let id = decoded.layer::<IcmpExtensionInterfaceId>().unwrap();
        assert_eq!(id.ipv6_value(), Some(addr));
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // The request L-bit is the rightmost bit of the flag byte and round-trips.
    #[test]
    fn icmpv4_rfc8335_extended_echo_request_l_bit() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
                .id(9)
                .seq(3)
                .extended_l_bit(true)
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_index(1))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        // Flag byte (offset 27): only the rightmost (L) bit set.
        assert_eq!(bytes[27], 0x01);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let icmp = decoded.layer::<Icmpv4>().unwrap();
        assert_eq!(icmp.extended_l_bit_value(), Some(true));
        // Reply-only accessors are not meaningful on a request.
        assert_eq!(icmp.extended_state_value(), None);
        assert_eq!(icmp.extended_active_value(), None);
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // Every reply code (0-4) compiles and decodes, keeping its numeric code and a
    // stable summary name; replies carry no body of their own.
    #[test]
    fn icmpv4_rfc8335_extended_echo_reply_all_codes() {
        let codes = [
            (ICMP_CODE_EXTENDED_ECHO_REPLY_NO_ERROR, "no-error"),
            (
                ICMP_CODE_EXTENDED_ECHO_REPLY_MALFORMED_QUERY,
                "malformed-query",
            ),
            (
                ICMP_CODE_EXTENDED_ECHO_REPLY_NO_SUCH_INTERFACE,
                "no-such-interface",
            ),
            (
                ICMP_CODE_EXTENDED_ECHO_REPLY_NO_SUCH_TABLE_ENTRY,
                "no-such-table-entry",
            ),
            (
                ICMP_CODE_EXTENDED_ECHO_REPLY_MULTIPLE_INTERFACES,
                "multiple-interfaces",
            ),
        ];
        for (code, name) in codes {
            let compiled = (Ipv4::new().src(src()).dst(dst())
                / Icmpv4::extended_echo_reply().id(0xabcd).seq(5).code(code))
            .compile()
            .unwrap();

            let bytes = compiled.as_bytes();
            assert_eq!(bytes[20], ICMP_EXTENDED_ECHO_REPLY);
            assert_eq!(bytes[21], code);

            let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
            let icmp = decoded.layer::<Icmpv4>().unwrap();
            assert_eq!(icmp.code_value(), code);
            assert_eq!(icmp.identifier_value(), Some(0xabcd));
            assert_eq!(icmp.sequence_number_value(), Some(5));
            assert!(
                crate::packet::Layer::summary(icmp).contains(name),
                "summary missing {name}"
            );
            assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
        }
    }

    // The reply flag byte packs State (3 bits), reserved (2 bits), and the A/4/6
    // flags; each typed accessor surfaces its field and the byte round-trips.
    #[test]
    fn icmpv4_rfc8335_extended_echo_reply_flags() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_reply()
                .code(ICMP_CODE_EXTENDED_ECHO_REPLY_NO_ERROR)
                .extended_state(super::ICMP_EXTENDED_ECHO_REPLY_STATE_REACHABLE)
                .extended_active(true)
                .extended_ipv4(true)
                .extended_ipv6(false))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        // State 2 in bits 5-7 (0b010 << 5 = 0x40), A bit (0x04), 4 bit (0x02).
        assert_eq!(bytes[27], 0x40 | 0x04 | 0x02);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let icmp = decoded.layer::<Icmpv4>().unwrap();
        assert_eq!(
            icmp.extended_state_value(),
            Some(super::ICMP_EXTENDED_ECHO_REPLY_STATE_REACHABLE)
        );
        assert_eq!(icmp.extended_active_value(), Some(true));
        assert_eq!(icmp.extended_ipv4_value(), Some(true));
        assert_eq!(icmp.extended_ipv6_value(), Some(false));
        // The L-bit accessor is request-only and not meaningful on a reply.
        assert_eq!(icmp.extended_l_bit_value(), None);
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // A reply with an unexpected trailing payload keeps it as a Raw layer rather
    // than typing it; the buffer round-trips unchanged.
    #[test]
    fn icmpv4_rfc8335_extended_echo_reply_trailing_payload_stays_raw() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_reply().code(ICMP_CODE_EXTENDED_ECHO_REPLY_NO_ERROR)
            / Raw::from_bytes([0xde, 0xad, 0xbe, 0xef]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let raw = decoded.layer::<Raw>().unwrap();
        assert_eq!(raw.as_bytes(), &[0xde, 0xad, 0xbe, 0xef]);
        assert!(decoded.layer::<IcmpExtension>().is_none());
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // The default request carries exactly one Interface Identification Object and
    // its object length covers just that object.
    #[test]
    fn icmpv4_rfc8335_extended_echo_exactly_one_object_default() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_index(3))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let object_count = decoded
            .iter()
            .filter(|layer| layer.as_any().is::<IcmpExtensionObject>())
            .count();
        assert_eq!(object_count, 1);
        let id_count = decoded
            .iter()
            .filter(|layer| layer.as_any().is::<IcmpExtensionInterfaceId>())
            .count();
        assert_eq!(id_count, 1);
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // A deliberately malformed object count (two objects in a single request) is
    // preserved on compile and decode; the crate does not refuse to emit it.
    #[test]
    fn icmpv4_rfc8335_extended_echo_malformed_object_count_preserved() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_index(1)
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_index(2))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        // Both Interface Identification Objects survive (RFC 8335 expects exactly
        // one, but malformed multi-object requests must still round-trip).
        let ids: Vec<_> = decoded
            .iter()
            .filter_map(|layer| layer.as_any().downcast_ref::<IcmpExtensionInterfaceId>())
            .map(|id| id.index_value())
            .collect();
        assert_eq!(ids, vec![Some(1), Some(2)]);
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // An unknown Interface Identification Object C-Type is not typed; it falls
    // back to the generic IcmpExtensionObject + Raw body and round-trips.
    #[test]
    fn icmpv4_rfc8335_extended_echo_unknown_object_falls_back_to_raw() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
                .class_num(ICMP_EXTENSION_CLASS_INTERFACE_ID)
                .c_type(0x7f)
            / Raw::from_bytes([1, 2, 3, 4]))
        .compile()
        .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        assert!(decoded.layer::<IcmpExtensionInterfaceId>().is_none());
        let object = decoded.layer::<IcmpExtensionObject>().unwrap();
        assert_eq!(object.class_num_value(), ICMP_EXTENSION_CLASS_INTERFACE_ID);
        assert_eq!(object.c_type_value(), 0x7f);
        assert!(decoded.layer::<Raw>().is_some());
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }

    // The RFC 4884 extension checksum covers the whole extension structure and
    // verifies on decode; an extended echo request round-trips byte-for-byte.
    #[test]
    fn icmpv4_rfc8335_extended_echo_checksum_roundtrip() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request().id(0x55aa).seq(2)
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_name("wlan0"))
        .compile()
        .unwrap();

        let bytes = compiled.as_bytes();
        // The extension structure starts at offset 28 (right after the 8-byte
        // ICMP header, no quote or padding) and carries a verifying checksum.
        assert!(verify_internet_checksum(&bytes[28..]));
        // The outer ICMP checksum also verifies (covers the ICMP header + body).
        assert!(verify_internet_checksum(&bytes[20..]));

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes).unwrap();
        let extension = decoded.layer::<IcmpExtension>().unwrap();
        assert!(extension.checksum_value().is_some());
        assert_eq!(decoded.compile().unwrap().as_bytes(), bytes);
    }

    // An explicit raw flag byte survives compilation untouched, the escape hatch
    // for crafting reserved bits the typed builders do not expose.
    #[test]
    fn icmpv4_rfc8335_extended_echo_explicit_flag_byte_preserved() {
        let compiled = (Ipv4::new().src(src()).dst(dst())
            / Icmpv4::extended_echo_request()
                .id(1)
                .seq(1)
                .extended_flags(0xfe)
            / IcmpExtension::new()
            / IcmpExtensionObject::new()
            / IcmpExtensionInterfaceId::by_index(1))
        .compile()
        .unwrap();

        // The raw flag byte (including the reserved bits) is emitted verbatim.
        assert_eq!(compiled.as_bytes()[27], 0xfe);

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, compiled.as_bytes()).unwrap();
        let icmp = decoded.layer::<Icmpv4>().unwrap();
        assert_eq!(icmp.extended_flags_value(), Some(0xfe));
        assert_eq!(decoded.compile().unwrap().as_bytes(), compiled.as_bytes());
    }
}