use std::error::Error;
use std::fmt;
use std::io;
use crate::ArchiveError;
use crate::ArchiveReader;
use crate::ExtractionReport;
use crate::ProgressCallback;
use crate::security::fs_view::PathModel;
use crate::security::permissions::SanitizedMode;
use crate::security::quota::AdmittedSize;
use crate::sink::EntrySink;
use crate::sink::MemoryEntry;
use crate::sink::MemoryEntryKind;
use crate::sink::MemoryExtractRequest;
use crate::sink::MemoryFile;
use crate::types::CheckedLinkTarget;
use crate::types::SafePath;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CallbackEntry {
Stored(MemoryEntry),
Hardlink {
target: SafePath,
},
}
impl CallbackEntry {
#[must_use]
pub const fn kind(&self) -> MemoryEntryKind {
match self {
Self::Stored(entry) => entry.kind(),
Self::Hardlink { .. } => MemoryEntryKind::Hardlink,
}
}
}
impl From<MemoryEntry> for CallbackEntry {
fn from(entry: MemoryEntry) -> Self {
Self::Stored(entry)
}
}
#[derive(Debug)]
pub struct CallbackSink<F> {
callback: F,
path_model: PathModel,
}
impl<F> CallbackSink<F>
where
F: FnMut(&SafePath, CallbackEntry) -> io::Result<()>,
{
#[must_use]
pub const fn new(callback: F) -> Self {
Self {
callback,
path_model: PathModel::Host,
}
}
#[must_use]
pub const fn with_path_model(mut self, path_model: PathModel) -> Self {
self.path_model = path_model;
self
}
}
impl<F> EntrySink for CallbackSink<F>
where
F: FnMut(&SafePath, CallbackEntry) -> io::Result<()>,
{
type File = MemoryFile;
fn path_model(&self) -> PathModel {
self.path_model
}
fn create_directory(&mut self, path: &SafePath) -> io::Result<()> {
(self.callback)(path, MemoryEntry::Directory.into())
}
fn create_file(
&mut self,
_path: &SafePath,
mode: Option<SanitizedMode>,
size: AdmittedSize,
) -> io::Result<MemoryFile> {
Ok(MemoryFile::with_size(size.get(), mode))
}
fn finish_file(&mut self, path: &SafePath, file: MemoryFile) -> io::Result<()> {
(self.callback)(path, file.into_entry().into())
}
fn create_symlink(&mut self, link: &SafePath, target: CheckedLinkTarget<'_>) -> io::Result<()> {
(self.callback)(
link,
MemoryEntry::Symlink {
target: target.as_path().to_path_buf(),
}
.into(),
)
}
fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()> {
(self.callback)(
link,
CallbackEntry::Hardlink {
target: target.clone(),
},
)
}
}
#[derive(Debug)]
pub enum CallbackError<E> {
Callback(E),
Archive(ArchiveError),
}
impl<E> fmt::Display for CallbackError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Callback(_) => f.write_str("entry callback failed"),
Self::Archive(err) => err.fmt(f),
}
}
}
impl<E: Error + 'static> Error for CallbackError<E> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Callback(err) => Some(err),
Self::Archive(err) => err.source(),
}
}
}
impl<E> From<ArchiveError> for CallbackError<E> {
fn from(err: ArchiveError) -> Self {
Self::Archive(err)
}
}
pub fn extract_reader_to_callback<F, E>(
reader: ArchiveReader<'_>,
request: &MemoryExtractRequest,
mut on_entry: F,
progress: &mut dyn ProgressCallback,
) -> Result<ExtractionReport, CallbackError<E>>
where
F: FnMut(&SafePath, CallbackEntry) -> Result<(), E>,
{
let mut failure = None;
let mut sink = CallbackSink::new(|path: &SafePath, entry| {
on_entry(path, entry).map_err(|err| {
failure.get_or_insert(err);
io::Error::other("entry callback failed")
})
})
.with_path_model(request.model);
let result = crate::SinkExtractRequest::new(&request.config)
.with_options(request.options)
.with_progress(progress)
.extract(reader, &mut sink);
match (failure, result) {
(Some(err), _) => Err(CallbackError::Callback(err)),
(None, Ok(report)) => Ok(report),
(None, Err(err)) => Err(CallbackError::Archive(err)),
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crate::SecurityConfig;
fn hardlink_target() -> SafePath {
SafePath::validate(
std::path::Path::new("target.txt"),
&crate::DestDir::new(std::env::temp_dir()).unwrap(),
&SecurityConfig::default(),
)
.unwrap()
}
#[test]
fn every_callback_entry_maps_to_a_memory_entry_kind() {
let entries = [
CallbackEntry::Stored(MemoryEntry::Directory),
CallbackEntry::Hardlink {
target: hardlink_target(),
},
];
let mut seen = Vec::new();
for entry in &entries {
let expected = match entry {
CallbackEntry::Stored(stored) => stored.kind(),
CallbackEntry::Hardlink { .. } => MemoryEntryKind::Hardlink,
};
assert_eq!(entry.kind(), expected);
seen.push(entry.kind());
}
assert!(seen.contains(&MemoryEntryKind::Directory));
assert!(seen.contains(&MemoryEntryKind::Hardlink));
}
}