Skip to main content

ostrya_core/
dirtree.rs

1//! Dirtree objects: the sorted lists of child files and subdirectories.
2//!
3//! The owned [`DirTree`] checks all rules of the object when it parses and
4//! when it serializes. The borrowed [`DirTreeRef`] checks each entry when an
5//! iterator visits it, and does no check across the two lists.
6
7use ostrya_gvariant::{ArrayIter, GvDecode, GvEncode, GvType, Slice};
8
9use crate::checksum::Checksum;
10use crate::error::{Error, Result};
11use crate::valiter::ValidatedIter;
12
13/// An owned dirtree object: the lists of child files and subdirectories.
14///
15/// # Wire form
16///
17/// The GVariant type is `(a(say)a(sayay))`. It holds two lists:
18///
19/// - the file entries `(say)`: the name and the checksum of the content object
20/// - the directory entries `(sayay)`: the name, the checksum of the dirtree
21///   object, and the checksum of the dirmeta object
22///
23/// Each checksum is a raw 32-byte `ay`.
24///
25/// # Rules
26///
27/// - Each list is sorted by name in byte-wise order. A name occurs at most
28///   once in a list. The sort order makes the checksum of a tree
29///   reproducible.
30/// - Each name is one path component, as [`check_name`](Self::check_name)
31///   states.
32/// - No name is in both lists, because the two entries have the same
33///   checkout path.
34///
35/// [`serialize`](Self::serialize) and [`parse`](Self::parse) check all three
36/// rules. [`DirTreeRef`] checks the first two rules only.
37#[derive(Debug, Clone, PartialEq, Eq, Default)]
38pub struct DirTree {
39    /// The file entries: the name and the content checksum, sorted by name.
40    pub files: Vec<(String, Checksum)>,
41    /// The directory entries, sorted by name.
42    ///
43    /// Each entry holds the name, the dirtree checksum, and the dirmeta
44    /// checksum.
45    pub dirs: Vec<(String, Checksum, Checksum)>,
46}
47
48/// Checks one visited name against the previous name of the same list. The
49/// name must be a valid component and must sort strictly after the previous
50/// name in byte-wise order, so a duplicate name is refused.
51fn check_entry<'a>(prev: &mut Option<&'a str>, name: &'a str) -> Result<()> {
52    DirTree::check_name(name)?;
53    if let Some(prev) = prev
54        && *prev >= name
55    {
56        return Err(Error::InvalidDirTree("entry names are not sorted"));
57    }
58    *prev = Some(name);
59    Ok(())
60}
61
62fn entry_checksum(bytes: &[u8]) -> Result<Checksum> {
63    Checksum::from_ay(bytes).map_err(|_| Error::InvalidDirTree("entry checksum is not 32 bytes"))
64}
65
66impl DirTree {
67    /// Checks that `name` is one path component.
68    ///
69    /// A valid name is not empty, is not `.` or `..`, and holds no `/`. This
70    /// check is the defense against path traversal through a dirtree entry.
71    /// The string decoder of the read path refuses a name that is not UTF-8.
72    ///
73    /// # Errors
74    ///
75    /// [`Error::InvalidDirTree`] with one of these reasons:
76    ///
77    /// - `"empty entry name"` if `name` is empty
78    /// - `"entry name is a directory traversal"` if `name` is `.` or `..`
79    /// - `"entry name contains a slash"` if `name` holds a `/`
80    pub fn check_name(name: &str) -> Result<()> {
81        if name.is_empty() {
82            return Err(Error::InvalidDirTree("empty entry name"));
83        }
84        if name == "." || name == ".." {
85            return Err(Error::InvalidDirTree("entry name is a directory traversal"));
86        }
87        if name.contains('/') {
88            return Err(Error::InvalidDirTree("entry name contains a slash"));
89        }
90        Ok(())
91    }
92
93    /// Parses a serialized dirtree object into an owned tree.
94    ///
95    /// The parse checks each entry when it collects the lists, as
96    /// [`DirTreeRef::to_owned`] does. Then it checks that no name is in both
97    /// lists. A tree that this function returns obeys all
98    /// [rules](DirTree#rules).
99    ///
100    /// # Errors
101    ///
102    /// - [`Error::Gvariant`] if `data` is not a normal-form value of type
103    ///   `(a(say)a(sayay))`.
104    /// - [`Error::InvalidDirTree`] if an entry breaks a rule. These are the
105    ///   reasons:
106    ///   - a reason of [`check_name`](Self::check_name) if a name is not one
107    ///     path component
108    ///   - `"entry names are not sorted"` if a name does not sort strictly
109    ///     after the previous name of its list
110    ///   - `"entry checksum is not 32 bytes"` if a checksum has a different
111    ///     length
112    ///   - `"a name appears in both the file and directory lists"` if a name
113    ///     is in both lists
114    pub fn parse(data: &[u8]) -> Result<DirTree> {
115        let tree = DirTreeRef::parse(data)?.to_owned()?;
116        tree.check_no_shared_names()?;
117        Ok(tree)
118    }
119
120    /// Serializes the tree to normal-form bytes.
121    ///
122    /// The SHA-256 of these bytes is the checksum of the dirtree object.
123    ///
124    /// # Errors
125    ///
126    /// - [`Error::InvalidDirTree`] if the tree breaks a
127    ///   [rule](DirTree#rules). These are the reasons:
128    ///   - a reason of [`check_name`](Self::check_name) if a name is not one
129    ///     path component
130    ///   - `"entry names are not sorted"` if a name does not sort strictly
131    ///     after the previous name of its list
132    ///   - `"a name appears in both the file and directory lists"` if a name
133    ///     is in both lists
134    /// - [`Error::Gvariant`] with
135    ///   [`InvalidValue`](ostrya_gvariant::Error::InvalidValue) if a name
136    ///   holds a NUL byte.
137    pub fn serialize(&self) -> Result<Vec<u8>> {
138        self.validate()?;
139        Ok(ostrya_gvariant::encode_to_vec(self)?)
140    }
141
142    fn validate(&self) -> Result<()> {
143        let mut prev = None;
144        for (name, _) in &self.files {
145            check_entry(&mut prev, name)?;
146        }
147        let mut prev = None;
148        for (name, _, _) in &self.dirs {
149            check_entry(&mut prev, name)?;
150        }
151        self.check_no_shared_names()
152    }
153
154    /// Checks that no name is in both lists. Both lists are sorted when this
155    /// function runs: `validate` checks the order on the write path, and
156    /// `to_owned` checks it on the read path. For this reason, one merge walk
157    /// over the two lists finds a shared name with no allocation.
158    fn check_no_shared_names(&self) -> Result<()> {
159        let mut files = self.files.iter().map(|(n, _)| n.as_str());
160        let mut dirs = self.dirs.iter().map(|(n, _, _)| n.as_str());
161        let (mut f, mut d) = (files.next(), dirs.next());
162        while let (Some(fname), Some(dname)) = (f, d) {
163            match fname.cmp(dname) {
164                std::cmp::Ordering::Less => f = files.next(),
165                std::cmp::Ordering::Greater => d = dirs.next(),
166                std::cmp::Ordering::Equal => {
167                    return Err(Error::InvalidDirTree(
168                        "a name appears in both the file and directory lists",
169                    ));
170                }
171            }
172        }
173        Ok(())
174    }
175}
176
177impl GvType for DirTree {
178    const SIGNATURE: &'static str = "(a(say)a(sayay))";
179    // Every member is alignment-1 (strings and byte arrays).
180    const ALIGNMENT: usize = 1;
181    const FIXED_SIZE: Option<usize> = None;
182}
183
184/// The encoder writes the two lists as they are and checks no
185/// [rule](DirTree#rules). [`DirTree::serialize`] checks the rules before it
186/// encodes.
187impl GvEncode for DirTree {
188    // `DirTree::serialize` is the only caller in this crate. `String` and
189    // `Checksum` implement `GvEncode`, so the owned entry vectors encode with
190    // no conversion.
191    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
192        (Slice(&self.files), Slice(&self.dirs)).encode(out)
193    }
194}
195
196/// A borrowed view of a serialized dirtree object.
197///
198/// A full walk of a dirtree borrows the object buffer for the whole walk and
199/// does not allocate.
200///
201/// # Checks
202///
203/// [`parse`](Self::parse) checks the container framing only. The iterators
204/// [`files`](Self::files) and [`dirs`](Self::dirs) check each entry when they
205/// visit it, so they yield `Result`. These are the checks:
206///
207/// - The name is one path component, as [`DirTree::check_name`] states.
208/// - Each checksum is 32 bytes long.
209/// - The name sorts strictly after the previous name of the same list, in
210///   byte-wise order.
211///
212/// After an error, an iterator is exhausted and returns `None`.
213///
214/// # Names in both lists
215///
216/// The view checks each list alone, because a check across the two lists
217/// needs an allocation. [`DirTree::parse`] refuses an object with a name in
218/// both lists.
219///
220/// The `ostree` command reads such an object in the same way as the view.
221/// `ostree fsck` accepts it, and `ostree ls` lists both entries. The `ostree`
222/// command aborts only when it resolves the name as a directory.
223#[derive(Clone, Copy)]
224pub struct DirTreeRef<'a> {
225    files: ArrayIter<'a, (&'a str, &'a [u8])>,
226    dirs: ArrayIter<'a, (&'a str, &'a [u8], &'a [u8])>,
227}
228
229impl<'a> DirTreeRef<'a> {
230    /// Parses a serialized dirtree object into a borrowed view.
231    ///
232    /// `data` must cover exactly one serialized dirtree object. The parse
233    /// checks the container framing only. The iterators check the entries,
234    /// as the [checks](DirTreeRef#checks) state.
235    ///
236    /// # Errors
237    ///
238    /// [`Error::Gvariant`] if the framing of the tuple or of one of its two
239    /// arrays is not in normal form.
240    pub fn parse(data: &'a [u8]) -> Result<DirTreeRef<'a>> {
241        let (files, dirs) = GvDecode::decode(data)?;
242        Ok(DirTreeRef { files, dirs })
243    }
244
245    /// Returns an iterator over the file entries.
246    ///
247    /// The iterator checks each entry when it visits it, as the
248    /// [checks](DirTreeRef#checks) state. An item is an error if the entry
249    /// fails a check or if its framing is not in normal form.
250    pub fn files(&self) -> impl Iterator<Item = Result<(&'a str, Checksum)>> + use<'a> {
251        ValidatedIter::new(
252            self.files,
253            None,
254            |prev: &mut Option<&'a str>, (name, csum): (&'a str, &'a [u8])| {
255                check_entry(prev, name)?;
256                Ok((name, entry_checksum(csum)?))
257            },
258        )
259    }
260
261    /// Returns an iterator over the directory entries.
262    ///
263    /// The iterator checks each entry when it visits it, as the
264    /// [checks](DirTreeRef#checks) state. An item is an error if the entry
265    /// fails a check or if its framing is not in normal form.
266    pub fn dirs(&self) -> impl Iterator<Item = Result<(&'a str, Checksum, Checksum)>> + use<'a> {
267        ValidatedIter::new(
268            self.dirs,
269            None,
270            |prev: &mut Option<&'a str>, (name, tree, meta): (&'a str, &'a [u8], &'a [u8])| {
271                check_entry(prev, name)?;
272                Ok((name, entry_checksum(tree)?, entry_checksum(meta)?))
273            },
274        )
275    }
276
277    /// Collects the entries into an owned [`DirTree`].
278    ///
279    /// The result can hold a name in both lists, because this function does
280    /// no check across the two lists. [`DirTree::parse`] adds that check.
281    ///
282    /// # Errors
283    ///
284    /// - [`Error::Gvariant`] if the framing of an entry is not in normal form.
285    /// - [`Error::InvalidDirTree`] if an entry fails a
286    ///   [check](DirTreeRef#checks). These are the reasons:
287    ///   - a reason of [`DirTree::check_name`] if a name is not one path
288    ///     component
289    ///   - `"entry names are not sorted"` if a name does not sort strictly
290    ///     after the previous name of its list
291    ///   - `"entry checksum is not 32 bytes"` if a checksum has a different
292    ///     length
293    pub fn to_owned(&self) -> Result<DirTree> {
294        let mut owned = DirTree::default();
295        for item in self.files() {
296            let (name, checksum) = item?;
297            owned.files.push((name.to_owned(), checksum));
298        }
299        for item in self.dirs() {
300            let (name, tree, meta) = item?;
301            owned.dirs.push((name.to_owned(), tree, meta));
302        }
303        Ok(owned)
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use ostrya_gvariant::{Type, Value, to_bytes};
311
312    fn csum(byte: u8) -> Checksum {
313        Checksum::from_bytes([byte; 32])
314    }
315
316    fn sample() -> DirTree {
317        DirTree {
318            files: vec![("a.txt".to_owned(), csum(1)), ("b.txt".to_owned(), csum(2))],
319            dirs: vec![("sub".to_owned(), csum(3), csum(4))],
320        }
321    }
322
323    #[test]
324    fn check_name_refuses_what_is_not_one_component() {
325        for name in ["", ".", "..", "a/b", "/"] {
326            assert!(DirTree::check_name(name).is_err(), "{name:?}");
327        }
328        for name in ["a", "...", ".a", "a."] {
329            assert!(DirTree::check_name(name).is_ok(), "{name:?}");
330        }
331    }
332
333    #[test]
334    fn round_trips_through_the_view() {
335        let tree = sample();
336        let bytes = tree.serialize().unwrap();
337        let view = DirTreeRef::parse(&bytes).unwrap();
338        let files: Vec<_> = view.files().map(Result::unwrap).collect();
339        assert_eq!(files, [("a.txt", csum(1)), ("b.txt", csum(2))]);
340        let dirs: Vec<_> = view.dirs().map(Result::unwrap).collect();
341        assert_eq!(dirs, [("sub", csum(3), csum(4))]);
342        assert_eq!(view.to_owned().unwrap(), tree);
343        assert_eq!(DirTree::parse(&bytes).unwrap().serialize().unwrap(), bytes);
344    }
345
346    #[test]
347    fn serialize_rejects_unsorted_and_invalid_names() {
348        for (files, expected) in [
349            (
350                vec![("b".to_owned(), csum(1)), ("a".to_owned(), csum(2))],
351                "entry names are not sorted",
352            ),
353            (
354                vec![("a".to_owned(), csum(1)), ("a".to_owned(), csum(2))],
355                "entry names are not sorted",
356            ),
357            (vec![(String::new(), csum(1))], "empty entry name"),
358            (
359                vec![("..".to_owned(), csum(1))],
360                "entry name is a directory traversal",
361            ),
362            (
363                vec![("a/b".to_owned(), csum(1))],
364                "entry name contains a slash",
365            ),
366        ] {
367            let tree = DirTree {
368                files,
369                dirs: Vec::new(),
370            };
371            assert_eq!(tree.serialize(), Err(Error::InvalidDirTree(expected)));
372        }
373    }
374
375    /// Serializes a dirtree with file entries only through the `Value` tree,
376    /// with none of the checks of `DirTree::serialize`.
377    fn craft(files: &[(&str, &[u8])]) -> Vec<u8> {
378        let ty = Type::parse("(a(say)a(sayay))").unwrap();
379        let value = Value::Tuple(vec![
380            Value::Array(
381                files
382                    .iter()
383                    .map(|(name, checksum)| {
384                        Value::Tuple(vec![
385                            Value::Str((*name).to_owned()),
386                            Value::Bytes(checksum.to_vec()),
387                        ])
388                    })
389                    .collect(),
390            ),
391            Value::Array(Vec::new()),
392        ]);
393        to_bytes(&ty, &value).unwrap()
394    }
395
396    #[test]
397    fn view_validates_entries_as_visited_and_fuses_on_error() {
398        let bytes = craft(&[("b", &[1; 32]), ("a", &[2; 32])]);
399        let view = DirTreeRef::parse(&bytes).unwrap();
400        let mut files = view.files();
401        assert!(files.next().unwrap().is_ok());
402        assert_eq!(
403            files.next().unwrap(),
404            Err(Error::InvalidDirTree("entry names are not sorted"))
405        );
406        assert!(files.next().is_none(), "iterator fuses after an error");
407
408        let bytes = craft(&[("a", &[1; 31])]);
409        let view = DirTreeRef::parse(&bytes).unwrap();
410        assert_eq!(
411            view.files().next().unwrap(),
412            Err(Error::InvalidDirTree("entry checksum is not 32 bytes"))
413        );
414
415        let bytes = craft(&[("a/../b", &[1; 32])]);
416        assert_eq!(
417            DirTreeRef::parse(&bytes).unwrap().to_owned(),
418            Err(Error::InvalidDirTree("entry name contains a slash"))
419        );
420    }
421
422    /// Serializes a dirtree with entries in both lists through the `Value`
423    /// tree, with none of the checks of `DirTree::serialize`.
424    fn craft2(files: &[(&str, &[u8])], dirs: &[(&str, &[u8], &[u8])]) -> Vec<u8> {
425        let ty = Type::parse("(a(say)a(sayay))").unwrap();
426        let value = Value::Tuple(vec![
427            Value::Array(
428                files
429                    .iter()
430                    .map(|(name, c)| {
431                        Value::Tuple(vec![
432                            Value::Str((*name).to_owned()),
433                            Value::Bytes(c.to_vec()),
434                        ])
435                    })
436                    .collect(),
437            ),
438            Value::Array(
439                dirs.iter()
440                    .map(|(name, t, m)| {
441                        Value::Tuple(vec![
442                            Value::Str((*name).to_owned()),
443                            Value::Bytes(t.to_vec()),
444                            Value::Bytes(m.to_vec()),
445                        ])
446                    })
447                    .collect(),
448            ),
449        ]);
450        to_bytes(&ty, &value).unwrap()
451    }
452
453    #[test]
454    fn rejects_a_name_shared_across_file_and_dir_lists() {
455        let shared = Error::InvalidDirTree("a name appears in both the file and directory lists");
456
457        // Write path: the serialization of such an object fails.
458        let tree = DirTree {
459            files: vec![("x".to_owned(), csum(1))],
460            dirs: vec![("x".to_owned(), csum(2), csum(3))],
461        };
462        assert_eq!(tree.serialize(), Err(shared.clone()));
463
464        // Owned read path: the parse of the crafted object fails with the
465        // same error.
466        let bytes = craft2(&[("x", &[1; 32])], &[("x", &[2; 32], &[3; 32])]);
467        assert_eq!(DirTree::parse(&bytes), Err(shared));
468
469        // Borrowed view: each list yields the shared name, because the view
470        // checks each list alone. The `ostree` command reads it the same way.
471        let view = DirTreeRef::parse(&bytes).unwrap();
472        assert_eq!(view.files().next().unwrap().unwrap().0, "x");
473        assert_eq!(view.dirs().next().unwrap().unwrap().0, "x");
474    }
475
476    #[test]
477    fn distinct_names_across_lists_are_accepted() {
478        // A file and a directory with different names make a round trip with
479        // no change.
480        let bytes = craft2(&[("a", &[1; 32])], &[("b", &[2; 32], &[3; 32])]);
481        let tree = DirTree::parse(&bytes).unwrap();
482        assert_eq!(tree.files.len(), 1);
483        assert_eq!(tree.dirs.len(), 1);
484        assert_eq!(tree.serialize().unwrap(), bytes);
485    }
486}