Skip to main content

ostrya_remote/tree/
mod.rs

1//! The walk of a local directory into a tree model.
2//!
3//! [`TreeModel::scan`] walks a directory with `std::fs` and computes the
4//! checksum of each object of the tree. [`ScanOptions`] holds the
5//! [`EntryFilter`]. The filter sees the [`EntryPath`] and the [`EntryMeta`] of
6//! each entry, can change the metadata, and returns an [`EntryAction`]. A
7//! [`TreeModel`] is the [`ObjectSource`](crate::session::ObjectSource) of a
8//! push of the tree.
9
10mod hash;
11mod model;
12mod walk;
13
14use std::fmt;
15use std::io;
16use std::path::Path;
17
18use ostrya_core::Xattrs;
19
20pub use model::TreeModel;
21
22/// The file-type mask of an `st_mode`.
23const S_IFMT: u32 = 0o170000;
24/// The directory file-type bits of an `st_mode`.
25const S_IFDIR: u32 = 0o040000;
26/// The regular-file file-type bits of an `st_mode`.
27const S_IFREG: u32 = 0o100000;
28/// The symlink file-type bits of an `st_mode`.
29const S_IFLNK: u32 = 0o120000;
30/// The bits of an `st_mode`: the file-type bits and the permission bits.
31const MODE_BITS: u32 = 0o177777;
32
33/// The mode of every symlink, on every platform.
34const SYMLINK_MODE: u32 = S_IFLNK | 0o777;
35
36/// The attribute bit of a Win32 reparse point, `FILE_ATTRIBUTE_REPARSE_POINT`.
37#[cfg(windows)]
38const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
39
40/// The kind of a tree entry.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum EntryKind {
43    /// A regular file.
44    File,
45    /// A directory.
46    Dir,
47    /// A symlink.
48    Symlink,
49}
50
51impl EntryKind {
52    /// Returns the file-type bits of the kind.
53    fn type_bits(self) -> u32 {
54        match self {
55            EntryKind::File => S_IFREG,
56            EntryKind::Dir => S_IFDIR,
57            EntryKind::Symlink => S_IFLNK,
58        }
59    }
60}
61
62/// The metadata of a tree entry, as the entry filter sees and changes it.
63///
64/// The walk fills it from the metadata read of the entry:
65///
66/// - On Unix, `uid`, `gid`, and `mode` come from the read, which does not
67///   follow a symlink. The mode of a symlink is the one exception.
68/// - On other platforms, `uid` and `gid` are 0. `mode` is `0o100644` for a
69///   regular file and `0o40755` for a directory.
70/// - A symlink has the mode `0o120777` on every platform. On Unix its owner
71///   comes from the read.
72/// - `xattrs` is empty on every platform.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct EntryMeta {
75    /// The kind of the entry, which the filter must not change.
76    pub kind: EntryKind,
77    /// The owner uid.
78    pub uid: u32,
79    /// The owner gid.
80    pub gid: u32,
81    /// The full `st_mode`, with the file-type bits.
82    ///
83    /// The filter can change the bits `0o7777`: the permission bits, the
84    /// set-id bits, and the sticky bit. It must not change the file-type bits
85    /// (`0o170000`) or set a bit outside `0o177777`.
86    pub mode: u32,
87    /// The extended attributes.
88    pub xattrs: Xattrs,
89    /// The target of a symlink, present for a symlink alone.
90    ///
91    /// The filter can give a symlink another target, the empty one included.
92    /// It must not remove the target or give a target to an entry of another
93    /// kind. On Windows, the walk refuses a target that holds `\` or starts
94    /// with a drive prefix, because that target does not resolve on Linux.
95    pub symlink_target: Option<String>,
96}
97
98/// The action of the walk on an entry, as the entry filter decides it.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum EntryAction {
101    /// The entry stays in the tree, and the walk enters it if it is a directory.
102    Keep,
103    /// The walk leaves out the entry, and for a directory its whole subtree.
104    Skip,
105}
106
107/// The path of a tree entry relative to the walk root.
108///
109/// The path joins the UTF-8 names of the parent directories and of the entry
110/// with `/`, on every platform. The walk root has the empty path.
111#[derive(Debug)]
112pub struct EntryPath {
113    path: String,
114}
115
116impl EntryPath {
117    /// Returns the path as a string slice.
118    pub fn as_str(&self) -> &str {
119        &self.path
120    }
121
122    /// Returns the path as a [`Path`].
123    pub fn as_path(&self) -> &Path {
124        Path::new(&self.path)
125    }
126
127    /// Returns `true` if the path names the walk root.
128    pub fn is_root(&self) -> bool {
129        self.path.is_empty()
130    }
131}
132
133impl fmt::Display for EntryPath {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.write_str(&self.path)
136    }
137}
138
139/// The entry filter of a scan.
140///
141/// The filter runs once for each entry, the root included, before the scan
142/// hashes the entry. For a directory, it runs before the walk enters the
143/// directory. It can change these fields of the [`EntryMeta`]:
144///
145/// - the owner, `uid` and `gid`
146/// - the bits `0o7777` of `mode`
147/// - `xattrs`
148/// - `symlink_target` of a symlink
149///
150/// The returned [`EntryAction`] decides whether the walk keeps the entry. If
151/// the filter makes a change that [`EntryMeta`] does not allow, the scan
152/// fails with [`Error::Walk`](crate::Error::Walk) of the kind `InvalidData`.
153///
154/// The filter runs on the task that drives the scan, so it must not block for
155/// long.
156pub type EntryFilter = Box<dyn FnMut(&EntryPath, &mut EntryMeta) -> EntryAction + Send>;
157
158/// The options of [`TreeModel::scan`].
159#[derive(Default)]
160pub struct ScanOptions {
161    /// The filter that sees each entry.
162    ///
163    /// If it is `None`, the walk keeps each entry with the metadata that
164    /// [`EntryMeta`] describes.
165    pub entry_filter: Option<EntryFilter>,
166    /// The most regular files that the hash pass reads at the same time.
167    ///
168    /// The default is the number of CPUs, or 1 if that number is not known.
169    /// The pass caps the number at the thread count of the blocking pool of
170    /// the runtime. If the value is `Some(0)`, the scan returns
171    /// [`Error::InvalidInput`](crate::Error::InvalidInput) and the walk does
172    /// not start.
173    pub hash_jobs: Option<usize>,
174}
175
176/// Returns an `io::Error` of the kind `InvalidData`.
177fn invalid_data(message: impl Into<String>) -> io::Error {
178    io::Error::new(io::ErrorKind::InvalidData, message.into())
179}
180
181/// Returns the kind of the entry whose metadata read gave `md`, or refuses an
182/// entry of another kind.
183fn classify(md: &std::fs::Metadata) -> io::Result<EntryKind> {
184    #[cfg(windows)]
185    {
186        use std::os::windows::fs::MetadataExt;
187        if md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 && !md.is_symlink() {
188            return Err(io::Error::new(
189                io::ErrorKind::Unsupported,
190                "the entry is a reparse point that is not a symlink",
191            ));
192        }
193    }
194    let ty = md.file_type();
195    if ty.is_symlink() {
196        Ok(EntryKind::Symlink)
197    } else if ty.is_dir() {
198        Ok(EntryKind::Dir)
199    } else if ty.is_file() {
200        Ok(EntryKind::File)
201    } else {
202        Err(io::Error::new(
203            io::ErrorKind::Unsupported,
204            "the entry is not a regular file, a directory, or a symlink",
205        ))
206    }
207}
208
209/// Returns the metadata that the filter sees for an entry of `kind` whose
210/// metadata read gave `md`.
211#[cfg(unix)]
212fn default_meta(kind: EntryKind, md: &std::fs::Metadata, target: Option<String>) -> EntryMeta {
213    use std::os::unix::fs::MetadataExt;
214    unix_meta(kind, md.uid(), md.gid(), md.mode(), target)
215}
216
217/// Returns the metadata that the filter sees for an entry of `kind` whose
218/// metadata read gave `uid`, `gid`, and `mode`.
219#[cfg(unix)]
220fn unix_meta(kind: EntryKind, uid: u32, gid: u32, mode: u32, target: Option<String>) -> EntryMeta {
221    let mode = match kind {
222        EntryKind::Symlink => SYMLINK_MODE,
223        EntryKind::File | EntryKind::Dir => mode,
224    };
225    EntryMeta {
226        kind,
227        uid,
228        gid,
229        mode,
230        xattrs: Xattrs::empty(),
231        symlink_target: target,
232    }
233}
234
235/// Returns the metadata that the filter sees for an entry of `kind`. The
236/// platform gives no owner and no Unix mode, so the values are fixed.
237#[cfg(not(unix))]
238fn default_meta(kind: EntryKind, _md: &std::fs::Metadata, target: Option<String>) -> EntryMeta {
239    let mode = match kind {
240        EntryKind::File => S_IFREG | 0o644,
241        EntryKind::Dir => S_IFDIR | 0o755,
242        EntryKind::Symlink => SYMLINK_MODE,
243    };
244    EntryMeta {
245        kind,
246        uid: 0,
247        gid: 0,
248        mode,
249        xattrs: Xattrs::empty(),
250        symlink_target: target,
251    }
252}
253
254/// Checks what the entry filter left in the metadata of an entry of `kind`.
255fn check_filtered(kind: EntryKind, meta: &EntryMeta) -> io::Result<()> {
256    if meta.kind != kind {
257        return Err(invalid_data(
258            "the entry filter changed the kind of the entry",
259        ));
260    }
261    if meta.mode & S_IFMT != kind.type_bits() {
262        return Err(invalid_data(
263            "the entry filter changed the file-type bits of the mode",
264        ));
265    }
266    if meta.mode & !MODE_BITS != 0 {
267        return Err(invalid_data(
268            "the entry filter set a bit above the file-type bits of the mode",
269        ));
270    }
271    match (kind, &meta.symlink_target) {
272        (EntryKind::Symlink, Some(target)) => check_target(target),
273        (EntryKind::Symlink, None) => Err(invalid_data(
274            "the entry filter removed the target of a symlink",
275        )),
276        (EntryKind::File | EntryKind::Dir, Some(_)) => Err(invalid_data(
277            "the entry filter gave a symlink target to an entry that is not a symlink",
278        )),
279        (EntryKind::File | EntryKind::Dir, None) => Ok(()),
280    }
281}
282
283/// Refuses a symlink target that does not resolve on Linux: a target that
284/// holds `\` or starts with a drive prefix.
285#[cfg(windows)]
286fn check_target(target: &str) -> io::Result<()> {
287    let bytes = target.as_bytes();
288    let drive = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
289    if drive || target.contains('\\') {
290        return Err(invalid_data(
291            "the symlink target holds `\\` or a drive prefix, and it does not resolve on Linux",
292        ));
293    }
294    Ok(())
295}
296
297/// Accepts every UTF-8 symlink target.
298#[cfg(not(windows))]
299fn check_target(_target: &str) -> io::Result<()> {
300    Ok(())
301}
302
303#[cfg(all(test, unix))]
304mod tests {
305    use super::*;
306
307    #[test]
308    fn a_symlink_gets_the_mode_0o120777_whatever_the_read_gives() {
309        let target = Some("target".to_owned());
310        let meta = unix_meta(EntryKind::Symlink, 7, 8, 0o120755, target.clone());
311        assert_eq!(meta.mode, 0o120777);
312        assert_eq!((meta.uid, meta.gid), (7, 8));
313        assert_eq!(meta.symlink_target, target);
314        let meta = unix_meta(EntryKind::File, 7, 8, 0o100600, None);
315        assert_eq!(meta.mode, 0o100600);
316    }
317}