use crate::btree::read_btree_extents;
use crate::bytes::{be_u16, be_u32, be_u64, u8_at};
use crate::crc::{verify_crc, DA3_BLKINFO_CRC_OFF, DIR3_DATA_CRC_OFF};
use crate::error::XfsError;
use crate::extent::{read_extents, BmbtRec};
use crate::inode::{Inode, InodeFormat};
use crate::superblock::Superblock;
pub const XFS_DIR3_BLOCK_MAGIC: u32 = 0x5844_4233;
pub const XFS_DIR2_BLOCK_MAGIC: u32 = 0x5844_3242;
pub const XFS_DIR3_DATA_MAGIC: u32 = 0x5844_4433;
pub const XFS_DIR2_DATA_MAGIC: u32 = 0x5844_3244;
const XFS_DIR3_LEAF1_MAGIC: u16 = 0x3df1;
const XFS_DIR3_LEAFN_MAGIC: u16 = 0x3dff;
const XFS_DA3_NODE_MAGIC: u16 = 0x3ebe;
const DIR3_DATA_HDR_LEN: usize = 64;
const DIR2_DATA_HDR_LEN: usize = 16;
const XFS_DIR2_LEAF_OFFSET: u64 = 1 << 35;
const BLOCK_TAIL_LEN: usize = 8;
const LEAF_ENTRY_LEN: usize = 8;
const DATA_FREE_TAG: u16 = 0xffff;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirEntry {
pub name: Vec<u8>,
pub inode: u64,
pub ftype: Option<u8>,
}
#[inline]
const fn align8(n: usize) -> usize {
n.saturating_add(7) & !7
}
#[must_use]
pub fn read_shortform_dir(fork: &[u8], has_ftype: bool) -> Vec<DirEntry> {
let count = usize::from(u8_at(fork, 0));
let i8count = u8_at(fork, 1);
let inum_width = if i8count == 0 { 4 } else { 8 };
let mut off = 2 + inum_width;
let mut entries = Vec::with_capacity(count);
for _ in 0..count {
let namelen = usize::from(u8_at(fork, off));
let name_start = off + 3;
let name_end = name_start + namelen;
let Some(name) = fork.get(name_start..name_end) else {
break; };
let ftype_off = name_end;
let (ftype, inum_off) = if has_ftype {
(Some(u8_at(fork, ftype_off)), ftype_off + 1)
} else {
(None, ftype_off)
};
let inum_end = inum_off + inum_width;
let Some(inum_bytes) = fork.get(inum_off..inum_end) else {
break; };
let inode = read_inum(inum_bytes);
entries.push(DirEntry {
name: name.to_vec(),
inode,
ftype,
});
off = inum_end;
}
entries
}
#[inline]
fn read_inum(bytes: &[u8]) -> u64 {
match bytes.len() {
4 => u64::from(be_u32(bytes, 0)),
_ => be_u64(bytes, 0),
}
}
pub fn read_block_dir(block: &[u8], has_ftype: bool) -> Result<Vec<DirEntry>, XfsError> {
let magic = be_u32(block, 0);
let hdr_len = match magic {
XFS_DIR3_BLOCK_MAGIC => DIR3_DATA_HDR_LEN,
XFS_DIR2_BLOCK_MAGIC => DIR2_DATA_HDR_LEN,
other => {
return Err(XfsError::UnsupportedDir {
detail: format!(
"block directory: unrecognized data-block magic {other:#010x} \
(bytes {:02x?}), expected XDB3 (0x58444233) or XD2B (0x58443242)",
&block.get(0..4).unwrap_or(&[])
),
});
}
};
let blocksize = block.len();
let leaf_start = if blocksize >= BLOCK_TAIL_LEN {
let count = usize::try_from(be_u32(block, blocksize - BLOCK_TAIL_LEN)).unwrap_or(0);
let leaf_bytes = count.saturating_mul(LEAF_ENTRY_LEN);
blocksize
.saturating_sub(BLOCK_TAIL_LEN)
.saturating_sub(leaf_bytes)
} else {
0
};
let region_end = leaf_start.max(hdr_len).min(blocksize);
Ok(walk_data_entries(block, hdr_len, region_end, has_ftype))
}
pub fn read_data_dir_block(block: &[u8], has_ftype: bool) -> Result<Vec<DirEntry>, XfsError> {
let magic = be_u32(block, 0);
let hdr_len = match magic {
XFS_DIR3_DATA_MAGIC => DIR3_DATA_HDR_LEN,
XFS_DIR2_DATA_MAGIC => DIR2_DATA_HDR_LEN,
other => {
return Err(XfsError::UnsupportedDir {
detail: format!(
"leaf/node directory data block: unrecognized data-block magic \
{other:#010x} (bytes {:02x?}), expected XDD3 (0x58444433) or \
XD2D (0x58443244)",
&block.get(0..4).unwrap_or(&[])
),
});
}
};
Ok(walk_data_entries(block, hdr_len, block.len(), has_ftype))
}
#[must_use]
pub fn verify_dir_block_crc(block: &[u8]) -> Option<bool> {
match be_u32(block, 0) {
XFS_DIR3_BLOCK_MAGIC | XFS_DIR3_DATA_MAGIC => {
return Some(verify_crc(block, DIR3_DATA_CRC_OFF));
}
XFS_DIR2_BLOCK_MAGIC | XFS_DIR2_DATA_MAGIC => return None,
_ => {}
}
match be_u16(block, 8) {
XFS_DIR3_LEAF1_MAGIC | XFS_DIR3_LEAFN_MAGIC | XFS_DA3_NODE_MAGIC => {
Some(verify_crc(block, DA3_BLKINFO_CRC_OFF))
}
_ => None,
}
}
fn walk_data_entries(block: &[u8], start: usize, end: usize, has_ftype: bool) -> Vec<DirEntry> {
let mut entries = Vec::new();
let mut off = start;
while off + 3 <= end {
if be_u16(block, off) == DATA_FREE_TAG {
let free_len = usize::from(be_u16(block, off + 2));
off = off.saturating_add(free_len.max(align8(1)));
continue;
}
let inode = be_u64(block, off);
let namelen = usize::from(u8_at(block, off + 8));
if namelen == 0 {
break;
}
let name_start = off + 9;
let name_end = name_start + namelen;
let Some(name) = block.get(name_start..name_end) else {
break; };
let ftype = if has_ftype {
Some(u8_at(block, name_end))
} else {
None
};
entries.push(DirEntry {
name: name.to_vec(),
inode,
ftype,
});
let ftype_len = usize::from(has_ftype);
let raw = 8 + 1 + namelen + ftype_len + 2;
off = off.saturating_add(align8(raw));
}
entries
}
impl Superblock {
pub fn read_dir(&self, image: &[u8], inode: &Inode) -> Result<Vec<DirEntry>, XfsError> {
match inode.format {
InodeFormat::Local => Ok(read_shortform_dir(&inode.data_fork, self.has_ftype())),
InodeFormat::Extents => {
let blocksize = u64::from(self.blocksize);
if inode.size == blocksize {
let block = self.read_file(image, inode)?;
read_block_dir(&block, self.has_ftype())
} else {
let recs = read_extents(&inode.data_fork, inode.nextents);
Ok(self.read_multiblock_dir(image, &recs))
}
}
InodeFormat::Btree => {
let recs = read_btree_extents(image, self, &inode.data_fork)?;
Ok(self.read_multiblock_dir(image, &recs))
}
other => Err(XfsError::UnsupportedDir {
detail: format!("directory format {other:?} not yet supported (dev/other)"),
}),
}
}
fn read_multiblock_dir(&self, image: &[u8], recs: &[BmbtRec]) -> Vec<DirEntry> {
let blocksize = self.blocksize as usize;
let has_ftype = self.has_ftype();
let leaf_boundary_block = XFS_DIR2_LEAF_OFFSET / u64::from(self.blocksize).max(1);
let mut entries = Vec::new();
for rec in recs {
if rec.startoff >= leaf_boundary_block {
continue;
}
for b in 0..rec.blockcount {
let fsblock = rec.startblock.saturating_add(b);
let Some(start) = (fsblock as usize).checked_mul(blocksize) else {
continue; };
let Some(block) = image.get(start..start.saturating_add(blocksize)) else {
continue; };
if let Ok(mut es) = read_data_dir_block(block, has_ftype) {
entries.append(&mut es);
}
}
}
entries
}
}
pub fn read_dir(image: &[u8], sb: &Superblock, inode: &Inode) -> Result<Vec<DirEntry>, XfsError> {
sb.read_dir(image, inode)
}
pub fn read_by_path(image: &[u8], sb: &Superblock, path: &str) -> Result<Vec<u8>, XfsError> {
let components: Vec<&str> = path.split('/').filter(|c| !c.is_empty()).collect();
let mut current = sb.read_inode(image, sb.rootino)?;
for (idx, comp) in components.iter().enumerate() {
let entries = sb.read_dir(image, ¤t)?;
let Some(entry) = entries.iter().find(|e| e.name == comp.as_bytes()) else {
return Err(XfsError::PathNotFound {
path: path.to_string(),
component: (*comp).to_string(),
});
};
let next = sb.read_inode(image, entry.inode)?;
let is_last = idx + 1 == components.len();
if is_last {
return sb.read_file(image, &next);
}
if !next.is_dir() {
return Err(XfsError::PathNotFound {
path: path.to_string(),
component: (*comp).to_string(),
});
}
current = next;
}
Err(XfsError::PathNotFound {
path: path.to_string(),
component: String::new(),
})
}