Skip to main content

ostrya_core/
filehdr.rs

1//! The header of a content object, its framing, and the content checksum.
2//!
3//! A content object (a `.file` or a `.filez` object) holds a framed header and
4//! then the payload. [`FileHeader`] reads and writes the header. [`frame`] and
5//! [`split_framed`] add and remove the framing. [`ContentHasher`] computes the
6//! checksum of a content object.
7
8use ostrya_gvariant::{GvDecode, GvEncode, GvType};
9use sha2::{Digest, Sha256};
10
11use crate::be::{Be32, Be64};
12use crate::checksum::Checksum;
13use crate::error::{Error, Result};
14use crate::xattr::Xattrs;
15
16pub(crate) const S_IFMT: u32 = 0o170000;
17pub(crate) const S_IFDIR: u32 = 0o040000;
18pub(crate) const S_IFREG: u32 = 0o100000;
19pub(crate) const S_IFLNK: u32 = 0o120000;
20
21/// The metadata of one file content object, common to all header wire forms.
22///
23/// # Wire forms
24///
25/// The header has two GVariant forms:
26///
27/// - The uncompressed form `(uuuusa(ayay))` holds the uid, the gid, the mode,
28///   the rdev, the symlink target, and the xattrs. The content stream of a
29///   bare mode holds this form. The content checksum uses this form.
30/// - The archive form `(tuuuusa(ayay))` holds the uncompressed payload size
31///   first, then the fields of the uncompressed form. This form is the on-disk
32///   form of `archive` mode.
33///
34/// The scalar fields (uid, gid, mode, rdev, and size) are big-endian in the
35/// serialized bytes. A `FileHeader` holds them in host order, and the parse and
36/// serialize functions convert them. The serialize functions write an rdev of
37/// 0, and the parse functions refuse an rdev that is not 0.
38///
39/// [`parse_stat_metadata`](FileHeader::parse_stat_metadata) reads a third
40/// layout, the `user.ostreemeta` xattr of a `bare-user` file object.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct FileHeader {
43    /// The owner uid.
44    pub uid: u32,
45    /// The owner gid.
46    pub gid: u32,
47    /// The full logical `st_mode`.
48    ///
49    /// The file-type bits must name a regular file or a symlink.
50    pub mode: u32,
51    /// The target of a symlink.
52    ///
53    /// A regular file must have an empty target.
54    pub symlink_target: String,
55    /// The extended attributes of the file.
56    pub xattrs: Xattrs,
57}
58
59impl FileHeader {
60    /// Returns `true` if the mode names a symlink.
61    pub fn is_symlink(&self) -> bool {
62        self.mode & S_IFMT == S_IFLNK
63    }
64
65    fn validate(&self) -> Result<()> {
66        match self.mode & S_IFMT {
67            S_IFREG => {
68                if self.symlink_target.is_empty() {
69                    Ok(())
70                } else {
71                    Err(Error::InvalidFileHeader(
72                        "regular file with a symlink target",
73                    ))
74                }
75            }
76            S_IFLNK => Ok(()),
77            _ => Err(Error::InvalidFileHeader(
78                "mode is not a regular file or symlink",
79            )),
80        }
81    }
82
83    fn build(
84        uid: u32,
85        gid: u32,
86        mode: u32,
87        rdev: u32,
88        target: &str,
89        xattrs: &[u8],
90    ) -> Result<FileHeader> {
91        if rdev != 0 {
92            return Err(Error::InvalidFileHeader("rdev is not zero"));
93        }
94        let header = FileHeader {
95            uid,
96            gid,
97            mode,
98            symlink_target: target.to_owned(),
99            xattrs: Xattrs::from_gvariant(xattrs)?,
100        };
101        header.validate()?;
102        Ok(header)
103    }
104
105    /// Parses the uncompressed header form `(uuuusa(ayay))`.
106    ///
107    /// `data` holds the header bytes with no framing. [`split_framed`] removes
108    /// the framing.
109    ///
110    /// # Errors
111    ///
112    /// - [`Error::Gvariant`] if `data` is not a normal-form GVariant of type
113    ///   `(uuuusa(ayay))`, or if the xattr array is not in normal form.
114    /// - [`Error::InvalidFileHeader`] with the reason "rdev is not zero" if
115    ///   the rdev field is not 0.
116    /// - [`Error::InvalidXattrs`] if an xattr name is not in the stored form,
117    ///   or if the names are not in strictly increasing byte order. The stored
118    ///   form has one trailing NUL, no interior NUL, and a prefix that is not
119    ///   empty.
120    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
121    ///   file or symlink" if the file-type bits of the mode name a different
122    ///   type.
123    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
124    ///   symlink target" if a regular file has a symlink target that is not
125    ///   empty.
126    pub fn parse(data: &[u8]) -> Result<FileHeader> {
127        let (uid, gid, mode, rdev, target, xattrs): (Be32, Be32, Be32, Be32, &str, &[u8]) =
128            GvDecode::decode(data)?;
129        FileHeader::build(uid.0, gid.0, mode.0, rdev.0, target, xattrs)
130    }
131
132    /// Serializes the uncompressed header form `(uuuusa(ayay))`.
133    ///
134    /// The output has no framing.
135    ///
136    /// # Errors
137    ///
138    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
139    ///   file or symlink" if the file-type bits of [`mode`](Self::mode) name a
140    ///   different type.
141    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
142    ///   symlink target" if a regular file has a symlink target that is not
143    ///   empty.
144    /// - [`Error::Gvariant`] if the symlink target holds a NUL byte.
145    pub fn serialize(&self) -> Result<Vec<u8>> {
146        self.validate()?;
147        Ok(ostrya_gvariant::encode_to_vec(self)?)
148    }
149
150    /// Parses the stat-metadata form `(uuua(ayay))`.
151    ///
152    /// The form holds the uid, the gid, and the full `st_mode`, big-endian,
153    /// then the sorted xattr array. It is the layout of a dirmeta object. It is
154    /// also the layout of the `user.ostreemeta` xattr of a `.file` object in
155    /// `bare-user` mode.
156    ///
157    /// The form has no rdev field and no symlink-target field, so the returned
158    /// header has an empty target. A `bare-user` symlink has a symlink
159    /// `st_mode` in this form and keeps its target in the file content. The
160    /// caller reads the target from the file content.
161    ///
162    /// # Errors
163    ///
164    /// - [`Error::Gvariant`] if `data` is not a normal-form GVariant of type
165    ///   `(uuua(ayay))`, or if the xattr array is not in normal form.
166    /// - [`Error::InvalidXattrs`] if an xattr name is not in the stored form,
167    ///   or if the names are not in strictly increasing byte order. The stored
168    ///   form has one trailing NUL, no interior NUL, and a prefix that is not
169    ///   empty.
170    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
171    ///   file or symlink" if the file-type bits of the mode name a different
172    ///   type. The function refuses a directory mode, so it does not read a
173    ///   dirmeta object.
174    pub fn parse_stat_metadata(data: &[u8]) -> Result<FileHeader> {
175        let (uid, gid, mode, xattrs): (Be32, Be32, Be32, &[u8]) = GvDecode::decode(data)?;
176        FileHeader::build(uid.0, gid.0, mode.0, 0, "", xattrs)
177    }
178
179    /// Serializes the stat-metadata form `(uuua(ayay))`.
180    ///
181    /// [`parse_stat_metadata`](Self::parse_stat_metadata) describes the form
182    /// and reads the output back. The output holds no symlink target, so a
183    /// symlink keeps only its `S_IFLNK` mode here.
184    ///
185    /// # Errors
186    ///
187    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
188    ///   file or symlink" if the file-type bits of [`mode`](Self::mode) name a
189    ///   different type.
190    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
191    ///   symlink target" if a regular file has a symlink target that is not
192    ///   empty.
193    pub fn serialize_stat_metadata(&self) -> Result<Vec<u8>> {
194        self.validate()?;
195        Ok(ostrya_gvariant::encode_to_vec(&(
196            Be32(self.uid),
197            Be32(self.gid),
198            Be32(self.mode),
199            &self.xattrs,
200        ))?)
201    }
202
203    /// Parses the archive header form `(tuuuusa(ayay))`.
204    ///
205    /// The function returns the header and the uncompressed payload size.
206    /// `data` holds the header bytes with no framing.
207    ///
208    /// # Errors
209    ///
210    /// - [`Error::Gvariant`] if `data` is not a normal-form GVariant of type
211    ///   `(tuuuusa(ayay))`, or if the xattr array is not in normal form.
212    /// - [`Error::InvalidFileHeader`] with the reason "rdev is not zero" if
213    ///   the rdev field is not 0.
214    /// - [`Error::InvalidXattrs`] if an xattr name is not in the stored form,
215    ///   or if the names are not in strictly increasing byte order.
216    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
217    ///   file or symlink" if the file-type bits of the mode name a different
218    ///   type.
219    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
220    ///   symlink target" if a regular file has a symlink target that is not
221    ///   empty.
222    pub fn parse_archive(data: &[u8]) -> Result<(FileHeader, u64)> {
223        let (size, uid, gid, mode, rdev, target, xattrs): (
224            Be64,
225            Be32,
226            Be32,
227            Be32,
228            Be32,
229            &str,
230            &[u8],
231        ) = GvDecode::decode(data)?;
232        Ok((
233            FileHeader::build(uid.0, gid.0, mode.0, rdev.0, target, xattrs)?,
234            size.0,
235        ))
236    }
237
238    /// Serializes the archive header form `(tuuuusa(ayay))`.
239    ///
240    /// `uncompressed_size` is the size of the payload before compression. The
241    /// output has no framing.
242    ///
243    /// # Errors
244    ///
245    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
246    ///   file or symlink" if the file-type bits of [`mode`](Self::mode) name a
247    ///   different type.
248    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
249    ///   symlink target" if a regular file has a symlink target that is not
250    ///   empty.
251    /// - [`Error::Gvariant`] if the symlink target holds a NUL byte.
252    pub fn serialize_archive(&self, uncompressed_size: u64) -> Result<Vec<u8>> {
253        self.validate()?;
254        Ok(ostrya_gvariant::encode_to_vec(
255            &self.archive_fields(uncompressed_size),
256        )?)
257    }
258
259    /// Writes the framed uncompressed header form into `out`.
260    ///
261    /// The bytes equal `frame(&self.serialize()?)`. The function clears `out`
262    /// first. A caller that uses one buffer for all its headers grows `out`
263    /// only for a header that is longer than each header before it. After an
264    /// error, the content of `out` is unspecified.
265    ///
266    /// # Errors
267    ///
268    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
269    ///   file or symlink" if the file-type bits of [`mode`](Self::mode) name a
270    ///   different type.
271    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
272    ///   symlink target" if a regular file has a symlink target that is not
273    ///   empty.
274    /// - [`Error::Gvariant`] if the symlink target holds a NUL byte.
275    /// - [`Error::InvalidFileHeader`] with the reason "header exceeds the
276    ///   framing length limit" if the header is longer than `u32::MAX` bytes.
277    pub fn write_framed(&self, out: &mut Vec<u8>) -> Result<()> {
278        self.validate()?;
279        write_framed_with(out, |out| self.encode(out))
280    }
281
282    /// Writes the framed archive header form into `out`.
283    ///
284    /// The bytes equal `frame(&self.serialize_archive(uncompressed_size)?)`.
285    /// The buffer rules of [`write_framed`](Self::write_framed) apply.
286    ///
287    /// # Errors
288    ///
289    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
290    ///   file or symlink" if the file-type bits of [`mode`](Self::mode) name a
291    ///   different type.
292    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
293    ///   symlink target" if a regular file has a symlink target that is not
294    ///   empty.
295    /// - [`Error::Gvariant`] if the symlink target holds a NUL byte.
296    /// - [`Error::InvalidFileHeader`] with the reason "header exceeds the
297    ///   framing length limit" if the header is longer than `u32::MAX` bytes.
298    pub fn write_framed_archive(&self, uncompressed_size: u64, out: &mut Vec<u8>) -> Result<()> {
299        self.validate()?;
300        write_framed_with(out, |out| {
301            self.archive_fields(uncompressed_size).encode(out)
302        })
303    }
304
305    /// Returns the fields of the archive header form `(tuuuusa(ayay))`, with
306    /// an rdev of 0.
307    fn archive_fields(
308        &self,
309        uncompressed_size: u64,
310    ) -> (Be64, Be32, Be32, Be32, Be32, &str, &Xattrs) {
311        (
312            Be64(uncompressed_size),
313            Be32(self.uid),
314            Be32(self.gid),
315            Be32(self.mode),
316            Be32(0),
317            self.symlink_target.as_str(),
318            &self.xattrs,
319        )
320    }
321}
322
323/// Writes a framed header into `out` in four steps:
324///
325/// 1. Clears `out`.
326/// 2. Writes the framing prefix with a placeholder length.
327/// 3. Appends the header variant that `encode` writes.
328/// 4. Writes the length into the prefix.
329///
330/// The variant starts at offset 8, so its alignment in `out` is its own
331/// alignment.
332fn write_framed_with(
333    out: &mut Vec<u8>,
334    encode: impl FnOnce(&mut Vec<u8>) -> ostrya_gvariant::Result<()>,
335) -> Result<()> {
336    out.clear();
337    out.extend_from_slice(&[0u8; 8]);
338    encode(out)?;
339    let len = u32::try_from(out.len() - 8)
340        .map_err(|_| Error::InvalidFileHeader("header exceeds the framing length limit"))?;
341    out[..4].copy_from_slice(&len.to_be_bytes());
342    Ok(())
343}
344
345/// The GVariant type of the uncompressed header form, `(uuuusa(ayay))`.
346impl GvType for FileHeader {
347    const SIGNATURE: &'static str = "(uuuusa(ayay))";
348    // Greatest member alignment: the u32 fields.
349    const ALIGNMENT: usize = 4;
350    const FIXED_SIZE: Option<usize> = None;
351}
352
353/// Writes the uncompressed header form with an rdev of 0.
354///
355/// The encoder does not check the mode or the symlink target.
356/// [`FileHeader::serialize`] and [`FileHeader::write_framed`] check them.
357// The `serialize*` and `write_framed*` functions are the only callers in this
358// crate, and each one checks the header before it encodes.
359impl GvEncode for FileHeader {
360    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
361        (
362            Be32(self.uid),
363            Be32(self.gid),
364            Be32(self.mode),
365            Be32(0),
366            self.symlink_target.as_str(),
367            &self.xattrs,
368        )
369            .encode(out)
370    }
371}
372
373/// Adds the content-stream framing in front of serialized header bytes.
374///
375/// The framed bytes are `[4 bytes BE u32 length][4 NUL bytes][header]`. The
376/// length is the byte count of `header`.
377///
378/// # Errors
379///
380/// - [`Error::InvalidFileHeader`] with the reason "header exceeds the framing
381///   length limit" if `header` is longer than `u32::MAX` bytes.
382pub fn frame(header: &[u8]) -> Result<Vec<u8>> {
383    let len = u32::try_from(header.len())
384        .map_err(|_| Error::InvalidFileHeader("header exceeds the framing length limit"))?;
385    let mut out = Vec::with_capacity(8 + header.len());
386    out.extend_from_slice(&len.to_be_bytes());
387    out.extend_from_slice(&[0u8; 4]);
388    out.extend_from_slice(header);
389    Ok(out)
390}
391
392/// Splits a framed content stream into the header bytes and the rest.
393///
394/// The header bytes have no framing. The rest is the payload, if the stream
395/// has one. [`frame`] describes the framing.
396///
397/// # Errors
398///
399/// - [`Error::InvalidFileHeader`] with the reason "framed stream is shorter
400///   than its length prefix" if `data` is shorter than 8 bytes.
401/// - [`Error::InvalidFileHeader`] with the reason "framing padding is not
402///   zero" if one of the bytes 4 to 7 is not 0.
403/// - [`Error::InvalidFileHeader`] with the reason "framed header length is out
404///   of bounds" if the length in the prefix points past the end of `data`.
405pub fn split_framed(data: &[u8]) -> Result<(&[u8], &[u8])> {
406    if data.len() < 8 {
407        return Err(Error::InvalidFileHeader(
408            "framed stream is shorter than its length prefix",
409        ));
410    }
411    let len = u32::from_be_bytes(data[..4].try_into().unwrap()) as usize;
412    if data[4..8] != [0u8; 4] {
413        return Err(Error::InvalidFileHeader("framing padding is not zero"));
414    }
415    let end = 8usize
416        .checked_add(len)
417        .filter(|&end| end <= data.len())
418        .ok_or(Error::InvalidFileHeader(
419            "framed header length is out of bounds",
420        ))?;
421    Ok((&data[8..end], &data[end..]))
422}
423
424/// A streaming hasher for the checksum of a content object.
425///
426/// The checksum is the SHA-256 digest of the framed uncompressed header, then
427/// the raw payload. The raw payload is the payload before compression. A
428/// symlink has no payload, so its checksum is the result of
429/// [`finish`](ContentHasher::finish) directly after
430/// [`new`](ContentHasher::new).
431///
432/// # Examples
433///
434/// ```
435/// use ostrya_core::filehdr::{ContentHasher, FileHeader, frame};
436/// use ostrya_core::{Checksum, Xattrs};
437///
438/// // A regular file: uid 0, gid 0, mode 0644, no xattrs.
439/// let header = FileHeader {
440///     uid: 0,
441///     gid: 0,
442///     mode: 0o100644,
443///     symlink_target: String::new(),
444///     xattrs: Xattrs::empty(),
445/// };
446/// let payload = b"hello, world\n";
447///
448/// let mut hasher = ContentHasher::new(&header)?;
449/// for chunk in payload.chunks(4) {
450///     hasher.update(chunk);
451/// }
452/// let checksum = hasher.finish();
453///
454/// // The same digest over the framed header and the payload in one buffer.
455/// let mut stream = frame(&header.serialize()?)?;
456/// stream.extend_from_slice(payload);
457/// assert_eq!(checksum, Checksum::sha256(&stream));
458/// # Ok::<(), ostrya_core::Error>(())
459/// ```
460pub struct ContentHasher {
461    hasher: Sha256,
462}
463
464impl ContentHasher {
465    /// Creates a hasher and feeds it the framed uncompressed form of `header`.
466    ///
467    /// The function feeds the framing prefix and the header bytes to the
468    /// hasher one after the other. It builds no framed buffer.
469    ///
470    /// # Errors
471    ///
472    /// - [`Error::InvalidFileHeader`] with the reason "mode is not a regular
473    ///   file or symlink" if the file-type bits of the mode name a different
474    ///   type.
475    /// - [`Error::InvalidFileHeader`] with the reason "regular file with a
476    ///   symlink target" if a regular file has a symlink target that is not
477    ///   empty.
478    /// - [`Error::Gvariant`] if the symlink target holds a NUL byte.
479    /// - [`Error::InvalidFileHeader`] with the reason "header exceeds the
480    ///   framing length limit" if the header is longer than `u32::MAX` bytes.
481    pub fn new(header: &FileHeader) -> Result<ContentHasher> {
482        let serialized = header.serialize()?;
483        let len = u32::try_from(serialized.len())
484            .map_err(|_| Error::InvalidFileHeader("header exceeds the framing length limit"))?;
485        let mut hasher = Sha256::new();
486        hasher.update(len.to_be_bytes());
487        hasher.update([0u8; 4]);
488        hasher.update(&serialized);
489        Ok(ContentHasher { hasher })
490    }
491
492    /// Feeds the next chunk of the raw payload to the hasher.
493    pub fn update(&mut self, payload: &[u8]) {
494        self.hasher.update(payload);
495    }
496
497    /// Returns the checksum of the content object.
498    pub fn finish(self) -> Checksum {
499        Checksum::from_bytes(self.hasher.finalize().into())
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506    use ostrya_gvariant::{Type, Value, to_bytes};
507
508    fn regular(mode: u32) -> FileHeader {
509        FileHeader {
510            uid: 1000,
511            gid: 1000,
512            mode,
513            symlink_target: String::new(),
514            xattrs: Xattrs::empty(),
515        }
516    }
517
518    fn symlink(target: &str) -> FileHeader {
519        FileHeader {
520            uid: 0,
521            gid: 0,
522            mode: 0o120777,
523            symlink_target: target.to_owned(),
524            xattrs: Xattrs::empty(),
525        }
526    }
527
528    #[test]
529    fn uncompressed_form_round_trips() {
530        let header = FileHeader {
531            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"1".to_vec())]).unwrap(),
532            ..regular(0o100644)
533        };
534        let bytes = header.serialize().unwrap();
535        assert_eq!(FileHeader::parse(&bytes).unwrap(), header);
536
537        let link = symlink("target");
538        let bytes = link.serialize().unwrap();
539        assert_eq!(FileHeader::parse(&bytes).unwrap(), link);
540    }
541
542    #[test]
543    fn archive_form_round_trips_with_the_size() {
544        let header = regular(0o100755);
545        let bytes = header.serialize_archive(1234).unwrap();
546        assert_eq!(FileHeader::parse_archive(&bytes).unwrap(), (header, 1234));
547    }
548
549    /// Checks that the framed forms equal the framing of the serialized forms.
550    /// The test uses a regular file with xattrs and a symlink, and a buffer
551    /// that holds bytes of an earlier call. A header that fails a check is
552    /// refused.
553    #[test]
554    fn the_framed_forms_equal_the_framed_serialization() {
555        let with_xattrs = FileHeader {
556            xattrs: Xattrs::new([
557                (b"user.a\0".to_vec(), b"1".to_vec()),
558                (b"user.bb\0".to_vec(), vec![7; 300]),
559            ])
560            .unwrap(),
561            ..regular(0o100644)
562        };
563        let mut out = vec![0xaa; 1000];
564        for header in [regular(0o100755), with_xattrs, symlink("a/target")] {
565            header.write_framed(&mut out).unwrap();
566            assert_eq!(out, frame(&header.serialize().unwrap()).unwrap());
567            for size in [0, 1234, u64::MAX] {
568                header.write_framed_archive(size, &mut out).unwrap();
569                assert_eq!(
570                    out,
571                    frame(&header.serialize_archive(size).unwrap()).unwrap()
572                );
573            }
574        }
575        let bad = FileHeader {
576            symlink_target: "x".into(),
577            ..regular(0o100644)
578        };
579        assert!(bad.write_framed(&mut out).is_err());
580        assert!(bad.write_framed_archive(1, &mut out).is_err());
581    }
582
583    #[test]
584    fn stat_metadata_decodes_the_bare_user_ostreemeta_form() {
585        // The exact `user.ostreemeta` bytes of a bare-user `.file` object for
586        // a 0644 regular file that root owns. The bytes come from a repository
587        // that the `ostree` command created: uid 0, gid 0, mode 0o100644 (all
588        // big-endian), no xattrs.
589        let regular = [0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x81, 0xa4];
590        let hdr = FileHeader::parse_stat_metadata(&regular).unwrap();
591        assert_eq!((hdr.uid, hdr.gid, hdr.mode), (0, 0, 0o100644));
592        assert!(!hdr.is_symlink());
593        assert_eq!(hdr.symlink_target, "");
594        assert!(hdr.xattrs.is_empty());
595
596        // The symlink form holds an S_IFLNK mode. The target is in the file
597        // content, so the target of the parsed header stays empty.
598        let symlink = [0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xa1, 0xff];
599        let hdr = FileHeader::parse_stat_metadata(&symlink).unwrap();
600        assert_eq!((hdr.uid, hdr.gid, hdr.mode), (0, 0, 0o120777));
601        assert!(hdr.is_symlink());
602        assert_eq!(hdr.symlink_target, "");
603
604        // The wire layout is the dirmeta layout. A directory mode names no
605        // regular file and no symlink, so the parse refuses it. This decoder
606        // reads `.file` objects only.
607        let dir_meta = crate::DirMeta {
608            uid: 1000,
609            gid: 100,
610            mode: 0o40750,
611            xattrs: Xattrs::empty(),
612        };
613        assert_eq!(
614            FileHeader::parse_stat_metadata(&dir_meta.serialize().unwrap()),
615            Err(Error::InvalidFileHeader(
616                "mode is not a regular file or symlink"
617            ))
618        );
619
620        // A file-mode header with xattrs round-trips its fields.
621        let with_xattr = ostrya_gvariant::encode_to_vec(&(
622            Be32(0),
623            Be32(0),
624            Be32(0o100600),
625            &Xattrs::new([(b"user.a\0".to_vec(), b"v".to_vec())]).unwrap(),
626        ))
627        .unwrap();
628        let hdr = FileHeader::parse_stat_metadata(&with_xattr).unwrap();
629        assert_eq!(hdr.mode, 0o100600);
630        assert_eq!(hdr.xattrs.len(), 1);
631    }
632
633    /// Serializes any uncompressed-form header through the `Value` tree. The
634    /// checks of `FileHeader` do not run.
635    fn craft(uid: u32, gid: u32, mode: u32, rdev: u32, target: &str) -> Vec<u8> {
636        let ty = Type::parse("(uuuusa(ayay))").unwrap();
637        let value = Value::Tuple(vec![
638            Value::U32(uid.swap_bytes()),
639            Value::U32(gid.swap_bytes()),
640            Value::U32(mode.swap_bytes()),
641            Value::U32(rdev.swap_bytes()),
642            Value::Str(target.to_owned()),
643            Value::Array(Vec::new()),
644        ]);
645        to_bytes(&ty, &value).unwrap()
646    }
647
648    #[test]
649    fn stat_metadata_serialize_round_trips_and_matches_the_tool_bytes() {
650        // A 0644 regular file that root owns. These are the exact
651        // `user.ostreemeta` bytes of a bare-user `.file` object, from a
652        // repository that the `ostree` command created.
653        let header = regular(0o100644);
654        let header = FileHeader {
655            uid: 0,
656            gid: 0,
657            ..header
658        };
659        assert_eq!(
660            header.serialize_stat_metadata().unwrap(),
661            [0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x81, 0xa4]
662        );
663
664        // A symlink stored as a regular file keeps mode S_IFLNK|0777 here. The
665        // `ostree` command writes these 12 bytes to the user.ostreemeta xattr
666        // of a symlink with uid 1000 and gid 100.
667        let link = FileHeader {
668            uid: 1000,
669            gid: 100,
670            ..symlink("hello.txt")
671        };
672        assert_eq!(
673            link.serialize_stat_metadata().unwrap(),
674            [0u8, 0, 3, 0xe8, 0, 0, 0, 0x64, 0, 0, 0xa1, 0xff]
675        );
676
677        // A header with xattrs round-trips through parse.
678        let with_xattr = FileHeader {
679            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"1".to_vec())]).unwrap(),
680            ..regular(0o100600)
681        };
682        let bytes = with_xattr.serialize_stat_metadata().unwrap();
683        let parsed = FileHeader::parse_stat_metadata(&bytes).unwrap();
684        assert_eq!(
685            (parsed.uid, parsed.gid, parsed.mode, parsed.xattrs),
686            (
687                with_xattr.uid,
688                with_xattr.gid,
689                with_xattr.mode,
690                with_xattr.xattrs
691            )
692        );
693    }
694
695    #[test]
696    fn parse_rejects_nonzero_rdev_and_bad_modes() {
697        assert_eq!(
698            FileHeader::parse(&craft(0, 0, 0o100644, 5, "")),
699            Err(Error::InvalidFileHeader("rdev is not zero"))
700        );
701        for mode in [0o040755, 0o020666, 0o010644, 0o140777] {
702            assert_eq!(
703                FileHeader::parse(&craft(0, 0, mode, 0, "")),
704                Err(Error::InvalidFileHeader(
705                    "mode is not a regular file or symlink"
706                )),
707                "mode {mode:o}"
708            );
709        }
710        assert_eq!(
711            FileHeader::parse(&craft(0, 0, 0o100644, 0, "oops")),
712            Err(Error::InvalidFileHeader(
713                "regular file with a symlink target"
714            ))
715        );
716    }
717
718    #[test]
719    fn serialize_rejects_what_parse_rejects() {
720        assert!(regular(0o040755).serialize().is_err());
721        let mut bad = regular(0o100644);
722        bad.symlink_target = "oops".into();
723        assert!(bad.serialize().is_err());
724    }
725
726    #[test]
727    fn framing_round_trips_and_is_strict() {
728        let header = regular(0o100644).serialize().unwrap();
729        let framed = frame(&header).unwrap();
730        assert_eq!(
731            u32::from_be_bytes(framed[..4].try_into().unwrap()) as usize,
732            header.len()
733        );
734        assert_eq!(&framed[4..8], [0u8; 4]);
735        let with_payload = [framed.clone(), b"payload".to_vec()].concat();
736        let (got_header, payload) = split_framed(&with_payload).unwrap();
737        assert_eq!(got_header, header);
738        assert_eq!(payload, b"payload");
739
740        let mut bad_pad = framed.clone();
741        bad_pad[5] = 1;
742        assert_eq!(
743            split_framed(&bad_pad),
744            Err(Error::InvalidFileHeader("framing padding is not zero"))
745        );
746        let mut bad_len = framed;
747        bad_len[..4].copy_from_slice(&u32::MAX.to_be_bytes());
748        assert_eq!(
749            split_framed(&bad_len),
750            Err(Error::InvalidFileHeader(
751                "framed header length is out of bounds"
752            ))
753        );
754        assert!(split_framed(&[0u8; 7]).is_err());
755    }
756
757    #[test]
758    fn symlink_checksum_hashes_the_framed_header_only() {
759        let link = symlink("hello.txt");
760        let framed = frame(&link.serialize().unwrap()).unwrap();
761        assert_eq!(
762            ContentHasher::new(&link).unwrap().finish(),
763            Checksum::sha256(&framed)
764        );
765    }
766
767    #[test]
768    fn scalar_fields_are_big_endian_on_the_wire() {
769        // The uid, gid, mode, and rdev are the first four u32 members of
770        // (uuuusa(ayay)), stored big-endian. A missing or asymmetric byte
771        // swap fails this test.
772        let header = regular(0o100644); // uid 1000, gid 1000
773        let bytes = header.serialize().unwrap();
774        assert_eq!(&bytes[0..4], &1000u32.to_be_bytes());
775        assert_eq!(&bytes[4..8], &1000u32.to_be_bytes());
776        assert_eq!(&bytes[8..12], &0o100644u32.to_be_bytes());
777        assert_eq!(&bytes[12..16], &[0, 0, 0, 0]);
778        assert_eq!(FileHeader::parse(&bytes).unwrap(), header);
779    }
780
781    #[test]
782    fn the_two_wire_forms_agree_on_the_common_fields() {
783        let header = FileHeader {
784            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"1".to_vec())]).unwrap(),
785            ..regular(0o100640)
786        };
787        let from_uncompressed = FileHeader::parse(&header.serialize().unwrap()).unwrap();
788        let (from_archive, _) =
789            FileHeader::parse_archive(&header.serialize_archive(4096).unwrap()).unwrap();
790        assert_eq!(from_uncompressed, header);
791        assert_eq!(from_archive, header);
792    }
793}