Skip to main content

ostrya_core/
xattr.rs

1//! Extended-attribute sets, owned and borrowed.
2//!
3//! The `Xattrs` type doc states the storage form and the canonical-form
4//! rules.
5
6use ostrya_gvariant::{ArrayIter, GvDecode, GvEncode, GvType, encode_to_vec, write_array};
7
8use crate::error::{Error, Result};
9use crate::valiter::ValidatedIter;
10
11/// A sorted set of extended attributes, in canonical form.
12///
13/// Equal sets hold equal bytes in equal order. Hashing agrees with equality,
14/// so a set can be a lookup key.
15///
16/// # Storage form
17///
18/// The GVariant type is `a(ayay)`. Each element is a pair of byte strings:
19/// the name and the value. The pairs are sorted by name in byte order.
20///
21/// A stored name is the attribute name with its namespace prefix, followed by
22/// one NUL byte. The text before the NUL is not empty and holds no NUL. The
23/// `ostree` command writes names in this form.
24///
25/// The xattr bytes are part of the object checksum, so each constructor
26/// makes a canonical set. Each serialization and each hash of a set uses
27/// this form.
28///
29/// [`new`](Xattrs::new) sorts the pairs.
30/// [`from_gvariant`](Xattrs::from_gvariant) refuses pairs that are not
31/// sorted. Each constructor refuses a duplicate name and checks each name.
32#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
33pub struct Xattrs(Vec<(Vec<u8>, Vec<u8>)>);
34
35impl Xattrs {
36    /// Creates an empty set.
37    pub fn empty() -> Xattrs {
38        Xattrs(Vec::new())
39    }
40
41    /// Creates a canonical set from (name, value) pairs in any order.
42    ///
43    /// The function sorts the pairs by name. Each name must be a stored name
44    /// of the [storage form](Xattrs#storage-form), with one NUL byte at the
45    /// end.
46    ///
47    /// # Errors
48    ///
49    /// [`Error::InvalidXattrs`] with one of these reasons:
50    ///
51    /// - `duplicate xattr name` if two pairs have the same name.
52    /// - `empty xattr name` if a name is empty.
53    /// - `xattr name is missing its terminating NUL` if the last byte of a
54    ///   name is not NUL.
55    /// - `xattr name is empty before its NUL` if a name is one NUL byte only.
56    /// - `xattr name has an interior NUL` if a name holds a NUL byte before
57    ///   its last byte.
58    pub fn new(pairs: impl IntoIterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<Xattrs> {
59        let mut pairs: Vec<(Vec<u8>, Vec<u8>)> = pairs.into_iter().collect();
60        pairs.sort_by(|a, b| a.0.cmp(&b.0));
61        for window in pairs.windows(2) {
62            if window[0].0 == window[1].0 {
63                return Err(Error::InvalidXattrs("duplicate xattr name"));
64            }
65        }
66        for (name, _) in &pairs {
67            check_name(name)?;
68        }
69        Ok(Xattrs(pairs))
70    }
71
72    /// Returns `true` if the set has no entries.
73    pub fn is_empty(&self) -> bool {
74        self.0.is_empty()
75    }
76
77    /// Returns the number of entries.
78    pub fn len(&self) -> usize {
79        self.0.len()
80    }
81
82    /// Returns an iterator over the (name, value) entries, sorted by name.
83    pub fn iter(&self) -> impl Iterator<Item = (&[u8], &[u8])> {
84        self.0.iter().map(|(n, v)| (n.as_slice(), v.as_slice()))
85    }
86
87    /// Serializes the set as normal-form GVariant `a(ayay)`.
88    ///
89    /// # Errors
90    ///
91    /// The function returns no error for any set. The encoder of `a(ayay)`
92    /// has no failure case.
93    pub fn to_gvariant(&self) -> Result<Vec<u8>> {
94        Ok(encode_to_vec(&self)?)
95    }
96
97    /// Parses a normal-form GVariant `a(ayay)` set.
98    ///
99    /// Each name must be greater than the name before it, in byte order. This
100    /// check refuses unsorted input and duplicate names.
101    ///
102    /// # Errors
103    ///
104    /// - [`Error::Gvariant`] if `bytes` is not a normal-form `a(ayay)` array.
105    /// - [`Error::InvalidXattrs`] with the reason `xattr names are not
106    ///   strictly sorted` if a name is not greater than the name before it.
107    /// - [`Error::InvalidXattrs`] if a name is not in the stored form. The
108    ///   reasons are `empty xattr name`, `xattr name is missing its
109    ///   terminating NUL`, `xattr name is empty before its NUL`, and `xattr
110    ///   name has an interior NUL`, as for [`new`](Xattrs::new).
111    pub fn from_gvariant(bytes: &[u8]) -> Result<Xattrs> {
112        XattrsRef::parse(bytes)?.to_owned()
113    }
114}
115
116/// The `a(ayay)` encoding of a set, written from the owned entries.
117///
118/// A dirmeta or a file header encodes its set as a member of a larger tuple
119/// with this impl. The encoder needs no list of borrowed pairs.
120impl GvType for &Xattrs {
121    const SIGNATURE: &'static str = "a(ayay)";
122    const ALIGNMENT: usize = 1;
123    const FIXED_SIZE: Option<usize> = None;
124}
125
126impl GvEncode for &Xattrs {
127    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
128        // Each element is (ayay): a two-member tuple of byte arrays.
129        type Entry<'e> = (&'e [u8], &'e [u8]);
130        write_array(
131            out,
132            <Entry as GvType>::ALIGNMENT,
133            <Entry as GvType>::FIXED_SIZE.is_some(),
134            self.0.len(),
135            |out, i| {
136                let (name, value) = &self.0[i];
137                (name.as_slice(), value.as_slice()).encode(out)
138            },
139        )
140    }
141}
142
143/// Checks a stored xattr name.
144///
145/// The name ends in one NUL byte. The text before the NUL is not empty and
146/// holds no NUL. The `ostree` command writes names in this form: in the
147/// `user.ostreemeta` blob of a committed file, one `\0` follows the name
148/// `user.demo`.
149fn check_name(name: &[u8]) -> Result<()> {
150    let Some((&last, rest)) = name.split_last() else {
151        return Err(Error::InvalidXattrs("empty xattr name"));
152    };
153    if last != 0 {
154        return Err(Error::InvalidXattrs(
155            "xattr name is missing its terminating NUL",
156        ));
157    }
158    if rest.is_empty() {
159        return Err(Error::InvalidXattrs("xattr name is empty before its NUL"));
160    }
161    if rest.contains(&0) {
162        return Err(Error::InvalidXattrs("xattr name has an interior NUL"));
163    }
164    Ok(())
165}
166
167/// A borrowed view of a serialized `a(ayay)` xattr set.
168///
169/// [`parse`](XattrsRef::parse) checks the framing of the array. The name
170/// checks and the order check run when [`iter`](XattrsRef::iter) visits each
171/// entry, so the iterator yields `Result`. After an error, the iterator is
172/// exhausted.
173#[derive(Clone, Copy)]
174pub struct XattrsRef<'a> {
175    entries: ArrayIter<'a, (&'a [u8], &'a [u8])>,
176}
177
178impl<'a> XattrsRef<'a> {
179    /// Creates a view of a slice that holds exactly one serialized `a(ayay)`.
180    ///
181    /// # Errors
182    ///
183    /// [`Error::Gvariant`] if the framing of the array is not normal form.
184    pub fn parse(data: &'a [u8]) -> Result<XattrsRef<'a>> {
185        Ok(XattrsRef {
186            entries: ArrayIter::decode(data)?,
187        })
188    }
189
190    /// Returns an iterator over the (name, value) entries.
191    ///
192    /// The iterator checks each entry when it visits it. The error items are
193    /// the errors of [`to_owned`](XattrsRef::to_owned).
194    pub fn iter(&self) -> impl Iterator<Item = Result<(&'a [u8], &'a [u8])>> + use<'a> {
195        ValidatedIter::new(
196            self.entries,
197            None,
198            |prev: &mut Option<&'a [u8]>, (name, value): (&'a [u8], &'a [u8])| {
199                check_name(name)?;
200                if let Some(prev) = prev
201                    && *prev >= name
202                {
203                    return Err(Error::InvalidXattrs("xattr names are not strictly sorted"));
204                }
205                *prev = Some(name);
206                Ok((name, value))
207            },
208        )
209    }
210
211    /// Collects the entries into an owned, canonical [`Xattrs`].
212    ///
213    /// # Errors
214    ///
215    /// - [`Error::Gvariant`] if an entry is not a normal-form `(ayay)` pair.
216    /// - [`Error::InvalidXattrs`] if a name is not in the stored form, or with
217    ///   the reason `xattr names are not strictly sorted`.
218    ///   [`Xattrs::from_gvariant`] lists the reasons.
219    pub fn to_owned(&self) -> Result<Xattrs> {
220        let mut pairs = Vec::new();
221        for item in self.iter() {
222            let (name, value) = item?;
223            pairs.push((name.to_vec(), value.to_vec()));
224        }
225        Ok(Xattrs(pairs))
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use ostrya_gvariant::Slice;
232
233    use super::*;
234
235    #[test]
236    fn new_sorts_by_name() {
237        let x = Xattrs::new([
238            (b"user.z\0".to_vec(), b"1".to_vec()),
239            (b"security.selinux\0".to_vec(), b"2".to_vec()),
240            (b"user.a\0".to_vec(), b"3".to_vec()),
241        ])
242        .unwrap();
243        let names: Vec<&[u8]> = x.iter().map(|(n, _)| n).collect();
244        assert_eq!(
245            names,
246            vec![
247                b"security.selinux\0".as_slice(),
248                b"user.a\0".as_slice(),
249                b"user.z\0".as_slice()
250            ]
251        );
252    }
253
254    #[test]
255    fn new_rejects_duplicate_and_empty_names() {
256        assert!(matches!(
257            Xattrs::new([
258                (b"user.a\0".to_vec(), b"1".to_vec()),
259                (b"user.a\0".to_vec(), b"2".to_vec()),
260            ]),
261            Err(Error::InvalidXattrs("duplicate xattr name"))
262        ));
263        assert!(matches!(
264            Xattrs::new([(Vec::new(), b"1".to_vec())]),
265            Err(Error::InvalidXattrs("empty xattr name"))
266        ));
267    }
268
269    #[test]
270    fn new_requires_terminating_nul_and_no_interior_nul() {
271        // A name taken straight from listxattr(2) output lacks the stored NUL.
272        assert_eq!(
273            Xattrs::new([(b"user.demo".to_vec(), b"v".to_vec())]),
274            Err(Error::InvalidXattrs(
275                "xattr name is missing its terminating NUL"
276            ))
277        );
278        // An interior NUL is not part of a real xattr name.
279        assert_eq!(
280            Xattrs::new([(b"user.\0demo\0".to_vec(), b"v".to_vec())]),
281            Err(Error::InvalidXattrs("xattr name has an interior NUL"))
282        );
283        // A lone NUL has an empty name before it.
284        assert_eq!(
285            Xattrs::new([(b"\0".to_vec(), b"v".to_vec())]),
286            Err(Error::InvalidXattrs("xattr name is empty before its NUL"))
287        );
288    }
289
290    #[test]
291    fn from_gvariant_rejects_names_without_terminating_nul() {
292        // Encode an a(ayay) whose single name lacks the stored NUL.
293        let raw: Vec<(&[u8], &[u8])> = vec![(b"user.demo", b"v")];
294        let bytes = encode_to_vec(&Slice(&raw)).unwrap();
295        assert_eq!(
296            Xattrs::from_gvariant(&bytes),
297            Err(Error::InvalidXattrs(
298                "xattr name is missing its terminating NUL"
299            ))
300        );
301    }
302
303    #[test]
304    fn gvariant_round_trips_and_reencodes_identically() {
305        let x = Xattrs::new([
306            (b"security.capability\0".to_vec(), vec![0x01, 0x00, 0x00]),
307            (b"user.mime_type\0".to_vec(), b"text/plain".to_vec()),
308        ])
309        .unwrap();
310        let bytes = x.to_gvariant().unwrap();
311        let decoded = Xattrs::from_gvariant(&bytes).unwrap();
312        assert_eq!(decoded, x);
313        assert_eq!(decoded.to_gvariant().unwrap(), bytes);
314    }
315
316    #[test]
317    fn empty_set_serializes_to_empty_array() {
318        let bytes = Xattrs::empty().to_gvariant().unwrap();
319        assert!(bytes.is_empty());
320        assert_eq!(Xattrs::from_gvariant(&bytes).unwrap(), Xattrs::empty());
321    }
322
323    #[test]
324    fn from_gvariant_rejects_unsorted_bytes() {
325        // The test encodes an out-of-order a(ayay) with no sort, so the bytes
326        // are not in canonical form.
327        let unsorted: Vec<(&[u8], &[u8])> = vec![(b"user.z\0", b"1"), (b"user.a\0", b"2")];
328        let bytes = encode_to_vec(&Slice(&unsorted)).unwrap();
329        assert!(matches!(
330            Xattrs::from_gvariant(&bytes),
331            Err(Error::InvalidXattrs("xattr names are not strictly sorted"))
332        ));
333    }
334
335    #[test]
336    fn view_validates_as_visited_and_fuses_on_error() {
337        let unsorted: Vec<(&[u8], &[u8])> = vec![(b"user.z\0", b"1"), (b"user.a\0", b"2")];
338        let bytes = encode_to_vec(&Slice(&unsorted)).unwrap();
339        let view = XattrsRef::parse(&bytes).unwrap();
340        let mut iter = view.iter();
341        assert_eq!(iter.next().unwrap(), Ok((&b"user.z\0"[..], &b"1"[..])));
342        assert_eq!(
343            iter.next().unwrap(),
344            Err(Error::InvalidXattrs("xattr names are not strictly sorted"))
345        );
346        assert!(iter.next().is_none(), "iterator fuses after an error");
347    }
348}