ext4fs-core 0.2.3

Forensic-grade ext4 filesystem parser
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
#![forbid(unsafe_code)]

pub mod block;
pub mod dir;
pub mod error;
pub mod forensic;
pub mod inode;
pub mod ondisk;
#[cfg(feature = "vfs")]
pub mod vfs;

use block::BlockReader;
use dir::DirReader;
use error::Result;
use inode::InodeReader;
use ondisk::{DirEntry, Inode, Superblock, Timestamp};
use std::io::{Read, Seek};

/// Full inode metadata for the public API.
#[derive(Debug, Clone)]
pub struct InodeMetadata {
    pub ino: u64,
    pub file_type: ondisk::FileType,
    pub mode: u16,
    pub uid: u32,
    pub gid: u32,
    pub size: u64,
    pub links_count: u16,
    pub atime: Timestamp,
    pub mtime: Timestamp,
    pub ctime: Timestamp,
    pub crtime: Timestamp,
    pub dtime: u32,
    pub flags: ondisk::InodeFlags,
    pub generation: u32,
    pub allocated: bool,
}

/// Forensic-grade ext4 filesystem reader.
///
/// Accepts any `Read + Seek` source (raw image file, EWF reader, etc.).
/// Provides both standard filesystem access (tier 1) and forensic operations (tier 2).
pub struct Ext4Fs<R: Read + Seek> {
    dir_reader: DirReader<R>,
}

impl<R: Read + Seek> Ext4Fs<R> {
    /// Open an ext4 filesystem from a Read+Seek source.
    pub fn open(source: R) -> Result<Self> {
        let block_reader = BlockReader::open(source)?;
        let inode_reader = InodeReader::new(block_reader);
        let dir_reader = DirReader::new(inode_reader);
        Ok(Ext4Fs { dir_reader })
    }

    // --- Tier 1: Standard filesystem access ---

    /// Reference to the superblock.
    pub fn superblock(&self) -> &Superblock {
        self.dir_reader.inode_reader().block_reader().superblock()
    }

    /// Read a file's contents by path.
    pub fn read_file(&mut self, path: &str) -> Result<Vec<u8>> {
        let ino = self.dir_reader.resolve_path(path)?;
        self.dir_reader.inode_reader_mut().read_inode_data(ino)
    }

    /// List directory entries by path.
    pub fn read_dir(&mut self, path: &str) -> Result<Vec<DirEntry>> {
        let ino = self.dir_reader.resolve_path(path)?;
        self.dir_reader.read_dir(ino)
    }

    /// Get full metadata for a path.
    pub fn metadata(&mut self, path: &str) -> Result<InodeMetadata> {
        let ino = self.dir_reader.resolve_path(path)?;
        let inode = self.dir_reader.inode_reader_mut().read_inode(ino)?;
        let allocated = self.dir_reader.inode_reader_mut().is_inode_allocated(ino)?;
        Ok(InodeMetadata {
            ino,
            file_type: inode.file_type(),
            mode: inode.mode,
            uid: inode.uid,
            gid: inode.gid,
            size: inode.size,
            links_count: inode.links_count,
            atime: inode.atime,
            mtime: inode.mtime,
            ctime: inode.ctime,
            crtime: inode.crtime,
            dtime: inode.dtime,
            flags: inode.flags,
            generation: inode.generation,
            allocated,
        })
    }

    /// Read a symlink's target by path.
    pub fn symlink_target(&mut self, path: &str) -> Result<Vec<u8>> {
        let ino = self.dir_reader.resolve_path(path)?;
        self.dir_reader.read_link(ino)
    }

    /// Check if a path exists.
    pub fn exists(&mut self, path: &str) -> Result<bool> {
        match self.dir_reader.resolve_path(path) {
            Ok(_) => Ok(true),
            Err(error::Ext4Error::PathNotFound(_)) => Ok(false),
            Err(e) => Err(e),
        }
    }

    // --- Tier 1b: Inode-based access (for FUSE) ---

    /// List directory entries by inode number.
    pub fn read_dir_by_ino(&mut self, dir_ino: u64) -> Result<Vec<DirEntry>> {
        self.dir_reader.read_dir(dir_ino)
    }

