Skip to main content

ostrya_core/
dirmeta.rs

1//! Dirmeta objects: the owner, the mode, and the xattrs of a directory.
2
3use ostrya_gvariant::{GvDecode, GvEncode, GvType};
4
5use crate::be::Be32;
6use crate::error::{Error, Result};
7use crate::filehdr::{S_IFDIR, S_IFMT};
8use crate::xattr::{Xattrs, XattrsRef};
9
10/// An owned dirmeta object: the owner, the mode, and the xattrs of a directory.
11///
12/// The scalar fields are in host byte order.
13///
14/// # Wire form
15///
16/// The GVariant type is `(uuua(ayay))`. The members are:
17///
18/// - the uid
19/// - the gid
20/// - the full `st_mode`, with the directory type bits
21/// - the xattrs, sorted by name, in the storage form of [`Xattrs`]
22///
23/// The three `u` values are big-endian. The mode must be a directory mode, so
24/// this type holds only `.dirmeta` objects. The same layout is the
25/// `user.ostreemeta` xattr of a bare-user file object.
26/// [`FileHeader::parse_stat_metadata`](crate::filehdr::FileHeader::parse_stat_metadata)
27/// reads that xattr.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct DirMeta {
30    /// The owner uid.
31    pub uid: u32,
32    /// The owner gid.
33    pub gid: u32,
34    /// The full `st_mode`, with the directory type bits.
35    pub mode: u32,
36    /// The extended attributes of the directory.
37    pub xattrs: Xattrs,
38}
39
40fn check_dir_mode(mode: u32) -> Result<()> {
41    if mode & S_IFMT == S_IFDIR {
42        Ok(())
43    } else {
44        Err(Error::InvalidDirMeta("mode is not a directory mode"))
45    }
46}
47
48impl DirMeta {
49    /// Parses a serialized dirmeta object.
50    ///
51    /// # Errors
52    ///
53    /// - [`Error::Gvariant`] if `data` is not a normal-form `(uuua(ayay))`
54    ///   tuple, or if an xattr entry is not a normal-form `(ayay)` pair.
55    /// - [`Error::InvalidDirMeta`] with the reason `mode is not a directory
56    ///   mode` if the type bits of the mode are not the directory type.
57    /// - [`Error::InvalidXattrs`] if an xattr name is not in the stored form,
58    ///   or if the names are not strictly sorted.
59    ///   [`Xattrs::from_gvariant`] lists the reasons.
60    pub fn parse(data: &[u8]) -> Result<DirMeta> {
61        DirMetaRef::parse(data)?.to_owned()
62    }
63
64    /// Serializes the object to normal-form bytes.
65    ///
66    /// The SHA-256 of these bytes is the checksum of the object.
67    ///
68    /// # Errors
69    ///
70    /// [`Error::InvalidDirMeta`] with the reason `mode is not a directory mode`
71    /// if the type bits of `mode` are not the directory type.
72    pub fn serialize(&self) -> Result<Vec<u8>> {
73        check_dir_mode(self.mode)?;
74        Ok(ostrya_gvariant::encode_to_vec(self)?)
75    }
76}
77
78impl GvType for DirMeta {
79    const SIGNATURE: &'static str = "(uuua(ayay))";
80    // Greatest member alignment: the u32 fields.
81    const ALIGNMENT: usize = 4;
82    const FIXED_SIZE: Option<usize> = None;
83}
84
85/// The `(uuua(ayay))` encoding, with no check of the mode.
86///
87/// [`DirMeta::serialize`] checks that the mode is a directory mode.
88impl GvEncode for DirMeta {
89    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
90        (
91            Be32(self.uid),
92            Be32(self.gid),
93            Be32(self.mode),
94            &self.xattrs,
95        )
96            .encode(out)
97    }
98}
99
100/// A borrowed view of a serialized dirmeta object.
101///
102/// [`parse`](DirMetaRef::parse) decodes the scalar fields and checks the mode.
103/// The xattrs stay serialized until a caller reads them.
104#[derive(Clone, Copy)]
105pub struct DirMetaRef<'a> {
106    uid: u32,
107    gid: u32,
108    mode: u32,
109    xattrs: XattrsRef<'a>,
110}
111
112impl<'a> DirMetaRef<'a> {
113    /// Parses a slice that holds exactly one serialized dirmeta object.
114    ///
115    /// The function does not check the xattr names.
116    /// [`to_owned`](DirMetaRef::to_owned) and the iterator of
117    /// [`xattrs`](DirMetaRef::xattrs) check them.
118    ///
119    /// # Errors
120    ///
121    /// - [`Error::Gvariant`] if `data` is not a normal-form `(uuua(ayay))`
122    ///   tuple, or if the framing of the xattr array is not normal form.
123    /// - [`Error::InvalidDirMeta`] with the reason `mode is not a directory
124    ///   mode` if the type bits of the mode are not the directory type.
125    pub fn parse(data: &'a [u8]) -> Result<DirMetaRef<'a>> {
126        let (uid, gid, mode, xattrs): (Be32, Be32, Be32, &[u8]) = GvDecode::decode(data)?;
127        let mode = mode.0;
128        check_dir_mode(mode)?;
129        Ok(DirMetaRef {
130            uid: uid.0,
131            gid: gid.0,
132            mode,
133            xattrs: XattrsRef::parse(xattrs)?,
134        })
135    }
136
137    /// Returns the owner uid, in host byte order.
138    pub fn uid(&self) -> u32 {
139        self.uid
140    }
141
142    /// Returns the owner gid, in host byte order.
143    pub fn gid(&self) -> u32 {
144        self.gid
145    }
146
147    /// Returns the full `st_mode`, in host byte order.
148    pub fn mode(&self) -> u32 {
149        self.mode
150    }
151
152    /// Returns a borrowed view of the extended attributes of the directory.
153    pub fn xattrs(&self) -> XattrsRef<'a> {
154        self.xattrs
155    }
156
157    /// Collects the view into an owned [`DirMeta`].
158    ///
159    /// # Errors
160    ///
161    /// - [`Error::Gvariant`] if an xattr entry is not a normal-form `(ayay)`
162    ///   pair.
163    /// - [`Error::InvalidXattrs`] if an xattr name is not in the stored form,
164    ///   or if the names are not strictly sorted.
165    ///   [`Xattrs::from_gvariant`] lists the reasons.
166    pub fn to_owned(&self) -> Result<DirMeta> {
167        Ok(DirMeta {
168            uid: self.uid,
169            gid: self.gid,
170            mode: self.mode,
171            xattrs: self.xattrs.to_owned()?,
172        })
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn round_trips_with_xattrs() {
182        let meta = DirMeta {
183            uid: 1000,
184            gid: 100,
185            mode: 0o40750,
186            xattrs: Xattrs::new([(b"user.a\0".to_vec(), b"v".to_vec())]).unwrap(),
187        };
188        let bytes = meta.serialize().unwrap();
189        let view = DirMetaRef::parse(&bytes).unwrap();
190        assert_eq!(view.uid(), 1000);
191        assert_eq!(view.gid(), 100);
192        assert_eq!(view.mode(), 0o40750);
193        assert_eq!(view.to_owned().unwrap(), meta);
194        assert_eq!(meta.serialize().unwrap(), bytes);
195    }
196
197    #[test]
198    fn rejects_a_non_directory_mode() {
199        let meta = DirMeta {
200            uid: 0,
201            gid: 0,
202            mode: 0o100644,
203            xattrs: Xattrs::empty(),
204        };
205        assert_eq!(
206            meta.serialize(),
207            Err(Error::InvalidDirMeta("mode is not a directory mode"))
208        );
209
210        // Craft bytes carrying a regular-file mode via the raw tuple, so the
211        // non-directory mode is rejected on the read path.
212        let bytes =
213            ostrya_gvariant::encode_to_vec(&(Be32(0), Be32(0), Be32(0o100644), &Xattrs::empty()))
214                .unwrap();
215        assert_eq!(
216            DirMetaRef::parse(&bytes).err(),
217            Some(Error::InvalidDirMeta("mode is not a directory mode"))
218        );
219    }
220}