use crate::fs_safety::{self, invalid, node_md};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
fs,
io::{self, Read, Write},
path::Path,
};
pub(crate) type Hash = [u8; 32];
#[cfg(feature = "lab")]
pub(crate) mod profiling;
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
File,
Directory,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Artifact {
pub path: String,
pub kind: Kind,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) struct Entry {
pub name: String,
pub file: Option<Hash>,
pub permissions: u32,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) struct Tree {
pub path: String,
pub entries: Vec<Entry>,
}
pub(crate) fn sha(bytes: &[u8]) -> Hash {
Sha256::digest(bytes).into()
}
pub(crate) fn text(hash: &Hash) -> String {
use std::fmt::Write as _;
let mut result = String::with_capacity(64);
for byte in hash {
write!(&mut result, "{byte:02x}").unwrap();
}
result
}
pub(crate) fn copy_hash(src: &Path, mut out: impl Write) -> io::Result<Hash> {
copy_hash_buffered(src, &mut out, &mut vec![0; 128 * 1024])
}
pub(crate) fn copy_hash_buffered(
src: &Path,
mut out: impl Write,
buf: &mut [u8],
) -> io::Result<Hash> {
let mut input = open_file(src, true)?;
let metadata = fs_safety::checked(src, input.metadata()?)?;
if !metadata.is_file() {
return Err(invalid("expected a regular file"));
}
let mut remaining = metadata.len();
let mut hash = Sha256::new();
while remaining != 0 {
let size = remaining.min(buf.len() as u64) as usize;
let block = &mut buf[..size];
input.read_exact(block)?;
out.write_all(block)?;
hash.update(block);
remaining -= size as u64;
}
#[cfg(unix)]
{
if input.read(&mut [0])? != 0 {
return Err(invalid("file size changed during fingerprinting"));
}
finish_read(src, &metadata, &input)?;
}
Ok(hash.finalize().into())
}
#[cfg(unix)]
fn finish_read(src: &Path, before: &fs::Metadata, input: &fs::File) -> io::Result<()> {
use std::os::unix::fs::MetadataExt;
let fingerprint = |md: &fs::Metadata| {
(
md.dev(),
md.ino(),
md.len(),
md.mtime(),
md.mtime_nsec(),
md.ctime(),
md.ctime_nsec(),
)
};
if fingerprint(before) != fingerprint(&input.metadata()?)
|| fingerprint(before) != fingerprint(&node_md(src)?)
{
return Err(invalid("file changed during fingerprinting"));
}
Ok(())
}
pub(crate) fn open_file(src: &Path, strict: bool) -> io::Result<fs::File> {
let mut settings = fs::OpenOptions::new();
settings.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
settings.custom_flags(0x0020_0000); if strict {
settings.share_mode(1); }
}
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
settings.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
let _ = strict;
}
settings.open(src)
}
pub(crate) fn fingerprint_file(src: &Path, pool: &rayon::ThreadPool) -> io::Result<Hash> {
const BLOCK: u64 = 8 * 1024 * 1024;
let file = open_file(src, true)?;
let meta = fs_safety::checked(src, file.metadata()?)?;
if !meta.is_file() {
return Err(invalid("expected a regular file"));
}
let length = meta.len();
let blocks = length.div_ceil(BLOCK).max(1);
let hash_part = |buffer: &mut Vec<u8>, part: u64| -> io::Result<Hash> {
let offset = part * BLOCK;
let mut remaining = length.saturating_sub(offset).min(BLOCK);
#[cfg(unix)]
let mut offset = offset;
let mut hash = Sha256::new();
#[cfg(not(unix))]
let mut source = {
use std::io::{Seek, SeekFrom};
let mut handle = open_file(src, true)?;
handle.seek(SeekFrom::Start(offset))?;
handle
};
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
#[cfg(unix)]
{
use std::os::unix::fs::FileExt;
file.read_exact_at(&mut buffer[..count], offset)?;
offset += count as u64;
}
#[cfg(not(unix))]
source.read_exact(&mut buffer[..count])?;
hash.update(&buffer[..count]);
remaining -= count as u64;
}
Ok(hash.finalize().into())
};
let count = usize::try_from(blocks).map_err(invalid)?;
let mut result = Sha256::new();
result.update(b"rustsy-input-sha256-segments-v1\0");
result.update(length.to_le_bytes());
result.update(BLOCK.to_le_bytes());
result.update(blocks.to_le_bytes());
if count == 1 {
if length > 0 {
result.update(hash_part(&mut vec![0; 128 * 1024], 0)?);
} else {
result.update(sha(b""));
}
} else {
let digests = pool.install(|| {
(0..count)
.into_par_iter()
.map_init(
|| vec![0; 128 * 1024],
|buffer, part| hash_part(buffer, part as u64),
)
.collect::<io::Result<Vec<_>>>()
})?;
for digest in digests {
result.update(digest);
}
}
#[cfg(unix)]
finish_read(src, &meta, &file)?;
Ok(result.finalize().into())
}
pub(crate) fn hash_input(
root: &Path,
input: &Artifact,
pool: Option<&rayon::ThreadPool>,
parallel_large: bool,
) -> io::Result<Tree> {
if parallel_large && input.kind == Kind::File {
let pool = pool.ok_or_else(|| invalid("missing segment worker pool"))?;
return describe(root, input, |path| fingerprint_file(path, pool));
}
hash_tree(root, input, pool)
}
pub(crate) fn hash_tree(
root: &Path,
declaration: &Artifact,
pool: Option<&rayon::ThreadPool>,
) -> io::Result<Tree> {
process_tree(root, declaration, pool, |buffer, path| {
copy_hash_buffered(path, io::sink(), buffer)
})
}
pub(crate) fn process_tree(
root: &Path,
declaration: &Artifact,
pool: Option<&rayon::ThreadPool>,
hash: impl Fn(&mut [u8], &Path) -> io::Result<Hash> + Sync,
) -> io::Result<Tree> {
let mut paths = Vec::new();
let mut tree = describe(root, declaration, |path| {
paths.push(path.to_owned());
Ok([0; 32])
})?;
let work = |buf: &mut Vec<u8>, path: &std::path::PathBuf| hash(buf, path);
let hashes = if let Some(pool) = pool.filter(|_| paths.len() >= 64) {
pool.install(|| {
paths
.par_iter()
.with_min_len(16)
.map_init(|| vec![0; 128 * 1024], work)
.collect::<io::Result<Vec<_>>>()
})?
} else {
let mut buffer = vec![0; 128 * 1024];
paths
.iter()
.map(|path| work(&mut buffer, path))
.collect::<io::Result<Vec<_>>>()?
};
for (entry, digest) in tree
.entries
.iter_mut()
.filter(|entry| entry.file.is_some())
.zip(hashes)
{
entry.file = Some(digest);
}
Ok(tree)
}
pub(crate) fn describe(
root: &Path,
declaration: &Artifact,
mut file: impl FnMut(&Path) -> io::Result<Hash>,
) -> io::Result<Tree> {
let target = fs_safety::path(root, &declaration.path, false)?;
let metadata = node_md(&target)?;
if metadata.is_file() != (declaration.kind == Kind::File) {
return Err(invalid(format!(
"artifact type changed for {}",
declaration.path
)));
}
let mut entries = Vec::new();
visit(&target, metadata, String::new(), &mut entries, &mut file)?;
Ok(Tree {
path: declaration.path.clone(),
entries,
})
}
fn visit(
path: &Path,
metadata: fs::Metadata,
name: String,
found: &mut Vec<Entry>,
file: &mut impl FnMut(&Path) -> io::Result<Hash>,
) -> io::Result<()> {
#[cfg(unix)]
let permissions = {
use std::os::unix::fs::PermissionsExt;
metadata.permissions().mode() & 0o777
};
#[cfg(not(unix))]
let permissions = 0;
found.push(Entry {
name: name.clone(),
file: metadata.is_file().then(|| file(path)).transpose()?,
permissions,
});
if metadata.is_dir() {
let mut children = fs::read_dir(path)?.collect::<io::Result<Vec<_>>>()?;
children.sort_unstable_by_key(|x| x.file_name());
for child in children {
let filename = child
.file_name()
.into_string()
.map_err(|_| invalid("artifact file name is not Unicode"))?;
if filename.contains('/') {
return Err(invalid("unexpected separator"));
}
fs_safety::relative(&filename, false)?;
let context = if name.is_empty() {
filename
} else {
format!("{name}/{filename}")
};
let path = child.path();
let metadata = fs_safety::checked(&path, child.metadata()?)?;
visit(&path, metadata, context, found, file)?;
}
}
Ok(())
}
pub(crate) fn permissions(path: &Path, mode: u32) -> io::Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(mode & 0o777))?;
}
#[cfg(not(unix))]
let _ = (path, mode);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
struct EditDuringCopy<'a>(&'a Path, bool);
impl Write for EditDuringCopy<'_> {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
if !self.1 {
let result = fs::write(self.0, [2; 1024]);
#[cfg(windows)]
assert_eq!(result.unwrap_err().raw_os_error(), Some(32));
#[cfg(unix)]
{
result?;
fs::File::options().write(true).open(self.0)?.set_modified(
std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000),
)?;
}
self.1 = true;
}
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
#[cfg(any(windows, unix))]
fn detect_or_exclude_same_size_write_during_read() -> io::Result<()> {
let root = fs_safety::Scratch::new(&std::env::temp_dir())?;
let path = root.0.join("data");
fs::write(&path, [1; 1024])?;
let digest = copy_hash_buffered(&path, EditDuringCopy(&path, false), &mut [0; 256]);
#[cfg(windows)]
assert_eq!(digest?, sha(&[1; 1024]));
#[cfg(unix)]
assert_eq!(digest.unwrap_err().kind(), io::ErrorKind::InvalidData);
Ok(())
}
#[test]
fn segmented_fingerprints_preserve_order_and_the_final_byte() -> io::Result<()> {
let root = fs_safety::Scratch::new(&std::env::temp_dir())?;
let path = root.0.join("file");
let mut data = vec![5; 8 * 1024 * 1024 + 1];
let one = rayon::ThreadPoolBuilder::new()
.num_threads(1)
.build()
.unwrap();
let many = rayon::ThreadPoolBuilder::new()
.num_threads(4)
.build()
.unwrap();
fs::write(&path, &data)?;
let digest = fingerprint_file(&path, &one)?;
assert_eq!(digest, fingerprint_file(&path, &many)?);
*data.last_mut().unwrap() = 9;
fs::write(&path, &data)?;
assert_ne!(digest, fingerprint_file(&path, &many)?);
data.rotate_right(1);
fs::write(&path, &data)?;
assert_ne!(digest, fingerprint_file(&path, &many)?);
Ok(())
}
}