    /// Lookup a name inside a directory by inode number.
    pub fn lookup_by_ino(&mut self, dir_ino: u64, name: &[u8]) -> Result<Option<u64>> {
        self.dir_reader.lookup(dir_ino, name)
    }

    /// Read symlink target by inode number.
    pub fn read_link_by_ino(&mut self, ino: u64) -> Result<Vec<u8>> {
        self.dir_reader.read_link(ino)
    }

    /// Read file data by inode number.
    pub fn read_inode_data(&mut self, ino: u64) -> Result<Vec<u8>> {
        self.dir_reader.inode_reader_mut().read_inode_data(ino)
    }

    /// Read a range of file data by inode number.
    pub fn read_inode_data_range(&mut self, ino: u64, offset: u64, len: usize) -> Result<Vec<u8>> {
        self.dir_reader
            .inode_reader_mut()
            .read_inode_data_range(ino, offset, len)
    }

    // --- Tier 2: Forensic access ---

    /// Read any inode by number.
    pub fn inode(&mut self, ino: u64) -> Result<Inode> {
        self.dir_reader.inode_reader_mut().read_inode(ino)
    }

    /// Enumerate all inodes (allocated and deleted).
    pub fn all_inodes(&mut self) -> Result<Vec<(u64, Inode)>> {
        self.dir_reader.inode_reader_mut().iter_all_inodes()
    }

    /// Find all deleted inodes (dtime != 0).
    pub fn deleted_inodes(&mut self) -> Result<Vec<forensic::DeletedInode>> {
        forensic::find_deleted_inodes(self.dir_reader.inode_reader_mut())
    }

    /// Find all orphan inodes (links_count == 0, dtime == 0, mode != 0).
    pub fn orphan_inodes(&mut self) -> Result<Vec<forensic::DeletedInode>> {
        forensic::find_orphan_inodes(self.dir_reader.inode_reader_mut())
    }

    /// Attempt to recover a deleted file by inode number.
    pub fn recover_file(&mut self, ino: u64) -> Result<forensic::RecoveryResult> {
        forensic::recovery::recover_file(self.dir_reader.inode_reader_mut(), ino)
    }

    /// Parse the jbd2 journal.
    pub fn journal(&mut self) -> Result<forensic::Journal> {
        forensic::journal::parse_journal(self.dir_reader.inode_reader_mut())
    }

    /// Generate a forensic timeline of all filesystem events.
    pub fn timeline(&mut self) -> Result<Vec<forensic::TimelineEvent>> {
        forensic::timeline::generate_timeline(self.dir_reader.inode_reader_mut())
    }

    /// Read block-stored extended attributes for an inode.
    pub fn xattrs(&mut self, ino: u64) -> Result<Vec<forensic::Xattr>> {
        forensic::xattr::read_xattrs(self.dir_reader.inode_reader_mut(), ino)
    }

    /// Get all unallocated block ranges.
    pub fn unallocated_blocks(&mut self) -> Result<Vec<forensic::BlockRange>> {
        forensic::carving::unallocated_blocks(self.dir_reader.inode_reader_mut())
    }

    /// Read raw data from an unallocated block range.
    pub fn read_unallocated(&mut self, range: &forensic::BlockRange) -> Result<Vec<u8>> {
        forensic::carving::read_unallocated(self.dir_reader.inode_reader_mut(), range)
    }

    /// Read slack space for a single file inode.
    pub fn slack_space(&mut self, ino: u64) -> Result<Option<forensic::SlackSpace>> {
        forensic::slack::read_slack_space(self.dir_reader.inode_reader_mut(), ino)
    }

    /// Scan all allocated regular file inodes for slack space.
    pub fn scan_all_slack(&mut self) -> Result<Vec<forensic::SlackSpace>> {
        forensic::slack::scan_all_slack(self.dir_reader.inode_reader_mut())
    }

    /// Compute BLAKE3, SHA-256, MD5, and SHA-1 hashes for a file by inode number.
    #[cfg(feature = "hashing")]
    pub fn hash_file(&mut self, ino: u64) -> Result<forensic::FileHash> {
        forensic::hash::hash_file(self.dir_reader.inode_reader_mut(), ino)
    }

