1use crate::fs_safety::{self, invalid, node_md};
2use rayon::prelude::*;
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5use std::{
6 fs,
7 io::{self, Read, Write},
8 path::Path,
9};
10
11pub(crate) type Hash = [u8; 32];
12#[cfg(feature = "lab")]
13pub(crate) mod profiling;
14
15#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
16#[serde(rename_all = "snake_case")]
17pub enum Kind {
18 File,
19 Directory,
20}
21
22#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
23pub struct Artifact {
24 pub path: String,
25 pub kind: Kind,
26}
27
28#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
29pub(crate) struct Entry {
30 pub name: String,
31 pub file: Option<Hash>,
32 pub permissions: u32,
33}
34
35#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
36pub(crate) struct Tree {
37 pub path: String,
38 pub entries: Vec<Entry>,
39}
40
41pub(crate) fn sha(bytes: &[u8]) -> Hash {
42 Sha256::digest(bytes).into()
43}
44
45pub(crate) fn text(hash: &Hash) -> String {
46 use std::fmt::Write as _;
47 let mut result = String::with_capacity(64);
48 for byte in hash {
49 write!(&mut result, "{byte:02x}").unwrap();
50 }
51 result
52}
53
54pub(crate) fn copy_hash(src: &Path, mut out: impl Write) -> io::Result<Hash> {
55 copy_hash_buffered(src, &mut out, &mut vec![0; 128 * 1024])
56}
57
58pub(crate) fn copy_hash_buffered(
59 src: &Path,
60 mut out: impl Write,
61 buf: &mut [u8],
62) -> io::Result<Hash> {
63 let mut input = open_file(src, true)?;
64 let metadata = fs_safety::checked(src, input.metadata()?)?;
65 if !metadata.is_file() {
66 return Err(invalid("expected a regular file"));
67 }
68 let mut remaining = metadata.len();
69 let mut hash = Sha256::new();
70 while remaining != 0 {
71 let size = remaining.min(buf.len() as u64) as usize;
72 let block = &mut buf[..size];
73 input.read_exact(block)?;
74 out.write_all(block)?;
75 hash.update(block);
76 remaining -= size as u64;
77 }
78 #[cfg(unix)]
79 {
80 if input.read(&mut [0])? != 0 {
81 return Err(invalid("file size changed during fingerprinting"));
82 }
83 finish_read(src, &metadata, &input)?;
84 }
85 Ok(hash.finalize().into())
86}
87
88#[cfg(unix)]
89fn finish_read(src: &Path, before: &fs::Metadata, input: &fs::File) -> io::Result<()> {
90 use std::os::unix::fs::MetadataExt;
91
92 let fingerprint = |md: &fs::Metadata| {
93 (
94 md.dev(),
95 md.ino(),
96 md.len(),
97 md.mtime(),
98 md.mtime_nsec(),
99 md.ctime(),
100 md.ctime_nsec(),
101 )
102 };
103 if fingerprint(before) != fingerprint(&input.metadata()?)
106 || fingerprint(before) != fingerprint(&node_md(src)?)
107 {
108 return Err(invalid("file changed during fingerprinting"));
109 }
110 Ok(())
111}
112
113pub(crate) fn open_file(src: &Path, strict: bool) -> io::Result<fs::File> {
114 let mut settings = fs::OpenOptions::new();
115 settings.read(true);
116 #[cfg(windows)]
117 {
118 use std::os::windows::fs::OpenOptionsExt;
119 settings.custom_flags(0x0020_0000); if strict {
121 settings.share_mode(1); }
124 }
125 #[cfg(unix)]
126 {
127 use std::os::unix::fs::OpenOptionsExt;
128 settings.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
129 let _ = strict;
130 }
131 settings.open(src)
132}
133
134pub(crate) fn fingerprint_file(src: &Path, pool: &rayon::ThreadPool) -> io::Result<Hash> {
137 const BLOCK: u64 = 8 * 1024 * 1024;
138 let file = open_file(src, true)?;
139 let meta = fs_safety::checked(src, file.metadata()?)?;
140 if !meta.is_file() {
141 return Err(invalid("expected a regular file"));
142 }
143 let length = meta.len();
144 let blocks = length.div_ceil(BLOCK).max(1);
145 let hash_part = |buffer: &mut Vec<u8>, part: u64| -> io::Result<Hash> {
146 let offset = part * BLOCK;
147 let mut remaining = length.saturating_sub(offset).min(BLOCK);
148 #[cfg(unix)]
149 let mut offset = offset;
150 let mut hash = Sha256::new();
151 #[cfg(not(unix))]
152 let mut source = {
153 use std::io::{Seek, SeekFrom};
154 let mut handle = open_file(src, true)?;
155 handle.seek(SeekFrom::Start(offset))?;
156 handle
157 };
158 while remaining > 0 {
159 let count = remaining.min(buffer.len() as u64) as usize;
160 #[cfg(unix)]
161 {
162 use std::os::unix::fs::FileExt;
163 file.read_exact_at(&mut buffer[..count], offset)?;
164 offset += count as u64;
165 }
166 #[cfg(not(unix))]
167 source.read_exact(&mut buffer[..count])?;
168 hash.update(&buffer[..count]);
169 remaining -= count as u64;
170 }
171 Ok(hash.finalize().into())
172 };
173 let count = usize::try_from(blocks).map_err(invalid)?;
174 let mut result = Sha256::new();
175 result.update(b"rustsy-input-sha256-segments-v1\0");
176 result.update(length.to_le_bytes());
177 result.update(BLOCK.to_le_bytes());
178 result.update(blocks.to_le_bytes());
179 if count == 1 {
180 if length > 0 {
181 result.update(hash_part(&mut vec![0; 128 * 1024], 0)?);
182 } else {
183 result.update(sha(b""));
184 }
185 } else {
186 let digests = pool.install(|| {
187 (0..count)
188 .into_par_iter()
189 .map_init(
190 || vec![0; 128 * 1024],
191 |buffer, part| hash_part(buffer, part as u64),
192 )
193 .collect::<io::Result<Vec<_>>>()
194 })?;
195 for digest in digests {
196 result.update(digest);
197 }
198 }
199 #[cfg(unix)]
200 finish_read(src, &meta, &file)?;
201 Ok(result.finalize().into())
202}
203
204pub(crate) fn hash_input(
205 root: &Path,
206 input: &Artifact,
207 pool: Option<&rayon::ThreadPool>,
208 parallel_large: bool,
209) -> io::Result<Tree> {
210 if parallel_large && input.kind == Kind::File {
211 let pool = pool.ok_or_else(|| invalid("missing segment worker pool"))?;
212 return describe(root, input, |path| fingerprint_file(path, pool));
213 }
214 hash_tree(root, input, pool)
215}
216
217pub(crate) fn hash_tree(
218 root: &Path,
219 declaration: &Artifact,
220 pool: Option<&rayon::ThreadPool>,
221) -> io::Result<Tree> {
222 process_tree(root, declaration, pool, |buffer, path| {
223 copy_hash_buffered(path, io::sink(), buffer)
224 })
225}
226
227pub(crate) fn process_tree(
228 root: &Path,
229 declaration: &Artifact,
230 pool: Option<&rayon::ThreadPool>,
231 hash: impl Fn(&mut [u8], &Path) -> io::Result<Hash> + Sync,
232) -> io::Result<Tree> {
233 let mut paths = Vec::new();
234 let mut tree = describe(root, declaration, |path| {
235 paths.push(path.to_owned());
236 Ok([0; 32])
237 })?;
238 let work = |buf: &mut Vec<u8>, path: &std::path::PathBuf| hash(buf, path);
239 let hashes = if let Some(pool) = pool.filter(|_| paths.len() >= 64) {
240 pool.install(|| {
241 paths
242 .par_iter()
243 .with_min_len(16)
244 .map_init(|| vec![0; 128 * 1024], work)
245 .collect::<io::Result<Vec<_>>>()
246 })?
247 } else {
248 let mut buffer = vec![0; 128 * 1024];
249 paths
250 .iter()
251 .map(|path| work(&mut buffer, path))
252 .collect::<io::Result<Vec<_>>>()?
253 };
254 for (entry, digest) in tree
255 .entries
256 .iter_mut()
257 .filter(|entry| entry.file.is_some())
258 .zip(hashes)
259 {
260 entry.file = Some(digest);
261 }
262 Ok(tree)
263}
264
265pub(crate) fn describe(
266 root: &Path,
267 declaration: &Artifact,
268 mut file: impl FnMut(&Path) -> io::Result<Hash>,
269) -> io::Result<Tree> {
270 let target = fs_safety::path(root, &declaration.path, false)?;
271 let metadata = node_md(&target)?;
272 if metadata.is_file() != (declaration.kind == Kind::File) {
273 return Err(invalid(format!(
274 "artifact type changed for {}",
275 declaration.path
276 )));
277 }
278 let mut entries = Vec::new();
279 visit(&target, metadata, String::new(), &mut entries, &mut file)?;
280 Ok(Tree {
281 path: declaration.path.clone(),
282 entries,
283 })
284}
285
286fn visit(
287 path: &Path,
288 metadata: fs::Metadata,
289 name: String,
290 found: &mut Vec<Entry>,
291 file: &mut impl FnMut(&Path) -> io::Result<Hash>,
292) -> io::Result<()> {
293 #[cfg(unix)]
294 let permissions = {
295 use std::os::unix::fs::PermissionsExt;
296 metadata.permissions().mode() & 0o777
297 };
298 #[cfg(not(unix))]
299 let permissions = 0;
300 found.push(Entry {
301 name: name.clone(),
302 file: metadata.is_file().then(|| file(path)).transpose()?,
303 permissions,
304 });
305 if metadata.is_dir() {
306 let mut children = fs::read_dir(path)?.collect::<io::Result<Vec<_>>>()?;
307 children.sort_unstable_by_key(|x| x.file_name());
308 for child in children {
309 let filename = child
310 .file_name()
311 .into_string()
312 .map_err(|_| invalid("artifact file name is not Unicode"))?;
313 if filename.contains('/') {
314 return Err(invalid("unexpected separator"));
315 }
316 fs_safety::relative(&filename, false)?;
317 let context = if name.is_empty() {
318 filename
319 } else {
320 format!("{name}/{filename}")
321 };
322 let path = child.path();
323 let metadata = fs_safety::checked(&path, child.metadata()?)?;
324 visit(&path, metadata, context, found, file)?;
325 }
326 }
327 Ok(())
328}
329
330pub(crate) fn permissions(path: &Path, mode: u32) -> io::Result<()> {
331 #[cfg(unix)]
332 {
333 use std::os::unix::fs::PermissionsExt;
334 fs::set_permissions(path, fs::Permissions::from_mode(mode & 0o777))?;
335 }
336 #[cfg(not(unix))]
337 let _ = (path, mode);
338 Ok(())
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344
345 struct EditDuringCopy<'a>(&'a Path, bool);
346
347 impl Write for EditDuringCopy<'_> {
348 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
349 if !self.1 {
350 let result = fs::write(self.0, [2; 1024]);
351 #[cfg(windows)]
352 assert_eq!(result.unwrap_err().raw_os_error(), Some(32));
353 #[cfg(unix)]
354 {
355 result?;
356 fs::File::options().write(true).open(self.0)?.set_modified(
358 std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000),
359 )?;
360 }
361 self.1 = true;
362 }
363 Ok(data.len())
364 }
365
366 fn flush(&mut self) -> io::Result<()> {
367 Ok(())
368 }
369 }
370
371 #[test]
372 #[cfg(any(windows, unix))]
373 fn detect_or_exclude_same_size_write_during_read() -> io::Result<()> {
374 let root = fs_safety::Scratch::new(&std::env::temp_dir())?;
375 let path = root.0.join("data");
376 fs::write(&path, [1; 1024])?;
377 let digest = copy_hash_buffered(&path, EditDuringCopy(&path, false), &mut [0; 256]);
378 #[cfg(windows)]
379 assert_eq!(digest?, sha(&[1; 1024]));
380 #[cfg(unix)]
381 assert_eq!(digest.unwrap_err().kind(), io::ErrorKind::InvalidData);
382 Ok(())
383 }
384
385 #[test]
386 fn segmented_fingerprints_preserve_order_and_the_final_byte() -> io::Result<()> {
387 let root = fs_safety::Scratch::new(&std::env::temp_dir())?;
388 let path = root.0.join("file");
389 let mut data = vec![5; 8 * 1024 * 1024 + 1];
390 let one = rayon::ThreadPoolBuilder::new()
391 .num_threads(1)
392 .build()
393 .unwrap();
394 let many = rayon::ThreadPoolBuilder::new()
395 .num_threads(4)
396 .build()
397 .unwrap();
398 fs::write(&path, &data)?;
399 let digest = fingerprint_file(&path, &one)?;
400 assert_eq!(digest, fingerprint_file(&path, &many)?);
401 *data.last_mut().unwrap() = 9;
402 fs::write(&path, &data)?;
403 assert_ne!(digest, fingerprint_file(&path, &many)?);
404 data.rotate_right(1);
405 fs::write(&path, &data)?;
406 assert_ne!(digest, fingerprint_file(&path, &many)?);
407 Ok(())
408 }
409}