ewf-forensic 0.5.0

Forensic integrity analysis and repair for EWF (Expert Witness Format / E01) images
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
use flate2::read::ZlibDecoder;
use md5::{Digest as _, Md5};
use sha1::Sha1;
use sha2::Sha256;
use std::fmt;
use std::io::Read as _;

// ── EWF v1 constants ─────────────────────────────────────────────────────────

const EVF_SIGNATURE: [u8; 8] = [0x45, 0x56, 0x46, 0x09, 0x0d, 0x0a, 0xff, 0x00];
/// DiskSig/Tableau "dvf" signature — a valid EWF v1 variant.
const DVF_SIGNATURE: [u8; 8] = [0x64, 0x76, 0x66, 0x09, 0x0d, 0x0a, 0xff, 0x00];
/// Logical Volume Format "LVF" signature — logical evidence images.
const LVF_SIGNATURE: [u8; 8] = [0x4c, 0x56, 0x46, 0x09, 0x0d, 0x0a, 0xff, 0x00];

const FILE_HEADER_SIZE: usize = 13;
pub(crate) const SECTION_DESCRIPTOR_SIZE: usize = 76;
const VOLUME_DATA_MIN: usize = 24;
/// The standard ewf_data_t body size (per libewf). Adler-32 at byte 1048.
const VOLUME_DATA_FULL: usize = 1052;
/// Valid media_type values from the ewf_data_t struct.
const VALID_MEDIA_TYPES: &[u8] = &[0x00, 0x01, 0x03, 0x0e, 0x10];

const KNOWN_TYPES: &[&str] = &[
    "header", "header2", "volume", "disk", "table", "table2", "sectors", "hash", "digest",
    "error2", "session", "done", "next", "data", "ltree", "ltreedata",
];

// ── EWF v2 constants ─────────────────────────────────────────────────────────

const EVF2_SIGNATURE: [u8; 8] = [0x45, 0x56, 0x46, 0x32, 0x0d, 0x0a, 0x81, 0x00];
const LEF2_SIGNATURE: [u8; 8] = [0x4c, 0x45, 0x46, 0x32, 0x0d, 0x0a, 0x81, 0x00];
const EVF2_FILE_HEADER_SIZE: usize = 32;
const EVF2_SECTION_DESCRIPTOR_SIZE: usize = 64;
const EVF2_DATA_FLAG_ENCRYPTED: u32 = 0x0000_0002;
const EVF2_CHUNK_FLAG_COMPRESSED: u32 = 0x0000_0001;
const EVF2_TYPE_MEDIA_INFO: u32 = 0x02;
const EVF2_TYPE_CHUNK_TABLE: u32 = 0x04;
const EVF2_TYPE_MD5_HASH: u32 = 0x08;
const EVF2_TYPE_SHA1_HASH: u32 = 0x09;
const EVF2_TYPE_SHA256_HASH: u32 = 0x0A;
const EVF2_CHUNK_TABLE_HEADER_SIZE: usize = 32;
const EVF2_CHUNK_TABLE_ENTRY_SIZE: usize = 16;

// ── Public types ──────────────────────────────────────────────────────────────

/// The canonical 5-level severity scale, shared across every SecurityRonin
/// analyzer via [`forensicnomicon::report`].
pub use forensicnomicon::report::Severity;

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EwfIntegrityAnomaly {
    // ── EWF v1 ───────────────────────────────────────────────────────────────
    InvalidSignature,
    SegmentNumberZero,
    SectionDescriptorCrcMismatch {
        offset: u64,
        section_type: String,
        computed: u32,
        stored: u32,
    },
    SectionChainBroken {
        at_offset: u64,
        next_offset: u64,
    },
    SectionGapNonZero {
        gap_offset: u64,
        gap_size: u64,
    },
    VolumeSectionMissing,
    UnknownSectionType {
        offset: u64,
        type_name: String,
    },
    DoneSectionMissing,
    /// No `sectors` section was found in this EWF v1 segment.
    SectorsSectionMissing,
    /// No `table` section was found in this EWF v1 segment.
    TableSectionMissing,
    ChunkSizeInvalid {
        sectors_per_chunk: u32,
        bytes_per_sector: u32,
    },
    SectorCountMismatch {
        declared: u64,
        expected: u64,
    },
    BytesPerSectorInvalid {
        bytes_per_sector: u32,
    },
    TableChunkCountMismatch {
        in_volume: u32,
        in_table: u32,
    },
    TableHeaderAdler32Mismatch {
        computed: u32,
        stored: u32,
    },
    TableEntryOutOfBounds {
        chunk_index: u32,
        entry_offset: u64,
        file_size: u64,
    },
    TableEntryOutsideSectorsRange {
        chunk_index: u32,
        entry_offset: u64,
        sectors_start: u64,
        sectors_end: u64,
    },
    SectionGapZero {
        gap_offset: u64,
        gap_size: u64,
    },
    HashMismatch {
        computed: [u8; 16],
        stored: [u8; 16],
    },
    HashSectionMissing,
    /// `table2` body differs from `table` body — one of the redundant copies is corrupt.
    Table2Mismatch {
        /// Byte offset into the table body where the first difference was found.
        offset: usize,
    },
    /// The `error2` section records acquisition errors (unreadable sectors).
    BadSectorsPresent {
        /// Number of error entries in the `error2` section.
        count: u32,
    },
    // ── Multi-segment ─────────────────────────────────────────────────────────
    /// Segment number does not match the expected sequential position.
    SegmentOutOfOrder {
        segment_number: u16,
        expected: u16,
    },
    // ── SHA-1 from EWF v1 digest section ─────────────────────────────────────
    /// Computed SHA-1 of all sector data does not match the stored SHA-1 in the digest section.
    DigestSha1Mismatch {
        computed: [u8; 20],
        stored: [u8; 20],
    },
    /// Computed SHA-256 of all sector data does not match the stored SHA-256 in the hash section.
    DigestSha256Mismatch {
        computed: [u8; 32],
        stored: [u8; 32],
    },
    // ── External reference hash ───────────────────────────────────────────────
    /// Computed MD5 does not match an externally supplied reference (e.g. chain-of-custody form).
    ExternalMd5Mismatch {
        computed: [u8; 16],
        expected: [u8; 16],
    },
    /// Computed SHA-1 does not match an externally supplied reference.
    ExternalSha1Mismatch {
        computed: [u8; 20],
        expected: [u8; 20],
    },
    // ── EWF v2 ───────────────────────────────────────────────────────────────
    /// A section's stored data_integrity_hash does not match MD5 of the section body.
    Ewf2SectionDataHashMismatch {
        offset: u64,
        section_type_id: u32,
        computed: [u8; 16],
        stored: [u8; 16],
    },
    /// An encrypted section was found; its content cannot be verified.
    Ewf2EncryptedSection {
        offset: u64,
    },
    /// No MD5 or SHA-1 hash section found in the final EWF v2 segment.
    Ewf2HashSectionMissing,
    /// Adler-32 of the 1052-byte ewf_data_t body is wrong.
    /// Only checked when the volume body is ≥ 1052 bytes (as in real acquisitions).
    VolumeBodyCrcMismatch { computed: u32, stored: u32 },
    /// `media_type` byte (offset 0 of ewf_data_t) is not a known valid value.
    /// Valid: 0x00=removable, 0x01=fixed, 0x03=optical, 0x0e=LVF, 0x10=memory.
    MediaTypeUnknown { media_type: u8 },
    /// The set_identifier GUID (bytes 64-79 of ewf_data_t) differs between segments
    /// of the same acquisition — indicates segments from different acquisitions were mixed.
    SetIdentifierMismatch { segment: usize },
    /// No media information (device information) section found in the EWF v2 image.
    Ewf2MediaInfoMissing,
    /// The Adler-32 checksum stored at the end of the EWF v2 chunk table body does not
    /// match the Adler-32 computed over the chunk table entries.
    Ewf2ChunkTableChecksumMismatch { computed: u32, stored: u32 },
    /// The Adler-32 stored at the end of a chunk's byte range does not match
    /// the Adler-32 computed over the chunk's raw (possibly compressed) bytes.
    ChunkChecksumMismatch {
        chunk_index: usize,
        computed: u32,
        stored: u32,
    },
    /// A compressed chunk's zlib stream could not be decompressed.
    /// The chunk index identifies exactly which chunk is corrupt.
    ChunkDecompressionError {
        chunk_index: usize,
    },
    /// EWF v2 file header specifies a compression algorithm not supported by this tool.
    UnsupportedCompressionAlgorithm {
        /// Value from file header bytes [10..12].
        method_id: u16,
    },
    /// Computed SHA-256 does not match an externally supplied reference.
    ExternalSha256Mismatch {
        computed: [u8; 32],
        expected: [u8; 32],
    },
    /// The EWF v2 media information section body could not be decompressed (zlib
    /// failure) or decoded as UTF-16LE.  The body is required to be a zlib-
    /// compressed, BOM-prefixed UTF-16LE key=value table.
    Ewf2MediaInfoParseFailed,
}