    /// Hash all allocated regular files on the filesystem.
    #[cfg(feature = "hashing")]
    pub fn hash_all_files(&mut self) -> Result<Vec<forensic::FileHash>> {
        forensic::hash::hash_all_files(self.dir_reader.inode_reader_mut())
    }

    /// Reconstruct the version history of an inode from the journal.
    pub fn inode_history(&mut self, ino: u64) -> Result<Vec<forensic::HistoryVersion>> {
        let journal = self.journal()?;
        forensic::history::inode_history(self.dir_reader.inode_reader_mut(), &journal, ino)
    }

    /// Recover deleted directory entries from rec_len gaps in a single directory.
    pub fn recover_dir_entries(
        &mut self,
        dir_ino: u64,
    ) -> Result<Vec<forensic::RecoveredDirEntry>> {
        forensic::dir_recovery::recover_dir_entries(self.dir_reader.inode_reader_mut(), dir_ino)
    }

    /// Recover deleted directory entries from all directories on the filesystem.
    pub fn recover_all_dir_entries(&mut self) -> Result<Vec<forensic::RecoveredDirEntry>> {
        forensic::dir_recovery::recover_all_dir_entries(self.dir_reader.inode_reader_mut())
    }

    /// Check if a specific inode is allocated.
    pub fn is_inode_allocated(&mut self, ino: u64) -> Result<bool> {
        self.dir_reader.inode_reader_mut().is_inode_allocated(ino)
    }

    /// Check if a specific block is allocated.
    pub fn is_block_allocated(&mut self, block: u64) -> Result<bool> {
        self.dir_reader.inode_reader_mut().is_block_allocated(block)
    }

    /// Read a raw block by number.
    pub fn read_block(&mut self, block: u64) -> Result<Vec<u8>> {
        self.dir_reader
            .inode_reader_mut()
            .block_reader_mut()
            .read_block(block)
    }

    /// Verify all superblock backups against the primary.
    pub fn verify_superblock_backups(&mut self) -> Result<Vec<forensic::SuperblockComparison>> {
        forensic::superblock_verify::verify_superblock_backups(self.dir_reader.inode_reader_mut())
    }

    /// Search for a byte pattern across filesystem blocks.
    pub fn search_blocks(
        &mut self,
        pattern: &[u8],
        scope: forensic::SearchScope,
    ) -> Result<Vec<forensic::SearchHit>> {
        forensic::search::search_blocks(
            self.dir_reader.inode_reader_mut(),
            pattern,
            scope,
            32, // default context bytes
        )
    }
}

