ext4fs-core 0.2.4

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
#![forbid(unsafe_code)]
use crate::error::{Ext4Error, Result};
use crate::inode::InodeReader;
use crate::ondisk::{parse_dir_block, DirEntry, FileType};
use std::io::{Read, Seek};

const MAX_SYMLINK_DEPTH: u32 = 40;

pub struct DirReader<R: Read + Seek> {
    inode_reader: InodeReader<R>,
}

impl<R: Read + Seek> DirReader<R> {
    /// Wrap an `InodeReader` to provide directory-level access.
    pub fn new(inode_reader: InodeReader<R>) -> Self {
        Self { inode_reader }
    }

    /// Borrow the underlying `InodeReader`.
    pub fn inode_reader(&self) -> &InodeReader<R> {
        &self.inode_reader
    }

    /// Mutably borrow the underlying `InodeReader`.
    pub fn inode_reader_mut(&mut self) -> &mut InodeReader<R> {
        &mut self.inode_reader
    }

    /// Read all (live) directory entries from inode `dir_ino`.
    ///
    /// Reads the inode's data blocks and calls `parse_dir_block` on each
    /// block-sized chunk, then filters out deleted entries (inode == 0).
    pub fn read_dir(&self, dir_ino: u64) -> Result<Vec<DirEntry>> {
        let block_size = self.inode_reader.block_reader().block_size() as usize;
        let data = self.inode_reader.read_inode_data(dir_ino)?;

        let mut entries = Vec::new();
        let mut offset = 0;
        while offset < data.len() {
            let end = (offset + block_size).min(data.len());
            let chunk = &data[offset..end];
            let block_entries = parse_dir_block(chunk);
            for e in block_entries {
                if e.inode != 0 {
                    entries.push(e);
                }
            }
            offset += block_size;
        }
        Ok(entries)
    }

    /// Look up a single name in directory inode `dir_ino`.
    ///
    /// Returns `Ok(Some(ino))` when found, `Ok(None)` when not found.
    pub fn lookup(&self, dir_ino: u64, name: &[u8]) -> Result<Option<u64>> {
        let entries = self.read_dir(dir_ino)?;
        for e in entries {
            if e.name.as_slice() == name {
                return Ok(Some(u64::from(e.inode)));
            }
        }
        Ok(None)
    }

    /// Resolve an absolute path to an inode number.
    ///
    /// Always starts at inode 2 (root). Follows symlinks up to
    /// `MAX_SYMLINK_DEPTH` times. Returns `Ext4Error::PathNotFound` when
    /// any component is missing.
    pub fn resolve_path(&self, path: &str) -> Result<u64> {
        self.resolve_path_inner(path, 0)
    }

    fn resolve_path_inner(&self, path: &str, depth: u32) -> Result<u64> {
        if depth > MAX_SYMLINK_DEPTH {
            return Err(Ext4Error::SymlinkLoop {
                path: path.to_string(),
                depth,
            });
        }

        // All paths are absolute; start from root inode 2.
        let mut cur_ino: u64 = 2;

        let components: Vec<&str> = path
            .trim_start_matches('/')
            .split('/')
            .filter(|c| !c.is_empty())
            .collect();

        for component in components {
            // Resolve next component in cur_ino directory.
            let next = self
                .lookup(cur_ino, component.as_bytes())?
                .ok_or_else(|| Ext4Error::PathNotFound(path.to_string()))?;

            // Check whether the resolved entry is a symlink.
            let inode = self.inode_reader.read_inode(next)?;
            if inode.file_type() == FileType::Symlink {
                let target = self.read_link(next)?;
                let target_str = String::from_utf8_lossy(&target).into_owned();
                if target_str.starts_with('/') {
                    // Absolute symlink — restart from root.
                    cur_ino = self.resolve_path_inner(&target_str, depth + 1)?;
                } else {
                    // Relative symlink — resolve from current directory.
                    // Build a path relative to cur_ino's parent by treating
                    // the symlink target as an absolute path under a synthetic
                    // prefix derived from current directory.
                    cur_ino = self.resolve_relative_link(cur_ino, &target_str, depth + 1)?;
                }
            } else {
                cur_ino = next;
            }
        }

        Ok(cur_ino)
    }