impl EwfIntegrityAnomaly {
    pub fn severity(&self) -> Severity {
        match self {
            Self::InvalidSignature => Severity::Critical,
            Self::SegmentNumberZero => Severity::High,
            Self::SectionDescriptorCrcMismatch { .. } => Severity::High,
            Self::SectionChainBroken { .. } => Severity::Critical,
            Self::SectionGapNonZero { .. } => Severity::Medium,
            Self::VolumeSectionMissing => Severity::Critical,
            Self::UnknownSectionType { .. } => Severity::Medium,
            Self::DoneSectionMissing => Severity::Medium,
            Self::SectorsSectionMissing => Severity::High,
            Self::TableSectionMissing => Severity::High,
            Self::ChunkSizeInvalid { .. } => Severity::High,
            Self::SectorCountMismatch { .. } => Severity::High,
            Self::BytesPerSectorInvalid { .. } => Severity::High,
            Self::TableChunkCountMismatch { .. } => Severity::High,
            Self::TableHeaderAdler32Mismatch { .. } => Severity::High,
            Self::TableEntryOutOfBounds { .. } => Severity::High,
            Self::TableEntryOutsideSectorsRange { .. } => Severity::High,
            Self::SectionGapZero { .. } => Severity::Info,
            Self::HashMismatch { .. } => Severity::High,
            Self::HashSectionMissing => Severity::Medium,
            Self::Table2Mismatch { .. } => Severity::High,
            Self::BadSectorsPresent { .. } => Severity::Medium,
            Self::SegmentOutOfOrder { .. } => Severity::High,
            Self::DigestSha1Mismatch { .. } => Severity::High,
            Self::DigestSha256Mismatch { .. } => Severity::High,
            Self::ExternalMd5Mismatch { .. } => Severity::Critical,
            Self::ExternalSha1Mismatch { .. } => Severity::Critical,
            Self::VolumeBodyCrcMismatch { .. } => Severity::High,
            Self::MediaTypeUnknown { .. } => Severity::Medium,
            Self::SetIdentifierMismatch { .. } => Severity::High,
            Self::Ewf2SectionDataHashMismatch { .. } => Severity::High,
            Self::Ewf2EncryptedSection { .. } => Severity::Medium,
            Self::Ewf2HashSectionMissing => Severity::Medium,
            Self::Ewf2MediaInfoMissing => Severity::Medium,
            Self::Ewf2ChunkTableChecksumMismatch { .. } => Severity::High,
            Self::ChunkChecksumMismatch { .. } => Severity::High,
            Self::ChunkDecompressionError { .. } => Severity::High,
            Self::UnsupportedCompressionAlgorithm { .. } => Severity::High,
            Self::ExternalSha256Mismatch { .. } => Severity::Critical,
            Self::Ewf2MediaInfoParseFailed => Severity::High,
        }
    }
}

impl fmt::Display for EwfIntegrityAnomaly {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidSignature =>
                write!(f, "invalid EWF signature — not a valid E01/Ex01 file"),
            Self::SegmentNumberZero =>
                write!(f, "segment number is zero (expected ≥ 1)"),
            Self::SectionDescriptorCrcMismatch { offset, section_type, computed, stored } =>
                write!(f, "section '{section_type}' at 0x{offset:x}: descriptor CRC mismatch (computed 0x{computed:08x}, stored 0x{stored:08x})"),
            Self::SectionChainBroken { at_offset, next_offset } =>
                write!(f, "section chain broken at 0x{at_offset:x}: next pointer 0x{next_offset:x} is invalid"),
            Self::SectionGapNonZero { gap_offset, gap_size } =>
                write!(f, "non-zero data in {gap_size}-byte gap at 0x{gap_offset:x} — possible hidden data"),
            Self::VolumeSectionMissing =>
                write!(f, "volume/disk section missing in segment 1"),
            Self::UnknownSectionType { offset, type_name } =>
                write!(f, "unknown section type '{type_name}' at 0x{offset:x}"),
            Self::DoneSectionMissing =>
                write!(f, "done section missing from final segment"),
            Self::SectorsSectionMissing =>
                write!(f, "sectors section missing — chunk data not found in segment"),
            Self::TableSectionMissing =>
                write!(f, "table section missing — chunk offset table not found in segment"),
            Self::ChunkSizeInvalid { sectors_per_chunk, bytes_per_sector } =>
                write!(f, "invalid chunk size: {sectors_per_chunk} sectors × {bytes_per_sector} bytes/sector"),
            Self::SectorCountMismatch { declared, expected } =>
                write!(f, "sector count mismatch: declared {declared}, expected {expected}"),
            Self::BytesPerSectorInvalid { bytes_per_sector } =>
                write!(f, "invalid bytes_per_sector: {bytes_per_sector} (expected 512 or 4096)"),
            Self::TableChunkCountMismatch { in_volume, in_table } =>
                write!(f, "chunk count mismatch: volume declares {in_volume}, table has {in_table}"),
            Self::TableHeaderAdler32Mismatch { computed, stored } =>
                write!(f, "table header Adler-32 mismatch: computed 0x{computed:08x}, stored 0x{stored:08x}"),
            Self::TableEntryOutOfBounds { chunk_index, entry_offset, file_size } =>
                write!(f, "table entry for chunk {chunk_index} points outside file: 0x{entry_offset:x} ≥ 0x{file_size:x}"),
            Self::TableEntryOutsideSectorsRange { chunk_index, entry_offset, sectors_start, sectors_end } =>
                write!(f, "table entry for chunk {chunk_index} at 0x{entry_offset:x} is outside sectors section [0x{sectors_start:x}..0x{sectors_end:x}]"),
            Self::SectionGapZero { gap_offset, gap_size } =>
                write!(f, "zero-padded {gap_size}-byte gap at 0x{gap_offset:x}"),
            Self::HashMismatch { computed, stored } =>
                write!(f, "MD5 mismatch: computed {}, stored {}", hex(computed), hex(stored)),
            Self::HashSectionMissing =>
                write!(f, "hash section missing — cannot verify MD5"),
            Self::Table2Mismatch { offset } =>
                write!(f, "table2 body differs from table at byte offset {offset} — one redundant copy is corrupt"),
            Self::BadSectorsPresent { count } =>
                write!(f, "error2 section reports {count} unreadable sector range(s) from acquisition"),
            Self::SegmentOutOfOrder { segment_number, expected } =>
                write!(f, "segment {segment_number} found where segment {expected} was expected"),
            Self::DigestSha1Mismatch { computed, stored } =>
                write!(f, "SHA-1 mismatch: computed {}, stored {}", hex(computed), hex(stored)),
            Self::DigestSha256Mismatch { computed, stored } =>
                write!(f, "SHA-256 mismatch: computed {}, stored {}", hex(computed), hex(stored)),
            Self::ExternalMd5Mismatch { computed, expected } =>
                write!(f, "MD5 does not match chain-of-custody reference: computed {}, expected {}", hex(computed), hex(expected)),
            Self::ExternalSha1Mismatch { computed, expected } =>
                write!(f, "SHA-1 does not match chain-of-custody reference: computed {}, expected {}", hex(computed), hex(expected)),
            Self::ExternalSha256Mismatch { computed, expected } =>
                write!(f, "SHA-256 does not match chain-of-custody reference: computed {}, expected {}", hex(computed), hex(expected)),
            Self::Ewf2SectionDataHashMismatch { offset, section_type_id, computed, stored } =>
                write!(f, "EWF v2 section (type 0x{section_type_id:02x}) at 0x{offset:x}: data integrity hash mismatch (computed {}, stored {})", hex(computed), hex(stored)),
            Self::Ewf2EncryptedSection { offset } =>
                write!(f, "EWF v2 encrypted section at 0x{offset:x} — content not verifiable"),
            Self::Ewf2HashSectionMissing =>
                write!(f, "EWF v2 hash section missing from final segment"),
            Self::VolumeBodyCrcMismatch { computed, stored } =>
                write!(f, "volume section body CRC mismatch (computed 0x{computed:08x}, stored 0x{stored:08x})"),
            Self::MediaTypeUnknown { media_type } =>
                write!(f, "unknown media_type 0x{media_type:02x}"),
            Self::SetIdentifierMismatch { segment } =>
                write!(f, "set_identifier GUID mismatch in segment {segment} — segments may be from different acquisitions"),
            Self::Ewf2MediaInfoMissing =>
                write!(f, "EWF v2 media information section missing"),
            Self::Ewf2ChunkTableChecksumMismatch { computed, stored } =>
                write!(f, "EWF v2 chunk table checksum mismatch (computed 0x{computed:08x}, stored 0x{stored:08x})"),
            Self::ChunkChecksumMismatch { chunk_index, computed, stored } =>
                write!(f, "chunk {chunk_index}: Adler-32 mismatch (computed 0x{computed:08x}, stored 0x{stored:08x})"),
            Self::ChunkDecompressionError { chunk_index } =>
                write!(f, "chunk {chunk_index}: zlib decompression failed — chunk data is corrupt"),
            Self::UnsupportedCompressionAlgorithm { method_id } =>
                write!(f, "EWF v2 file header specifies unsupported compression algorithm 0x{method_id:04x} — only deflate (0/1) is supported"),
            Self::Ewf2MediaInfoParseFailed =>
                write!(f, "EWF v2 media information section body could not be decompressed or decoded"),
        }
    }
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Snapshot of analysis progress, delivered to the callback passed to
/// [`EwfIntegrity::analyse_with_progress`] after each chunk is processed.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AnalysisProgress {
    /// Number of chunks fully processed (hashed + Adler-32 verified) so far.
    pub chunks_done: usize,
    /// Total chunks in the current segment; `None` until the chunk table is parsed.
    pub chunks_total: Option<usize>,
    /// Total sector-data bytes processed so far.
    pub bytes_done: u64,
}

/// The three hashes computed over all sector data in an EWF image.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ComputedHashes {
    pub md5: [u8; 16],
    pub sha1: [u8; 20],
    pub sha256: [u8; 32],
}

/// Acquisition metadata parsed from the zlib-compressed `header` section of an EWF v1 image.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EwfHeaderMetadata {
    pub description: String,
    pub case_number: String,
    pub evidence_number: String,
    pub examiner_name: String,
    pub acquisition_date: String,
    pub system_date: String,
    pub password_hash: String,
    pub acquisition_software: String,
}

// ── Public entry point ────────────────────────────────────────────────────────

pub struct EwfIntegrity<'a> {
    segments: Vec<&'a [u8]>,
    expected_md5: Option<[u8; 16]>,
    expected_sha1: Option<[u8; 20]>,
    expected_sha256: Option<[u8; 32]>,
}

impl<'a> EwfIntegrity<'a> {
    /// Analyse a single-segment E01 or Ex01 file.
    pub fn new(data: &'a [u8]) -> Self {
        Self {
            segments: vec![data],
            expected_md5: None,
            expected_sha1: None,
            expected_sha256: None,
        }
    }