#[cfg(feature = "ewf")]
impl Ext4Fs<ewf::EwfReader> {
    /// Open an ext4 filesystem from an E01/EWF forensic disk image.
    ///
    /// This is a convenience method that opens the EWF image and passes
    /// the reader to `Ext4Fs::open()`.
    pub fn open_ewf<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
        let reader = ewf::EwfReader::open(path.as_ref())
            .map_err(|e| error::Ext4Error::Io(std::io::Error::other(e.to_string())))?;
        Self::open(reader)
    }
}

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

    fn open_minimal() -> Option<Ext4Fs<Cursor<Vec<u8>>>> {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../tests/data/minimal.img");
        let data = std::fs::read(path).ok()?;
        Ext4Fs::open(Cursor::new(data)).ok()
    }

    #[test]
    fn open_and_read_superblock() {
        let fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        assert_eq!(fs.superblock().magic, 0xEF53);
    }

    #[test]
    fn read_file_by_path() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let data = fs.read_file("/hello.txt").unwrap();
        assert_eq!(data, b"Hello, ext4!");
    }

    #[test]
    fn read_nested_file() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let data = fs.read_file("/subdir/nested.txt").unwrap();
        assert_eq!(data, b"Nested file");
    }

    #[test]
    fn list_root_directory() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let entries = fs.read_dir("/").unwrap();
        let names: Vec<String> = entries
            .iter()
            .map(super::ondisk::dir_entry::DirEntry::name_str)
            .collect();
        assert!(names.contains(&"hello.txt".to_string()));
        assert!(names.contains(&"subdir".to_string()));
    }

    #[test]
    fn file_metadata() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let meta = fs.metadata("/hello.txt").unwrap();
        assert_eq!(meta.file_type, ondisk::FileType::RegularFile);
        assert_eq!(meta.size, 12);
        assert!(meta.mtime.seconds > 0);
    }

    #[test]
    fn exists_check() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        assert!(fs.exists("/hello.txt").unwrap());
        assert!(!fs.exists("/nonexistent").unwrap());
    }

    #[test]
    fn all_inodes() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let inodes = fs.all_inodes().unwrap();
        assert!(!inodes.is_empty());
    }

    #[test]
    fn deleted_inodes_on_fresh_image() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let deleted = fs.deleted_inodes().unwrap();
        assert!(deleted.is_empty());
    }

    #[test]
    fn timeline_generation() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let events = fs.timeline().unwrap();
        assert!(!events.is_empty());
    }

    #[test]
    fn unallocated_blocks_exist() {
        let mut fs = if let Some(f) = open_minimal() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let ranges = fs.unallocated_blocks().unwrap();
        assert!(!ranges.is_empty());
    }

    // --- forensic.img tests ---

    fn open_forensic() -> Option<Ext4Fs<Cursor<Vec<u8>>>> {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../tests/data/forensic.img");
        let data = std::fs::read(path).ok()?;
        Ext4Fs::open(Cursor::new(data)).ok()
    }

    #[test]
    fn symlink_target_resolves_through_symlink() {
        // symlink_target() calls resolve_path() which follows symlinks,
        // so /abs-link resolves to hello.txt (inode 12), not the symlink itself.
        // Verify the method returns NotASymlink for a followed-through path.
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let err = fs.symlink_target("/abs-link").unwrap_err();
        assert!(
            format!("{err:?}").contains("NotASymlink"),
            "symlink_target on a followed symlink should return NotASymlink, got: {err:?}"
        );
    }

    #[test]
    fn inode_root_is_directory() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let root = fs.inode(2).unwrap();
        assert_eq!(
            root.file_type(),
            ondisk::FileType::Directory,
            "inode 2 should be a directory"
        );
    }

    #[test]
    fn orphan_inodes_returns_ok() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let result = fs.orphan_inodes();
        assert!(result.is_ok(), "orphan_inodes should not error");
    }

    #[test]
    fn recover_file_deleted_inode() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let result = fs.recover_file(21);
        assert!(
            result.is_ok(),
            "recover_file(21) should return a RecoveryResult"
        );
    }

    #[test]
    fn journal_has_transactions() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let journal = fs.journal().unwrap();
        assert!(
            !journal.transactions.is_empty(),
            "journal should have transactions"
        );
    }

    #[test]
    fn xattrs_on_hello_txt() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let attrs = fs.xattrs(12).unwrap();
        let names: Vec<String> = attrs
            .iter()
            .map(|a| String::from_utf8_lossy(&a.name).to_string())
            .collect();
        assert!(
            names.iter().any(|n| n.contains("forensic")),
            "inode 12 should have user.forensic xattr, got: {names:?}"
        );
    }

    #[test]
    fn read_unallocated_first_range() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let ranges = fs.unallocated_blocks().unwrap();
        assert!(!ranges.is_empty(), "should have unallocated ranges");
        let data = fs.read_unallocated(&ranges[0]).unwrap();
        assert!(!data.is_empty(), "unallocated data should not be empty");
    }

    #[test]
    fn is_inode_allocated_root() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        assert!(
            fs.is_inode_allocated(2).unwrap(),
            "root inode 2 should be allocated"
        );
        // inode 21 is deleted, may or may not be allocated depending on reuse
        let _alloc21 = fs.is_inode_allocated(21).unwrap();
    }

    #[test]
    fn is_block_allocated_zero() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let allocated = fs.is_block_allocated(0).unwrap();
        assert!(allocated, "block 0 (superblock) should be allocated");
    }

    #[test]
    fn read_block_zero() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let block_size = fs.superblock().block_size as usize;
        let data = fs.read_block(0).unwrap();
        assert_eq!(data.len(), block_size, "block 0 should be block_size bytes");
    }

    #[test]
    fn read_dir_by_ino_root() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let entries = fs.read_dir_by_ino(2).unwrap();
        let names: Vec<String> = entries
            .iter()
            .map(super::ondisk::dir_entry::DirEntry::name_str)
            .collect();
        assert!(
            names.contains(&"hello.txt".to_string()),
            "root dir should contain hello.txt, got: {names:?}"
        );
    }

    #[test]
    fn lookup_by_ino_hello_txt() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let result = fs.lookup_by_ino(2, b"hello.txt").unwrap();
        assert!(result.is_some(), "hello.txt should exist in root dir");
    }

    #[test]
    fn read_link_by_ino_abs_link() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        // First resolve abs-link's inode
        let ino = fs
            .lookup_by_ino(2, b"abs-link")
            .unwrap()
            .expect("abs-link should exist in root");
        let target = fs.read_link_by_ino(ino).unwrap();
        assert_eq!(target, b"/hello.txt", "abs-link should point to /hello.txt");
    }

    #[test]
    fn read_inode_data_hello_txt() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let data = fs.read_inode_data(12).unwrap();
        let text = std::str::from_utf8(&data).unwrap_or("");
        assert!(
            text.contains("Hello"),
            "inode 12 (hello.txt) should contain 'Hello', got: {text:?}"
        );
    }

    #[test]
    fn read_inode_data_range_hello_txt() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let data = fs.read_inode_data_range(12, 0, 5).unwrap();
        assert_eq!(
            data, b"Hello",
            "first 5 bytes of hello.txt should be 'Hello'"
        );
    }

    #[test]
    fn slack_space_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        // Find a regular file inode with non-block-aligned size
        let all = fs.all_inodes().unwrap();
        let block_size = u64::from(fs.superblock().block_size);
        let file_ino = all
            .iter()
            .find(|(_, inode)| {
                inode.file_type() == ondisk::FileType::RegularFile
                    && inode.size > 0
                    && inode.size % block_size != 0
            })
            .map(|(ino, _)| *ino)
            .expect("forensic.img should have a non-block-aligned regular file");
        let slack = fs.slack_space(file_ino).unwrap();
        assert!(
            slack.is_some(),
            "non-block-aligned file should have slack space"
        );
    }

    #[test]
    fn hash_file_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let hash = fs.hash_file(12).unwrap();
        assert_eq!(hash.md5.len(), 32);
    }

    #[test]
    fn recover_dir_entries_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let recovered = fs.recover_dir_entries(2).unwrap();
        let _ = recovered; // may be empty depending on kernel behavior
    }

    #[test]
    fn recover_all_dir_entries_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let all = fs.recover_all_dir_entries().unwrap();
        let _ = all;
    }

    #[test]
    fn hash_all_files_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let hashes = fs.hash_all_files().unwrap();
        assert!(!hashes.is_empty());
    }

    #[test]
    fn inode_history_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let versions = fs.inode_history(12).unwrap();
        // Should not error
        let _ = versions;
    }

    #[test]
    fn scan_all_slack_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let slacks = fs.scan_all_slack().unwrap();
        assert!(
            !slacks.is_empty(),
            "forensic.img should have files with slack"
        );
    }

    #[test]
    fn verify_superblock_backups_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let results = fs.verify_superblock_backups().unwrap();
        let _ = results; // small image may have no backups
    }

    #[test]
    fn search_blocks_api() {
        let mut fs = if let Some(f) = open_forensic() {
            f
        } else {
            eprintln!("skip");
            return;
        };
        let hits = fs
            .search_blocks(b"Hello", forensic::SearchScope::Allocated)
            .unwrap();
        assert!(!hits.is_empty());
    }

    #[cfg(feature = "ewf")]
    mod ewf_tests {
        use super::*;

        #[test]
        fn open_ewf_with_valid_e01() {
            // We don't have a real E01 file in test data, so test that the
            // method exists and returns an appropriate error for a non-E01 file
            let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../tests/data/forensic.img");
            let result = Ext4Fs::open_ewf(path);
            // forensic.img is a raw image, not E01 — ewf should fail to open it
            assert!(result.is_err(), "raw image should not open as E01");
        }

        #[test]
        fn open_ewf_nonexistent_file() {
            let result = Ext4Fs::open_ewf("/nonexistent/file.E01");
            assert!(result.is_err());
        }
    }
}