xfs/inode.rs
1//! XFS inode core (`di_core`) parse — v2 (v4 image) and v3 (v5 image).
2//!
3//! Reads a single inode from its inode-sized slice and decodes the core fields
4//! a forensic tool needs: identity/mode/format selector, size/extent counts,
5//! and the timestamps (with the v3 **bigtime** vs legacy branch). Field offsets
6//! follow `struct xfs_dinode` in `fs/xfs/libxfs/xfs_format.h`; the data-fork
7//! union ("u") begins at **offset 176** on v3 and **offset 100** on v2 — the
8//! offset P3/P4 use to find the extent array / short-form directory.
9//!
10//! ## Timestamp encoding (the load-bearing branch)
11//!
12//! Every timestamp is a `__be64` on disk. Two decodings, selected by the v3
13//! `di_flags2` BIGTIME bit:
14//!
15//! - **Legacy** (v2 always; v3 without BIGTIME): high 32 bits = signed seconds
16//! from the Unix epoch, low 32 = nanoseconds. Seconds are *signed* so a
17//! pre-1970 stamp decodes negative.
18//! - **Bigtime** (v3 with `XFS_DIFLAG2_BIGTIME`): an *unsigned* 64-bit
19//! nanosecond counter from the epoch `1901-12-13 20:45:52 UTC`. Decode is
20//! `sec = raw / 1e9 - 2^31`, `nsec = raw % 1e9` (the kernel's
21//! `xfs_inode_decode_bigtime` / `xfs_bigtime_to_unix`).
22
23use crate::bytes::{be_u16, be_u32, be_u64, u8_at};
24use crate::crc::{crc_status, DINODE_CRC_OFF};
25use crate::error::XfsError;
26
27/// The XFS inode magic number, ASCII `"IN"` at byte 0 (`XFS_DINODE_MAGIC`).
28pub const XFS_DINODE_MAGIC: u16 = 0x494e;
29
30/// `XFS_DIFLAG2_BIGTIME` (bit 3) — set in v3 `di_flags2` when timestamps use the
31/// 64-bit bigtime counter instead of the legacy `(sec:i32, nsec:i32)` pair.
32pub const XFS_DIFLAG2_BIGTIME: u64 = 1 << 3;
33
34/// Difference between the Unix epoch and the bigtime epoch, in seconds
35/// (`XFS_BIGTIME_EPOCH_OFFSET = -(int64_t)S32_MIN = 2^31`).
36const XFS_BIGTIME_EPOCH_OFFSET: i64 = 1 << 31;
37
38/// Nanoseconds per second.
39const NSEC_PER_SEC: u64 = 1_000_000_000;
40
41/// Data-fork ("u" union) start offset within the inode.
42const V2_LITINO_OFFSET: usize = 100;
43const V3_LITINO_OFFSET: usize = 176;
44
45/// Minimum bytes to parse a v2 inode core (through the data-fork start at 100).
46const V2_MIN_LEN: usize = V2_LITINO_OFFSET;
47/// Minimum bytes to parse a v3 inode core (through `di_uuid`, ending at 176).
48const V3_MIN_LEN: usize = V3_LITINO_OFFSET;
49
50/// The `S_IFMT` file-type mask and the type values (POSIX; XFS reuses them
51/// verbatim in `di_mode`).
52const S_IFMT: u16 = 0o170_000;
53const S_IFIFO: u16 = 0o010_000;
54const S_IFCHR: u16 = 0o020_000;
55const S_IFDIR: u16 = 0o040_000;
56const S_IFBLK: u16 = 0o060_000;
57const S_IFREG: u16 = 0o100_000;
58const S_IFLNK: u16 = 0o120_000;
59const S_IFSOCK: u16 = 0o140_000;
60
61/// The data-fork format selector (`di_format` / `di_aformat`).
62///
63/// P3/P4 branch on this to interpret the fork: [`InodeFormat::Local`] is inline
64/// data (short-form dir / symlink), [`InodeFormat::Extents`] is an inline
65/// `xfs_bmbt_rec` array, [`InodeFormat::Btree`] is an inline bmap-btree root.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum InodeFormat {
69 /// `XFS_DINODE_FMT_DEV` (0) — device number in the fork.
70 Dev,
71 /// `XFS_DINODE_FMT_LOCAL` (1) — inline data (short-form dir / symlink).
72 Local,
73 /// `XFS_DINODE_FMT_EXTENTS` (2) — inline `xfs_bmbt_rec` extent array.
74 Extents,
75 /// `XFS_DINODE_FMT_BTREE` (3) — inline bmap-btree root header.
76 Btree,
77 /// Any other value (e.g. 5 = the unused `UUID` format) — carried verbatim so
78 /// an unrecognized selector shows its value rather than being coerced.
79 Other(u8),
80}
81
82impl InodeFormat {
83 /// Decode a raw `di_format` / `di_aformat` byte, preserving unknowns.
84 #[must_use]
85 pub fn from_raw(v: u8) -> Self {
86 match v {
87 0 => Self::Dev,
88 1 => Self::Local,
89 2 => Self::Extents,
90 3 => Self::Btree,
91 other => Self::Other(other),
92 }
93 }
94}
95
96/// The `S_IFMT` file type decoded from `di_mode`.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98#[non_exhaustive]
99pub enum FileType {
100 /// FIFO / named pipe (`S_IFIFO`).
101 Fifo,
102 /// Character device (`S_IFCHR`).
103 CharDevice,
104 /// Directory (`S_IFDIR`).
105 Directory,
106 /// Block device (`S_IFBLK`).
107 BlockDevice,
108 /// Regular file (`S_IFREG`).
109 Regular,
110 /// Symbolic link (`S_IFLNK`).
111 Symlink,
112 /// Unix-domain socket (`S_IFSOCK`).
113 Socket,
114 /// A type field not matching any known `S_IFMT` value — carried verbatim.
115 Other(u16),
116}
117
118impl FileType {
119 /// Decode the `S_IFMT` type bits of a `di_mode`.
120 #[must_use]
121 pub fn from_mode(mode: u16) -> Self {
122 match mode & S_IFMT {
123 S_IFIFO => Self::Fifo,
124 S_IFCHR => Self::CharDevice,
125 S_IFDIR => Self::Directory,
126 S_IFBLK => Self::BlockDevice,
127 S_IFREG => Self::Regular,
128 S_IFLNK => Self::Symlink,
129 S_IFSOCK => Self::Socket,
130 other => Self::Other(other),
131 }
132 }
133}
134
135/// A decoded inode timestamp: signed Unix seconds + nanoseconds.
136///
137/// Stored as `(secs: i64, nsecs: u32)` rather than a calendar type so the core
138/// stays free of any date/time dependency (a consumer converts as it wishes).
139/// `secs` is signed because legacy timestamps carry a signed 32-bit seconds
140/// field (pre-1970 stamps are negative).
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub struct XfsTimestamp {
143 /// Seconds from the Unix epoch (signed).
144 pub secs: i64,
145 /// Nanoseconds within the second (`0..1_000_000_000`).
146 pub nsecs: u32,
147}
148
149impl XfsTimestamp {
150 /// Decode a raw `__be64` timestamp using the legacy `(sec:i32, nsec:i32)`
151 /// packing: high 32 bits = signed seconds, low 32 = nanoseconds.
152 #[must_use]
153 fn from_legacy(raw: u64) -> Self {
154 let secs = i64::from((raw >> 32) as i32);
155 let nsecs = (raw & 0xffff_ffff) as u32;
156 Self { secs, nsecs }
157 }
158
159 /// Decode a raw `__be64` bigtime counter (unsigned nanoseconds from the
160 /// 1901 epoch): `sec = raw/1e9 - 2^31`, `nsec = raw%1e9`.
161 #[must_use]
162 fn from_bigtime(raw: u64) -> Self {
163 let ondisk_secs = raw / NSEC_PER_SEC;
164 let nsecs = (raw % NSEC_PER_SEC) as u32;
165 // ondisk_secs fits in i64 (raw is u64, /1e9), so the subtraction is
166 // exact; a hostile raw at the u64 ceiling stays within i64 range.
167 let secs = ondisk_secs as i64 - XFS_BIGTIME_EPOCH_OFFSET;
168 Self { secs, nsecs }
169 }
170
171 /// Decode with the branch chosen by `bigtime`.
172 #[must_use]
173 fn decode(raw: u64, bigtime: bool) -> Self {
174 if bigtime {
175 Self::from_bigtime(raw)
176 } else {
177 Self::from_legacy(raw)
178 }
179 }
180}
181
182/// A parsed XFS inode core (`di_core`), v2 or v3.
183///
184/// Carries the subset of `struct xfs_dinode` a forensic reader needs; the v3
185/// tail fields (`crtime`/`di_ino`/`uuid`/`crc`/`flags2`/`cowextsize`) are
186/// `Option` — `None` on a v2 inode where they do not exist. `#[non_exhaustive]`
187/// so later phases add fields without a breaking change.
188#[derive(Debug, Clone, PartialEq, Eq)]
189#[non_exhaustive]
190pub struct Inode {
191 /// `di_magic` (offset 0) — validated to equal [`XFS_DINODE_MAGIC`].
192 pub magic: u16,
193 /// `di_mode` (offset 2) — file type (`S_IFMT`) + permission bits.
194 pub mode: u16,
195 /// `di_version` (offset 4) — inode format version (1 / 2 / 3).
196 pub version: u8,
197 /// `di_format` (offset 5) — the **data-fork** format selector P3/P4 use.
198 pub format: InodeFormat,
199 /// `di_aformat` (offset 83) — the attribute-fork format selector.
200 pub aformat: u8,
201 /// `di_size` (offset 56) — logical size in bytes.
202 pub size: u64,
203 /// `di_nblocks` (offset 64) — data + btree blocks used.
204 pub nblocks: u64,
205 /// `di_nextents` (offset 76) — number of data-fork extents.
206 pub nextents: u32,
207 /// `di_anextents` (offset 80) — number of attribute-fork extents.
208 pub aextents: u16,
209 /// `di_forkoff` (offset 82) — attr-fork offset (in 8-byte units).
210 pub forkoff: u8,
211 /// `di_atime` (offset 32) — last-access time (decoded).
212 pub atime: XfsTimestamp,
213 /// `di_mtime` (offset 40) — last-modification time (decoded).
214 pub mtime: XfsTimestamp,
215 /// `di_ctime` (offset 48) — inode-change time (decoded).
216 pub ctime: XfsTimestamp,
217 /// `di_crtime` (offset 144) — creation time; `None` on v2.
218 pub crtime: Option<XfsTimestamp>,
219 /// `di_flags2` (offset 120) — extended flags (BIGTIME/…); `None` on v2.
220 pub flags2: Option<u64>,
221 /// `di_cowextsize` (offset 128) — copy-on-write extent-size hint; `None` v2.
222 pub cowextsize: Option<u32>,
223 /// `di_ino` (offset 152) — the inode's self-reference; `None` on v2. A nice
224 /// integrity check: it must equal the number used to locate the inode.
225 pub di_ino: Option<u64>,
226 /// `di_uuid` (offset 160) — owning filesystem UUID; `None` on v2.
227 pub uuid: Option<[u8; 16]>,
228 /// `di_crc` (offset 100, little-endian) — inode CRC32c; `None` on v2.
229 /// The raw stored value; [`Self::crc_valid`] carries the verification result.
230 pub crc: Option<u32>,
231 /// The v5 CRC32c status of this inode: `Some(true)` if `di_crc` (offset 100)
232 /// verifies over the whole inode-sized slice, `Some(false)` if it does not
233 /// (corrupt/tampered), or `None` on a v2 inode (no CRC). **Non-fatal** — a
234 /// bad CRC does not fail the parse; the `-forensic` layer turns it into a
235 /// Finding. Computed only when [`Self::parse`] receives the full inode; a
236 /// short slice (< inodesize) verifies as `Some(false)`.
237 pub crc_valid: Option<bool>,
238 /// The raw data-fork ("u" union) bytes — everything from
239 /// [`Self::data_fork_offset`] to the end of the inode-sized slice. For an
240 /// [`InodeFormat::Extents`] inode this holds the inline `xfs_bmbt_rec`
241 /// array P3 decodes; for [`InodeFormat::Local`] it holds the short-form
242 /// dir/symlink (P4). Empty when the slice was exactly the core length.
243 pub data_fork: Vec<u8>,
244}
245
246impl Inode {
247 /// Parse an inode core from `data` (the inode-sized slice at the byte offset
248 /// [`crate::Superblock::inode_to_location`] yields).
249 ///
250 /// # Errors
251 ///
252 /// - [`XfsError::BadMagic`] if bytes 0..2 are not `IN` — the offending value
253 /// is carried (as a `be32` with the high half zero, matching the shared
254 /// error type).
255 /// - [`XfsError::Truncated`] if `data` is shorter than the core for its
256 /// version (v2: 100 bytes; v3: 176 bytes).
257 pub fn parse(data: &[u8]) -> Result<Self, XfsError> {
258 // Identity before length so a wrong-slice error names the bytes read.
259 let magic = be_u16(data, 0);
260 if magic != XFS_DINODE_MAGIC {
261 let bytes = [0, 0, u8_at(data, 0), u8_at(data, 1)];
262 return Err(XfsError::BadMagic {
263 found: u32::from(magic),
264 bytes,
265 });
266 }
267
268 let version = u8_at(data, 4);
269 let is_v3 = version >= 3;
270 let need = if is_v3 { V3_MIN_LEN } else { V2_MIN_LEN };
271 if data.len() < need {
272 return Err(XfsError::Truncated {
273 structure: "inode core",
274 need,
275 have: data.len(),
276 });
277 }
278
279 // v3 timestamps use bigtime iff the flag is set in di_flags2; v2 never
280 // has di_flags2, so it always takes the legacy path.
281 let flags2 = if is_v3 { Some(be_u64(data, 120)) } else { None };
282 let bigtime = flags2.is_some_and(|f| f & XFS_DIFLAG2_BIGTIME != 0);
283
284 let atime = XfsTimestamp::decode(be_u64(data, 32), bigtime);
285 let mtime = XfsTimestamp::decode(be_u64(data, 40), bigtime);
286 let ctime = XfsTimestamp::decode(be_u64(data, 48), bigtime);
287
288 let (crtime, cowextsize, di_ino, uuid, crc) = if is_v3 {
289 let mut u = [0u8; 16];
290 if let Some(s) = data.get(160..176) {
291 u.copy_from_slice(s);
292 }
293 (
294 Some(XfsTimestamp::decode(be_u64(data, 144), bigtime)),
295 Some(be_u32(data, 128)),
296 Some(be_u64(data, 152)),
297 Some(u),
298 // di_crc is stored little-endian (the only LE field in the core).
299 Some(u32::from_le_bytes([
300 u8_at(data, 100),
301 u8_at(data, 101),
302 u8_at(data, 102),
303 u8_at(data, 103),
304 ])),
305 )
306 } else {
307 (None, None, None, None, None)
308 };
309
310 // The data fork ("u" union) begins at 176 (v3) / 100 (v2). Capture the
311 // remainder of the inode slice so P3/P4 can decode the inline extent
312 // array / short-form dir without re-slicing the image.
313 let fork_off = if is_v3 {
314 V3_LITINO_OFFSET
315 } else {
316 V2_LITINO_OFFSET
317 };
318 let data_fork = data.get(fork_off..).unwrap_or(&[]).to_vec();
319
320 // A v3 (v5-filesystem) inode carries a CRC32c over the whole inode-sized
321 // slice; a v2 inode has none. Non-fatal — surfaced, never fails parse.
322 let crc_valid = crc_status(is_v3, data, DINODE_CRC_OFF);
323
324 Ok(Self {
325 magic,
326 mode: be_u16(data, 2),
327 version,
328 format: InodeFormat::from_raw(u8_at(data, 5)),
329 aformat: u8_at(data, 83),
330 size: be_u64(data, 56),
331 nblocks: be_u64(data, 64),
332 nextents: be_u32(data, 76),
333 aextents: be_u16(data, 80),
334 forkoff: u8_at(data, 82),
335 atime,
336 mtime,
337 ctime,
338 crtime,
339 flags2,
340 cowextsize,
341 di_ino,
342 uuid,
343 crc,
344 crc_valid,
345 data_fork,
346 })
347 }
348
349 /// The `S_IFMT` file type from [`Self::mode`].
350 #[must_use]
351 pub fn file_type(&self) -> FileType {
352 FileType::from_mode(self.mode)
353 }
354
355 /// True if this inode is a directory.
356 #[must_use]
357 pub fn is_dir(&self) -> bool {
358 self.file_type() == FileType::Directory
359 }
360
361 /// True if this inode is a regular file.
362 #[must_use]
363 pub fn is_reg(&self) -> bool {
364 self.file_type() == FileType::Regular
365 }
366
367 /// True if the timestamps were decoded with the bigtime encoding (a v3
368 /// inode carrying `XFS_DIFLAG2_BIGTIME`).
369 #[must_use]
370 pub fn is_bigtime(&self) -> bool {
371 self.flags2.is_some_and(|f| f & XFS_DIFLAG2_BIGTIME != 0)
372 }
373
374 /// Byte offset of the data-fork ("u" union) within the inode: **176** on a
375 /// v3 inode, **100** on a v2 inode. P3/P4 read the extent array / short-form
376 /// directory starting here.
377 #[must_use]
378 pub fn data_fork_offset(&self) -> usize {
379 if self.version >= 3 {
380 V3_LITINO_OFFSET
381 } else {
382 V2_LITINO_OFFSET
383 }
384 }
385}