    /// Analyse a multi-segment image. Pass segments in order: E01, E02, E03 …
    pub fn from_segments(segs: &[&'a [u8]]) -> Self {
        Self {
            segments: segs.to_vec(),
            expected_md5: None,
            expected_sha1: None,
            expected_sha256: None,
        }
    }

    /// Compare the computed MD5 against an externally-sourced reference
    /// (e.g., a chain-of-custody form). Mismatch → `ExternalMd5Mismatch` (Critical).
    pub fn with_expected_md5(mut self, hash: [u8; 16]) -> Self {
        self.expected_md5 = Some(hash);
        self
    }

    /// Compare the computed SHA-1 against an externally-sourced reference.
    /// Mismatch → `ExternalSha1Mismatch` (Critical).
    pub fn with_expected_sha1(mut self, hash: [u8; 20]) -> Self {
        self.expected_sha1 = Some(hash);
        self
    }

    /// Compare the computed SHA-256 against an externally-sourced reference.
    /// Mismatch → `ExternalSha256Mismatch` (Critical).
    pub fn with_expected_sha256(mut self, hash: [u8; 32]) -> Self {
        self.expected_sha256 = Some(hash);
        self
    }

    /// Parse the zlib-compressed acquisition metadata from the `header` section.
    ///
    /// Returns `Some` on the first segment that contains a valid, decompressible
    /// `header` section with a parseable key-value block.  Returns `None` if no
    /// such section exists or any parse step fails.
    pub fn header_metadata(&self) -> Option<EwfHeaderMetadata> {
        for &data in &self.segments {
            if let Some(meta) = parse_header_section(data) {
                return Some(meta);
            }
        }
        None
    }

    /// Compute MD5, SHA-1, and SHA-256 of all sector data without verifying stored hashes.
    ///
    /// Returns `None` if the image is unparseable (too short, invalid signature,
    /// missing geometry, or no chunk table found in an EWF v2 image).
    pub fn compute_hashes(&self) -> Option<ComputedHashes> {
        let first = self.segments.first().copied().unwrap_or(&[]);
        if first.len() >= 8
            && (first[0..8] == EVF2_SIGNATURE || first[0..8] == LEF2_SIGNATURE)
        {
            return compute_hashes_ewf2(&self.segments);
        }
        compute_hashes_ewf1(&self.segments)
    }

    pub fn analyse(&self) -> Vec<EwfIntegrityAnomaly> {
        let first = self.segments.first().copied().unwrap_or(&[]);
        if first.len() >= 8
            && (first[0..8] == EVF2_SIGNATURE || first[0..8] == LEF2_SIGNATURE)
        {
            return self.analyse_all_ewf2();
        }
        self.analyse_all_ewf1()
    }

    /// Analyse with a per-chunk progress callback.
    ///
    /// The callback receives an [`AnalysisProgress`] snapshot after each chunk
    /// is processed.  The final call has `chunks_done == chunks_total` (for
    /// EWF v2) or `chunks_done > 0` (for EWF v1).
    ///
    /// Returns the same anomaly list as [`analyse`][Self::analyse].
    pub fn analyse_with_progress(
        &self,
        progress: impl FnMut(AnalysisProgress),
    ) -> Vec<EwfIntegrityAnomaly> {
        let first = self.segments.first().copied().unwrap_or(&[]);
        if first.len() >= 8
            && (first[0..8] == EVF2_SIGNATURE || first[0..8] == LEF2_SIGNATURE)
        {
            return self.analyse_all_ewf2_with_progress(progress);
        }
        self.analyse_all_ewf1_with_progress(progress)
    }

    // ── EWF v1 ───────────────────────────────────────────────────────────────

    fn analyse_all_ewf1(&self) -> Vec<EwfIntegrityAnomaly> {
        let mut issues = Vec::new();
        let n = self.segments.len();
        let multi = n > 1;
        let mut geometry: Option<VolumeGeometry> = None;
        let mut all_sections: Vec<Vec<Section>> = Vec::with_capacity(n);
        let mut total_table_entries: u32 = 0;

        for (idx, &data) in self.segments.iter().enumerate() {
            let expected_seg_num = (idx + 1) as u16;
            let is_last = idx == n - 1;
            let file_size = data.len() as u64;

            if data.len() < FILE_HEADER_SIZE {
                issues.push(EwfIntegrityAnomaly::SectionChainBroken {
                    at_offset: 0,
                    next_offset: 0,
                });
                all_sections.push(Vec::new());
                continue;
            }

            if data[0..8] != EVF_SIGNATURE
                && data[0..8] != DVF_SIGNATURE
                && data[0..8] != LVF_SIGNATURE
            {
                issues.push(EwfIntegrityAnomaly::InvalidSignature);
            }

            let seg_num = u16::from_le_bytes(data[9..11].try_into().unwrap());
            if seg_num == 0 {
                issues.push(EwfIntegrityAnomaly::SegmentNumberZero);
            } else if seg_num != expected_seg_num {
                issues.push(EwfIntegrityAnomaly::SegmentOutOfOrder {
                    segment_number: seg_num,
                    expected: expected_seg_num,
                });
            }

            let sections = walk_sections_v1(data, &mut issues);

            // Volume/disk geometry — required in segment 0; compared in later segments.
            if let Some(vol_sec) = sections
                .iter()
                .find(|s| s.type_name == "volume" || s.type_name == "disk")
            {
                if idx == 0 {
                    geometry = check_volume_v1(data, vol_sec.offset, vol_sec.size, &mut issues);
                } else {
                    // Later segments with a volume section: validate its GUID against seg 0.
                    let later = check_volume_v1(data, vol_sec.offset, vol_sec.size, &mut issues);
                    if let (Some(ref base), Some(ref later_geom)) = (&geometry, &later) {
                        let base_guid = base.set_identifier;
                        let later_guid = later_geom.set_identifier;
                        let neither_zero =
                            base_guid != [0u8; 16] && later_guid != [0u8; 16];
                        if neither_zero && base_guid != later_guid {
                            issues.push(EwfIntegrityAnomaly::SetIdentifierMismatch {
                                segment: idx + 1,
                            });
                        }
                    }
                }
            } else if idx == 0 {
                issues.push(EwfIntegrityAnomaly::VolumeSectionMissing);
            }

            // Table integrity — single-segment: check per-entry-count vs volume directly.
            // Multi-segment: accumulate for post-loop total comparison.
            let vol_count = if !multi && idx == 0 {
                geometry.as_ref().map(|g| g.chunk_count)
            } else {
                None
            };
            let sectors_section = sections.iter().find(|s| s.type_name == "sectors");
            let sectors_range = sectors_section
                .map(|s| (s.offset + SECTION_DESCRIPTOR_SIZE as u64, s.offset + s.size));
            if sectors_section.is_none() {
                issues.push(EwfIntegrityAnomaly::SectorsSectionMissing);
            }
            if let Some(table) = sections.iter().find(|s| s.type_name == "table") {
                let data_start = (table.offset as usize) + SECTION_DESCRIPTOR_SIZE;
                if data.len() >= data_start + 4 {
                    let count = u32::from_le_bytes(data[data_start..data_start + 4].try_into().unwrap());
                    total_table_entries = total_table_entries.saturating_add(count);
                }
                check_table_v1(
                    data,
                    table.offset,
                    vol_count,
                    file_size,
                    sectors_range,
                    &mut issues,
                );
            } else {
                issues.push(EwfIntegrityAnomaly::TableSectionMissing);
            }

            // table2 consistency: when both table and table2 exist, bodies must match.
            if let (Some(t1), Some(t2)) = (
                sections.iter().find(|s| s.type_name == "table"),
                sections.iter().find(|s| s.type_name == "table2"),
            ) {
                let b1_start = (t1.offset + SECTION_DESCRIPTOR_SIZE as u64) as usize;
                let b1_end = (t1.offset + t1.size) as usize;
                let b2_start = (t2.offset + SECTION_DESCRIPTOR_SIZE as u64) as usize;
                let b2_end = (t2.offset + t2.size) as usize;
                if let (Some(body1), Some(body2)) = (data.get(b1_start..b1_end), data.get(b2_start..b2_end)) {
                    if body1.len() == body2.len() {
                        if let Some(offset) = body1.iter().zip(body2).position(|(a, b)| a != b) {
                            issues.push(EwfIntegrityAnomaly::Table2Mismatch { offset });
                        }
                    } else {
                        issues.push(EwfIntegrityAnomaly::Table2Mismatch { offset: 0 });
                    }
                }
            }

            // error2 section: parse entry_count, warn if any unreadable sectors.
            if let Some(e2) = sections.iter().find(|s| s.type_name == "error2") {
                let body_start = (e2.offset + SECTION_DESCRIPTOR_SIZE as u64) as usize;
                if body_start + 4 <= data.len() {
                    let count = u32::from_le_bytes(data[body_start..body_start + 4].try_into().unwrap());
                    if count > 0 {
                        issues.push(EwfIntegrityAnomaly::BadSectorsPresent { count });
                    }
                }
            }

            // Done section expected only in the last segment
            if is_last && !sections.iter().any(|s| s.type_name == "done") {
                issues.push(EwfIntegrityAnomaly::DoneSectionMissing);
            }

            all_sections.push(sections);
        }

        // Multi-segment total chunk count vs sum of all table entry counts.
        if multi {
            if let Some(geom) = &geometry {
                if total_table_entries != geom.chunk_count {
                    issues.push(EwfIntegrityAnomaly::TableChunkCountMismatch {
                        in_volume: geom.chunk_count,
                        in_table: total_table_entries,
                    });
                }
            }
        }

        // Hash verification spans all segments
        if let Some(geom) = &geometry {
            check_hash_all_segments(
                &self.segments,
                &all_sections,
                geom,
                self.expected_md5,
                self.expected_sha1,
                self.expected_sha256,
                &mut issues,
                &mut |_| {},
            );
        }

        issues
    }

    // ── EWF v2 ───────────────────────────────────────────────────────────────

    fn analyse_all_ewf2(&self) -> Vec<EwfIntegrityAnomaly> {
        self.analyse_all_ewf2_with_progress(|_| {})
    }

    fn analyse_all_ewf2_impl(&self, progress: &mut dyn FnMut(AnalysisProgress)) -> Vec<EwfIntegrityAnomaly> {
        let mut issues = Vec::new();
        let n = self.segments.len();

        // Stored hashes live in the FINAL segment and cover ALL segments' data.
        let mut final_stored_md5:    Option<[u8; 16]> = None;
        let mut final_stored_sha1:   Option<[u8; 20]> = None;
        let mut final_stored_sha256: Option<[u8; 32]> = None;

        for (idx, &data) in self.segments.iter().enumerate() {
            let expected_seg_num = (idx + 1) as u32;

            if data.len() < EVF2_FILE_HEADER_SIZE + EVF2_SECTION_DESCRIPTOR_SIZE {
                issues.push(EwfIntegrityAnomaly::SectionChainBroken {
                    at_offset: 0,
                    next_offset: 0,
                });
                continue;
            }

            if data[0..8] != EVF2_SIGNATURE && data[0..8] != LEF2_SIGNATURE {
                issues.push(EwfIntegrityAnomaly::InvalidSignature);
            }

            let seg_num = u32::from_le_bytes(data[12..16].try_into().unwrap());
            if seg_num == 0 {
                issues.push(EwfIntegrityAnomaly::SegmentNumberZero);
            } else if seg_num != expected_seg_num {
                issues.push(EwfIntegrityAnomaly::SegmentOutOfOrder {
                    segment_number: seg_num as u16,
                    expected: expected_seg_num as u16,
                });
            }

            // compression_method at file header [10..12]: 0=none/deflate, 1=deflate.
            // Values ≥ 2 indicate bzip2, lzma, or other algorithms not supported here.
            let compression_method = u16::from_le_bytes(data[10..12].try_into().unwrap());
            if compression_method > 1 {
                issues.push(EwfIntegrityAnomaly::UnsupportedCompressionAlgorithm {
                    method_id: compression_method,
                });
            }

            // EWF v2: section body precedes its descriptor; the DONE/NEXT descriptor
            // is the last 64 bytes of the segment. Walk backward via prev_section_offset.
            let mut has_hash = false;
            let mut has_media_info = false;
            let mut chunk_table_body: Option<(usize, usize)> = None;
            let mut stored_sector_md5: Option<[u8; 16]> = None;
            let mut stored_sector_sha1: Option<[u8; 20]> = None;
            let mut stored_sector_sha256: Option<[u8; 32]> = None;
            let mut desc_offset = data.len().saturating_sub(EVF2_SECTION_DESCRIPTOR_SIZE);

            loop {
                if desc_offset + EVF2_SECTION_DESCRIPTOR_SIZE > data.len()
                    || desc_offset < EVF2_FILE_HEADER_SIZE
                {
                    break;
                }
                let desc = &data[desc_offset..desc_offset + EVF2_SECTION_DESCRIPTOR_SIZE];
                let section_type = u32::from_le_bytes(desc[0..4].try_into().unwrap());
                let data_flags  = u32::from_le_bytes(desc[4..8].try_into().unwrap());
                let prev_offset = u64::from_le_bytes(desc[8..16].try_into().unwrap()) as usize;
                let data_size   = u64::from_le_bytes(desc[16..24].try_into().unwrap()) as usize;
                let stored_hash: [u8; 16] = desc[32..48].try_into().unwrap();

                // Body occupies [desc_offset - data_size .. desc_offset].
                let body_end   = desc_offset;
                let body_start = desc_offset.saturating_sub(data_size);

                if data_flags & EVF2_DATA_FLAG_ENCRYPTED != 0 {
                    issues.push(EwfIntegrityAnomaly::Ewf2EncryptedSection {
                        offset: desc_offset as u64,
                    });
                } else {
                    if stored_hash != [0u8; 16] {
                        if let Some(body) = data.get(body_start..body_end) {
                            let computed: [u8; 16] = Md5::digest(body).into();
                            if computed != stored_hash {
                                issues.push(EwfIntegrityAnomaly::Ewf2SectionDataHashMismatch {
                                    offset: desc_offset as u64,
                                    section_type_id: section_type,
                                    computed,
                                    stored: stored_hash,
                                });
                            }
                        }
                    }

                    match section_type {
                        EVF2_TYPE_MEDIA_INFO => {
                            has_media_info = true;
                            if let Some(body) = data.get(body_start..body_end) {
                                if !parse_media_info_body(body) {
                                    issues.push(EwfIntegrityAnomaly::Ewf2MediaInfoParseFailed);
                                }
                            } else {
                                issues.push(EwfIntegrityAnomaly::Ewf2MediaInfoParseFailed);
                            }
                        }
                        EVF2_TYPE_CHUNK_TABLE => {
                            chunk_table_body = Some((body_start, body_end));
                        }
                        EVF2_TYPE_MD5_HASH => {
                            has_hash = true;
                            // Body[0..16] = MD5 of all sector data
                            if data_size >= 16 {
                                if let Some(body) = data.get(body_start..body_end) {
                                    let mut h = [0u8; 16];
                                    h.copy_from_slice(&body[..16]);
                                    stored_sector_md5 = Some(h);
                                }
                            }
                        }
                        EVF2_TYPE_SHA1_HASH => {
                            has_hash = true;
                            if data_size >= 20 {
                                if let Some(body) = data.get(body_start..body_end) {
                                    let mut h = [0u8; 20];
                                    h.copy_from_slice(&body[..20]);
                                    stored_sector_sha1 = Some(h);
                                }
                            }
                        }
                        EVF2_TYPE_SHA256_HASH => {
                            has_hash = true;
                            if data_size >= 32 {
                                if let Some(body) = data.get(body_start..body_end) {
                                    let mut h = [0u8; 32];
                                    h.copy_from_slice(&body[..32]);
                                    stored_sector_sha256 = Some(h);
                                }
                            }
                        }
                        _ => {}
                    }
                }

                if prev_offset == 0 {
                    break;
                }
                desc_offset = prev_offset;
            }

            if idx == n - 1 && !has_hash {
                issues.push(EwfIntegrityAnomaly::Ewf2HashSectionMissing);
            }
            if idx == 0 && !has_media_info {
                issues.push(EwfIntegrityAnomaly::Ewf2MediaInfoMissing);
            }

            // Capture stored hashes from the final segment; they cover ALL segments' data.
            if idx == n - 1 {
                final_stored_md5    = stored_sector_md5;
                final_stored_sha1   = stored_sector_sha1;
                final_stored_sha256 = stored_sector_sha256;
            }

            // Per-chunk Adler-32 verification only; stored-hash comparison happens
            // cross-segment after the loop to avoid false positives on multi-segment images.
            if let Some((ct_start, ct_end)) = chunk_table_body {
                verify_ewf2_sector_data(data, ct_start, ct_end, None, None, None, &mut issues, progress);
            }
        }

        // Cross-segment hash comparison: compute hashes over ALL segments and compare
        // with stored values from the final segment, plus any external reference hashes.
        if let Some(computed) = compute_hashes_ewf2(&self.segments) {
            if let Some(stored) = final_stored_md5 {
                if computed.md5 != stored {
                    issues.push(EwfIntegrityAnomaly::HashMismatch { computed: computed.md5, stored });
                }
            }
            if let Some(stored) = final_stored_sha1 {
                if computed.sha1 != stored {
                    issues.push(EwfIntegrityAnomaly::DigestSha1Mismatch { computed: computed.sha1, stored });
                }
            }
            if let Some(stored) = final_stored_sha256 {
                if computed.sha256 != stored {
                    issues.push(EwfIntegrityAnomaly::DigestSha256Mismatch { computed: computed.sha256, stored });
                }
            }
            if let Some(expected) = self.expected_md5 {
                if computed.md5 != expected {
                    issues.push(EwfIntegrityAnomaly::ExternalMd5Mismatch { computed: computed.md5, expected });
                }
            }
            if let Some(expected) = self.expected_sha1 {
                if computed.sha1 != expected {
                    issues.push(EwfIntegrityAnomaly::ExternalSha1Mismatch { computed: computed.sha1, expected });
                }
            }
            if let Some(expected) = self.expected_sha256 {
                if computed.sha256 != expected {
                    issues.push(EwfIntegrityAnomaly::ExternalSha256Mismatch { computed: computed.sha256, expected });
                }
            }
        }

        issues
    }

    fn analyse_all_ewf1_with_progress(
        &self,
        mut progress: impl FnMut(AnalysisProgress),
    ) -> Vec<EwfIntegrityAnomaly> {
        let mut issues = Vec::new();
        let n = self.segments.len();
        let multi = n > 1;
        let mut geometry: Option<VolumeGeometry> = None;
        let mut all_sections: Vec<Vec<Section>> = Vec::with_capacity(n);
        let mut total_table_entries: u32 = 0;

        for (idx, &data) in self.segments.iter().enumerate() {
            let expected_seg_num = (idx + 1) as u16;
            let is_last = idx == n - 1;
            let file_size = data.len() as u64;

            if data.len() < FILE_HEADER_SIZE {
                issues.push(EwfIntegrityAnomaly::SectionChainBroken { at_offset: 0, next_offset: 0 });
                all_sections.push(Vec::new());
                continue;
            }
            if data[0..8] != EVF_SIGNATURE && data[0..8] != DVF_SIGNATURE && data[0..8] != LVF_SIGNATURE {
                issues.push(EwfIntegrityAnomaly::InvalidSignature);
            }
            let seg_num = u16::from_le_bytes(data[9..11].try_into().unwrap());
            if seg_num == 0 {
                issues.push(EwfIntegrityAnomaly::SegmentNumberZero);
            } else if seg_num != expected_seg_num {
                issues.push(EwfIntegrityAnomaly::SegmentOutOfOrder { segment_number: seg_num, expected: expected_seg_num });
            }
            let sections = walk_sections_v1(data, &mut issues);
            if let Some(vol_sec) = sections.iter().find(|s| s.type_name == "volume" || s.type_name == "disk") {
                if idx == 0 {
                    geometry = check_volume_v1(data, vol_sec.offset, vol_sec.size, &mut issues);
                } else {
                    let later = check_volume_v1(data, vol_sec.offset, vol_sec.size, &mut issues);
                    if let (Some(ref base), Some(ref later_geom)) = (&geometry, &later) {
                        let base_guid = base.set_identifier;
                        let later_guid = later_geom.set_identifier;
                        if base_guid != [0u8; 16] && later_guid != [0u8; 16] && base_guid != later_guid {
                            issues.push(EwfIntegrityAnomaly::SetIdentifierMismatch { segment: idx + 1 });
                        }
                    }
                }
            } else if idx == 0 {
                issues.push(EwfIntegrityAnomaly::VolumeSectionMissing);
            }
            let vol_count = if !multi && idx == 0 { geometry.as_ref().map(|g| g.chunk_count) } else { None };
            let sectors_section = sections.iter().find(|s| s.type_name == "sectors");
            let sectors_range = sectors_section
                .map(|s| (s.offset + SECTION_DESCRIPTOR_SIZE as u64, s.offset + s.size));
            if sectors_section.is_none() {
                issues.push(EwfIntegrityAnomaly::SectorsSectionMissing);
            }
            if let Some(table) = sections.iter().find(|s| s.type_name == "table") {
                let data_start = (table.offset as usize) + SECTION_DESCRIPTOR_SIZE;
                if data.len() >= data_start + 4 {
                    let count = u32::from_le_bytes(data[data_start..data_start + 4].try_into().unwrap());
                    total_table_entries = total_table_entries.saturating_add(count);
                }
                check_table_v1(data, table.offset, vol_count, file_size, sectors_range, &mut issues);
            } else {
                issues.push(EwfIntegrityAnomaly::TableSectionMissing);
            }
            if let (Some(t1), Some(t2)) = (
                sections.iter().find(|s| s.type_name == "table"),
                sections.iter().find(|s| s.type_name == "table2"),
            ) {
                let b1_start = (t1.offset + SECTION_DESCRIPTOR_SIZE as u64) as usize;
                let b1_end = (t1.offset + t1.size) as usize;
                let b2_start = (t2.offset + SECTION_DESCRIPTOR_SIZE as u64) as usize;
                let b2_end = (t2.offset + t2.size) as usize;
                if let (Some(body1), Some(body2)) = (data.get(b1_start..b1_end), data.get(b2_start..b2_end)) {
                    if body1.len() == body2.len() {
                        if let Some(offset) = body1.iter().zip(body2).position(|(a, b)| a != b) {
                            issues.push(EwfIntegrityAnomaly::Table2Mismatch { offset });
                        }
                    } else {
                        issues.push(EwfIntegrityAnomaly::Table2Mismatch { offset: 0 });
                    }
                }
            }
            if let Some(e2) = sections.iter().find(|s| s.type_name == "error2") {
                let body_start = (e2.offset + SECTION_DESCRIPTOR_SIZE as u64) as usize;
                if body_start + 4 <= data.len() {
                    let count = u32::from_le_bytes(data[body_start..body_start + 4].try_into().unwrap());
                    if count > 0 {
                        issues.push(EwfIntegrityAnomaly::BadSectorsPresent { count });
                    }
                }
            }
            if is_last && !sections.iter().any(|s| s.type_name == "done") {
                issues.push(EwfIntegrityAnomaly::DoneSectionMissing);
            }
            all_sections.push(sections);
        }

        if multi {
            if let Some(geom) = &geometry {
                if total_table_entries != geom.chunk_count {
                    issues.push(EwfIntegrityAnomaly::TableChunkCountMismatch {
                        in_volume: geom.chunk_count,
                        in_table: total_table_entries,
                    });
                }
            }
        }

        if let Some(geom) = &geometry {
            check_hash_all_segments(
                &self.segments, &all_sections, geom,
                self.expected_md5, self.expected_sha1, self.expected_sha256,
                &mut issues, &mut progress,
            );
        }
        issues
    }

    fn analyse_all_ewf2_with_progress(
        &self,
        mut progress: impl FnMut(AnalysisProgress),
    ) -> Vec<EwfIntegrityAnomaly> {
        self.analyse_all_ewf2_impl(&mut progress)
    }
}

// ── Private helpers ───────────────────────────────────────────────────────────

fn parse_header_section(data: &[u8]) -> Option<EwfHeaderMetadata> {
    if data.len() < FILE_HEADER_SIZE + SECTION_DESCRIPTOR_SIZE {
        return None;
    }
    let desc_off = FILE_HEADER_SIZE;
    let desc = &data[desc_off..desc_off + SECTION_DESCRIPTOR_SIZE];
    let type_end = desc[..16].iter().position(|&b| b == 0).unwrap_or(16);
    if &desc[..type_end] != b"header" {
        return None;
    }
    let section_size = u64::from_le_bytes(desc[24..32].try_into().unwrap()) as usize;
    let body_start = desc_off + SECTION_DESCRIPTOR_SIZE;
    let body_end = (desc_off + section_size).min(data.len());
    if body_start >= body_end {
        return None;
    }
    let compressed = &data[body_start..body_end];

    let mut decoder = ZlibDecoder::new(compressed);
    let mut text = String::new();
    decoder.read_to_string(&mut text).ok()?;

    parse_header_text(&text)
}

fn parse_header_text(text: &str) -> Option<EwfHeaderMetadata> {
    // Format (CRLF or LF line endings):
    //   line 0: "1"
    //   line 1: "main"
    //   line 2: tab-delimited key names
    //   line 3: tab-delimited values
    let lines: Vec<&str> = text
        .lines()
        .map(|l| l.trim_end_matches('\r'))
        .filter(|l| !l.is_empty())
        .collect();
    if lines.len() < 4 {
        return None;
    }
    let keys: Vec<&str> = lines[2].split('\t').collect();
    let vals: Vec<&str> = lines[3].split('\t').collect();

    let mut meta = EwfHeaderMetadata {
        description: String::new(),
        case_number: String::new(),
        evidence_number: String::new(),
        examiner_name: String::new(),
        acquisition_date: String::new(),
        system_date: String::new(),
        password_hash: String::new(),
        acquisition_software: String::new(),
    };

    for (i, &key) in keys.iter().enumerate() {
        let val = vals.get(i).copied().unwrap_or("").to_owned();
        match key {
            "a" => meta.description = val,
            "c" => meta.case_number = val,
            "e" => meta.evidence_number = val,
            "t" => meta.examiner_name = val,
            "m" => meta.acquisition_date = val,
            "u" => meta.system_date = val,
            "p" => meta.password_hash = val,
            "r" => meta.acquisition_software = val,
            _ => {}
        }
    }

    Some(meta)
}

struct Section {
    type_name: String,
    offset: u64,
    size: u64,
}

struct VolumeGeometry {
    chunk_count: u32,
    sectors_per_chunk: u32,
    bytes_per_sector: u32,
    sector_count: u64,
    /// set_identifier GUID from ewf_data_t[64..80]; all-zero = not present.
    set_identifier: [u8; 16],
}

fn walk_sections_v1(data: &[u8], issues: &mut Vec<EwfIntegrityAnomaly>) -> Vec<Section> {
    let file_size = data.len() as u64;
    let mut sections = Vec::new();
    let mut pos = FILE_HEADER_SIZE as u64;

    loop {
        let off = pos as usize;
        if off + SECTION_DESCRIPTOR_SIZE > data.len() {
            break;
        }
        let desc = &data[off..off + SECTION_DESCRIPTOR_SIZE];

        let type_end = desc[..16].iter().position(|&b| b == 0).unwrap_or(16);
        let type_name = String::from_utf8_lossy(&desc[..type_end]).into_owned();

        let stored_crc = u32::from_le_bytes(desc[72..76].try_into().unwrap());
        let computed_crc = adler32(&desc[..72]);
        if computed_crc != stored_crc {
            issues.push(EwfIntegrityAnomaly::SectionDescriptorCrcMismatch {
                offset: pos,
                section_type: type_name.clone(),
                computed: computed_crc,
                stored: stored_crc,
            });
        }

        if !KNOWN_TYPES.contains(&type_name.as_str()) {
            issues.push(EwfIntegrityAnomaly::UnknownSectionType {
                offset: pos,
                type_name: type_name.clone(),
            });
        }

        let next = u64::from_le_bytes(desc[16..24].try_into().unwrap());
        let section_size = u64::from_le_bytes(desc[24..32].try_into().unwrap());
        let section_end = pos.saturating_add(section_size);

        sections.push(Section {
            type_name: type_name.clone(),
            offset: pos,
            size: section_size,
        });

        // "done" and "next" both terminate a segment's chain
        if type_name == "done" || type_name == "next" {
            break;
        }

        if next == 0 || next > file_size || next <= pos {
            issues.push(EwfIntegrityAnomaly::SectionChainBroken {
                at_offset: pos,
                next_offset: next,
            });
            break;
        }

        if next > section_end {
            let gap_offset = section_end;
            let gap_size = next - section_end;
            let non_zero = data
                .get(section_end as usize..next as usize)
                .map(|s| s.iter().any(|&b| b != 0))
                .unwrap_or(false);
            if non_zero {
                issues.push(EwfIntegrityAnomaly::SectionGapNonZero { gap_offset, gap_size });
            } else {
                issues.push(EwfIntegrityAnomaly::SectionGapZero { gap_offset, gap_size });
            }
        }

        pos = next;
    }

    sections
}

fn check_volume_v1(
    data: &[u8],
    desc_offset: u64,
    section_size: u64,
    issues: &mut Vec<EwfIntegrityAnomaly>,
) -> Option<VolumeGeometry> {
    let data_start = (desc_offset as usize) + SECTION_DESCRIPTOR_SIZE;
    if data.len() < data_start + VOLUME_DATA_MIN {
        return None;
    }
    let body_len = (section_size as usize).saturating_sub(SECTION_DESCRIPTOR_SIZE);
    let vol_end = (data_start + body_len).min(data.len());
    let vol = &data[data_start..vol_end];

    // media_type: byte 0 of ewf_data_t (valid: 0x00/0x01/0x03/0x0e/0x10)
    let media_type = vol[0];
    if !VALID_MEDIA_TYPES.contains(&media_type) {
        issues.push(EwfIntegrityAnomaly::MediaTypeUnknown { media_type });
    }

    let chunk_count = u32::from_le_bytes(vol[4..8].try_into().unwrap());
    let sectors_per_chunk = u32::from_le_bytes(vol[8..12].try_into().unwrap());
    let bytes_per_sector = u32::from_le_bytes(vol[12..16].try_into().unwrap());
    let sector_count = u64::from_le_bytes(vol[16..24].try_into().unwrap());

    if bytes_per_sector != 512 && bytes_per_sector != 4096 {
        issues.push(EwfIntegrityAnomaly::BytesPerSectorInvalid { bytes_per_sector });
    }
    if sectors_per_chunk == 0 || !sectors_per_chunk.is_power_of_two() {
        issues.push(EwfIntegrityAnomaly::ChunkSizeInvalid {
            sectors_per_chunk,
            bytes_per_sector,
        });
    }

    let max_sectors = u64::from(chunk_count) * u64::from(sectors_per_chunk);
    let min_sectors = max_sectors.saturating_sub(u64::from(sectors_per_chunk));
    if sectors_per_chunk.is_power_of_two() {
        let out_of_range =
            sector_count > max_sectors || (chunk_count > 0 && sector_count <= min_sectors);
        if out_of_range {
            issues.push(EwfIntegrityAnomaly::SectorCountMismatch {
                declared: sector_count,
                expected: max_sectors,
            });
        }
    }

    // set_identifier GUID at ewf_data_t[64..80]
    let set_identifier: [u8; 16] = if vol.len() >= 80 {
        vol[64..80].try_into().unwrap()
    } else {
        [0u8; 16]
    };

    // Adler-32 of ewf_data_t bytes 0..1048 stored at bytes 1048..1052.
    // Only present when the section body is ≥ VOLUME_DATA_FULL (1052) bytes.
    if vol.len() >= VOLUME_DATA_FULL {
        let stored_crc = u32::from_le_bytes(vol[1048..1052].try_into().unwrap());
        let computed_crc = adler32(&vol[..1048]);
        if computed_crc != stored_crc {
            issues.push(EwfIntegrityAnomaly::VolumeBodyCrcMismatch {
                computed: computed_crc,
                stored: stored_crc,
            });
        }
    }

    Some(VolumeGeometry {
        chunk_count,
        sectors_per_chunk,
        bytes_per_sector,
        sector_count,
        set_identifier,
    })
}

fn check_table_v1(
    data: &[u8],
    desc_offset: u64,
    volume_chunk_count: Option<u32>,
    file_size: u64,
    sectors_range: Option<(u64, u64)>,
    issues: &mut Vec<EwfIntegrityAnomaly>,
) {
    let data_start = (desc_offset as usize) + SECTION_DESCRIPTOR_SIZE;
    if data.len() < data_start + 24 {
        return;
    }
    let tbl = &data[data_start..];
    let entry_count = u32::from_le_bytes(tbl[0..4].try_into().unwrap());
    let base_offset = u64::from_le_bytes(tbl[8..16].try_into().unwrap());

    // Table header Adler-32: covers bytes [0..16], stored at [16..20].
    // When stored = 0 the writer chose not to include the checksum; skip check.
    let stored_crc = u32::from_le_bytes(tbl[16..20].try_into().unwrap());
    if stored_crc != 0 {
        let computed_crc = adler32(&tbl[..16]);
        if computed_crc != stored_crc {
            issues.push(EwfIntegrityAnomaly::TableHeaderAdler32Mismatch {
                computed: computed_crc,
                stored: stored_crc,
            });
        }
    }

    if let Some(vol_count) = volume_chunk_count {
        if entry_count != vol_count {
            issues.push(EwfIntegrityAnomaly::TableChunkCountMismatch {
                in_volume: vol_count,
                in_table: entry_count,
            });
        }
    }

    let entries_start = data_start + 24;
    for i in 0..entry_count {
        let entry_off = entries_start + (i as usize) * 4;
        if entry_off + 4 > data.len() {
            break;
        }
        let raw = u32::from_le_bytes(data[entry_off..entry_off + 4].try_into().unwrap());
        let chunk_rel = u64::from(raw & 0x7FFF_FFFF);
        let absolute = base_offset.saturating_add(chunk_rel);
        if absolute >= file_size {
            issues.push(EwfIntegrityAnomaly::TableEntryOutOfBounds {
                chunk_index: i,
                entry_offset: absolute,
                file_size,
            });
        } else if let Some((sec_start, sec_end)) = sectors_range {
            if absolute < sec_start || absolute >= sec_end {
                issues.push(EwfIntegrityAnomaly::TableEntryOutsideSectorsRange {
                    chunk_index: i,
                    entry_offset: absolute,
                    sectors_start: sec_start,
                    sectors_end: sec_end,
                });
            }
        }
    }
}

/// Extract `(chunk_start, chunk_end, compressed)` for every chunk in one segment's table.
fn iter_segment_chunks(data: &[u8], sections: &[Section]) -> Vec<(usize, usize, bool)> {
    let table = match sections.iter().find(|s| s.type_name == "table") {
        Some(s) => s,
        None => return Vec::new(),
    };
    let sectors = match sections.iter().find(|s| s.type_name == "sectors") {
        Some(s) => s,
        None => return Vec::new(),
    };

    let tbl_data_start = (table.offset as usize) + SECTION_DESCRIPTOR_SIZE;
    if data.len() < tbl_data_start + 24 {
        return Vec::new();
    }
    let tbl = &data[tbl_data_start..];
    let entry_count = u32::from_le_bytes(tbl[0..4].try_into().unwrap()) as usize;
    let base_offset = u64::from_le_bytes(tbl[8..16].try_into().unwrap()) as usize;
    let entries_start = tbl_data_start + 24;
    let sectors_body_end = (sectors.offset + sectors.size) as usize;

    let mut chunks = Vec::with_capacity(entry_count);
    for i in 0..entry_count {
        let entry_off = entries_start + i * 4;
        if entry_off + 4 > data.len() {
            break;
        }
        let raw = u32::from_le_bytes(data[entry_off..entry_off + 4].try_into().unwrap());
        let compressed = raw & 0x8000_0000 != 0;
        let rel = (raw & 0x7FFF_FFFF) as usize;
        let start = base_offset + rel;

        let end = if i + 1 < entry_count {
            let next_off = entries_start + (i + 1) * 4;
            if next_off + 4 > data.len() {
                break;
            }
            let next_raw = u32::from_le_bytes(data[next_off..next_off + 4].try_into().unwrap());
            let next_rel = (next_raw & 0x7FFF_FFFF) as usize;
            base_offset + next_rel
        } else {
            sectors_body_end.min(data.len())
        };

        if start >= end || end > data.len() {
            break;
        }
        chunks.push((start, end, compressed));
    }
    chunks
}

/// Hash all chunk data across all segments, verify against stored and external hashes.
fn check_hash_all_segments(
    segments: &[&[u8]],
    all_sections: &[Vec<Section>],
    geom: &VolumeGeometry,
    expected_md5: Option<[u8; 16]>,
    expected_sha1: Option<[u8; 20]>,
    expected_sha256: Option<[u8; 32]>,
    issues: &mut Vec<EwfIntegrityAnomaly>,
    progress: &mut dyn FnMut(AnalysisProgress),
) {
    let chunk_size = u64::from(geom.sectors_per_chunk) * u64::from(geom.bytes_per_sector);
    let total_bytes = geom.sector_count * u64::from(geom.bytes_per_sector);
    let mut bytes_remaining = total_bytes;

    let mut md5_h = Md5::new();
    let mut sha1_h = Sha1::new();
    let mut sha256_h = Sha256::new();

    let chunk_size_usize = chunk_size as usize;
    let mut global_chunk_idx: usize = 0;

    'outer: for (&seg_data, sections) in segments.iter().zip(all_sections.iter()) {
        for (start, end, compressed) in iter_segment_chunks(seg_data, sections) {
            if bytes_remaining == 0 {
                break 'outer;
            }
            let to_hash = bytes_remaining.min(chunk_size) as usize;
            let raw = &seg_data[start..end];

            // Per-chunk Adler-32 (ewfverify parity).
            //
            // Compressed chunks are self-checksummed by the zlib stream (RFC 1950
            // appends its own big-endian Adler-32 internally); decompression failure
            // already catches corruption via the HashMismatch path.
            //
            // Uncompressed chunks MAY have a separate 4-byte little-endian Adler-32
            // appended by the acquisition tool. Presence is detected by
            // raw.len() > chunk_size (the chunk byte range includes extra bytes).
            let this_chunk_idx = global_chunk_idx;
            global_chunk_idx += 1;

            let has_uncompressed_checksum = !compressed && (raw.len() > chunk_size_usize);
            if has_uncompressed_checksum && raw.len() >= chunk_size_usize + 4 {
                let crc_end = chunk_size_usize;
                let stored = u32::from_le_bytes(raw[crc_end..crc_end + 4].try_into().unwrap());
                let computed = adler32(&raw[..crc_end]);
                if computed != stored {
                    issues.push(EwfIntegrityAnomaly::ChunkChecksumMismatch {
                        chunk_index: this_chunk_idx,
                        computed,
                        stored,
                    });
                }
            }

            if compressed {
                let limit = (to_hash as u64).saturating_add(1);
                let mut decompressed = Vec::with_capacity(to_hash);
                if ZlibDecoder::new(raw)
                    .take(limit)
                    .read_to_end(&mut decompressed)
                    .is_err()
                {
                    issues.push(EwfIntegrityAnomaly::ChunkDecompressionError {
                        chunk_index: this_chunk_idx,
                    });
                    bytes_remaining = bytes_remaining.saturating_sub(to_hash as u64);
                    continue;
                }
                let slice = &decompressed[..decompressed.len().min(to_hash)];
                md5_h.update(slice);
                sha1_h.update(slice);
                sha256_h.update(slice);
            } else {
                // For uncompressed chunks with trailing checksum, raw.len() = chunk_size + 4;
                // hash only the sector data (to_hash bytes), not the trailing checksum.
                let slice = &raw[..raw.len().min(to_hash)];
                md5_h.update(slice);
                sha1_h.update(slice);
                sha256_h.update(slice);
            }
            bytes_remaining = bytes_remaining.saturating_sub(to_hash as u64);
            progress(AnalysisProgress {
                chunks_done: global_chunk_idx,
                chunks_total: None,
                bytes_done: total_bytes - bytes_remaining,
            });
        }
    }

