use forensic_vfs::{
Allocation, ByteRun, Confidence, DirEntry as VfsDirEntry, DirStream, DynSource, ExtentStream,
FileId, FileSystem, FsKind, FsMeta, MacbTimes, NodeKind, NodeStream, ResidencyKind, RunAlloc,
RunFlags, RunInfo, SectorSizes, SmallHex, SniffWindow, StreamId, TimeResolution, TimeSource,
TimeStamp, TimeZonePolicy, VfsError, VfsResult,
};
use crate::error::XfsError;
use crate::extent::read_extents;
use crate::inode::{FileType, Inode, InodeFormat, XfsTimestamp};
use crate::superblock::Superblock;
const XFSB_MAGIC: &[u8] = b"XFSB";
#[must_use]
pub fn xfs_probe(w: &SniffWindow) -> Confidence {
if w.has_magic(0, XFSB_MAGIC) {
Confidence::Yes {
how: "XFS XFSB superblock magic",
}
} else {
Confidence::No
}
}
pub struct XfsFs {
image: Vec<u8>,
sb: Superblock,
}
impl XfsFs {
pub fn open(source: &DynSource) -> VfsResult<Self> {
let len = source.len();
let cap = usize::try_from(len).unwrap_or(usize::MAX);
let mut image = vec![0u8; cap];
let n = source.read_at(0, &mut image)?;
image.truncate(n);
let sb = Superblock::parse(&image).map_err(map_err)?;
Ok(Self { image, sb })
}
fn inode(&self, id: FileId) -> VfsResult<Inode> {
let ino = ino_of(id)?;
self.sb.read_inode(&self.image, ino).map_err(map_err)
}
}
fn ino_of(id: FileId) -> VfsResult<u64> {
match id {
FileId::Opaque(ino) => Ok(ino),
other => Err(VfsError::Unsupported {
layer: "xfs file-id",
scheme: format!("{other:?}"),
}),
}
}
fn require_default_stream(stream: StreamId) -> VfsResult<()> {
match stream {
StreamId::Default => Ok(()),
other => Err(VfsError::Unsupported {
layer: "xfs stream",
scheme: format!("{other:?}"),
}),
}
}
fn map_err(e: XfsError) -> VfsError {
match e {
XfsError::Truncated { need, have, .. } => VfsError::OutOfRange {
what: "xfs image slice",
offset: need as u64,
len: 1,
bound: have as u64,
},
other => VfsError::Decode {
layer: "xfs",
offset: 0,
detail: other.to_string(),
bytes: SmallHex::new(&[]),
},
}
}
fn node_kind(ft: FileType) -> NodeKind {
match ft {
FileType::Regular => NodeKind::File,
FileType::Directory => NodeKind::Dir,
FileType::Symlink => NodeKind::Symlink,
FileType::CharDevice | FileType::BlockDevice => NodeKind::Device,
FileType::Fifo | FileType::Socket | FileType::Other(_) => NodeKind::Other,
}
}
fn to_ts(ts: XfsTimestamp) -> TimeStamp {
TimeStamp {
unix_nanos: i128::from(ts.secs) * 1_000_000_000 + i128::from(ts.nsecs),
source: TimeSource::InodeTable,
resolution: TimeResolution::Nanos,
}
}
impl FileSystem for XfsFs {
fn kind(&self) -> FsKind {
FsKind::XFS
}
fn root(&self) -> FileId {
FileId::Opaque(self.sb.rootino)
}
fn sector_sizes(&self) -> SectorSizes {
SectorSizes {
logical: 512,
physical: 512,
cluster_or_block: self.sb.blocksize,
}
}
fn timestamp_zone(&self) -> TimeZonePolicy {
TimeZonePolicy::Utc
}
fn read_dir(&self, ino: FileId) -> VfsResult<DirStream> {
let inode = self.inode(ino)?;
let entries = self.sb.read_dir(&self.image, &inode).map_err(map_err)?;
let out: Vec<VfsResult<VfsDirEntry>> = entries
.into_iter()
.map(|e| {
Ok(VfsDirEntry {
name: e.name,
id: FileId::Opaque(e.inode),
kind: self.entry_kind(e.inode),
})
})
.collect();
Ok(DirStream::new(out.into_iter()))
}
fn extents(&self, ino: FileId, stream: StreamId) -> VfsResult<ExtentStream> {
require_default_stream(stream)?;
let inode = self.inode(ino)?;
let blocksize = u64::from(self.sb.blocksize);
let recs = match inode.format {
InodeFormat::Extents => read_extents(&inode.data_fork, inode.nextents),
_ => Vec::new(),
};
let out: Vec<VfsResult<RunInfo>> = recs
.into_iter()
.map(|r| {
Ok(RunInfo {
run: ByteRun {
image_offset: r.startblock.saturating_mul(blocksize),
len: r.blockcount.saturating_mul(blocksize),
flags: RunFlags::default(),
},
alloc: RunAlloc::Allocated,
})
})
.collect();
Ok(ExtentStream::new(out.into_iter()))
}
fn lookup(&self, parent: FileId, name: &[u8]) -> VfsResult<Option<FileId>> {
let inode = self.inode(parent)?;
let entries = self.sb.read_dir(&self.image, &inode).map_err(map_err)?;
Ok(entries
.into_iter()
.find(|e| e.name == name)
.map(|e| FileId::Opaque(e.inode)))
}
fn meta(&self, ino: FileId) -> VfsResult<FsMeta> {
let inode_no = ino_of(ino)?;
let inode = self.sb.read_inode(&self.image, inode_no).map_err(map_err)?;
let residency = match inode.format {
InodeFormat::Local => ResidencyKind::Resident {
inline_len: u32::try_from(inode.data_fork.len()).unwrap_or(u32::MAX),
},
_ => ResidencyKind::NonResident,
};
Ok(FsMeta {
ino: inode_no,
kind: node_kind(inode.file_type()),
allocated: Allocation::Allocated,
size: inode.size,
nlink: 1,
uid: None,
gid: None,
mode: Some(u32::from(inode.mode)),
times: MacbTimes {
modified: Some(to_ts(inode.mtime)),
accessed: Some(to_ts(inode.atime)),
changed: Some(to_ts(inode.ctime)),
born: inode.crtime.map(to_ts),
},
streams: Vec::new(),
residency,
link_target: None,
})
}
fn read_at(&self, ino: FileId, stream: StreamId, off: u64, buf: &mut [u8]) -> VfsResult<usize> {
require_default_stream(stream)?;
let inode = self.inode(ino)?;
let file = self.sb.read_file(&self.image, &inode).map_err(map_err)?;
let start = usize::try_from(off).unwrap_or(usize::MAX);
let Some(slice) = file.get(start..) else {
return Ok(0);
};
let n = slice.len().min(buf.len());
buf[..n].copy_from_slice(&slice[..n]);
Ok(n)
}
fn read_link(&self, ino: FileId, cap: usize) -> VfsResult<Vec<u8>> {
let inode = self.inode(ino)?;
if inode.file_type() != FileType::Symlink {
return Ok(Vec::new());
}
let mut target = match inode.format {
InodeFormat::Local => {
let size = usize::try_from(inode.size).unwrap_or(usize::MAX);
let n = size.min(inode.data_fork.len());
inode.data_fork.get(..n).unwrap_or(&[]).to_vec()
}
_ => self.sb.read_file(&self.image, &inode).map_err(map_err)?, };
target.truncate(cap);
Ok(target)
}
fn deleted(&self) -> VfsResult<NodeStream> {
Ok(NodeStream::empty())
}
fn unallocated(&self) -> VfsResult<ExtentStream> {
Ok(ExtentStream::empty())
}
}
impl XfsFs {
fn entry_kind(&self, ino: u64) -> NodeKind {
self.sb
.read_inode(&self.image, ino)
.map_or(NodeKind::Other, |i| node_kind(i.file_type())) }
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn node_kind_maps_every_s_ifmt_type() {
assert_eq!(node_kind(FileType::Regular), NodeKind::File);
assert_eq!(node_kind(FileType::Directory), NodeKind::Dir);
assert_eq!(node_kind(FileType::Symlink), NodeKind::Symlink);
assert_eq!(node_kind(FileType::CharDevice), NodeKind::Device);
assert_eq!(node_kind(FileType::BlockDevice), NodeKind::Device);
assert_eq!(node_kind(FileType::Fifo), NodeKind::Other);
assert_eq!(node_kind(FileType::Socket), NodeKind::Other);
assert_eq!(node_kind(FileType::Other(0)), NodeKind::Other);
}
#[test]
fn to_ts_carries_ns_and_inode_table_provenance() {
let ts = to_ts(XfsTimestamp {
secs: 5,
nsecs: 123,
});
assert_eq!(ts.unix_nanos, 5 * 1_000_000_000 + 123);
assert_eq!(ts.source, TimeSource::InodeTable);
assert_eq!(ts.resolution, TimeResolution::Nanos);
assert_eq!(
to_ts(XfsTimestamp { secs: -1, nsecs: 0 }).unix_nanos,
-1_000_000_000
);
}
#[test]
fn map_err_splits_truncated_from_decode() {
let oor = map_err(XfsError::Truncated {
structure: "x",
need: 9,
have: 4,
});
assert!(matches!(
oor,
VfsError::OutOfRange {
offset: 9,
bound: 4,
..
}
));
let dec = map_err(XfsError::BadMagic {
found: 0,
bytes: [0; 4],
});
assert!(matches!(dec, VfsError::Decode { layer: "xfs", .. }));
}
#[test]
fn require_default_stream_refuses_named_streams() {
assert!(require_default_stream(StreamId::Default).is_ok());
assert!(matches!(
require_default_stream(StreamId::Slack),
Err(VfsError::Unsupported {
layer: "xfs stream",
..
})
));
}
#[test]
fn ino_of_refuses_foreign_identity() {
assert_eq!(ino_of(FileId::Opaque(42)).unwrap(), 42);
assert!(matches!(
ino_of(FileId::NtfsRef { entry: 1, seq: 1 }),
Err(VfsError::Unsupported {
layer: "xfs file-id",
..
})
));
}
#[test]
fn xfs_probe_matches_only_the_xfsb_magic() {
let mut good = vec![0u8; 8];
good[0..4].copy_from_slice(b"XFSB");
assert!(matches!(
xfs_probe(&SniffWindow::new(0, &good)),
Confidence::Yes { .. }
));
assert_eq!(xfs_probe(&SniffWindow::new(0, b"XFS")), Confidence::No);
assert_eq!(xfs_probe(&SniffWindow::new(0, &[])), Confidence::No);
}
use std::sync::Arc as StdArc;
struct Bytes(Vec<u8>);
impl forensic_vfs::ImageSource for Bytes {
fn len(&self) -> u64 {
self.0.len() as u64
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> VfsResult<usize> {
let off = usize::try_from(offset).unwrap_or(usize::MAX);
let Some(s) = self.0.get(off..) else {
return Ok(0); };
let n = s.len().min(buf.len());
buf[..n].copy_from_slice(&s[..n]);
Ok(n)
}
}
fn image_with_local_symlink(target: &[u8]) -> Vec<u8> {
let mut img = vec![0u8; 4096];
img[0..4].copy_from_slice(b"XFSB"); img[4..8].copy_from_slice(&512u32.to_be_bytes()); img[56..64].copy_from_slice(&128u64.to_be_bytes()); img[84..88].copy_from_slice(&64u32.to_be_bytes()); img[88..92].copy_from_slice(&1u32.to_be_bytes()); img[100..102].copy_from_slice(&4u16.to_be_bytes()); img[104..106].copy_from_slice(&256u16.to_be_bytes()); img[106..108].copy_from_slice(&2u16.to_be_bytes()); img[120] = 9; img[122] = 8; img[123] = 1; img[124] = 6;
let ioff = 2048usize;
img[ioff..ioff + 2].copy_from_slice(&0x494eu16.to_be_bytes()); let mode = 0o120_000u16 | 0o777; img[ioff + 2..ioff + 4].copy_from_slice(&mode.to_be_bytes()); img[ioff + 4] = 2; img[ioff + 5] = 1; img[ioff + 56..ioff + 64].copy_from_slice(&(target.len() as u64).to_be_bytes()); img[ioff + 100..ioff + 100 + target.len()].copy_from_slice(target);
img
}
#[test]
fn read_link_returns_the_inline_local_symlink_target() {
let target = b"../etc/passwd";
let img = image_with_local_symlink(target);
let fs = XfsFs::open(&(StdArc::new(Bytes(img)) as DynSource)).unwrap();
let vfs: &dyn FileSystem = &fs;
assert_eq!(vfs.kind(), FsKind::XFS);
let link = FileId::Opaque(8);
assert_eq!(vfs.meta(link).unwrap().kind, NodeKind::Symlink);
assert_eq!(vfs.read_link(link, 4096).unwrap(), target);
assert_eq!(vfs.read_link(link, 4).unwrap(), b"../e");
}
fn write_inode_core(img: &mut [u8], ioff: usize, mode: u16, format: u8, size: u64) {
img[ioff..ioff + 2].copy_from_slice(&0x494eu16.to_be_bytes()); img[ioff + 2..ioff + 4].copy_from_slice(&mode.to_be_bytes()); img[ioff + 4] = 2; img[ioff + 5] = format; img[ioff + 56..ioff + 64].copy_from_slice(&size.to_be_bytes()); }
fn image_with_tree() -> Vec<u8> {
let mut img = vec![0u8; 4096];
img[0..4].copy_from_slice(b"XFSB"); img[4..8].copy_from_slice(&512u32.to_be_bytes()); img[56..64].copy_from_slice(&4u64.to_be_bytes()); img[84..88].copy_from_slice(&64u32.to_be_bytes()); img[88..92].copy_from_slice(&1u32.to_be_bytes()); img[100..102].copy_from_slice(&4u16.to_be_bytes()); img[104..106].copy_from_slice(&256u16.to_be_bytes()); img[106..108].copy_from_slice(&2u16.to_be_bytes()); img[120] = 9; img[122] = 8; img[123] = 1; img[124] = 6;
let root = 1024usize;
write_inode_core(&mut img, root, 0o040_000 | 0o755, 1, 0); let f = root + 100; img[f] = 2; img[f + 1] = 0; img[f + 2..f + 6].copy_from_slice(&4u32.to_be_bytes()); let mut off = f + 6;
img[off] = 8; img[off + 1..off + 3].copy_from_slice(&0u16.to_be_bytes()); img[off + 3..off + 11].copy_from_slice(b"file.txt");
img[off + 11..off + 15].copy_from_slice(&9u32.to_be_bytes());
off += 15;
img[off] = 3;
img[off + 1..off + 3].copy_from_slice(&0u16.to_be_bytes());
img[off + 3..off + 6].copy_from_slice(b"sym");
img[off + 6..off + 10].copy_from_slice(&8u32.to_be_bytes());
let symi = 2048usize;
let target = b"../etc/passwd";
write_inode_core(&mut img, symi, 0o120_000 | 0o777, 1, target.len() as u64);
img[symi + 100..symi + 100 + target.len()].copy_from_slice(target);
let filei = 2304usize;
let content = b"content-1\n";
write_inode_core(&mut img, filei, 0o100_000 | 0o644, 2, content.len() as u64);
img[filei + 76..filei + 80].copy_from_slice(&1u32.to_be_bytes()); let rec: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xA0, 0, 1];
img[filei + 100..filei + 116].copy_from_slice(&rec);
img[2560..2560 + content.len()].copy_from_slice(content);
img
}
#[test]
fn adapter_navigates_the_synthetic_tree() {
let fs = XfsFs::open(&(StdArc::new(Bytes(image_with_tree())) as DynSource)).unwrap();
let vfs: &dyn FileSystem = &fs;
assert_eq!(vfs.kind(), FsKind::XFS);
assert_eq!(vfs.timestamp_zone(), TimeZonePolicy::Utc);
let sizes = vfs.sector_sizes();
assert_eq!(sizes.logical, 512);
assert_eq!(sizes.physical, 512);
assert_eq!(sizes.cluster_or_block, 512);
let root = vfs.root();
assert_eq!(root, FileId::Opaque(4));
assert_eq!(vfs.meta(root).unwrap().kind, NodeKind::Dir);
let mut listing: Vec<(String, FileId, NodeKind)> = vfs
.read_dir(root)
.unwrap()
.filter_map(Result::ok)
.map(|e| (String::from_utf8_lossy(&e.name).into_owned(), e.id, e.kind))
.collect();
listing.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
listing,
vec![
("file.txt".to_string(), FileId::Opaque(9), NodeKind::File),
("sym".to_string(), FileId::Opaque(8), NodeKind::Symlink),
]
);
let file = vfs.lookup(root, b"file.txt").unwrap().expect("file.txt");
assert!(vfs.lookup(root, b"nope").unwrap().is_none());
let meta = vfs.meta(file).unwrap();
assert_eq!(meta.kind, NodeKind::File);
assert_eq!(meta.size, 10);
assert_eq!(meta.residency, ResidencyKind::NonResident);
let mut buf = vec![0u8; meta.size as usize];
let n = vfs.read_at(file, StreamId::Default, 0, &mut buf).unwrap();
buf.truncate(n);
assert_eq!(buf, b"content-1\n");
assert_eq!(
vfs.read_at(file, StreamId::Default, meta.size + 100, &mut [0u8; 4])
.unwrap(),
0
);
let runs: Vec<_> = vfs
.extents(file, StreamId::Default)
.unwrap()
.filter_map(Result::ok)
.collect();
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].run.image_offset, 2560); assert_eq!(runs[0].run.len, 512);
assert!(vfs
.extents(root, StreamId::Default)
.unwrap()
.find_map(Result::ok)
.is_none());
let sym = vfs.lookup(root, b"sym").unwrap().expect("sym");
assert_eq!(vfs.read_link(sym, 4096).unwrap(), b"../etc/passwd");
assert_eq!(vfs.read_link(root, 4096).unwrap(), Vec::<u8>::new());
assert!(vfs.extents(file, StreamId::Named(1)).is_err());
assert!(vfs
.read_at(file, StreamId::Slack, 0, &mut [0u8; 4])
.is_err());
assert_eq!(vfs.deleted().unwrap().count(), 0);
assert_eq!(vfs.unallocated().unwrap().count(), 0);
}
}