use std::collections::BTreeMap;
use std::io;
use std::io::Write;
use std::num::NonZeroU64;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use crate::ArchiveError;
use crate::ArchiveReader;
use crate::ExtractionReport;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::closed_enum::closed_enum;
use crate::security::fs_view::PathModel;
use crate::security::permissions::SanitizedMode;
use crate::security::quota::AdmittedSize;
use crate::sink::EntrySink;
use crate::sink::SinkFull;
use crate::sink::SinkOptions;
use crate::types::CheckedLinkTarget;
use crate::types::SafePath;
const DEFAULT_LIMIT_BYTES: u64 = 500 * 1024 * 1024;
const INITIAL_CAPACITY_CAP: u64 = 64 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryLimit(NonZeroU64);
impl MemoryLimit {
pub const DEFAULT: Self = Self(match NonZeroU64::new(DEFAULT_LIMIT_BYTES) {
Some(bytes) => bytes,
None => NonZeroU64::MIN,
});
#[must_use]
pub const fn new(bytes: NonZeroU64) -> Self {
Self(bytes)
}
#[must_use]
pub const fn bytes(self) -> NonZeroU64 {
self.0
}
#[must_use]
pub fn from_config(config: &SecurityConfig) -> Self {
Self(match config.max_total_size {
crate::Limit::Bounded(bytes) => bytes,
crate::Limit::Unbounded => NonZeroU64::MAX,
})
}
}
#[derive(Debug, Clone, Default)]
pub struct SinkUsage(Arc<AtomicU64>);
impl SinkUsage {
pub(crate) fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
pub(crate) fn set(&self, bytes: u64) {
self.0.store(bytes, Ordering::Relaxed);
}
}
#[derive(Debug)]
pub struct SinkReuse {
pub(crate) usage: SinkUsage,
pub(crate) limit: MemoryLimit,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MemoryEntry {
File {
data: Vec<u8>,
mode: Option<SanitizedMode>,
},
Directory,
Symlink {
target: PathBuf,
},
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MemoryEntryKind {
File => "file",
Directory => "directory",
Symlink => "symlink",
Hardlink => "hardlink",
}
}
impl MemoryEntry {
#[must_use]
pub const fn kind(&self) -> MemoryEntryKind {
match self {
Self::File { .. } => MemoryEntryKind::File,
Self::Directory => MemoryEntryKind::Directory,
Self::Symlink { .. } => MemoryEntryKind::Symlink,
}
}
fn payload_bytes(&self) -> u64 {
match self {
Self::File { data, .. } => data.len() as u64,
Self::Symlink { target } => target.as_os_str().len() as u64,
Self::Directory => 0,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct MemoryExtractRequest {
pub(super) config: SecurityConfig,
pub(super) options: SinkOptions,
limit: Option<MemoryLimit>,
pub(super) model: PathModel,
}
impl MemoryExtractRequest {
#[must_use]
pub fn with_config(mut self, config: SecurityConfig) -> Self {
self.config = config;
self
}
#[must_use]
pub const fn with_options(mut self, options: SinkOptions) -> Self {
self.options = options;
self
}
#[must_use]
pub const fn with_limit(mut self, limit: MemoryLimit) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub const fn with_path_model(mut self, model: PathModel) -> Self {
self.model = model;
self
}
}
pub fn extract_reader_to_memory(
reader: ArchiveReader<'_>,
request: &MemoryExtractRequest,
progress: &mut dyn ProgressCallback,
) -> Result<(ExtractionReport, MemorySink)> {
let limit = request
.limit
.unwrap_or_else(|| MemoryLimit::from_config(&request.config));
let mut sink = MemorySink::new(limit).with_path_model(request.model);
let reuse = SinkReuse {
usage: sink.usage(),
limit,
};
let report = crate::api::extract_to_sink_reusing(
reader,
&mut sink,
&request.config,
request.options,
progress,
Some(reuse),
)
.map_err(ArchiveError::discarded)?;
Ok((report, sink))
}
#[derive(Debug)]
pub struct MemoryFile {
data: Vec<u8>,
mode: Option<SanitizedMode>,
}
impl MemoryFile {
pub(crate) const fn from_vec(data: Vec<u8>, mode: Option<SanitizedMode>) -> Self {
Self { data, mode }
}
pub(crate) fn with_size(size: u64, mode: Option<SanitizedMode>) -> Self {
let capacity = usize::try_from(size.min(INITIAL_CAPACITY_CAP)).unwrap_or(0);
Self {
data: Vec::with_capacity(capacity),
mode,
}
}
pub(crate) fn into_entry(self) -> MemoryEntry {
let Self { mut data, mode } = self;
data.shrink_to_fit();
MemoryEntry::File { data, mode }
}
}
impl Write for MemoryFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.data.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[derive(Debug)]
pub struct MemorySink {
limit: MemoryLimit,
path_model: PathModel,
stored: u64,
usage: SinkUsage,
entries: BTreeMap<PathBuf, MemoryEntry>,
}
impl Default for MemorySink {
fn default() -> Self {
Self::new(MemoryLimit::DEFAULT)
}
}
impl MemorySink {
pub const ENTRY_OVERHEAD: u64 = 256;
#[must_use]
pub fn new(limit: MemoryLimit) -> Self {
Self {
limit,
path_model: PathModel::Host,
stored: 0,
usage: SinkUsage(Arc::new(AtomicU64::new(0))),
entries: BTreeMap::new(),
}
}
#[must_use]
pub const fn with_path_model(mut self, path_model: PathModel) -> Self {
self.path_model = path_model;
self
}
#[must_use]
pub const fn limit(&self) -> MemoryLimit {
self.limit
}
#[must_use]
pub const fn stored_bytes(&self) -> u64 {
self.stored
}
#[must_use]
pub fn get(&self, path: &Path) -> Option<&MemoryEntry> {
self.entries.get(path)
}
pub fn iter(&self) -> impl Iterator<Item = (&Path, &MemoryEntry)> {
self.entries
.iter()
.map(|(path, entry)| (path.as_path(), entry))
}
#[must_use]
pub fn into_entries(self) -> BTreeMap<PathBuf, MemoryEntry> {
self.entries
}
fn full(&self) -> io::Error {
io::Error::new(
io::ErrorKind::QuotaExceeded,
SinkFull::new(self.limit.bytes().get()),
)
}
pub(crate) fn usage(&self) -> SinkUsage {
self.usage.clone()
}
pub(crate) fn charge_of(path: &Path, payload: u64) -> u64 {
Self::ENTRY_OVERHEAD
.saturating_add(path.as_os_str().len() as u64)
.saturating_add(payload)
}
fn held_at(&self, path: &Path) -> u64 {
self.entries
.get(path)
.map_or(0, |entry| Self::charge_of(path, entry.payload_bytes()))
}
fn charged_with(&self, path: &Path, payload: u64) -> io::Result<u64> {
self.stored
.saturating_sub(self.held_at(path))
.checked_add(Self::charge_of(path, payload))
.filter(|total| *total <= self.limit.bytes().get())
.ok_or_else(|| self.full())
}
fn store(&mut self, path: &SafePath, entry: MemoryEntry) -> io::Result<()> {
let key = path.as_path();
self.stored = self.charged_with(key, entry.payload_bytes())?;
self.usage.set(self.stored);
self.entries.insert(key.to_path_buf(), entry);
Ok(())
}
fn reserve_file(&mut self, path: &SafePath, size: u64) -> io::Result<()> {
self.charged_with(path.as_path(), size)?;
self.stored = self.stored.saturating_sub(self.held_at(path.as_path()));
self.usage.set(self.stored);
self.entries.remove(path.as_path());
Ok(())
}
}
impl EntrySink for MemorySink {
type File = MemoryFile;
fn path_model(&self) -> PathModel {
self.path_model
}
fn create_directory(&mut self, path: &SafePath) -> io::Result<()> {
self.store(path, MemoryEntry::Directory)
}
fn create_file(
&mut self,
path: &SafePath,
mode: Option<SanitizedMode>,
size: AdmittedSize,
) -> io::Result<MemoryFile> {
self.reserve_file(path, size.get())?;
Ok(MemoryFile::with_size(size.get(), mode))
}
fn create_file_from(
&mut self,
path: &SafePath,
mode: Option<SanitizedMode>,
size: AdmittedSize,
bytes: Vec<u8>,
) -> io::Result<MemoryFile> {
self.reserve_file(path, size.get())?;
Ok(MemoryFile::from_vec(bytes, mode))
}
fn finish_file(&mut self, path: &SafePath, file: MemoryFile) -> io::Result<()> {
self.store(path, file.into_entry())
}
fn create_symlink(&mut self, link: &SafePath, target: CheckedLinkTarget<'_>) -> io::Result<()> {
self.store(
link,
MemoryEntry::Symlink {
target: target.as_path().to_path_buf(),
},
)
}
fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()> {
let Some(MemoryEntry::File { data, mode }) = self.entries.get(target.as_path()) else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"hardlink target is not a file",
));
};
self.charged_with(link.as_path(), data.len() as u64)?;
let copy = MemoryEntry::File {
data: data.clone(),
mode: *mode,
};
self.store(link, copy)
}
}