Skip to main content

eazip/utils/
mod.rs

1pub mod cp437;
2mod crc32;
3
4pub use crc32::{Crc32Checker, Crc32Writer};
5
6use hashbrown::HashTable;
7
8use crate::io;
9use alloc::{boxed::Box, fmt, string::String, vec::Vec};
10use core::hash::{BuildHasher, Hash};
11#[cfg(feature = "std")]
12use std::{hash::RandomState, time::SystemTime};
13
14#[must_use]
15pub(crate) fn validate_name(name: &str) -> Option<Box<str>> {
16    if name.starts_with('/')
17        || memchr::memchr2(b'\\', b'\0', name.as_bytes()).is_some()
18        || (cfg!(windows) && name.contains(':'))
19    {
20        return None;
21    }
22
23    let mut dst = String::with_capacity(name.len());
24    for part in name.split_inclusive('/') {
25        match part {
26            // Forbid parent parts as they have weird interactions with symlinks
27            "." | ".." | "../" => return None,
28            "/" | "./" => (),
29            _ => dst.push_str(part),
30        }
31    }
32
33    if dst.is_empty() {
34        return None;
35    }
36
37    Some(dst.into_boxed_str())
38}
39
40/// Checks whether a symlink is safe to use.
41///
42/// A symlink contained in an untrusted zip file may point to an absolute path,
43/// to a parent path (eg `../../etc/passwd`), or even use another symlink to
44/// point outside the extraction directory. This function tests against such
45/// malicious links.
46///
47/// This function is public because `eazip` doesn't validate symlinks when an
48/// archive is read, because they could be compressed with an algorithm unknown
49/// to `eazip`. This enables users of this crate to be safe even in such
50/// circumstance.
51///
52/// # Example
53///
54/// ```
55/// use eazip::read::validate_symlink;
56///
57/// assert!(validate_symlink("a", "b/c"));
58/// assert!(!validate_symlink("a", "/b/c"));
59/// assert!(!validate_symlink("a", "../b/c"));
60/// ```
61pub fn validate_symlink(name: &str, target: &str) -> bool {
62    if target.starts_with('/')
63        || memchr::memchr2(b'\\', b'\0', target.as_bytes()).is_some()
64        || (cfg!(windows) && target.contains(':'))
65    {
66        return false;
67    }
68
69    let mut depth = Some(name.split('/').count() - 1);
70
71    for part in target.split('/') {
72        match part {
73            "" | "." => (),
74            ".." => match depth.and_then(|d| d.checked_sub(1)) {
75                Some(d) => depth = Some(d),
76                None => return false,
77            },
78            // Once the link goes down, forbid it going up again (eg "a/../b")
79            // to prevent it using another link as a "trampoline" to escape.
80            _ => depth = None,
81        }
82    }
83
84    true
85}
86
87/// The type of an entry in an archive.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum FileType {
90    /// A file.
91    File,
92    /// A directory.
93    Directory,
94    /// A symlink.
95    Symlink,
96}
97
98impl FileType {
99    /// Returns whether `self` is `FileType::File`.
100    #[inline]
101    pub fn is_file(&self) -> bool {
102        matches!(self, FileType::File)
103    }
104
105    /// Returns whether `self` is `FileType::Directory`.
106    #[inline]
107    pub fn is_directory(&self) -> bool {
108        matches!(self, FileType::Directory)
109    }
110
111    /// Returns whether `self` is `FileType::Symlink`.
112    #[inline]
113    pub fn is_symlink(&self) -> bool {
114        matches!(self, FileType::Symlink)
115    }
116}
117
118/// A timestamp for an entry in an archive.
119///
120/// It is stored as a 64-bits UNIX timestamp, and therefore has second precision.
121#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
122pub struct Timestamp(u64);
123
124impl Timestamp {
125    pub const UNIX_EPOCH: Self = Self(0);
126
127    /// Returns the timestamp corresponding to "now".
128    #[cfg(feature = "std")]
129    #[inline]
130    pub fn now() -> Self {
131        Self::from_std(SystemTime::now())
132    }
133
134    /// Returns a `Timestamp` from a NTFS timestamp.
135    ///
136    /// Sub-second precision is lost in the process.
137    pub fn from_ntfs(time: u64) -> Self {
138        /// Time in seconds between NT and Unix epochs
139        const NT_EPOCH: u64 = 11_644_473_600;
140
141        let time = time.saturating_sub(NT_EPOCH * 10_000_000);
142
143        Self(time / 10_000_000)
144    }
145
146    /// Returns a `Timestamp` from an UNIX timestamp.
147    #[inline]
148    pub fn from_unix(time: u64) -> Self {
149        Self(time)
150    }
151
152    /// Returns a `Timestamp` from a [`SystemTime`].
153    ///
154    /// Sub-second precision is lost in the process.
155    #[cfg(feature = "std")]
156    #[inline]
157    pub fn from_std(t: SystemTime) -> Self {
158        Self(t.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs())
159    }
160
161    /// Converts this timestamp to an UNIX timestamp.
162    #[inline]
163    pub fn to_unix(self) -> u64 {
164        self.0
165    }
166
167    /// Converts this timestamp to a [`SystemTime`].
168    #[cfg(feature = "std")]
169    #[inline]
170    pub fn to_std(self) -> SystemTime {
171        SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(self.0)
172    }
173}
174
175impl fmt::Debug for Timestamp {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        write!(f, "Timestamp({})", self.0)
178    }
179}
180
181#[derive(Default)]
182pub(crate) struct Counter<T> {
183    pub amt: u64,
184    pub inner: T,
185}
186
187impl<T> Counter<T> {
188    #[inline]
189    pub const fn new(inner: T) -> Self {
190        Self { amt: 0, inner }
191    }
192
193    pub(crate) fn advance(&mut self, amt: u64) -> io::Result<()>
194    where
195        T: io::Seek,
196    {
197        #[cold]
198        fn out_of_range() -> io::Error {
199            io::Error::new(io::ErrorKind::InvalidInput, "seek out of range")
200        }
201
202        let offset = amt.try_into().map_err(|_| out_of_range())?;
203        self.amt = self.amt.checked_add(amt).ok_or_else(out_of_range)?;
204        self.inner.seek_relative(offset)
205    }
206}
207
208impl<R: io::Read> io::Read for Counter<R> {
209    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
210        let n = self.inner.read(buf)?;
211        self.amt += n as u64;
212        Ok(n)
213    }
214}
215
216impl<R: io::BufRead> io::BufRead for Counter<R> {
217    #[inline]
218    fn fill_buf(&mut self) -> io::Result<&[u8]> {
219        self.inner.fill_buf()
220    }
221
222    #[inline]
223    fn consume(&mut self, amount: usize) {
224        self.amt += amount as u64;
225        self.inner.consume(amount);
226    }
227}
228
229impl<W: io::Write> io::Write for Counter<W> {
230    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
231        let n = self.inner.write(buf)?;
232        self.amt += n as u64;
233        Ok(n)
234    }
235
236    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
237        let n = self.inner.write_vectored(bufs)?;
238        self.amt += n as u64;
239        Ok(n)
240    }
241
242    #[inline]
243    fn flush(&mut self) -> io::Result<()> {
244        self.inner.flush()
245    }
246}
247
248#[cold]
249fn bad_length() -> io::Error {
250    io::Error::new(io::ErrorKind::InvalidData, "unexpected file length")
251}
252
253pub(crate) struct LengthChecker<R> {
254    expected: u64,
255    reader: R,
256}
257
258impl<R> LengthChecker<R> {
259    #[inline]
260    pub fn new(reader: R, expected: u64) -> Self {
261        Self { expected, reader }
262    }
263}
264
265impl<R: io::Read> io::Read for LengthChecker<R> {
266    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
267        let n = self.reader.read(buf)?;
268        if n == 0 && self.expected != 0 {
269            return Err(bad_length());
270        }
271        self.expected = self.expected.checked_sub(n as u64).ok_or_else(bad_length)?;
272        Ok(n)
273    }
274
275    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
276        let size = self
277            .expected
278            .try_into()
279            .map_err(|_| io::ErrorKind::OutOfMemory)?;
280        buf.try_reserve(size)?;
281
282        let initial_len = buf.len();
283        buf.extend((0..size).map(|_| 0));
284        self.read_exact(&mut buf[initial_len..])?;
285
286        // Check that we really are at EOF
287        self.read(&mut [0])?;
288
289        Ok(size)
290    }
291
292    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
293        let size = self
294            .expected
295            .try_into()
296            .map_err(|_| io::ErrorKind::OutOfMemory)?;
297        buf.try_reserve(size)?;
298
299        // Forward to the default implementation of `read_to_string`
300
301        struct Reader<R>(R);
302        impl<R: io::Read> io::Read for Reader<R> {
303            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
304                self.0.read(buf)
305            }
306            fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
307                self.0.read_to_end(buf)
308            }
309        }
310
311        Reader(self).read_to_string(buf)
312    }
313}
314
315#[cfg(not(feature = "std"))]
316struct RandomState(u64, u64);
317
318#[cfg(not(feature = "std"))]
319impl Default for RandomState {
320    fn default() -> Self {
321        use core::sync::atomic;
322
323        static NEXT_KEY: atomic::AtomicUsize = atomic::AtomicUsize::new(0x8742e7ce);
324        let x = ();
325
326        // Unfortunately a proper random seed isn't available here, so we do our
327        // best to use different seeds each time, even with very low entropy.
328        Self(
329            &raw const x as u64,
330            NEXT_KEY.fetch_add(9, atomic::Ordering::Relaxed) as _,
331        )
332    }
333}
334
335#[cfg(not(feature = "std"))]
336#[expect(deprecated)]
337impl BuildHasher for RandomState {
338    type Hasher = core::hash::SipHasher;
339
340    fn build_hasher(&self) -> Self::Hasher {
341        core::hash::SipHasher::new_with_keys(self.0, self.1)
342    }
343}
344
345#[derive(Default)]
346pub(crate) struct NameTable<T> {
347    table: HashTable<T>,
348    hasher: RandomState,
349}
350
351impl<T> NameTable<T> {
352    pub fn with_capacity(cap: usize) -> Self {
353        Self {
354            table: HashTable::with_capacity(cap),
355            hasher: RandomState::default(),
356        }
357    }
358
359    #[inline]
360    pub fn try_reserve<'a>(
361        &mut self,
362        cap: usize,
363        f: impl Fn(&T) -> &'a [u8],
364    ) -> Result<(), io::ErrorKind> {
365        self.table
366            .try_reserve(cap, |x| self.hasher.hash_one(f(x)))
367            .map_err(|_| io::ErrorKind::OutOfMemory)
368    }
369
370    #[inline]
371    pub fn len(&self) -> usize {
372        self.table.len()
373    }
374
375    pub fn get<'a>(&self, name: &[u8], f: impl Fn(&T) -> &'a [u8]) -> Option<&T> {
376        let hash = self.hasher.hash_one(name);
377        self.table.find(hash, |x| f(x) == name)
378    }
379
380    pub fn insert<'a>(&mut self, value: T, f: impl Fn(&T) -> &'a [u8]) -> bool {
381        let name = f(&value);
382        let hash = self.hasher.hash_one(name);
383        let entry = self
384            .table
385            .entry(hash, |x| f(x) == name, |x| self.hasher.hash_one(f(x)));
386        match entry {
387            hashbrown::hash_table::Entry::Occupied(_) => false,
388            hashbrown::hash_table::Entry::Vacant(entry) => {
389                entry.insert(value);
390                true
391            }
392        }
393    }
394}
395
396#[test]
397fn symlink_validation() {
398    assert!(validate_symlink("a/b", "../c"));
399    assert!(!validate_symlink("a/b", "../../c"));
400    assert!(!validate_symlink("a/b", "/c"));
401    assert!(!validate_symlink("a/b", ".//////../../c"));
402    assert!(!validate_symlink("a/b", "a/../c"));
403    assert!(!validate_symlink("a/b", "a\\b"));
404    #[cfg(windows)]
405    assert!(!validate_symlink("a/b", "C:/e"));
406}