Skip to main content

ostrya_core/
filehdr.rs

1//! File content-object headers and the content checksum.
2//!
3//! A content object (`.file` / `.filez`) is a header GVariant followed by the
4//! payload. Two header wire forms exist:
5//!
6//! - uncompressed `(uuuusa(ayay))` -- bare-mode streams and checksum
7//!   computation;
8//! - archive `(tuuuusa(ayay))` -- stored on disk in archive mode, with the
9//!   uncompressed payload size prepended.
10//!
11//! The scalar fields (uid, gid, mode, rdev, size) are big-endian at the value
12//! level; [`FileHeader`] holds them in host order and the (de)serializers
13//! convert. On parse, a nonzero rdev and a mode that is neither a regular
14//! file nor a symlink are rejected.
15//!
16//! The on-disk framing of a content stream prefixes the header variant with
17//! its length: `[4 bytes BE u32 length][4 NUL bytes][header variant]`. The
18//! object checksum is SHA-256 over the framed uncompressed header followed by
19//! the raw payload; [`ContentHasher`] computes it.
20
21use ostrya_gvariant::{GvDecode, GvEncode, GvType};
22use sha2::{Digest, Sha256};
23
24use crate::be::{Be32, Be64};
25use crate::checksum::Checksum;
26use crate::error::{Error, Result};
27use crate::xattr::Xattrs;
28
29pub(crate) const S_IFMT: u32 = 0o170000;
30pub(crate) const S_IFDIR: u32 = 0o040000;
31pub(crate) const S_IFREG: u32 = 0o100000;
32pub(crate) const S_IFLNK: u32 = 0o120000;
33
34/// The metadata of one file content object, common to all header wire forms.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct FileHeader {
37    /// The owner uid.
38    pub uid: u32,
39    /// The owner gid.
40    pub gid: u32,
41    /// Full logical `st_mode`; the file-type bits must name a regular file or
42    /// a symlink.
43    pub mode: u32,
44    /// Symlink target; must be empty for regular files.
45    pub symlink_target: String,
46    /// The file's extended attributes.
47    pub xattrs: Xattrs,
48}
49
50impl FileHeader {
51    /// Whether the mode names a symlink.
52    pub fn is_symlink(&self) -> bool {
53        self.mode & S_IFMT == S_IFLNK
54    }
55
56    fn validate(&self) -> Result<()> {
57        match self.mode & S_IFMT {
58            S_IFREG => {
59                if self.symlink_target.is_empty() {
60                    Ok(())
61                } else {
62                    Err(Error::InvalidFileHeader(
63                        "regular file with a symlink target",
64                    ))
65                }
66            }
67            S_IFLNK => Ok(()),
68            _ => Err(Error::InvalidFileHeader(
69                "mode is not a regular file or symlink",
70            )),
71        }
72    }
73
74    fn build(
75        uid: u32,
76        gid: u32,
77        mode: u32,
78        rdev: u32,
79        target: &str,
80        xattrs: &[u8],
81    ) -> Result<FileHeader> {
82        if rdev != 0 {
83            return Err(Error::InvalidFileHeader("rdev is not zero"));
84        }
85        let header = FileHeader {
86            uid,
87            gid,
88            mode,
89            symlink_target: target.to_owned(),
90            xattrs: Xattrs::from_gvariant(xattrs)?,
91        };
92        header.validate()?;
93        Ok(header)
94    }
95
96    /// Parse the uncompressed header form `(uuuusa(ayay))`.
97    pub fn parse(data: &[u8]) -> Result<FileHeader> {
98        let (uid, gid, mode, rdev, target, xattrs): (Be32, Be32, Be32, Be32, &str, &[u8]) =
99            GvDecode::decode(data)?;
100        FileHeader::build(uid.0, gid.0, mode.0, rdev.0, target, xattrs)
101    }
102
103    /// Serialize the uncompressed header form `(uuuusa(ayay))`.
104    pub fn serialize(&self) -> Result<Vec<u8>> {
105        self.validate()?;
106        Ok(ostrya_gvariant::encode_to_vec(self)?)
107    }
108
109    /// Parse the stat-metadata form `(uuua(ayay))` -- the layout dirmeta uses,
110    /// and the layout stored in the `user.ostreemeta` xattr of a bare-user
111    /// `.file` object. The three scalar fields are uid, gid, and the full
112    /// `st_mode` (big-endian); there is no rdev and no symlink-target field, so
113    /// the returned header has an empty target. A bare-user symlink carries a
114    /// symlink `st_mode` here and keeps its target in the file content, which
115    /// the caller supplies separately.
116    pub fn parse_stat_metadata(data: &[u8]) -> Result<FileHeader> {
117        let (uid, gid, mode, xattrs): (Be32, Be32, Be32, &[u8]) = GvDecode::decode(data)?;
118        FileHeader::build(uid.0, gid.0, mode.0, 0, "", xattrs)
119    }
120
121    /// Serialize the stat-metadata form `(uuua(ayay))` -- uid, gid, and the
122    /// full `st_mode` (big-endian) followed by the sorted xattr array. This is
123    /// the layout stored in the `user.ostreemeta` xattr of a bare-user `.file`
124    /// object; a bare-user symlink carries its `S_IFLNK` mode here and keeps its
125    /// target in the file content. There is no rdev or symlink-target field.
126    /// The inverse of [`parse_stat_metadata`](Self::parse_stat_metadata).
127    pub fn serialize_stat_metadata(&self) -> Result<Vec<u8>> {
128        self.validate()?;
129        Ok(ostrya_gvariant::encode_to_vec(&(
130            Be32(self.uid),
131            Be32(self.gid),
132            Be32(self.mode),
133            &self.xattrs,
134        ))?)
135    }
136
137    /// Parse the archive header form `(tuuuusa(ayay))`, returning the header
138    /// and the uncompressed payload size.
139    pub fn parse_archive(data: &[u8]) -> Result<(FileHeader, u64)> {
140        let (size, uid, gid, mode, rdev, target, xattrs): (
141            Be64,
142            Be32,
143            Be32,
144            Be32,
145            Be32,
146            &str,
147            &[u8],
148        ) = GvDecode::decode(data)?;
149        Ok((
150            FileHeader::build(uid.0, gid.0, mode.0, rdev.0, target, xattrs)?,
151            size.0,
152        ))
153    }
154
155    /// Serialize the archive header form `(tuuuusa(ayay))`.
156    pub fn serialize_archive(&self, uncompressed_size: u64) -> Result<Vec<u8>> {
157        self.validate()?;
158        Ok(ostrya_gvariant::encode_to_vec(&(
159            Be64(uncompressed_size),
160            Be32(self.uid),
161            Be32(self.gid),
162            Be32(self.mode),
163            Be32(0),
164            self.symlink_target.as_str(),
165            &self.xattrs,
166        ))?)
167    }
168}
169
170/// The uncompressed header form, `(uuuusa(ayay))`.
171impl GvType for FileHeader {
172    const SIGNATURE: &'static str = "(uuuusa(ayay))";
173    // Greatest member alignment: the u32 fields.
174    const ALIGNMENT: usize = 4;
175    const FIXED_SIZE: Option<usize> = None;
176}
177
178/// The encode path is purely mechanical: domain validation runs in the
179/// `serialize*` entry points, which are the only callers.
180impl GvEncode for FileHeader {
181    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
182        (
183            Be32(self.uid),
184            Be32(self.gid),
185            Be32(self.mode),
186            Be32(0),
187            self.symlink_target.as_str(),
188            &self.xattrs,
189        )
190            .encode(out)
191    }
192}
193
194/// Prefix serialized header bytes with the content-stream framing:
195/// `[4 bytes BE u32 length][4 NUL bytes][header]`.
196pub fn frame(header: &[u8]) -> Result<Vec<u8>> {
197    let len = u32::try_from(header.len())
198        .map_err(|_| Error::InvalidFileHeader("header exceeds the framing length limit"))?;
199    let mut out = Vec::with_capacity(8 + header.len());
200    out.extend_from_slice(&len.to_be_bytes());
201    out.extend_from_slice(&[0u8; 4]);
202    out.extend_from_slice(header);
203    Ok(out)
204}
205
206/// Split a framed content stream into the header variant bytes and the
207/// remainder (the payload, where present).
208pub fn split_framed(data: &[u8]) -> Result<(&[u8], &[u8])> {
209    if data.len() < 8 {
210        return Err(Error::InvalidFileHeader(
211            "framed stream is shorter than its length prefix",
212        ));
213    }
214    let len = u32::from_be_bytes(data[..4].try_into().unwrap()) as usize;
215    if data[4..8] != [0u8; 4] {
216        return Err(Error::InvalidFileHeader("framing padding is not zero"));
217    }
218    let end = 8usize
219        .checked_add(len)
220        .filter(|&end| end <= data.len())
221        .ok_or(Error::InvalidFileHeader(
222            "framed header length is out of bounds",
223        ))?;
224    Ok((&data[8..end], &data[end..]))
225}
226
227/// Computes a content-object checksum: SHA-256 over the framed uncompressed
228/// header followed by the raw (uncompressed) payload. Symlinks carry no
229/// payload, so their checksum is [`finish`](ContentHasher::finish) right
230/// after construction.
231pub struct ContentHasher {
232    hasher: Sha256,
233}
234
235impl ContentHasher {
236    /// Start a checksum with the framed uncompressed form of `header`. The
237    /// framing prefix and the header bytes are fed to the hasher directly,
238    /// without materializing the framed buffer.
239    pub fn new(header: &FileHeader) -> Result<ContentHasher> {
240        let serialized = header.serialize()?;
241        let len = u32::try_from(serialized.len())
242            .map_err(|_| Error::InvalidFileHeader("header exceeds the framing length limit"))?;
243        let mut hasher = Sha256::new();
244        hasher.update(len.to_be_bytes());
245        hasher.update([0u8; 4]);
246        hasher.update(&serialized);
247        Ok(ContentHasher { hasher })
248    }
249
250    /// Feed the next chunk of raw payload.
251    pub fn update(&mut self, payload: &[u8]) {
252        self.hasher.update(payload);
253    }
254
255    /// The content-object checksum.
256    pub fn finish(self) -> Checksum {
257        Checksum::from_bytes(self.hasher.finalize().into())
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use ostrya_gvariant::{Type, Value, to_bytes};
265
266    fn regular(mode: u32) -> FileHeader {
267        FileHeader {
268            uid: 1000,
269            gid: 1000,
270            mode,
271            symlink_target: String::new(),
272            xattrs: Xattrs::empty(),
273        }
274    }
275
276    fn symlink(target: &str) -> FileHeader {
277        FileHeader {
278            uid: 0,
279            gid: 0,
280            mode: 0o120777,
281            symlink_target: target.to_owned(),
282            xattrs: Xattrs::empty(),
283        }
284    }
285
286    #[test]
287    fn uncompressed_form_round_trips() {
288        let header = FileHeader {
289            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"1".to_vec())]).unwrap(),
290            ..regular(0o100644)
291        };
292        let bytes = header.serialize().unwrap();
293        assert_eq!(FileHeader::parse(&bytes).unwrap(), header);
294
295        let link = symlink("target");
296        let bytes = link.serialize().unwrap();
297        assert_eq!(FileHeader::parse(&bytes).unwrap(), link);
298    }
299
300    #[test]
301    fn archive_form_round_trips_with_the_size() {
302        let header = regular(0o100755);
303        let bytes = header.serialize_archive(1234).unwrap();
304        assert_eq!(FileHeader::parse_archive(&bytes).unwrap(), (header, 1234));
305    }
306
307    #[test]
308    fn stat_metadata_decodes_the_bare_user_ostreemeta_form() {
309        // The exact `user.ostreemeta` bytes a bare-user `.file` carries for a
310        // 0644 root-owned regular file, recovered from a tool-created repo:
311        // uid 0, gid 0, mode 0o100644 (all big-endian), no xattrs.
312        let regular = [0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x81, 0xa4];
313        let hdr = FileHeader::parse_stat_metadata(&regular).unwrap();
314        assert_eq!((hdr.uid, hdr.gid, hdr.mode), (0, 0, 0o100644));
315        assert!(!hdr.is_symlink());
316        assert_eq!(hdr.symlink_target, "");
317        assert!(hdr.xattrs.is_empty());
318
319        // The symlink form carries an S_IFLNK mode; the target lives in the
320        // file content, so the parsed header's target stays empty.
321        let symlink = [0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xa1, 0xff];
322        let hdr = FileHeader::parse_stat_metadata(&symlink).unwrap();
323        assert_eq!((hdr.uid, hdr.gid, hdr.mode), (0, 0, 0o120777));
324        assert!(hdr.is_symlink());
325        assert_eq!(hdr.symlink_target, "");
326
327        // The wire layout is exactly dirmeta's, but a directory mode names
328        // neither a regular file nor a symlink, so it is rejected: this
329        // decoder only describes `.file` objects.
330        let dir_meta = crate::DirMeta {
331            uid: 1000,
332            gid: 100,
333            mode: 0o40750,
334            xattrs: Xattrs::empty(),
335        };
336        assert_eq!(
337            FileHeader::parse_stat_metadata(&dir_meta.serialize().unwrap()),
338            Err(Error::InvalidFileHeader(
339                "mode is not a regular file or symlink"
340            ))
341        );
342
343        // A file-mode header with xattrs round-trips its fields.
344        let with_xattr = ostrya_gvariant::encode_to_vec(&(
345            Be32(0),
346            Be32(0),
347            Be32(0o100600),
348            &Xattrs::new([(b"user.a\0".to_vec(), b"v".to_vec())]).unwrap(),
349        ))
350        .unwrap();
351        let hdr = FileHeader::parse_stat_metadata(&with_xattr).unwrap();
352        assert_eq!(hdr.mode, 0o100600);
353        assert_eq!(hdr.xattrs.len(), 1);
354    }
355
356    /// Serialize an arbitrary uncompressed-form header through the `Value`
357    /// tree, bypassing the struct's validation.
358    fn craft(uid: u32, gid: u32, mode: u32, rdev: u32, target: &str) -> Vec<u8> {
359        let ty = Type::parse("(uuuusa(ayay))").unwrap();
360        let value = Value::Tuple(vec![
361            Value::U32(uid.swap_bytes()),
362            Value::U32(gid.swap_bytes()),
363            Value::U32(mode.swap_bytes()),
364            Value::U32(rdev.swap_bytes()),
365            Value::Str(target.to_owned()),
366            Value::Array(Vec::new()),
367        ]);
368        to_bytes(&ty, &value).unwrap()
369    }
370
371    #[test]
372    fn stat_metadata_serialize_round_trips_and_matches_the_tool_bytes() {
373        // A 0644 root-owned regular file: the exact `user.ostreemeta` bytes a
374        // bare-user `.file` carries, recovered from a tool-created repo.
375        let header = regular(0o100644);
376        let header = FileHeader {
377            uid: 0,
378            gid: 0,
379            ..header
380        };
381        assert_eq!(
382            header.serialize_stat_metadata().unwrap(),
383            [0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x81, 0xa4]
384        );
385
386        // A symlink stored as a regular file keeps mode S_IFLNK|0777 here; the
387        // tool writes these 12 bytes for a 1000:100 symlink's user.ostreemeta.
388        let link = FileHeader {
389            uid: 1000,
390            gid: 100,
391            ..symlink("hello.txt")
392        };
393        assert_eq!(
394            link.serialize_stat_metadata().unwrap(),
395            [0u8, 0, 3, 0xe8, 0, 0, 0, 0x64, 0, 0, 0xa1, 0xff]
396        );
397
398        // Round-trips through parse for a header bearing xattrs.
399        let with_xattr = FileHeader {
400            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"1".to_vec())]).unwrap(),
401            ..regular(0o100600)
402        };
403        let bytes = with_xattr.serialize_stat_metadata().unwrap();
404        let parsed = FileHeader::parse_stat_metadata(&bytes).unwrap();
405        assert_eq!(
406            (parsed.uid, parsed.gid, parsed.mode, parsed.xattrs),
407            (
408                with_xattr.uid,
409                with_xattr.gid,
410                with_xattr.mode,
411                with_xattr.xattrs
412            )
413        );
414    }
415
416    #[test]
417    fn parse_rejects_nonzero_rdev_and_bad_modes() {
418        assert_eq!(
419            FileHeader::parse(&craft(0, 0, 0o100644, 5, "")),
420            Err(Error::InvalidFileHeader("rdev is not zero"))
421        );
422        for mode in [0o040755, 0o020666, 0o010644, 0o140777] {
423            assert_eq!(
424                FileHeader::parse(&craft(0, 0, mode, 0, "")),
425                Err(Error::InvalidFileHeader(
426                    "mode is not a regular file or symlink"
427                )),
428                "mode {mode:o}"
429            );
430        }
431        assert_eq!(
432            FileHeader::parse(&craft(0, 0, 0o100644, 0, "oops")),
433            Err(Error::InvalidFileHeader(
434                "regular file with a symlink target"
435            ))
436        );
437    }
438
439    #[test]
440    fn serialize_rejects_what_parse_rejects() {
441        assert!(regular(0o040755).serialize().is_err());
442        let mut bad = regular(0o100644);
443        bad.symlink_target = "oops".into();
444        assert!(bad.serialize().is_err());
445    }
446
447    #[test]
448    fn framing_round_trips_and_is_strict() {
449        let header = regular(0o100644).serialize().unwrap();
450        let framed = frame(&header).unwrap();
451        assert_eq!(
452            u32::from_be_bytes(framed[..4].try_into().unwrap()) as usize,
453            header.len()
454        );
455        assert_eq!(&framed[4..8], [0u8; 4]);
456        let with_payload = [framed.clone(), b"payload".to_vec()].concat();
457        let (got_header, payload) = split_framed(&with_payload).unwrap();
458        assert_eq!(got_header, header);
459        assert_eq!(payload, b"payload");
460
461        let mut bad_pad = framed.clone();
462        bad_pad[5] = 1;
463        assert_eq!(
464            split_framed(&bad_pad),
465            Err(Error::InvalidFileHeader("framing padding is not zero"))
466        );
467        let mut bad_len = framed;
468        bad_len[..4].copy_from_slice(&u32::MAX.to_be_bytes());
469        assert_eq!(
470            split_framed(&bad_len),
471            Err(Error::InvalidFileHeader(
472                "framed header length is out of bounds"
473            ))
474        );
475        assert!(split_framed(&[0u8; 7]).is_err());
476    }
477
478    #[test]
479    fn symlink_checksum_hashes_the_framed_header_only() {
480        let link = symlink("hello.txt");
481        let framed = frame(&link.serialize().unwrap()).unwrap();
482        assert_eq!(
483            ContentHasher::new(&link).unwrap().finish(),
484            Checksum::sha256(&framed)
485        );
486    }
487
488    #[test]
489    fn scalar_fields_are_big_endian_on_the_wire() {
490        // uid/gid/mode/rdev are the first four u32 members of (uuuusa(ayay))
491        // and are stored big-endian; a missed or asymmetric swap shows here.
492        let header = regular(0o100644); // uid 1000, gid 1000
493        let bytes = header.serialize().unwrap();
494        assert_eq!(&bytes[0..4], &1000u32.to_be_bytes());
495        assert_eq!(&bytes[4..8], &1000u32.to_be_bytes());
496        assert_eq!(&bytes[8..12], &0o100644u32.to_be_bytes());
497        assert_eq!(&bytes[12..16], &[0, 0, 0, 0]);
498        assert_eq!(FileHeader::parse(&bytes).unwrap(), header);
499    }
500
501    #[test]
502    fn the_two_wire_forms_agree_on_the_common_fields() {
503        let header = FileHeader {
504            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"1".to_vec())]).unwrap(),
505            ..regular(0o100640)
506        };
507        let from_uncompressed = FileHeader::parse(&header.serialize().unwrap()).unwrap();
508        let (from_archive, _) =
509            FileHeader::parse_archive(&header.serialize_archive(4096).unwrap()).unwrap();
510        assert_eq!(from_uncompressed, header);
511        assert_eq!(from_archive, header);
512    }
513}