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    ///
222    /// The scan sets `Scanning` with
223    /// [`start_phase`](crate::PushProgress::start_phase), so the hook of
224    /// `progress` gets one call before the walk, also on a new handle.
225    pub(crate) async fn scan_with(
226        root: &Path,
227        options: ScanOptions,
228        progress: Option<&PushProgress>,
229    ) -> Result<TreeModel> {
230        walk::scan(root, options, progress).await
231    }
232
233    /// Returns the dirtree checksum of the walk root.
234    pub fn root_dirtree(&self) -> Checksum {
235        self.dir_sums(0).0
236    }
237
238    /// Returns the dirmeta checksum of the walk root.
239    pub fn root_dirmeta(&self) -> Checksum {
240        self.dir_sums(0).1
241    }
242
243    /// Returns the name of each object of the tree, once each.
244    ///
245    /// The list holds the content object of each regular file and symlink,
246    /// and the dirtree and dirmeta objects of each directory. It holds no
247    /// commit object. The order is the order in which the walk reached the
248    /// first source of each object.
249    pub fn object_names(&self) -> Vec<ObjectName> {
250        let Sources {
251            files,
252            dirtrees,
253            dirmetas,
254        } = &self.sources;
255        let mut names = Vec::with_capacity(files.len() + dirtrees.len() + dirmetas.len());
256        for (index, node) in (0u32..).zip(&self.nodes) {
257            for name in node_names(node).into_iter().flatten() {
258                if self.source(&name) == Some(index) {
259                    names.push(name);
260                }
261            }
262        }
263        names
264    }
265
266    /// Returns the path on the local filesystem of the entry that gives the
267    /// object `name`, or `None` for an object that the tree does not give.
268    ///
269    /// The entry is the first one in walk order that gives the object. The
270    /// call reads no file.
271    pub fn source_path(&self, name: &ObjectName) -> Option<PathBuf> {
272        self.source(name).map(|index| self.os_path(index))
273    }
274
275    /// An empty model of the walk root `root`.
276    pub(super) fn new(root: &Path) -> TreeModel {
277        TreeModel {
278            root: root.to_path_buf(),
279            nodes: Vec::new(),
280            sources: Sources::default(),
281        }
282    }
283
284    /// The walk root.
285    pub(super) fn root(&self) -> &Path {
286        &self.root
287    }
288
289    /// The index the next entry gets.
290    pub(super) fn next_index(&self) -> io::Result<u32> {
291        u32::try_from(self.nodes.len())
292            .map_err(|_| invalid_data("the tree holds more entries than the model can index"))
293    }
294
295    /// Adds the walk root, with the metadata the filter left.
296    pub(super) fn push_root(&mut self, meta: EntryMeta, id: FileId) {
297        self.push(0, String::new(), meta, id);
298    }
299
300    /// Adds an entry under the directory `parent`, with the metadata the filter
301    /// left and the identity the walk read. The caller checked the index with
302    /// [`next_index`](TreeModel::next_index).
303    pub(super) fn push(&mut self, parent: u32, name: String, meta: EntryMeta, id: FileId) {
304        let EntryMeta {
305            kind,
306            uid,
307            gid,
308            mode,
309            xattrs,
310            symlink_target,
311        } = meta;
312        let meta = Meta {
313            uid,
314            gid,
315            mode,
316            xattrs,
317        };
318        let data = match kind {
319            super::EntryKind::Dir => NodeData::Dir {
320                meta,
321                children: 0..0,
322                sums: None,
323            },
324            super::EntryKind::File | super::EntryKind::Symlink => NodeData::Content {
325                meta,
326                id,
327                target: symlink_target.map(String::into_boxed_str),
328                hashed: None,
329            },
330        };
331        self.nodes.push(Node {
332            parent,
333            name: name.into_boxed_str(),
334            data,
335        });
336    }
337
338    /// Records the hash of the symlink `index`, whose content object has no
339    /// payload.
340    pub(super) fn hash_symlink(&mut self, index: u32) -> io::Result<()> {
341        let checksum = ostrya_core::ContentHasher::new(&self.header(index))
342            .map_err(|e| invalid_data(e.to_string()))?
343            .finish();
344        self.set_hashed(index, Hashed { checksum, size: 0 });
345        Ok(())
346    }
347
348    /// Records the kept entries of the directory `dir`.
349    pub(super) fn set_children(&mut self, dir: u32, range: Range<u32>) {
350        if let NodeData::Dir { children, .. } = &mut self.node_mut(dir).data {
351            *children = range;
352        }
353    }
354
355    /// The kept entries of the directory `dir`.
356    pub(super) fn children(&self, dir: u32) -> Range<u32> {
357        match &self.node(dir).data {
358            NodeData::Dir { children, .. } => children.clone(),
359            NodeData::Content { .. } => 0..0,
360        }
361    }
362
363    /// Returns `true` if the entry `index` is a directory.
364    pub(super) fn is_dir(&self, index: u32) -> bool {
365        matches!(self.node(index).data, NodeData::Dir { .. })
366    }
367
368    /// The path of the entry `index` relative to the walk root, joined with
369    /// `/`, written into `out`.
370    pub(super) fn rel_path(&self, index: u32, out: &mut String) {
371        out.clear();
372        for i in self.chain(index) {
373            if !out.is_empty() {
374                out.push('/');
375            }
376            out.push_str(&self.node(i).name);
377        }
378    }
379
380    /// The path of the entry `index` on the local filesystem.
381    pub(super) fn os_path(&self, index: u32) -> PathBuf {
382        let mut path = self.root.clone();
383        for i in self.chain(index) {
384            path.push(&*self.node(i).name);
385        }
386        path
387    }
388
389    /// The identity of the regular file `index`, as the walk read it.
390    pub(super) fn file_id(&self, index: u32) -> FileId {
391        match &self.node(index).data {
392            NodeData::Content { id, .. } => *id,
393            NodeData::Dir { .. } => unreachable!("a directory is not opened as a file"),
394        }
395    }
396
397    /// The file header of the regular file or symlink `index`.
398    pub(super) fn header(&self, index: u32) -> FileHeader {
399        match &self.node(index).data {
400            NodeData::Content { meta, target, .. } => FileHeader {
401                uid: meta.uid,
402                gid: meta.gid,
403                mode: meta.mode,
404                symlink_target: target.as_deref().unwrap_or_default().to_owned(),
405                xattrs: meta.xattrs.clone(),
406            },
407            NodeData::Dir { .. } => unreachable!("a directory has no file header"),
408        }
409    }
410
411    /// Hashes each directory bottom-up, once each regular file is hashed, and
412    /// records the source of each object.
413    pub(super) fn finish(&mut self) -> Result<()> {
414        // The entries of a directory come after it, so the reverse order
415        // hashes each directory after all of its subdirectories.
416        for index in (0..self.next_index_unchecked()).rev() {
417            if !self.is_dir(index) {
418                continue;
419            }
420            let sums = self.hash_dir(index).map_err(|source| Error::Walk {
421                path: self.os_path(index),
422                source,
423            })?;
424            if let NodeData::Dir { sums: slot, .. } = &mut self.node_mut(index).data {
425                *slot = Some(sums);
426            }
427        }
428        let mut sources = Sources::default();
429        for (index, node) in (0u32..).zip(&self.nodes) {
430            match node.data {
431                NodeData::Content { .. } => sources.files.push(index),
432                NodeData::Dir { .. } => {
433                    sources.dirtrees.push(index);
434                    sources.dirmetas.push(index);
435                }
436            }
437        }
438        for (list, ty) in [
439            (&mut sources.files, ObjectType::File),
440            (&mut sources.dirtrees, ObjectType::DirTree),
441            (&mut sources.dirmetas, ObjectType::DirMeta),
442        ] {
443            // The sort is stable, so the first entry of each run of equal
444            // checksums is the first in walk order, and the dedup keeps it.
445            list.sort_by_key(|&index| self.object_checksum(index, ty));
446            list.dedup_by_key(|index| self.object_checksum(*index, ty));
447            list.shrink_to_fit();
448        }
449        self.sources = sources;
450        Ok(())
451    }
452
453    /// The source entry of the object `name`, or `None` for an object the
454    /// tree does not give.
455    fn source(&self, name: &ObjectName) -> Option<u32> {
456        let list = match name.ty {
457            ObjectType::File => &self.sources.files,
458            ObjectType::DirTree => &self.sources.dirtrees,
459            ObjectType::DirMeta => &self.sources.dirmetas,
460            _ => return None,
461        };
462        list.binary_search_by_key(&name.checksum, |&index| {
463            self.object_checksum(index, name.ty)
464        })
465        .ok()
466        .map(|k| list[k])
467    }
468
469    /// The checksum of the object of type `ty` that the hashed entry `index`
470    /// gives.
471    fn object_checksum(&self, index: u32, ty: ObjectType) -> Checksum {
472        match (&self.node(index).data, ty) {
473            (
474                NodeData::Content {
475                    hashed: Some(hashed),
476                    ..
477                },
478                ObjectType::File,
479            ) => hashed.checksum,
480            (NodeData::Dir { .. }, ObjectType::DirTree) => self.dir_sums(index).0,
481            (NodeData::Dir { .. }, ObjectType::DirMeta) => self.dir_sums(index).1,
482            _ => unreachable!("each source entry is hashed and gives an object of its type"),
483        }
484    }
485
486    /// The dirtree object of the directory `dir`.
487    fn dirtree(&self, dir: u32) -> DirTree {
488        let mut tree = DirTree::default();
489        for index in self.children(dir) {
490            let node = self.node(index);
491            let name = node.name.to_string();
492            match &node.data {
493                NodeData::Content { hashed, .. } => {
494                    let hashed = hashed.expect("each kept file is hashed before its directory");
495                    tree.files.push((name, hashed.checksum));
496                }
497                NodeData::Dir { .. } => {
498                    let (dirtree, dirmeta) = self.dir_sums(index);
499                    tree.dirs.push((name, dirtree, dirmeta));
500                }
501            }
502        }
503        tree.files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
504        tree.dirs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
505        tree
506    }
507
508    /// The dirmeta object of the directory `dir`.
509    fn dirmeta(&self, dir: u32) -> DirMeta {
510        match &self.node(dir).data {
511            NodeData::Dir { meta, .. } => DirMeta {
512                uid: meta.uid,
513                gid: meta.gid,
514                mode: meta.mode,
515                xattrs: meta.xattrs.clone(),
516            },
517            NodeData::Content { .. } => unreachable!("a file has no dirmeta"),
518        }
519    }
520
521    /// The dirtree and dirmeta checksums of the directory `dir`.
522    fn hash_dir(&self, dir: u32) -> io::Result<(Checksum, Checksum)> {
523        let dirtree = self
524            .dirtree(dir)
525            .serialize()
526            .map_err(|e| invalid_data(e.to_string()))?;
527        check_metadata_size(&dirtree, "dirtree", MAX_METADATA_SIZE)?;
528        let dirmeta = self
529            .dirmeta(dir)
530            .serialize()
531            .map_err(|e| invalid_data(e.to_string()))?;
532        check_metadata_size(&dirmeta, "dirmeta", MAX_METADATA_SIZE)?;
533        Ok((Checksum::sha256(&dirtree), Checksum::sha256(&dirmeta)))
534    }
535
536    /// The data of the object `name` for the send pass.
537    async fn open_object(&self, name: &ObjectName) -> Result<ObjectData> {
538        let index = self.source(name).ok_or_else(|| {
539            Error::InvalidInput(format!(
540                "object {} of type {:?} is not in the tree model",
541                name.checksum, name.ty
542            ))
543        })?;
544        let bytes = match name.ty {
545            ObjectType::File => return self.open_content(index).await,
546            ObjectType::DirTree => self.dirtree(index).serialize(),
547            ObjectType::DirMeta => self.dirmeta(index).serialize(),
548            _ => unreachable!("the model is the source of three object types alone"),
549        };
550        let bytes = bytes.map_err(|e| Error::Walk {
551            path: self.os_path(index),
552            source: invalid_data(e.to_string()),
553        })?;
554        Ok(encoded(bytes))
555    }
556
557    /// The payload bytes of the file objects of `names`, as the hash pass
558    /// read them. A symlink counts 0. A file object that the model does not
559    /// hold is [`Error::InvalidInput`].
560    fn content_bytes(&self, names: &[ObjectName]) -> Result<u64> {
561        let mut total = 0u64;
562        for name in names.iter().filter(|n| n.ty == ObjectType::File) {
563            let hashed = self
564                .source(name)
565                .and_then(|index| match &self.node(index).data {
566                    NodeData::Content { hashed, .. } => *hashed,
567                    NodeData::Dir { .. } => None,
568                });
569            let Some(hashed) = hashed else {
570                return Err(Error::InvalidInput(format!(
571                    "object {} of type {:?} is not in the tree model",
572                    name.checksum, name.ty
573                )));
574            };
575            total = total.saturating_add(hashed.size);
576        }
577        Ok(total)
578    }
579
580    /// The content object of the regular file or symlink `index`. A regular
581    /// file is opened again, on the blocking pool, with the open of the hash
582    /// pass, and its payload stops after the size of the hash pass plus one
583    /// byte. A symlink opens nothing.
584    async fn open_content(&self, index: u32) -> Result<ObjectData> {
585        let NodeData::Content {
586            target,
587            hashed: Some(hashed),
588            ..
589        } = &self.node(index).data
590        else {
591            unreachable!("each source of a content object is a hashed file or symlink");
592        };
593        let header = self.header(index);
594        if target.is_some() {
595            return Ok(ObjectData::Content {
596                header,
597                size: 0,
598                payload: None,
599            });
600        }
601        let path = self.os_path(index);
602        let id = self.file_id(index);
603        let open_path = path.clone();
604        let (file, _len) = ostrya_rt::unblock(move || open_regular(&open_path, &id))
605            .await
606            .map_err(|source| Error::Walk { path, source })?;
607        Ok(ObjectData::Content {
608            header,
609            size: hashed.size,
610            // One byte past the size of the hash pass lets the server see a
611            // file that grew, and stops the read there.
612            payload: Some(Box::new(
613                ostrya_rt::FileReader::with_len_hint(file, hashed.size)
614                    .take(hashed.size.saturating_add(1)),
615            )),
616        })
617    }
618
619    /// The dirtree and dirmeta checksums of the hashed directory `dir`.
620    fn dir_sums(&self, dir: u32) -> (Checksum, Checksum) {
621        match &self.node(dir).data {
622            NodeData::Dir {
623                sums: Some(sums), ..
624            } => *sums,
625            _ => unreachable!("each directory is hashed after its subdirectories"),
626        }
627    }
628
629    /// Records the hash of the regular file or symlink `index`.
630    pub(super) fn set_hashed(&mut self, index: u32, result: Hashed) {
631        if let NodeData::Content { hashed, .. } = &mut self.node_mut(index).data {
632            *hashed = Some(result);
633        }
634    }
635
636    /// Returns the number of entries. The walk checks each index with
637    /// [`next_index`](TreeModel::next_index), so the number fits in a `u32`.
638    fn next_index_unchecked(&self) -> u32 {
639        self.nodes.len() as u32
640    }
641
642    /// The indices of the entries from the root down to `index`, the root
643    /// left out.
644    fn chain(&self, mut index: u32) -> Vec<u32> {
645        let mut chain = Vec::new();
646        while index != 0 {
647            chain.push(index);
648            index = self.node(index).parent;
649        }
650        chain.reverse();
651        chain
652    }
653
654    fn node(&self, index: u32) -> &Node {
655        &self.nodes[index as usize]
656    }
657
658    fn node_mut(&mut self, index: u32) -> &mut Node {
659        &mut self.nodes[index as usize]
660    }
661}
662
663/// The objects an entry gives: the content object of a regular file or a
664/// symlink, and the dirtree and dirmeta objects of a directory.
665fn node_names(node: &Node) -> [Option<ObjectName>; 2] {
666    match &node.data {
667        NodeData::Content { hashed, .. } => [
668            hashed.map(|h| ObjectName::new(h.checksum, ObjectType::File)),
669            None,
670        ],
671        NodeData::Dir { sums, .. } => match sums {
672            Some((dirtree, dirmeta)) => [
673                Some(ObjectName::new(*dirtree, ObjectType::DirTree)),
674                Some(ObjectName::new(*dirmeta, ObjectType::DirMeta)),
675            ],
676            None => [None, None],
677        },
678    }
679}
680
681impl ObjectSource for TreeModel {
682    fn objects<'a>(&'a self, commit: &'a Checksum) -> BoxFuture<'a, Result<Vec<ObjectName>>> {
683        Box::pin(async move { Err(no_commit(commit)) })
684    }
685
686    fn open<'a>(
687        &'a self,
688        name: &'a ObjectName,
689        _encoding: Encoding,
690    ) -> BoxFuture<'a, Result<ObjectData>> {
691        Box::pin(self.open_object(name))
692    }
693
694    fn detached_metadata<'a>(
695        &'a self,
696        commit: &'a Checksum,
697    ) -> BoxFuture<'a, Result<Option<Value>>> {
698        Box::pin(async move { Err(no_commit(commit)) })
699    }
700
701    fn content_size<'a>(
702        &'a self,
703        names: &'a [ObjectName],
704        _encoding: Encoding,
705    ) -> BoxFuture<'a, Result<Option<u64>>> {
706        Box::pin(async move { self.content_bytes(names).map(Some) })
707    }
708}
709
710/// The error of a call that names the commit `commit`, which the model does
711/// not hold.
712fn no_commit(commit: &Checksum) -> Error {
713    Error::InvalidInput(format!(
714        "commit {commit} is not in the tree model, which holds no commit"
715    ))
716}
717
718/// Metadata object bytes, given as they are in `raw`.
719fn encoded(bytes: Vec<u8>) -> ObjectData {
720    ObjectData::Encoded {
721        encoding: Encoding::Raw,
722        reader: Box::new(Cursor::new(bytes)),
723    }
724}
725
726/// Refuses a metadata object of more than `limit` bytes.
727fn check_metadata_size(bytes: &[u8], what: &str, limit: u64) -> io::Result<()> {
728    if bytes.len() as u64 > limit {
729        return Err(invalid_data(format!(
730            "the {what} object of the directory is {} bytes, over the limit of {limit}",
731            bytes.len()
732        )));
733    }
734    Ok(())
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740
741    fn assert_limit(bytes: &[u8], what: &str) {
742        let len = bytes.len() as u64;
743        check_metadata_size(bytes, what, len).unwrap();
744        let err = check_metadata_size(bytes, what, len - 1).unwrap_err();
745        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
746        assert!(err.to_string().contains(what), "{err}");
747    }
748
749    #[test]
750    fn a_dirtree_one_byte_over_the_limit_is_invalid_data() {
751        let dirtree = DirTree {
752            files: ["a", "b", "c"]
753                .into_iter()
754                .map(|name| (name.to_owned(), Checksum::sha256(name.as_bytes())))
755                .collect(),
756            dirs: vec![(
757                "d".to_owned(),
758                Checksum::sha256(b"dirtree"),
759                Checksum::sha256(b"dirmeta"),
760            )],
761        };
762        assert_limit(&dirtree.serialize().unwrap(), "dirtree");
763    }
764
765    #[test]
766    fn a_dirmeta_one_byte_over_the_limit_is_invalid_data() {
767        let dirmeta = DirMeta {
768            uid: 0,
769            gid: 0,
770            mode: 0o40755,
771            xattrs: Xattrs::new([(b"user.test\0".to_vec(), vec![7; 100])]).unwrap(),
772        };
773        assert_limit(&dirmeta.serialize().unwrap(), "dirmeta");
774    }
775}