raf_source/tree/disk/capture.rs
1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! Checked host captures retain the logical path and actual host identity.
5
6use std::fs::Permissions;
7use std::path::PathBuf;
8
9use purrdf_lex::walk::try_sort_unstable_by;
10
11use super::{DiskTree, Entry, FileId, RelPath, TreeError, Want};
12
13/// A regular file's bytes, permissions and identity from one verified handle.
14///
15/// Unix identities are device/inode pairs and preserve hardlink equality.
16/// Windows uses verified path identities, so hardlink names can differ.
17/// This is an observation, not an immutable filesystem snapshot. A caller
18/// preparing a later publication must compare the source again before publishing.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct CapturedFile {
21 /// The requested logical path, including its source authority.
22 pub path: RelPath,
23 /// The verified backend identity; a copy must use its own backend identity.
24 pub id: FileId,
25 /// Exact bounded bytes, including non-UTF-8 contents.
26 pub bytes: Vec<u8>,
27 /// Native permissions, including Unix executable bits.
28 pub permissions: Permissions,
29}
30
31/// A directory's sorted entries and identity from one verified directory handle.
32///
33/// Retaining this observation lets a later comparison detect added or removed
34/// names as well as changes to the files that were originally present.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct CapturedDirectory {
37 /// The requested logical path, including its source authority.
38 pub path: RelPath,
39 /// The original directory's host identity.
40 pub id: FileId,
41 /// All entries, including links and unsupported special files.
42 pub entries: Vec<Entry>,
43 /// Native directory permissions needed to preserve access semantics.
44 pub permissions: Permissions,
45}
46
47/// A lexical symbolic link, captured without opening or reading its target.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct CapturedLink {
50 /// The requested link path, including its source authority.
51 pub path: RelPath,
52 /// The link's identity, rather than its destination's identity.
53 pub id: FileId,
54 /// The native target spelling, without UTF-8 conversion or normalization.
55 pub target: PathBuf,
56}
57
58impl DiskTree {
59 /// Capture bytes, identity and permissions through one verified regular handle.
60 ///
61 /// The type and permissions are checked again after reading. Symlinks are
62 /// followed under the same containment rules as [`Tree::read_bytes`](crate::Tree::read_bytes). Ownership,
63 /// ACLs and extended attributes are not captured by this operation.
64 ///
65 /// # Errors
66 /// The errors of [`Tree::read_bytes`](crate::Tree::read_bytes), or an interrupted observation when
67 /// the file's type or permissions change during the read.
68 pub fn capture_file(&self, path: &RelPath, max_bytes: u64) -> Result<CapturedFile, TreeError> {
69 super::super::require_first_party(path)?;
70 let shown = path.to_string();
71 let handle = self.open(path, Want::File, &shown)?;
72 self.used(&handle, &shown, |handle| {
73 let before = handle.metadata(&shown)?;
74 let id = handle.identity(&self.root, &shown)?;
75 let bytes = handle.read(max_bytes, &shown)?;
76 #[cfg(test)]
77 self.observed();
78 let after = handle.metadata(&shown)?;
79 if !after.is_file() || before.permissions() != after.permissions() {
80 return Err(changed(&shown));
81 }
82 Ok(CapturedFile {
83 path: path.clone(),
84 id,
85 bytes,
86 permissions: after.permissions(),
87 })
88 })
89 }
90
91 /// Capture a complete sorted listing and the verified directory's identity.
92 ///
93 /// # Errors
94 /// The errors of [`super::Tree::list`]. A directory symlink is refused.
95 pub fn capture_directory(&self, path: &RelPath) -> Result<CapturedDirectory, TreeError> {
96 self.capture_directory_bounded(path, usize::MAX)
97 }
98
99 /// Capture complete membership, refusing before collecting more than the bound.
100 ///
101 /// Both verified observations use `max_entries`; no truncated listing is returned.
102 /// # Errors
103 /// The errors of [`Self::capture_directory`], or an `InvalidData` I/O cause
104 /// naming this directory when its membership exceeds `max_entries`.
105 pub fn capture_directory_bounded(
106 &self,
107 path: &RelPath,
108 max_entries: usize,
109 ) -> Result<CapturedDirectory, TreeError> {
110 super::super::require_first_party(path)?;
111 let shown = path.to_string();
112 let handle = self.open(path, Want::Listing, &shown)?;
113 self.used(&handle, &shown, |handle| {
114 let before = handle.metadata(&shown)?;
115 let id = handle.identity(&self.root, &shown)?;
116 let mut entries = handle.entries_bounded(&shown, max_entries)?;
117 try_sort_unstable_by(&mut entries, |left, right| {
118 Ok::<_, TreeError>(left.cmp(right))
119 })?;
120 #[cfg(test)]
121 self.observed();
122 let mut repeated = handle.entries_bounded(&shown, max_entries)?;
123 try_sort_unstable_by(&mut repeated, |left, right| {
124 Ok::<_, TreeError>(left.cmp(right))
125 })?;
126 let after = handle.metadata(&shown)?;
127 if !after.is_dir() || before.permissions() != after.permissions() || entries != repeated
128 {
129 return Err(changed(&shown));
130 }
131 Ok(CapturedDirectory {
132 path: path.clone(),
133 id,
134 entries,
135 permissions: after.permissions(),
136 })
137 })
138 }
139
140 /// Capture a link through its verified containing-directory handle.
141 ///
142 /// The target is not followed, so dangling and outside-pointing links can
143 /// be described safely. This does not authorize materializing or following
144 /// them elsewhere. Native Unix captures compare the link identity and exact
145 /// target spelling before and after reading; other hosts refuse explicitly.
146 ///
147 /// # Errors
148 /// Foreign authorities, outside parents, a non-link, a changed link, an
149 /// unsupported host or a failed host operation refuse without a capture.
150 pub fn capture_link(&self, path: &RelPath) -> Result<CapturedLink, TreeError> {
151 super::super::require_first_party(path)?;
152 let shown = path.to_string();
153 let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
154 return Err(super::not_regular(&shown));
155 };
156 if name == ".." {
157 return Err(super::not_regular(&shown));
158 }
159 super::refuse_windows_names(path, &shown)?;
160 let handle = self.open(&parent, Want::Dir, &shown)?;
161 let (id, target) = self.used(&handle, &shown, |handle| {
162 handle.link(name, &shown, || {
163 #[cfg(test)]
164 self.observed();
165 })
166 })?;
167 Ok(CapturedLink {
168 path: path.clone(),
169 id,
170 target,
171 })
172 }
173}
174
175pub(super) fn changed(shown: &str) -> TreeError {
176 TreeError::from_io(
177 shown,
178 std::io::Error::new(
179 std::io::ErrorKind::Interrupted,
180 "entry changed during capture; retry from a stable source",
181 ),
182 )
183}