Skip to main content

ostrya_remote/tree/
model.rs

1//! The tree model: the entries of a walk, their checksums, and the source of
2//! each object.
3
4use std::io;
5use std::ops::Range;
6use std::path::{Path, PathBuf};
7
8use futures_lite::io::{AsyncReadExt, Cursor};
9use ostrya_core::{
10    Checksum, DirMeta, DirTree, FileHeader, MAX_METADATA_SIZE, ObjectName, ObjectType, Xattrs,
11};
12use ostrya_gvariant::Value;
13
14use super::hash::{FileId, open_regular};
15use super::{EntryMeta, ScanOptions, invalid_data, walk};
16use crate::error::{Error, Result};
17use crate::proto::Encoding;
18use crate::session::{BoxFuture, ObjectData, ObjectSource, PushProgress};
19
20/// The result of the hash of one regular file.
21#[derive(Debug, Clone, Copy)]
22pub(super) struct Hashed {
23    /// The content-object checksum.
24    pub(super) checksum: Checksum,
25    /// The number of payload bytes the hash read.
26    pub(super) size: u64,
27}
28
29/// The owner, the mode, and the extended attributes of an entry.
30struct Meta {
31    uid: u32,
32    gid: u32,
33    mode: u32,
34    xattrs: Xattrs,
35}
36
37/// What the model keeps of an entry.
38enum NodeData {
39    /// A directory.
40    Dir {
41        meta: Meta,
42        /// The indices of the kept entries of the directory, which are
43        /// contiguous.
44        children: Range<u32>,
45        /// The dirtree and dirmeta checksums, once the bottom-up pass ran.
46        sums: Option<(Checksum, Checksum)>,
47    },
48    /// A regular file or a symlink.
49    Content {
50        meta: Meta,
51        /// The identity of a regular file, as the walk read it. The open of
52        /// the file checks it.
53        id: FileId,
54        /// The target of a symlink. A regular file has none.
55        target: Option<Box<str>>,
56        /// The checksum and the payload size, once the entry is hashed.
57        hashed: Option<Hashed>,
58    },
59}
60
61/// One entry of the model.
62struct Node {
63    /// The index of the parent directory. The root names itself.
64    parent: u32,
65    /// The name of the entry. The root has the empty name.
66    name: Box<str>,
67    data: NodeData,
68}
69
70/// The model of a local tree that [`TreeModel::scan`] walked and hashed.
71///
72/// For each entry, the model keeps the name, the metadata, and the index of
73/// the parent directory. For each regular file, it also keeps the number of
74/// payload bytes that the hash pass read. The model holds no file content, and
75/// it serializes a dirtree or a dirmeta object again from its fields on each
76/// request. Its memory grows with the number of entries and the length of
77/// their names.
78///
79/// # Object source
80///
81/// The model is the [`ObjectSource`] of the objects of the tree.
82/// [`object_names`](TreeModel::object_names) gives each object of the tree
83/// once. The model holds no commit.
84///
85/// - [`open`](ObjectSource::open) of a regular file opens the file again on
86///   the blocking pool, with the open and the checks of the hash pass. These
87///   are the type check, and on Unix the identity check. It gives the file as
88///   [`ObjectData::Content`], whose `size` is the payload size that the hash
89///   pass read.
90/// - `open` of a symlink opens no file. `open` of a dirtree or a dirmeta
91///   object serializes the object again from the model. Each of the two is
92///   [`ObjectData::Encoded`] in the `raw` encoding.
93/// - [`content_size`](ObjectSource::content_size) gives the sum of the
94///   payload sizes of the hash pass, in each encoding. It reads no file.
95/// - [`objects`](ObjectSource::objects) and
96///   [`detached_metadata`](ObjectSource::detached_metadata) name a commit,
97///   so each call returns [`Error::InvalidInput`].
98///
99/// When the model sends a file, it gives the payload size of the hash pass and
100/// does not hash the file again. If a file changes after the hash pass, the
101/// server verifies the object and refuses it.
102///
103/// If a call names an object that the model does not hold, a commit
104/// included, it returns [`Error::InvalidInput`]. If the open of a file fails,
105/// the call returns [`Error::Walk`] with the path of the file and one of the
106/// kinds that [`scan`](TreeModel::scan) lists. The session returns that error
107/// inside [`Error::Source`].
108pub struct TreeModel {
109    /// The walk root.
110    root: PathBuf,
111    /// The entries in the order the walk kept them. The root is at 0, and the
112    /// kept entries of a directory follow each other.
113    nodes: Vec<Node>,
114    /// The source entry of each object.
115    sources: Sources,
116}
117
118/// The source entry of each object: the first entry, in walk order, that
119/// gives it. Each list holds one entry for each distinct object of its type,
120/// sorted by the checksum of the object.
121#[derive(Default)]
122struct Sources {
123    files: Vec<u32>,
124    dirtrees: Vec<u32>,
125    dirmetas: Vec<u32>,
126}
127
128impl TreeModel {
129    /// Walks the directory `root` and hashes each object of its tree.
130    ///
131    /// The scan gives the checksum of each object of the tree: a content
132    /// object for each regular file and symlink, and a dirtree and a dirmeta
133    /// object for each directory.
134    ///
135    /// # Walk
136    ///
137    /// - The walk does not follow symlinks. The walk root must be a directory.
138    /// - The walk holds one directory open at a time. It reads a listing to its
139    ///   end and closes the directory before it enters a subdirectory.
140    /// - While it reads a listing, the walk reads the metadata of each entry
141    ///   with `DirEntry::metadata` and the target of each symlink. It reads
142    ///   only the walk root with `symlink_metadata`.
143    /// - Each name must be valid UTF-8 and must pass the dirtree name rule of
144    ///   `ostrya-core`. Each symlink target must be valid UTF-8.
145    /// - The walk takes regular files, directories, and symlinks. Any other
146    ///   entry stops the walk before the entry filter runs, so the filter never
147    ///   sees it. Other entries are device nodes, fifos, sockets, and Windows
148    ///   reparse points that are not symlinks.
149    /// - After the walk closes a directory, it runs the
150    ///   [`EntryFilter`](super::EntryFilter) on each entry in the order of the
151    ///   listing. Then it enters each kept subdirectory in turn, depth first.
152    /// - The filter sees the root first, with the empty path.
153    /// - [`EntryAction::Skip`](super::EntryAction::Skip) leaves out an entry,
154    ///   and for a directory its whole subtree. The walk does not open a
155    ///   skipped entry. `Skip` on the root stops the walk.
156    /// - If a file has more than one hard link in the tree, the walk reads and
157    ///   hashes the file once for each of its paths.
158    ///
159    /// # Hash pass
160    ///
161    /// - The pass reads each kept regular file once, on the blocking pool of
162    ///   the runtime. It hashes the file over its file header and its payload.
163    /// - The pass starts each file as soon as the filter keeps it, in the order
164    ///   of the walk, with at most [`ScanOptions::hash_jobs`] files in flight.
165    /// - A job reads its file in chunks of at most 64 KiB. Before each chunk,
166    ///   it checks the stop flag of the pass.
167    /// - At the first error of the walk or of a job, the pass sets the stop flag
168    ///   and starts no new job. It returns the error after each job in flight
169    ///   stops, so no file of the pass is open when the scan returns.
170    /// - If the future of the scan is dropped, the pass sets the stop flag.
171    ///   Each job in flight then stops at its next chunk.
172    /// - On Unix, a job opens its file with `O_NOFOLLOW | O_NONBLOCK`. On
173    ///   Windows, it opens the file with
174    ///   `FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS`.
175    /// - One metadata read of the open file must show a regular file. On Unix,
176    ///   the device and inode numbers must also equal those that the walk
177    ///   read. If a parent directory of the file becomes a symlink after the
178    ///   walk, the open can reach another file, and this check refuses it.
179    ///   Windows has no identity check.
180    /// - The model records the number of payload bytes that each job read.
181    /// - After the walk and the jobs end, the scan hashes each directory bottom
182    ///   up: its dirtree object, with the entries sorted by name, and its
183    ///   dirmeta object.
184    ///
185    /// # Errors
186    ///
187    /// - [`Error::InvalidInput`] if [`ScanOptions::hash_jobs`] is `Some(0)`.
188    ///   The walk does not start.
189    /// - [`Error::Walk`] for each failure of the walk and of the hash pass. The
190    ///   error names the entry on the local filesystem, the walk root
191    ///   included. It keeps one of these `io::ErrorKind` values:
192    ///   - the kind of the call that failed, for example `PermissionDenied` or
193    ///     `NotFound`
194    ///   - `InvalidInput` if the walk root is not a directory, or if the filter
195    ///     returns `Skip` for the root
196    ///   - `Unsupported` for an entry that is not a regular file, a directory,
197    ///     or a symlink, and on Windows for a symlink whose target `std` cannot
198    ///     read
199    ///   - `InvalidData` for a name that is not valid UTF-8 or that fails the
200    ///     name rule, and for a symlink target that is not valid UTF-8
201    ///   - `InvalidData` for a change by the filter that [`EntryMeta`] does not
202    ///     allow, and for a file header that `ostrya-core` refuses, for example
203    ///     a symlink target with a NUL byte
204    ///   - `InvalidData` on Windows for a symlink target that holds `\` or
205    ///     starts with a drive prefix, also if no filter runs
206    ///   - `InvalidData` for a file whose type or identity changed after the
207    ///     walk read it
208    ///   - `InvalidData` for a dirtree or a dirmeta object of more than
209    ///     [`MAX_METADATA_SIZE`] bytes, and for a tree of more than `u32::MAX`
210    ///     kept entries
211    ///
212    /// If more than one entry fails, the error names one of the failing paths.
213    /// If more than one hash job runs, the order of the failures is not fixed.
214    pub async fn scan(root: &Path, options: ScanOptions) -> Result<TreeModel> {
215        walk::scan(root, options, None).await
216    }
217
218    /// Runs [`scan`](TreeModel::scan) and sets the phases of the scan in
219    /// `progress`: [`Scanning`](crate::PushPhase::Scanning) during the walk,
220    /// and [`Hashing`](crate::PushPhase::Hashing) after it.
221    pub(crate) async fn scan_with(
222        root: &Path,
223        options: ScanOptions,
224        progress: Option<&PushProgress>,
225    ) -> Result<TreeModel> {
226        walk::scan(root, options, progress).await
227    }
228
229    /// Returns the dirtree checksum of the walk root.
230    pub fn root_dirtree(&self) -> Checksum {
231        self.dir_sums(0).0
232    }
233
234    /// Returns the dirmeta checksum of the walk root.
235    pub fn root_dirmeta(&self) -> Checksum {
236        self.dir_sums(0).1
237    }
238
239    /// Returns the name of each object of the tree, once each.
240    ///
241    /// The list holds the content object of each regular file and symlink,
242    /// and the dirtree and dirmeta objects of each directory. It holds no
243    /// commit object. The order is the order in which the walk reached the
244    /// first source of each object.
245    pub fn object_names(&self) -> Vec<ObjectName> {
246        let Sources {
247            files,
248            dirtrees,
249            dirmetas,
250        } = &self.sources;
251        let mut names = Vec::with_capacity(files.len() + dirtrees.len() + dirmetas.len());
252        for (index, node) in (0u32..).zip(&self.nodes) {
253            for name in node_names(node).into_iter().flatten() {
254                if self.source(&name) == Some(index) {
255                    names.push(name);
256                }
257            }
258        }
259        names
260    }
261
262    /// An empty model of the walk root `root`.
263    pub(super) fn new(root: &Path) -> TreeModel {
264        TreeModel {
265            root: root.to_path_buf(),
266            nodes: Vec::new(),
267            sources: Sources::default(),
268        }
269    }
270
271    /// The walk root.
272    pub(super) fn root(&self) -> &Path {
273        &self.root
274    }
275
276    /// The index the next entry gets.
277    pub(super) fn next_index(&self) -> io::Result<u32> {
278        u32::try_from(self.nodes.len())
279            .map_err(|_| invalid_data("the tree holds more entries than the model can index"))
280    }
281
282    /// Adds the walk root, with the metadata the filter left.
283    pub(super) fn push_root(&mut self, meta: EntryMeta, id: FileId) {
284        self.push(0, String::new(), meta, id);
285    }
286
287    /// Adds an entry under the directory `parent`, with the metadata the filter
288    /// left and the identity the walk read. The caller checked the index with
289    /// [`next_index`](TreeModel::next_index).
290    pub(super) fn push(&mut self, parent: u32, name: String, meta: EntryMeta, id: FileId) {
291        let EntryMeta {
292            kind,
293            uid,
294            gid,
295            mode,
296            xattrs,
297            symlink_target,
298        } = meta;
299        let meta = Meta {
300            uid,
301            gid,
302            mode,
303            xattrs,
304        };
305        let data = match kind {
306            super::EntryKind::Dir => NodeData::Dir {
307                meta,
308                children: 0..0,
309                sums: None,
310            },
311            super::EntryKind::File | super::EntryKind::Symlink => NodeData::Content {
312                meta,
313                id,
314                target: symlink_target.map(String::into_boxed_str),
315                hashed: None,
316            },
317        };
318        self.nodes.push(Node {
319            parent,
320            name: name.into_boxed_str(),
321            data,
322        });
323    }
324
325    /// Records the hash of the symlink `index`, whose content object has no
326    /// payload.
327    pub(super) fn hash_symlink(&mut self, index: u32) -> io::Result<()> {
328        let checksum = ostrya_core::ContentHasher::new(&self.header(index))
329            .map_err(|e| invalid_data(e.to_string()))?
330            .finish();
331        self.set_hashed(index, Hashed { checksum, size: 0 });
332        Ok(())
333    }
334
335    /// Records the kept entries of the directory `dir`.
336    pub(super) fn set_children(&mut self, dir: u32, range: Range<u32>) {
337        if let NodeData::Dir { children, .. } = &mut self.node_mut(dir).data {
338            *children = range;
339        }
340    }
341
342    /// The kept entries of the directory `dir`.
343    pub(super) fn children(&self, dir: u32) -> Range<u32> {
344        match &self.node(dir).data {
345            NodeData::Dir { children, .. } => children.clone(),
346            NodeData::Content { .. } => 0..0,
347        }
348    }
349
350    /// Returns `true` if the entry `index` is a directory.
351    pub(super) fn is_dir(&self, index: u32) -> bool {
352        matches!(self.node(index).data, NodeData::Dir { .. })
353    }
354
355    /// The path of the entry `index` relative to the walk root, joined with
356    /// `/`, written into `out`.
357    pub(super) fn rel_path(&self, index: u32, out: &mut String) {
358        out.clear();
359        for i in self.chain(index) {
360            if !out.is_empty() {
361                out.push('/');
362            }
363            out.push_str(&self.node(i).name);
364        }
365    }
366
367    /// The path of the entry `index` on the local filesystem.
368    pub(super) fn os_path(&self, index: u32) -> PathBuf {
369        let mut path = self.root.clone();
370        for i in self.chain(index) {
371            path.push(&*self.node(i).name);
372        }
373        path
374    }
375
376    /// The identity of the regular file `index`, as the walk read it.
377    pub(super) fn file_id(&self, index: u32) -> FileId {
378        match &self.node(index).data {
379            NodeData::Content { id, .. } => *id,
380            NodeData::Dir { .. } => unreachable!("a directory is not opened as a file"),
381        }
382    }
383
384    /// The file header of the regular file or symlink `index`.
385    pub(super) fn header(&self, index: u32) -> FileHeader {
386        match &self.node(index).data {
387            NodeData::Content { meta, target, .. } => FileHeader {
388                uid: meta.uid,
389                gid: meta.gid,
390                mode: meta.mode,
391                symlink_target: target.as_deref().unwrap_or_default().to_owned(),
392                xattrs: meta.xattrs.clone(),
393            },
394            NodeData::Dir { .. } => unreachable!("a directory has no file header"),
395        }
396    }
397
398    /// Hashes each directory bottom-up, once each regular file is hashed, and
399    /// records the source of each object.
400    pub(super) fn finish(&mut self) -> Result<()> {
401        // The entries of a directory come after it, so the reverse order
402        // hashes each directory after all of its subdirectories.
403        for index in (0..self.next_index_unchecked()).rev() {
404            if !self.is_dir(index) {
405                continue;
406            }
407            let sums = self.hash_dir(index).map_err(|source| Error::Walk {
408                path: self.os_path(index),
409                source,
410            })?;
411            if let NodeData::Dir { sums: slot, .. } = &mut self.node_mut(index).data {
412                *slot = Some(sums);
413            }
414        }
415        let mut sources = Sources::default();
416        for (index, node) in (0u32..).zip(&self.nodes) {
417            match node.data {
418                NodeData::Content { .. } => sources.files.push(index),
419                NodeData::Dir { .. } => {
420                    sources.dirtrees.push(index);
421                    sources.dirmetas.push(index);
422                }
423            }
424        }
425        for (list, ty) in [
426            (&mut sources.files, ObjectType::File),
427            (&mut sources.dirtrees, ObjectType::DirTree),
428            (&mut sources.dirmetas, ObjectType::DirMeta),
429        ] {
430            // The sort is stable, so the first entry of each run of equal
431            // checksums is the first in walk order, and the dedup keeps it.
432            list.sort_by_key(|&index| self.object_checksum(index, ty));
433            list.dedup_by_key(|index| self.object_checksum(*index, ty));
434            list.shrink_to_fit();
435        }
436        self.sources = sources;
437        Ok(())
438    }
439
440    /// The source entry of the object `name`, or `None` for an object the
441    /// tree does not give.
442    fn source(&self, name: &ObjectName) -> Option<u32> {
443        let list = match name.ty {
444            ObjectType::File => &self.sources.files,
445            ObjectType::DirTree => &self.sources.dirtrees,
446            ObjectType::DirMeta => &self.sources.dirmetas,
447            _ => return None,
448        };
449        list.binary_search_by_key(&name.checksum, |&index| {
450            self.object_checksum(index, name.ty)
451        })
452        .ok()
453        .map(|k| list[k])
454    }
455
456    /// The checksum of the object of type `ty` that the hashed entry `index`
457    /// gives.
458    fn object_checksum(&self, index: u32, ty: ObjectType) -> Checksum {
459        match (&self.node(index).data, ty) {
460            (
461                NodeData::Content {
462                    hashed: Some(hashed),
463                    ..
464                },
465                ObjectType::File,
466            ) => hashed.checksum,
467            (NodeData::Dir { .. }, ObjectType::DirTree) => self.dir_sums(index).0,
468            (NodeData::Dir { .. }, ObjectType::DirMeta) => self.dir_sums(index).1,
469            _ => unreachable!("each source entry is hashed and gives an object of its type"),
470        }
471    }
472
473    /// The dirtree object of the directory `dir`.
474    fn dirtree(&self, dir: u32) -> DirTree {
475        let mut tree = DirTree::default();
476        for index in self.children(dir) {
477            let node = self.node(index);
478            let name = node.name.to_string();
479            match &node.data {
480                NodeData::Content { hashed, .. } => {
481                    let hashed = hashed.expect("each kept file is hashed before its directory");
482                    tree.files.push((name, hashed.checksum));
483                }
484                NodeData::Dir { .. } => {
485                    let (dirtree, dirmeta) = self.dir_sums(index);
486                    tree.dirs.push((name, dirtree, dirmeta));
487                }
488            }
489        }
490        tree.files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
491        tree.dirs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
492        tree
493    }
494
495    /// The dirmeta object of the directory `dir`.
496    fn dirmeta(&self, dir: u32) -> DirMeta {
497        match &self.node(dir).data {
498            NodeData::Dir { meta, .. } => DirMeta {
499                uid: meta.uid,
500                gid: meta.gid,
501                mode: meta.mode,
502                xattrs: meta.xattrs.clone(),
503            },
504            NodeData::Content { .. } => unreachable!("a file has no dirmeta"),
505        }
506    }
507
508    /// The dirtree and dirmeta checksums of the directory `dir`.
509    fn hash_dir(&self, dir: u32) -> io::Result<(Checksum, Checksum)> {
510        let dirtree = self
511            .dirtree(dir)
512            .serialize()
513            .map_err(|e| invalid_data(e.to_string()))?;
514        check_metadata_size(&dirtree, "dirtree", MAX_METADATA_SIZE)?;
515        let dirmeta = self
516            .dirmeta(dir)
517            .serialize()
518            .map_err(|e| invalid_data(e.to_string()))?;
519        check_metadata_size(&dirmeta, "dirmeta", MAX_METADATA_SIZE)?;
520        Ok((Checksum::sha256(&dirtree), Checksum::sha256(&dirmeta)))
521    }
522
523    /// The data of the object `name` for the send pass.
524    async fn open_object(&self, name: &ObjectName) -> Result<ObjectData> {
525        let index = self.source(name).ok_or_else(|| {
526            Error::InvalidInput(format!(
527                "object {} of type {:?} is not in the tree model",
528                name.checksum, name.ty
529            ))
530        })?;
531        let bytes = match name.ty {
532            ObjectType::File => return self.open_content(index).await,
533            ObjectType::DirTree => self.dirtree(index).serialize(),
534            ObjectType::DirMeta => self.dirmeta(index).serialize(),
535            _ => unreachable!("the model is the source of three object types alone"),
536        };
537        let bytes = bytes.map_err(|e| Error::Walk {
538            path: self.os_path(index),
539            source: invalid_data(e.to_string()),
540        })?;
541        Ok(encoded(bytes))
542    }
543
544    /// The payload bytes of the file objects of `names`, as the hash pass
545    /// read them. A symlink counts 0. A file object that the model does not
546    /// hold is [`Error::InvalidInput`].
547    fn content_bytes(&self, names: &[ObjectName]) -> Result<u64> {
548        let mut total = 0u64;
549        for name in names.iter().filter(|n| n.ty == ObjectType::File) {
550            let hashed = self
551                .source(name)
552                .and_then(|index| match &self.node(index).data {
553                    NodeData::Content { hashed, .. } => *hashed,
554                    NodeData::Dir { .. } => None,
555                });
556            let Some(hashed) = hashed else {
557                return Err(Error::InvalidInput(format!(
558                    "object {} of type {:?} is not in the tree model",
559                    name.checksum, name.ty
560                )));
561            };
562            total = total.saturating_add(hashed.size);
563        }
564        Ok(total)
565    }
566
567    /// The content object of the regular file or symlink `index`. A regular
568    /// file is opened again, on the blocking pool, with the open of the hash
569    /// pass, and its payload stops after the size of the hash pass plus one
570    /// byte. A symlink opens nothing.
571    async fn open_content(&self, index: u32) -> Result<ObjectData> {
572        let NodeData::Content {
573            target,
574            hashed: Some(hashed),
575            ..
576        } = &self.node(index).data
577        else {
578            unreachable!("each source of a content object is a hashed file or symlink");
579        };
580        let header = self.header(index);
581        if target.is_some() {
582            return Ok(ObjectData::Content {
583                header,
584                size: 0,
585                payload: None,
586            });
587        }
588        let path = self.os_path(index);
589        let id = self.file_id(index);
590        let open_path = path.clone();
591        let (file, _len) = ostrya_rt::unblock(move || open_regular(&open_path, &id))
592            .await
593            .map_err(|source| Error::Walk { path, source })?;
594        Ok(ObjectData::Content {
595            header,
596            size: hashed.size,
597            // One byte past the size of the hash pass lets the server see a
598            // file that grew, and stops the read there.
599            payload: Some(Box::new(
600                ostrya_rt::FileReader::with_len_hint(file, hashed.size)
601                    .take(hashed.size.saturating_add(1)),
602            )),
603        })
604    }
605
606    /// The dirtree and dirmeta checksums of the hashed directory `dir`.
607    fn dir_sums(&self, dir: u32) -> (Checksum, Checksum) {
608        match &self.node(dir).data {
609            NodeData::Dir {
610                sums: Some(sums), ..
611            } => *sums,
612            _ => unreachable!("each directory is hashed after its subdirectories"),
613        }
614    }
615
616    /// Records the hash of the regular file or symlink `index`.
617    pub(super) fn set_hashed(&mut self, index: u32, result: Hashed) {
618        if let NodeData::Content { hashed, .. } = &mut self.node_mut(index).data {
619            *hashed = Some(result);
620        }
621    }
622
623    /// Returns the number of entries. The walk checks each index with
624    /// [`next_index`](TreeModel::next_index), so the number fits in a `u32`.
625    fn next_index_unchecked(&self) -> u32 {
626        self.nodes.len() as u32
627    }
628
629    /// The indices of the entries from the root down to `index`, the root
630    /// left out.
631    fn chain(&self, mut index: u32) -> Vec<u32> {
632        let mut chain = Vec::new();
633        while index != 0 {
634            chain.push(index);
635            index = self.node(index).parent;
636        }
637        chain.reverse();
638        chain
639    }
640
641    fn node(&self, index: u32) -> &Node {
642        &self.nodes[index as usize]
643    }
644
645    fn node_mut(&mut self, index: u32) -> &mut Node {
646        &mut self.nodes[index as usize]
647    }
648}
649
650/// The objects an entry gives: the content object of a regular file or a
651/// symlink, and the dirtree and dirmeta objects of a directory.
652fn node_names(node: &Node) -> [Option<ObjectName>; 2] {
653    match &node.data {
654        NodeData::Content { hashed, .. } => [
655            hashed.map(|h| ObjectName::new(h.checksum, ObjectType::File)),
656            None,
657        ],
658        NodeData::Dir { sums, .. } => match sums {
659            Some((dirtree, dirmeta)) => [
660                Some(ObjectName::new(*dirtree, ObjectType::DirTree)),
661                Some(ObjectName::new(*dirmeta, ObjectType::DirMeta)),
662            ],
663            None => [None, None],
664        },
665    }
666}
667
668impl ObjectSource for TreeModel {
669    fn objects<'a>(&'a self, commit: &'a Checksum) -> BoxFuture<'a, Result<Vec<ObjectName>>> {
670        Box::pin(async move { Err(no_commit(commit)) })
671    }
672
673    fn open<'a>(
674        &'a self,
675        name: &'a ObjectName,
676        _encoding: Encoding,
677    ) -> BoxFuture<'a, Result<ObjectData>> {
678        Box::pin(self.open_object(name))
679    }
680
681    fn detached_metadata<'a>(
682        &'a self,
683        commit: &'a Checksum,
684    ) -> BoxFuture<'a, Result<Option<Value>>> {
685        Box::pin(async move { Err(no_commit(commit)) })
686    }
687
688    fn content_size<'a>(
689        &'a self,
690        names: &'a [ObjectName],
691        _encoding: Encoding,
692    ) -> BoxFuture<'a, Result<Option<u64>>> {
693        Box::pin(async move { self.content_bytes(names).map(Some) })
694    }
695}
696
697/// The error of a call that names the commit `commit`, which the model does
698/// not hold.
699fn no_commit(commit: &Checksum) -> Error {
700    Error::InvalidInput(format!(
701        "commit {commit} is not in the tree model, which holds no commit"
702    ))
703}
704
705/// Metadata object bytes, given as they are in `raw`.
706fn encoded(bytes: Vec<u8>) -> ObjectData {
707    ObjectData::Encoded {
708        encoding: Encoding::Raw,
709        reader: Box::new(Cursor::new(bytes)),
710    }
711}
712
713/// Refuses a metadata object of more than `limit` bytes.
714fn check_metadata_size(bytes: &[u8], what: &str, limit: u64) -> io::Result<()> {
715    if bytes.len() as u64 > limit {
716        return Err(invalid_data(format!(
717            "the {what} object of the directory is {} bytes, over the limit of {limit}",
718            bytes.len()
719        )));
720    }
721    Ok(())
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727
728    fn assert_limit(bytes: &[u8], what: &str) {
729        let len = bytes.len() as u64;
730        check_metadata_size(bytes, what, len).unwrap();
731        let err = check_metadata_size(bytes, what, len - 1).unwrap_err();
732        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
733        assert!(err.to_string().contains(what), "{err}");
734    }
735
736    #[test]
737    fn a_dirtree_one_byte_over_the_limit_is_invalid_data() {
738        let dirtree = DirTree {
739            files: ["a", "b", "c"]
740                .into_iter()
741                .map(|name| (name.to_owned(), Checksum::sha256(name.as_bytes())))
742                .collect(),
743            dirs: vec![(
744                "d".to_owned(),
745                Checksum::sha256(b"dirtree"),
746                Checksum::sha256(b"dirmeta"),
747            )],
748        };
749        assert_limit(&dirtree.serialize().unwrap(), "dirtree");
750    }
751
752    #[test]
753    fn a_dirmeta_one_byte_over_the_limit_is_invalid_data() {
754        let dirmeta = DirMeta {
755            uid: 0,
756            gid: 0,
757            mode: 0o40755,
758            xattrs: Xattrs::new([(b"user.test\0".to_vec(), vec![7; 100])]).unwrap(),
759        };
760        assert_limit(&dirmeta.serialize().unwrap(), "dirmeta");
761    }
762}