Skip to main content

powerio_archive/
session.rs

1//! Shared cancellation and bounded verification for adapter-owned ZIP namespaces.
2use crate::{ArchiveLimits, Result, end_records, limit, malformed};
3use std::io::{Cursor, Read};
4use std::sync::{
5    Arc,
6    atomic::{AtomicBool, Ordering},
7};
8
9/// Cooperative cancellation. Clones signal the same operation/session.
10#[derive(Clone, Default, Debug)]
11pub struct Cancellation(Arc<AtomicBool>);
12impl Cancellation {
13    pub fn cancel(&self) {
14        self.0.store(true, Ordering::Relaxed);
15    }
16    pub fn check(&self) -> Result<()> {
17        if self.0.load(Ordering::Relaxed) {
18            Err(limit("archive operation cancelled"))
19        } else {
20            Ok(())
21        }
22    }
23}
24pub(crate) struct CancellableReader<'a, R>(pub &'a mut R, pub &'a Cancellation);
25impl<R: Read> Read for CancellableReader<'_, R> {
26    fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
27        self.1.check().map_err(std::io::Error::other)?;
28        // Bound cancellation latency even when read_to_end offers a large slice.
29        let n = bytes.len().min(64 << 10);
30        self.0.read(&mut bytes[..n])
31    }
32}
33
34/// Verify an adapter-owned ZIP under session limits without changing its names
35/// or flattening its contents. Allows the ZIP reader's compatible layouts and
36/// compression methods; the adapter still owns namespace/format validation.
37/// Every payload is checked against its declared size and CRC before delegation.
38/// Returns total entries and expansion, including opaque native companions.
39pub fn verify_native(
40    bytes: &[u8],
41    limits: ArchiveLimits,
42    cancel: &Cancellation,
43    reserve: impl FnOnce(usize, u64) -> Result<()>,
44) -> Result<(usize, u64)> {
45    cancel.check()?;
46    if bytes.len() as u64 > limits.max_input_bytes() {
47        return Err(limit("native ZIP input limit exceeded"));
48    }
49    let declared = end_records::declared_entries(bytes, 8)
50        .map_err(|_| malformed("invalid native ZIP end records"))?;
51    // A legacy fallback can allocate a 16-bit entry table before the actual
52    // count is checked. Its fixed maximum is bounded; all ZIP64 reservations
53    // are checked before constructing the reader.
54    if declared.first > limits.max_entries() as u64
55        || declared.largest_zip64 > limits.max_entries() as u64
56    {
57        return Err(limit("native ZIP entry limit exceeded"));
58    }
59    let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| malformed(e.to_string()))?;
60    if zip.len() > limits.max_entries() || zip.len() as u64 != declared.first {
61        return Err(limit("native ZIP count differs from bounded end record"));
62    }
63    let mut total = 0u64;
64    for i in 0..zip.len() {
65        cancel.check()?;
66        let entry = zip.by_index(i).map_err(|e| malformed(e.to_string()))?;
67        let size = entry.size();
68        total = total
69            .checked_add(size)
70            .ok_or_else(|| limit("native ZIP expanded byte overflow"))?;
71        if total > limits.max_expanded_bytes()
72            || size
73                > entry
74                    .compressed_size()
75                    .max(1)
76                    .saturating_mul(limits.max_ratio())
77        {
78            return Err(limit("native ZIP expansion limit exceeded"));
79        }
80    }
81    // Commit the entire declared allowance before decompression. The caller's
82    // counters remain charged even if a later size/CRC check fails.
83    reserve(zip.len(), total)?;
84    for i in 0..zip.len() {
85        cancel.check()?;
86        let mut entry = zip.by_index(i).map_err(|e| malformed(e.to_string()))?;
87        let size = entry.size();
88        let read = std::io::copy(
89            &mut CancellableReader(&mut entry, cancel).take(size.saturating_add(1)),
90            &mut std::io::sink(),
91        )
92        .map_err(|e| malformed(e.to_string()))?;
93        if read != size {
94            return Err(malformed("native ZIP declared size mismatch"));
95        }
96    }
97    cancel.check()?;
98    Ok((zip.len(), total))
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    #[test]
105    fn cancellation_interrupts_between_chunks() {
106        struct CancelAfterRead(Cancellation);
107        impl Read for CancelAfterRead {
108            fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
109                bytes.fill(1);
110                self.0.cancel();
111                Ok(bytes.len())
112            }
113        }
114        let cancel = Cancellation::default();
115        let mut reader = CancelAfterRead(cancel.clone());
116        let mut wrapped = CancellableReader(&mut reader, &cancel);
117        let mut bytes = vec![0; 128 << 10];
118        assert_eq!(wrapped.read(&mut bytes).unwrap(), 64 << 10);
119        assert!(wrapped.read(&mut bytes).is_err());
120    }
121}