    /// Resolve a relative symlink `target` whose link inode is inside
    /// directory `dir_ino`.
    fn resolve_relative_link(&self, dir_ino: u64, target: &str, depth: u32) -> Result<u64> {
        if depth > MAX_SYMLINK_DEPTH {
            return Err(Ext4Error::SymlinkLoop {
                path: target.to_string(),
                depth,
            });
        }

        let mut cur_ino = dir_ino;
        let components: Vec<&str> = target.split('/').filter(|c| !c.is_empty()).collect();

        for component in components {
            match component {
                "." => {}
                ".." => {
                    if let Some(parent) = self.lookup(cur_ino, b"..")? {
                        cur_ino = parent;
                    }
                }
                name => {
                    let next = self
                        .lookup(cur_ino, name.as_bytes())?
                        .ok_or_else(|| Ext4Error::PathNotFound(target.to_string()))?;

                    let inode = self.inode_reader.read_inode(next)?;
                    if inode.file_type() == FileType::Symlink {
                        let link_target = self.read_link(next)?;
                        let link_str = String::from_utf8_lossy(&link_target).into_owned();
                        if link_str.starts_with('/') {
                            cur_ino = self.resolve_path_inner(&link_str, depth + 1)?;
                        } else {
                            cur_ino = self.resolve_relative_link(cur_ino, &link_str, depth + 1)?;
                        }
                    } else {
                        cur_ino = next;
                    }
                }
            }
        }

        Ok(cur_ino)
    }

