use std::collections::VecDeque;
use std::fs;
use std::future::{Future, poll_fn};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::pin::{Pin, pin};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll};
use ostrya_core::{ContentHasher, FileHeader};
use super::invalid_data;
use super::model::{Hashed, TreeModel};
const HASH_CHUNK: usize = 64 * 1024;
#[cfg(windows)]
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
#[cfg(windows)]
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct FileId {
#[cfg(unix)]
dev: u64,
#[cfg(unix)]
ino: u64,
}
impl FileId {
#[cfg(unix)]
pub(super) fn of(md: &fs::Metadata) -> FileId {
use std::os::unix::fs::MetadataExt;
FileId {
dev: md.dev(),
ino: md.ino(),
}
}
#[cfg(not(unix))]
pub(super) fn of(_md: &fs::Metadata) -> FileId {
FileId {}
}
}
pub(super) struct Stopped;
enum Outcome {
Done(Hashed),
Stopped,
Failed(PathBuf, io::Error),
}
type Job = Pin<Box<dyn Future<Output = (u32, Outcome)> + Send>>;
pub(super) struct Jobs {
limit: usize,
stop: Arc<AtomicBool>,
pending: VecDeque<u32>,
running: Vec<Job>,
error: Option<(PathBuf, io::Error)>,
}
impl Jobs {
pub(super) fn new() -> Jobs {
Jobs {
limit: 1,
stop: Arc::new(AtomicBool::new(false)),
pending: VecDeque::new(),
running: Vec::new(),
error: None,
}
}
pub(super) fn set_limit(&mut self, limit: usize) {
self.limit = limit;
}
pub(super) fn push(&mut self, index: u32) {
self.pending.push_back(index);
}
pub(super) fn fail(&mut self, path: PathBuf, error: io::Error) -> Stopped {
if self.error.is_none() {
self.error = Some((path, error));
}
self.stop.store(true, Ordering::Relaxed);
Stopped
}
pub(super) fn is_stopped(&self) -> bool {
self.error.is_some()
}
pub(super) async fn drive<F: Future>(&mut self, model: &mut TreeModel, future: F) -> F::Output {
let mut future = pin!(future);
poll_fn(|cx| {
self.poll(model, cx);
future.as_mut().poll(cx)
})
.await
}
pub(super) async fn finish(
&mut self,
model: &mut TreeModel,
) -> Result<(), (PathBuf, io::Error)> {
poll_fn(|cx| {
self.poll(model, cx);
if self.running.is_empty() && (self.pending.is_empty() || self.is_stopped()) {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
match self.error.take() {
Some(error) => Err(error),
None => Ok(()),
}
}
fn poll(&mut self, model: &mut TreeModel, cx: &mut Context<'_>) {
loop {
while !self.is_stopped()
&& !self.stop.load(Ordering::Relaxed)
&& self.running.len() < self.limit
&& let Some(index) = self.pending.pop_front()
{
let job = self.start(model, index);
self.running.push(job);
}
let before = self.running.len();
let mut k = 0;
while k < self.running.len() {
match self.running[k].as_mut().poll(cx) {
Poll::Ready((index, outcome)) => {
drop(self.running.swap_remove(k));
match outcome {
Outcome::Done(hashed) => model.set_hashed(index, hashed),
Outcome::Stopped => {}
Outcome::Failed(path, error) => {
self.fail(path, error);
}
}
}
Poll::Pending => k += 1,
}
}
if self.running.len() == before {
return;
}
}
}
fn start(&self, model: &TreeModel, index: u32) -> Job {
let path = model.os_path(index);
let header = model.header(index);
let id = model.file_id(index);
let stop = Arc::clone(&self.stop);
Box::pin(async move {
let outcome = ostrya_rt::unblock(move || hash_file(path, &header, &id, &stop)).await;
(index, outcome)
})
}
}
impl Drop for Jobs {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
}
}
fn hash_file(path: PathBuf, header: &FileHeader, id: &FileId, stop: &AtomicBool) -> Outcome {
let outcome = read_file(path, header, id, stop);
if matches!(outcome, Outcome::Failed(..)) {
stop.store(true, Ordering::Relaxed);
}
outcome
}
fn read_file(path: PathBuf, header: &FileHeader, id: &FileId, stop: &AtomicBool) -> Outcome {
if stop.load(Ordering::Relaxed) {
return Outcome::Stopped;
}
let mut hasher = match ContentHasher::new(header) {
Ok(hasher) => hasher,
Err(e) => return Outcome::Failed(path, invalid_data(e.to_string())),
};
let (mut file, len) = match open_regular(&path, id) {
Ok(opened) => opened,
Err(e) => return Outcome::Failed(path, e),
};
let cap = usize::try_from(len).map_or(HASH_CHUNK, |len| len.saturating_add(1).min(HASH_CHUNK));
let mut buf = vec![0u8; cap];
let mut size = 0u64;
loop {
if stop.load(Ordering::Relaxed) {
return Outcome::Stopped;
}
match file.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
hasher.update(&buf[..n]);
size += n as u64;
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Outcome::Failed(path, e),
}
}
Outcome::Done(Hashed {
checksum: hasher.finish(),
size,
})
}
fn not_regular() -> io::Error {
invalid_data("the entry is no longer a regular file")
}
pub(super) fn open_regular(path: &Path, id: &FileId) -> io::Result<(fs::File, u64)> {
let mut options = fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(
&mut options,
libc::O_NOFOLLOW | libc::O_NONBLOCK,
);
#[cfg(windows)]
std::os::windows::fs::OpenOptionsExt::custom_flags(
&mut options,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
);
let file = match options.open(path) {
Ok(file) => file,
#[cfg(unix)]
Err(e) if e.raw_os_error() == Some(libc::ELOOP) => return Err(not_regular()),
#[cfg(unix)]
Err(e) if e.raw_os_error() == Some(libc::ENXIO) => return Err(not_regular()),
#[cfg(target_os = "macos")]
Err(e) if e.raw_os_error() == Some(libc::EOPNOTSUPP) => return Err(not_regular()),
Err(e) => return Err(e),
};
let md = file.metadata()?;
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
if md.file_attributes() & super::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
return Err(not_regular());
}
}
if !md.file_type().is_file() {
return Err(not_regular());
}
if FileId::of(&md) != *id {
return Err(invalid_data(
"the entry is no longer the file the walk read",
));
}
Ok((file, md.len()))
}