    let computed_md5: [u8; 16] = md5_h.finalize().into();
    let computed_sha1: [u8; 20] = sha1_h.finalize().into();
    let computed_sha256: [u8; 32] = sha256_h.finalize().into();

    let last_sections = match all_sections.last() {
        Some(s) => s,
        None => return,
    };
    let last_data = match segments.last() {
        Some(d) => d,
        None => return,
    };

    // Stored MD5 from the EWF hash section
    match last_sections.iter().find(|s| s.type_name == "hash") {
        Some(hash_sec) => {
            let body_start = (hash_sec.offset as usize) + SECTION_DESCRIPTOR_SIZE;
            if let Some(stored_slice) = last_data.get(body_start..body_start + 16) {
                let stored: [u8; 16] = stored_slice.try_into().unwrap();
                if computed_md5 != stored {
                    issues.push(EwfIntegrityAnomaly::HashMismatch {
                        computed: computed_md5,
                        stored,
                    });
                }
            }
        }
        None => issues.push(EwfIntegrityAnomaly::HashSectionMissing),
    }

    // Stored SHA-1 from the EWF digest section (layout: 16-byte MD5, then 20-byte SHA-1)
    if let Some(digest_sec) = last_sections.iter().find(|s| s.type_name == "digest") {
        let body_start = (digest_sec.offset as usize) + SECTION_DESCRIPTOR_SIZE;
        if let Some(sha1_slice) = last_data.get(body_start + 16..body_start + 36) {
            let stored: [u8; 20] = sha1_slice.try_into().unwrap();
            // All-zero stored SHA-1 means "not set" — skip comparison
            if stored != [0u8; 20] && computed_sha1 != stored {
                issues.push(EwfIntegrityAnomaly::DigestSha1Mismatch {
                    computed: computed_sha1,
                    stored,
                });
            }
        }
    }

