Skip to main content

ostrya_core/
dirmeta.rs

1//! Dirmeta objects: directory uid/gid/mode/xattrs.
2//!
3//! Wire form `(uuua(ayay))`: uid, gid, and the full `st_mode` (all big-endian
4//! at the value level) plus the sorted xattr array. The mode must carry the
5//! directory file-type bits. The same layout serves the `user.ostreemeta`
6//! xattr of bare-user file objects, but this type models `.dirmeta` objects
7//! and therefore requires a directory mode.
8
9use ostrya_gvariant::{GvDecode, GvEncode, GvType};
10
11use crate::be::Be32;
12use crate::error::{Error, Result};
13use crate::filehdr::{S_IFDIR, S_IFMT};
14use crate::xattr::{Xattrs, XattrsRef};
15
16/// An owned dirmeta object. Scalar fields are host-order.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct DirMeta {
19    /// The owner uid.
20    pub uid: u32,
21    /// The owner gid.
22    pub gid: u32,
23    /// Full `st_mode` including the directory file-type bits.
24    pub mode: u32,
25    /// The directory's extended attributes.
26    pub xattrs: Xattrs,
27}
28
29fn check_dir_mode(mode: u32) -> Result<()> {
30    if mode & S_IFMT == S_IFDIR {
31        Ok(())
32    } else {
33        Err(Error::InvalidDirMeta("mode is not a directory mode"))
34    }
35}
36
37impl DirMeta {
38    /// Parse a serialized dirmeta object.
39    pub fn parse(data: &[u8]) -> Result<DirMeta> {
40        DirMetaRef::parse(data)?.to_owned()
41    }
42
43    /// Serialize to normal-form bytes; their SHA-256 is the object identity.
44    pub fn serialize(&self) -> Result<Vec<u8>> {
45        check_dir_mode(self.mode)?;
46        Ok(ostrya_gvariant::encode_to_vec(self)?)
47    }
48}
49
50impl GvType for DirMeta {
51    const SIGNATURE: &'static str = "(uuua(ayay))";
52    // Greatest member alignment: the u32 fields.
53    const ALIGNMENT: usize = 4;
54    const FIXED_SIZE: Option<usize> = None;
55}
56
57/// The encode path is purely mechanical: the directory-mode check runs in
58/// [`DirMeta::serialize`], the only caller.
59impl GvEncode for DirMeta {
60    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
61        (
62            Be32(self.uid),
63            Be32(self.gid),
64            Be32(self.mode),
65            &self.xattrs,
66        )
67            .encode(out)
68    }
69}
70
71/// A borrowed view of a serialized dirmeta object. The scalar fields decode
72/// on parse; the xattrs stay lazy.
73#[derive(Clone, Copy)]
74pub struct DirMetaRef<'a> {
75    uid: u32,
76    gid: u32,
77    mode: u32,
78    xattrs: XattrsRef<'a>,
79}
80
81impl<'a> DirMetaRef<'a> {
82    /// Parse the slice covering exactly a serialized dirmeta object.
83    pub fn parse(data: &'a [u8]) -> Result<DirMetaRef<'a>> {
84        let (uid, gid, mode, xattrs): (Be32, Be32, Be32, &[u8]) = GvDecode::decode(data)?;
85        let mode = mode.0;
86        check_dir_mode(mode)?;
87        Ok(DirMetaRef {
88            uid: uid.0,
89            gid: gid.0,
90            mode,
91            xattrs: XattrsRef::parse(xattrs)?,
92        })
93    }
94
95    /// The owner uid, host-order.
96    pub fn uid(&self) -> u32 {
97        self.uid
98    }
99
100    /// The owner gid, host-order.
101    pub fn gid(&self) -> u32 {
102        self.gid
103    }
104
105    /// Full `st_mode`, host-order.
106    pub fn mode(&self) -> u32 {
107        self.mode
108    }
109
110    /// A borrowed view of the directory's extended attributes.
111    pub fn xattrs(&self) -> XattrsRef<'a> {
112        self.xattrs
113    }
114
115    /// Collect into an owned [`DirMeta`].
116    pub fn to_owned(&self) -> Result<DirMeta> {
117        Ok(DirMeta {
118            uid: self.uid,
119            gid: self.gid,
120            mode: self.mode,
121            xattrs: self.xattrs.to_owned()?,
122        })
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn round_trips_with_xattrs() {
132        let meta = DirMeta {
133            uid: 1000,
134            gid: 100,
135            mode: 0o40750,
136            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"v".to_vec())]).unwrap(),
137        };
138        let bytes = meta.serialize().unwrap();
139        let view = DirMetaRef::parse(&bytes).unwrap();
140        assert_eq!(view.uid(), 1000);
141        assert_eq!(view.gid(), 100);
142        assert_eq!(view.mode(), 0o40750);
143        assert_eq!(view.to_owned().unwrap(), meta);
144        assert_eq!(meta.serialize().unwrap(), bytes);
145    }
146
147    #[test]
148    fn rejects_a_non_directory_mode() {
149        let meta = DirMeta {
150            uid: 0,
151            gid: 0,
152            mode: 0o100644,
153            xattrs: Xattrs::empty(),
154        };
155        assert_eq!(
156            meta.serialize(),
157            Err(Error::InvalidDirMeta("mode is not a directory mode"))
158        );
159
160        // Craft bytes carrying a regular-file mode via the raw tuple, so the
161        // non-directory mode is rejected on the read path.
162        let bytes =
163            ostrya_gvariant::encode_to_vec(&(Be32(0), Be32(0), Be32(0o100644), &Xattrs::empty()))
164                .unwrap();
165        assert_eq!(
166            DirMetaRef::parse(&bytes).err(),
167            Some(Error::InvalidDirMeta("mode is not a directory mode"))
168        );
169    }
170}