aboutsummaryrefslogtreecommitdiff
path: root/src/zip/file/read.rs
blob: c26b3044db0bb3a77c04b8765443f2c4ddfd3607 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
use crate::driver::FileDriver;
use crate::utils::{IoCursor, ReadUtils};
use crate::zip::encryption::WeakDecoder;
use crate::zip::{CompressionMethod, EncryptionMethod, ZipError, ZipFileInfo, ZipResult};
use bzip2::read::BzDecoder;
use flate2::read::DeflateDecoder;
use liblzma::read::XzDecoder;
use liblzma::stream::{Filters, LzmaOptions, Stream};
use std::io::{
    BufReader, Error as IoError, ErrorKind as IoErrorKind, Read, Result as IoResult, Seek, SeekFrom,
};
use zstd::stream::Decoder as ZstdDecoder;

enum Encryption<Io: Read> {
    None(Io),
    Weak(WeakDecoder<Io>),
}

impl<Io: Read> Encryption<Io> {
    pub fn new(io: Io, info: &ZipFileInfo, password: Option<&[u8]>) -> ZipResult<Self> {
        Ok(match info.encryption_method {
            EncryptionMethod::None => Self::None(io),
            EncryptionMethod::Weak(check) => Self::Weak(WeakDecoder::new(
                io,
                check,
                password.ok_or(ZipError::PasswordIsNotSpecified)?,
            )?),
            EncryptionMethod::Unsupported => {
                return Err(ZipError::UnsupportedEncryptionMethod.into())
            }
        })
    }
}

impl<Io: Read> Read for Encryption<Io> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        match self {
            Self::None(io) => io.read(buf),
            Self::Weak(io) => io.read(buf),
        }
    }
}

impl<Io: Read + Seek> Seek for Encryption<Io> {
    fn seek(&mut self, pos: SeekFrom) -> IoResult<u64> {
        match self {
            Self::None(io) => io.seek(pos),
            _ => Err(IoError::new(
                IoErrorKind::Unsupported,
                ZipError::EncryptedDataIsUnseekable,
            )),
        }
    }
}

enum Compression<Io: Read> {
    Store(Io),
    Deflate(DeflateDecoder<Io>),
    BZip2(BzDecoder<Io>),
    Zstd(ZstdDecoder<'static, BufReader<Io>>),
    Xz(XzDecoder<Io>),
}

impl<Io: Read + Seek> Compression<Io> {
    pub fn new(mut io: Io, info: &ZipFileInfo) -> ZipResult<Self> {
        Ok(match info.compression_method {
            CompressionMethod::Store => Self::Store(io),
            CompressionMethod::Deflate => Self::Deflate(DeflateDecoder::new(io)),
            CompressionMethod::BZip2 => Self::BZip2(BzDecoder::new(io)),
            CompressionMethod::Lzma => {
                let buf = io.read_arr::<9>()?;
                Compression::Xz(XzDecoder::new_stream(
                    io,
                    Stream::new_raw_decoder(
                        Filters::new().lzma1(
                            LzmaOptions::new()
                                .literal_context_bits((buf[4] % 9) as u32)
                                .literal_position_bits((buf[4] / 9 % 5) as u32)
                                .position_bits((buf[4] / 45) as u32)
                                .dict_size(
                                    u32::from_le_bytes(buf[5..9].try_into().unwrap()).max(4096),
                                ),
                        ),
                    )
                    .unwrap(),
                ))
            }
            CompressionMethod::Zstd => Self::Zstd(ZstdDecoder::new(io)?),
            CompressionMethod::Xz => Self::Xz(XzDecoder::new(io)),
            CompressionMethod::Unsupported(id) => {
                return Err(ZipError::UnsupportedCompressionMethod(id).into())
            }
        })
    }
}

impl<Io: Read> Read for Compression<Io> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        match self {
            Compression::Store(io) => io.read(buf),
            Compression::Deflate(io) => io.read(buf),
            Compression::BZip2(io) => io.read(buf),
            Compression::Zstd(io) => io.read(buf),
            Compression::Xz(io) => io.read(buf),
        }
    }
}

impl<Io: Read + Seek> Seek for Compression<Io> {
    fn seek(&mut self, pos: SeekFrom) -> IoResult<u64> {
        match self {
            Compression::Store(io) => io.seek(pos),
            _ => Err(IoError::new(
                IoErrorKind::Unsupported,
                ZipError::CompressedDataIsUnseekable,
            )),
        }
    }
}

pub struct ZipFileReader<'d, Io: Read> {
    io: Compression<Encryption<IoCursor<&'d mut Io>>>,
    info: &'d ZipFileInfo,
}

impl<'d, Io: Read> FileDriver for ZipFileReader<'d, Io> {
    type Io = Io;
    type FileInfo = ZipFileInfo;
}

impl<'d, Io: Read + Seek> ZipFileReader<'d, Io> {
    pub(crate) fn new(
        io: &'d mut Io,
        info: &'d ZipFileInfo,
        password: Option<&[u8]>,
    ) -> ZipResult<Self> {
        io.seek(SeekFrom::Start(info.header_pointer))?;

        let buf = io.read_arr::<30>()?;
        if u32::from_le_bytes(buf[..4].try_into().unwrap()) != 0x04034b50 {
            return Err(ZipError::InvalidFileHeaderSignature.into());
        }
        let data_pointer = info.header_pointer
            + 30
            + u16::from_le_bytes(buf[26..28].try_into().unwrap()) as u64
            + u16::from_le_bytes(buf[28..30].try_into().unwrap()) as u64;

        Ok(Self {
            io: Compression::new(
                Encryption::new(
                    IoCursor::new(io, data_pointer, data_pointer + info.compressed_size)?,
                    info,
                    password,
                )?,
                info,
            )?,
            info,
        })
    }

    pub fn info(&self) -> &ZipFileInfo {
        self.info
    }

    pub fn is_seekable(&self) -> bool {
        match self.io {
            Compression::Store(Encryption::None(..)) => true,
            _ => false,
        }
    }
}

impl<'d, Io: Read> Read for ZipFileReader<'d, Io> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        self.io.read(buf)
    }
}

impl<'d, Io: Read + Seek> Seek for ZipFileReader<'d, Io> {
    fn seek(&mut self, pos: SeekFrom) -> IoResult<u64> {
        self.io.seek(pos)
    }
}