    // External reference hashes (supplied by caller, e.g. from chain of custody)
    if let Some(expected) = expected_md5 {
        if computed_md5 != expected {
            issues.push(EwfIntegrityAnomaly::ExternalMd5Mismatch {
                computed: computed_md5,
                expected,
            });
        }
    }
    if let Some(expected) = expected_sha1 {
        if computed_sha1 != expected {
            issues.push(EwfIntegrityAnomaly::ExternalSha1Mismatch {
                computed: computed_sha1,
                expected,
            });
        }
    }
    if let Some(expected) = expected_sha256 {
        if computed_sha256 != expected {
            issues.push(EwfIntegrityAnomaly::ExternalSha256Mismatch {
                computed: computed_sha256,
                expected,
            });
        }
    }
}

/// Verify EWF v2 chunk data integrity and compare overall MD5 against stored value.
///
/// Chunk table entry layout (16 bytes each, starting at body offset 32):
///   [0..8]:   file_offset (u64 LE) — absolute position of chunk data in the file
///   [8..12]:  data_size (u32 LE) — raw_sector_bytes + 4 (Adler-32 trailer)
/// Attempt to zlib-decompress and UTF-16LE-decode a media_info section body.
///
/// Returns `true` if the body is a valid zlib stream that decodes as UTF-16LE
/// (with or without BOM), `false` on any failure.  An empty body is rejected.
fn parse_media_info_body(body: &[u8]) -> bool {
    if body.is_empty() {
        return false;
    }
    let mut decompressed = Vec::new();
    if ZlibDecoder::new(body).read_to_end(&mut decompressed).is_err() {
        return false;
    }
    // Strip BOM if present
    let text_bytes = if decompressed.starts_with(&[0xFF, 0xFE]) {
        &decompressed[2..]
    } else {
        &decompressed[..]
    };
    // Must be even-length for UTF-16LE
    if text_bytes.len() % 2 != 0 {
        return false;
    }
    let units: Vec<u16> = text_bytes
        .chunks_exact(2)
        .map(|b| u16::from_le_bytes([b[0], b[1]]))
        .collect();
    String::from_utf16(&units).is_ok()
}