    /// Read the target of a symlink inode.
    ///
    /// For short symlinks (size <= 60 and no extents), the path is stored
    /// inline in `i_block`. Otherwise it is read from the data blocks.
    pub fn read_link(&self, ino: u64) -> Result<Vec<u8>> {
        let inode = self.inode_reader.read_inode(ino)?;
        if inode.file_type() != FileType::Symlink {
            return Err(Ext4Error::NotASymlink(format!("inode {ino}")));
        }
        // Inline symlink: size <= 60 and not using extents.
        if inode.size <= 60 && !inode.uses_extents() {
            let len = inode.size as usize;
            return Ok(inode.i_block[..len].to_vec());
        }
        // Data-block symlink.
        let data = self.inode_reader.read_inode_data(ino)?;
        Ok(data)
    }
}

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

    fn open_minimal() -> DirReader<Cursor<Vec<u8>>> {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../tests/data/minimal.img");
        let data = std::fs::read(path).expect("minimal.img required");
        let br = BlockReader::open(Cursor::new(data)).unwrap();
        let ir = InodeReader::new(br);
        DirReader::new(ir)
    }

    #[test]
    fn read_root_directory() {
        let r = open_minimal();
        let entries = r.read_dir(2).unwrap();
        let names: Vec<String> = entries
            .iter()
            .map(super::super::ondisk::dir_entry::DirEntry::name_str)
            .collect();
        assert!(names.contains(&".".to_string()));
        assert!(names.contains(&"..".to_string()));
        assert!(names.contains(&"hello.txt".to_string()));
        assert!(names.contains(&"subdir".to_string()));
        assert!(names.contains(&"lost+found".to_string()));
    }

    #[test]
    fn lookup_file_in_root() {
        let r = open_minimal();
        let ino = r.lookup(2, b"hello.txt").unwrap();
        assert!(ino.is_some());
        assert!(ino.unwrap() > 0);
    }

    #[test]
    fn lookup_nonexistent() {
        let r = open_minimal();
        let ino = r.lookup(2, b"nonexistent.txt").unwrap();
        assert!(ino.is_none());
    }

    #[test]
    fn resolve_path_root() {
        let r = open_minimal();
        assert_eq!(r.resolve_path("/").unwrap(), 2);
    }

    #[test]
    fn resolve_path_file() {
        let r = open_minimal();
        let ino = r.resolve_path("/hello.txt").unwrap();
        assert!(ino > 0);
    }

    #[test]
    fn resolve_path_nested() {
        let r = open_minimal();
        let ino = r.resolve_path("/subdir/nested.txt").unwrap();
        assert!(ino > 0);
    }

    #[test]
    fn resolve_path_not_found() {
        let r = open_minimal();
        let err = r.resolve_path("/nonexistent").unwrap_err();
        assert!(matches!(err, Ext4Error::PathNotFound(_)));
    }

    #[test]
    fn read_file_content_via_path() {
        let mut r = open_minimal();
        let ino = r.resolve_path("/hello.txt").unwrap();
        let data = r.inode_reader_mut().read_inode_data(ino).unwrap();
        assert_eq!(data, b"Hello, ext4!");
    }

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

    #[test]
    fn inode_reader_accessor() {
        let r = open_minimal();
        // Verify inode_reader() returns a reference we can use to access the superblock.
        let sb = r.inode_reader().block_reader().superblock();
        assert!(sb.block_size > 0);
    }

    #[test]
    fn resolve_absolute_symlink() {
        let mut r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        // Read expected content from /hello.txt
        let hello_ino = r.resolve_path("/hello.txt").unwrap();
        let expected = r.inode_reader_mut().read_inode_data(hello_ino).unwrap();
        // Resolve through absolute symlink
        let link_ino = r.resolve_path("/abs-link").unwrap();
        let actual = r.inode_reader_mut().read_inode_data(link_ino).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn resolve_relative_symlink() {
        let mut r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let hello_ino = r.resolve_path("/hello.txt").unwrap();
        let expected = r.inode_reader_mut().read_inode_data(hello_ino).unwrap();
        let link_ino = r.resolve_path("/rel-link").unwrap();
        let actual = r.inode_reader_mut().read_inode_data(link_ino).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn resolve_deep_symlink() {
        let mut r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let nested_ino = r.resolve_path("/subdir/nested.txt").unwrap();
        let expected = r.inode_reader_mut().read_inode_data(nested_ino).unwrap();
        let link_ino = r.resolve_path("/deep-link").unwrap();
        let actual = r.inode_reader_mut().read_inode_data(link_ino).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn resolve_updir_symlink() {
        let mut r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let hello_ino = r.resolve_path("/hello.txt").unwrap();
        let expected = r.inode_reader_mut().read_inode_data(hello_ino).unwrap();
        let link_ino = r.resolve_path("/linkdir/up-link").unwrap();
        let actual = r.inode_reader_mut().read_inode_data(link_ino).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn read_link_inline() {
        let r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let link_ino = r.lookup(2, b"abs-link").unwrap().unwrap();
        let target = r.read_link(link_ino).unwrap();
        let target_str = String::from_utf8_lossy(&target);
        assert_eq!(target_str, "/hello.txt");
    }

    #[test]
    fn read_link_not_a_symlink() {
        let r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let file_ino = r.lookup(2, b"hello.txt").unwrap().unwrap();
        let err = r.read_link(file_ino).unwrap_err();
        assert!(matches!(err, Ext4Error::NotASymlink(_)));
    }

    #[test]
    fn resolve_nonexistent_through_symlink() {
        let r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        // Try resolving a path that doesn't exist — the symlink target is missing
        let err = r.resolve_path("/nonexistent-link");
        // If there's no such symlink entry, we get PathNotFound on the name itself
        assert!(err.is_err());
        assert!(matches!(err.unwrap_err(), Ext4Error::PathNotFound(_)));
    }

    #[test]
    fn lookup_returns_none_for_missing_forensic() {
        let r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let result = r.lookup(2, b"does-not-exist.xyz").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn read_dir_handles_all_directory_types() {
        let mut r = if let Some(r) = open_forensic() {
            r
        } else {
            eprintln!("skip: forensic.img not found");
            return;
        };
        let all_inodes = r.inode_reader_mut().iter_all_inodes().unwrap();
        let mut dir_count = 0;
        for (ino, inode) in &all_inodes {
            if inode.file_type() == FileType::Directory && inode.mode != 0 {
                let entries = r.read_dir(*ino).unwrap();
                let names: Vec<String> = entries
                    .iter()
                    .map(super::super::ondisk::dir_entry::DirEntry::name_str)
                    .collect();
                assert!(
                    names.contains(&".".to_string()),
                    "dir ino {ino} missing '.'"
                );
                assert!(
                    names.contains(&"..".to_string()),
                    "dir ino {ino} missing '..'"
                );
                dir_count += 1;
            }
        }
        assert!(dir_count > 0, "no directories found");
    }
}