///   [12..16]: flags (u32 LE) — bit 0: compressed (zlib); other bits: reserved
///
/// On-disk chunk layout: [sector_data: raw_size bytes][adler32: 4 bytes][alignment pad]
fn verify_ewf2_sector_data(
    data: &[u8],
    ct_start: usize,
    ct_end: usize,
    stored_md5: Option<[u8; 16]>,
    stored_sha1: Option<[u8; 20]>,
    stored_sha256: Option<[u8; 32]>,
    issues: &mut Vec<EwfIntegrityAnomaly>,
    progress: &mut dyn FnMut(AnalysisProgress),
) -> Option<ComputedHashes> {
    let tbl = match data.get(ct_start..ct_end) {
        Some(t) => t,
        None => return None,
    };
    if tbl.len() < EVF2_CHUNK_TABLE_HEADER_SIZE + EVF2_CHUNK_TABLE_ENTRY_SIZE {
        return None;
    }
    let chunk_count = u64::from_le_bytes(tbl[8..16].try_into().unwrap()) as usize;

    // Chunk table Adler-32: covers entries[0..chunk_count] immediately after the header.
    let checksum_off = EVF2_CHUNK_TABLE_HEADER_SIZE + chunk_count * EVF2_CHUNK_TABLE_ENTRY_SIZE;
    if checksum_off + 4 <= tbl.len() {
        let computed_cs = adler32(&tbl[EVF2_CHUNK_TABLE_HEADER_SIZE..checksum_off]);
        let stored_cs = u32::from_le_bytes(tbl[checksum_off..checksum_off + 4].try_into().unwrap());
        if computed_cs != stored_cs {
            issues.push(EwfIntegrityAnomaly::Ewf2ChunkTableChecksumMismatch {
                computed: computed_cs,
                stored: stored_cs,
            });
        }
    }

    let mut md5_h   = Md5::new();
    let mut sha1_h  = Sha1::new();
    let mut sha256_h = Sha256::new();

    for i in 0..chunk_count {
        let entry_off = EVF2_CHUNK_TABLE_HEADER_SIZE + i * EVF2_CHUNK_TABLE_ENTRY_SIZE;
        if entry_off + EVF2_CHUNK_TABLE_ENTRY_SIZE > tbl.len() {
            break;
        }
        let file_offset = u64::from_le_bytes(tbl[entry_off..entry_off + 8].try_into().unwrap()) as usize;
        let chunk_data_size = u32::from_le_bytes(tbl[entry_off + 8..entry_off + 12].try_into().unwrap()) as usize;
        let flags = u32::from_le_bytes(tbl[entry_off + 12..entry_off + 16].try_into().unwrap());

        // data_size includes a 4-byte Adler-32 trailer; raw sector data precedes it.
        let raw_size = chunk_data_size.saturating_sub(4);
        let chunk_raw = match data.get(file_offset..file_offset + raw_size) {
            Some(r) => r,
            None => break,
        };

        // Per-chunk Adler-32
        if chunk_data_size >= 4 {
            if let Some(crc_bytes) = data.get(file_offset + raw_size..file_offset + raw_size + 4) {
                let stored_crc = u32::from_le_bytes(crc_bytes.try_into().unwrap());
                let computed_crc = adler32(chunk_raw);
                if computed_crc != stored_crc {
                    issues.push(EwfIntegrityAnomaly::ChunkChecksumMismatch {
                        chunk_index: i,
                        computed: computed_crc,
                        stored: stored_crc,
                    });
                }
            }
        }

        if flags & EVF2_CHUNK_FLAG_COMPRESSED != 0 {
            // Zlib-compressed chunk: decompress before hashing.
            let mut decompressed = Vec::with_capacity(raw_size);
            if ZlibDecoder::new(chunk_raw)
                .read_to_end(&mut decompressed)
                .is_err()
            {
                issues.push(EwfIntegrityAnomaly::ChunkDecompressionError { chunk_index: i });
                continue;
            }
            md5_h.update(&decompressed);
            sha1_h.update(&decompressed);
            sha256_h.update(&decompressed);
        } else {
            md5_h.update(chunk_raw);
            sha1_h.update(chunk_raw);
            sha256_h.update(chunk_raw);
        }
        progress(AnalysisProgress {
            chunks_done: i + 1,
            chunks_total: Some(chunk_count),
            bytes_done: ((i + 1) * raw_size) as u64,
        });
    }

    let computed_md5:    [u8; 16] = md5_h.finalize().into();
    let computed_sha1:   [u8; 20] = sha1_h.finalize().into();
    let computed_sha256: [u8; 32] = sha256_h.finalize().into();

    if let Some(stored) = stored_md5 {
        if computed_md5 != stored {
            issues.push(EwfIntegrityAnomaly::HashMismatch { computed: computed_md5, stored });
        }
    }

    if let Some(stored) = stored_sha1 {
        if computed_sha1 != stored {
            issues.push(EwfIntegrityAnomaly::DigestSha1Mismatch {
                computed: computed_sha1,
                stored,
            });
        }
    }

    if let Some(stored) = stored_sha256 {
        if computed_sha256 != stored {
            issues.push(EwfIntegrityAnomaly::DigestSha256Mismatch {
                computed: computed_sha256,
                stored,
            });
        }
    }

    Some(ComputedHashes { md5: computed_md5, sha1: computed_sha1, sha256: computed_sha256 })
}

/// Extract sector-data hashes from EWF v2 segments without full anomaly checking.
fn compute_hashes_ewf2(segments: &[&[u8]]) -> Option<ComputedHashes> {
    let mut md5_h   = Md5::new();
    let mut sha1_h  = Sha1::new();
    let mut sha256_h = Sha256::new();
    let mut found_chunks = false;

    for &data in segments {
        if data.len() < EVF2_FILE_HEADER_SIZE + EVF2_SECTION_DESCRIPTOR_SIZE {
            continue;
        }

        // Walk backward to find the chunk table section.
        let mut desc_offset = data.len().saturating_sub(EVF2_SECTION_DESCRIPTOR_SIZE);
        let mut chunk_table_body: Option<(usize, usize)> = None;

        loop {
            if desc_offset + EVF2_SECTION_DESCRIPTOR_SIZE > data.len()
                || desc_offset < EVF2_FILE_HEADER_SIZE
            {
                break;
            }
            let desc = &data[desc_offset..desc_offset + EVF2_SECTION_DESCRIPTOR_SIZE];
            let section_type = u32::from_le_bytes(desc[0..4].try_into().unwrap());
            let data_flags   = u32::from_le_bytes(desc[4..8].try_into().unwrap());
            let prev_offset  = u64::from_le_bytes(desc[8..16].try_into().unwrap()) as usize;
            let data_size    = u64::from_le_bytes(desc[16..24].try_into().unwrap()) as usize;
            let body_end   = desc_offset;
            let body_start = desc_offset.saturating_sub(data_size);

            if data_flags & EVF2_DATA_FLAG_ENCRYPTED == 0
                && section_type == EVF2_TYPE_CHUNK_TABLE
            {
                chunk_table_body = Some((body_start, body_end));
            }

            if prev_offset == 0 { break; }
            desc_offset = prev_offset;
        }

        let (ct_start, ct_end) = match chunk_table_body {
            Some(b) => b,
            None => continue,
        };
        let tbl = match data.get(ct_start..ct_end) {
            Some(t) => t,
            None => continue,
        };
        if tbl.len() < EVF2_CHUNK_TABLE_HEADER_SIZE + EVF2_CHUNK_TABLE_ENTRY_SIZE {
            continue;
        }
        let chunk_count = u64::from_le_bytes(tbl[8..16].try_into().unwrap()) as usize;

        for i in 0..chunk_count {
            let entry_off = EVF2_CHUNK_TABLE_HEADER_SIZE + i * EVF2_CHUNK_TABLE_ENTRY_SIZE;
            if entry_off + EVF2_CHUNK_TABLE_ENTRY_SIZE > tbl.len() { break; }
            let file_offset = u64::from_le_bytes(tbl[entry_off..entry_off + 8].try_into().unwrap()) as usize;
            let chunk_data_size = u32::from_le_bytes(tbl[entry_off + 8..entry_off + 12].try_into().unwrap()) as usize;
            let flags = u32::from_le_bytes(tbl[entry_off + 12..entry_off + 16].try_into().unwrap());
            let raw_size = chunk_data_size.saturating_sub(4);
            let chunk_raw = match data.get(file_offset..file_offset + raw_size) {
                Some(r) => r,
                None => break,
            };

            if flags & EVF2_CHUNK_FLAG_COMPRESSED != 0 {
                let mut decompressed = Vec::with_capacity(raw_size);
                if ZlibDecoder::new(chunk_raw)
                    .read_to_end(&mut decompressed)
                    .is_err()
                {
                    continue;
                }
                md5_h.update(&decompressed);
                sha1_h.update(&decompressed);
                sha256_h.update(&decompressed);
            } else {
                md5_h.update(chunk_raw);
                sha1_h.update(chunk_raw);
                sha256_h.update(chunk_raw);
            }
            found_chunks = true;
        }
    }

    if !found_chunks {
        return None;
    }
    Some(ComputedHashes {
        md5:    md5_h.finalize().into(),
        sha1:   sha1_h.finalize().into(),
        sha256: sha256_h.finalize().into(),
    })
}

/// Hash all sector data from EWF v1 segments without running anomaly checks.
/// This is the independent computation path for `compute_hashes()`.
fn compute_hashes_ewf1(segments: &[&[u8]]) -> Option<ComputedHashes> {
    let first = segments.first().copied()?;
    if first.len() < FILE_HEADER_SIZE {
        return None;
    }
    if first[0..8] != EVF_SIGNATURE && first[0..8] != DVF_SIGNATURE && first[0..8] != LVF_SIGNATURE {
        return None;
    }

    let mut dummy = Vec::new();
    let sections_first = walk_sections_v1(first, &mut dummy);
    let vol_sec = sections_first
        .iter()
        .find(|s| s.type_name == "volume" || s.type_name == "disk")?;
    let geom = check_volume_v1(first, vol_sec.offset, vol_sec.size, &mut dummy)?;

    let chunk_size = u64::from(geom.sectors_per_chunk) * u64::from(geom.bytes_per_sector);
    let total_bytes = geom.sector_count * u64::from(geom.bytes_per_sector);
    let mut bytes_remaining = total_bytes;

    let mut md5_h = Md5::new();
    let mut sha1_h = Sha1::new();
    let mut sha256_h = Sha256::new();

    let mut all_sections: Vec<Vec<Section>> = Vec::new();
    for &seg in segments {
        let mut d = Vec::new();
        all_sections.push(walk_sections_v1(seg, &mut d));
    }

    'outer: for (&seg_data, sections) in segments.iter().zip(all_sections.iter()) {
        for (start, end, compressed) in iter_segment_chunks(seg_data, sections) {
            if bytes_remaining == 0 {
                break 'outer;
            }
            let to_hash = bytes_remaining.min(chunk_size) as usize;
            let raw = &seg_data[start..end];

            if compressed {
                let limit = (to_hash as u64).saturating_add(1);
                let mut decompressed = Vec::with_capacity(to_hash);
                if ZlibDecoder::new(raw)
                    .take(limit)
                    .read_to_end(&mut decompressed)
                    .is_err()
                {
                    bytes_remaining = bytes_remaining.saturating_sub(to_hash as u64);
                    continue;
                }
                let slice = &decompressed[..decompressed.len().min(to_hash)];
                md5_h.update(slice);
                sha1_h.update(slice);
                sha256_h.update(slice);
            } else {
                let slice = &raw[..raw.len().min(to_hash)];
                md5_h.update(slice);
                sha1_h.update(slice);
                sha256_h.update(slice);
            }
            bytes_remaining = bytes_remaining.saturating_sub(to_hash as u64);
        }
    }

    Some(ComputedHashes {
        md5: md5_h.finalize().into(),
        sha1: sha1_h.finalize().into(),
        sha256: sha256_h.finalize().into(),
    })
}

pub(crate) fn adler32(data: &[u8]) -> u32 {
    const MOD: u32 = 65521;
    let mut s1: u32 = 1;
    let mut s2: u32 = 0;
    for &b in data {
        s1 = (s1 + u32::from(b)) % MOD;
        s2 = (s2 + s1) % MOD;
    }
    (s2 << 16) | s1
}


impl EwfIntegrityAnomaly {
    /// Stable, scheme-prefixed machine code for this anomaly.
    #[must_use]
    pub fn code(&self) -> &'static str {
        match self {
            Self::InvalidSignature => "EWF-INVALID-SIGNATURE",
            Self::SegmentNumberZero => "EWF-SEGMENT-NUMBER-ZERO",
            Self::SectionDescriptorCrcMismatch { .. } => "EWF-SECTION-DESCRIPTOR-CRC-MISMATCH",
            Self::SectionChainBroken { .. } => "EWF-SECTION-CHAIN-BROKEN",
            Self::SectionGapNonZero { .. } => "EWF-SECTION-GAP-NON-ZERO",
            Self::VolumeSectionMissing => "EWF-VOLUME-SECTION-MISSING",
            Self::UnknownSectionType { .. } => "EWF-UNKNOWN-SECTION-TYPE",
            Self::DoneSectionMissing => "EWF-DONE-SECTION-MISSING",
            Self::SectorsSectionMissing => "EWF-SECTORS-SECTION-MISSING",
            Self::TableSectionMissing => "EWF-TABLE-SECTION-MISSING",
            Self::ChunkSizeInvalid { .. } => "EWF-CHUNK-SIZE-INVALID",
            Self::SectorCountMismatch { .. } => "EWF-SECTOR-COUNT-MISMATCH",
            Self::BytesPerSectorInvalid { .. } => "EWF-BYTES-PER-SECTOR-INVALID",
            Self::TableChunkCountMismatch { .. } => "EWF-TABLE-CHUNK-COUNT-MISMATCH",
            Self::TableHeaderAdler32Mismatch { .. } => "EWF-TABLE-HEADER-ADLER32-MISMATCH",
            Self::TableEntryOutOfBounds { .. } => "EWF-TABLE-ENTRY-OUT-OF-BOUNDS",
            Self::TableEntryOutsideSectorsRange { .. } => "EWF-TABLE-ENTRY-OUTSIDE-SECTORS-RANGE",
            Self::SectionGapZero { .. } => "EWF-SECTION-GAP-ZERO",
            Self::HashMismatch { .. } => "EWF-HASH-MISMATCH",
            Self::HashSectionMissing => "EWF-HASH-SECTION-MISSING",
            Self::Table2Mismatch { .. } => "EWF-TABLE2-MISMATCH",
            Self::BadSectorsPresent { .. } => "EWF-BAD-SECTORS-PRESENT",
            Self::SegmentOutOfOrder { .. } => "EWF-SEGMENT-OUT-OF-ORDER",
            Self::DigestSha1Mismatch { .. } => "EWF-DIGEST-SHA1-MISMATCH",
            Self::DigestSha256Mismatch { .. } => "EWF-DIGEST-SHA256-MISMATCH",
            Self::ExternalMd5Mismatch { .. } => "EWF-EXTERNAL-MD5-MISMATCH",
            Self::ExternalSha1Mismatch { .. } => "EWF-EXTERNAL-SHA1-MISMATCH",
            Self::Ewf2SectionDataHashMismatch { .. } => "EWF-EWF2-SECTION-DATA-HASH-MISMATCH",
            Self::Ewf2EncryptedSection { .. } => "EWF-EWF2-ENCRYPTED-SECTION",
            Self::Ewf2HashSectionMissing => "EWF-EWF2-HASH-SECTION-MISSING",
            Self::VolumeBodyCrcMismatch { .. } => "EWF-VOLUME-BODY-CRC-MISMATCH",
            Self::MediaTypeUnknown { .. } => "EWF-MEDIA-TYPE-UNKNOWN",
            Self::SetIdentifierMismatch { .. } => "EWF-SET-IDENTIFIER-MISMATCH",
            Self::Ewf2MediaInfoMissing => "EWF-EWF2-MEDIA-INFO-MISSING",
            Self::Ewf2ChunkTableChecksumMismatch { .. } => "EWF-EWF2-CHUNK-TABLE-CHECKSUM-MISMATCH",
            Self::ChunkChecksumMismatch { .. } => "EWF-CHUNK-CHECKSUM-MISMATCH",
            Self::ChunkDecompressionError { .. } => "EWF-CHUNK-DECOMPRESSION-ERROR",
            Self::UnsupportedCompressionAlgorithm { .. } => "EWF-UNSUPPORTED-COMPRESSION-ALGORITHM",
            Self::ExternalSha256Mismatch { .. } => "EWF-EXTERNAL-SHA256-MISMATCH",
            Self::Ewf2MediaInfoParseFailed => "EWF-EWF2-MEDIA-INFO-PARSE-FAILED",
        }
    }
}

impl forensicnomicon::report::Observation for EwfIntegrityAnomaly {
    fn severity(&self) -> Option<Severity> {
        Some(self.severity())
    }
    fn code(&self) -> &'static str {
        self.code()
    }
    fn note(&self) -> String {
        self.to_string()
    }
}