Debian Codegraph @

debian/rust-vendor/zip/src/read/readers.rs

raw
1 //! Code related to reader
2
3 use crate::AesMode;
4 use crate::compression::{CompressionMethod, Decompressor};
5 use crate::crc32::Crc32Reader;
6 use crate::result::{ZipError, ZipResult};
7 use crate::types::AesVendorVersion;
8 use crate::types::ZipFileData;
9 use crate::zipcrypto::{ZipCryptoReader, ZipCryptoReaderValid, ZipCryptoValidator};
10 use std::io::{self, Read, Seek, SeekFrom};
11
12 pub(crate) enum ZipFileSeekReader<'a, R: ?Sized> {
13 Raw(SeekableTake<'a, R>),
14 }
15
16 pub(crate) struct SeekableTake<'a, R: ?Sized> {
17 inner: &'a mut R,
18 inner_starting_offset: u64,
19 length: u64,
20 current_offset: u64,
21 }
22
23 impl<'a, R: Seek + ?Sized> SeekableTake<'a, R> {
24 pub fn new(inner: &'a mut R, length: u64) -> io::Result<Self> {
25 let inner_starting_offset = inner.stream_position()?;
26 Ok(Self {
27 inner,
28 inner_starting_offset,
29 length,
30 current_offset: 0,
31 })
32 }
33 }
34
35 impl<R: Seek + ?Sized> Seek for SeekableTake<'_, R> {
36 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
37 let offset = match pos {
38 SeekFrom::Start(offset) => Some(offset),
39 SeekFrom::End(offset) => self.length.checked_add_signed(offset),
40 SeekFrom::Current(offset) => self.current_offset.checked_add_signed(offset),
41 };
42 match offset {
43 None => Err(io::Error::new(
44 io::ErrorKind::InvalidInput,
45 "invalid seek to a negative or overflowing position",
46 )),
47 Some(offset) => {
48 let clamped_offset = std::cmp::min(self.length, offset);
49 let new_inner_offset = self
50 .inner
51 .seek(SeekFrom::Start(self.inner_starting_offset + clamped_offset))?;
52 self.current_offset = new_inner_offset - self.inner_starting_offset;
53 Ok(self.current_offset)
54 }
55 }
56 }
57 }
58
59 impl<R: Read + ?Sized> Read for SeekableTake<'_, R> {
60 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
61 let written = self
62 .inner
63 .take(self.length - self.current_offset)
64 .read(buf)?;
65 self.current_offset += written as u64;
66 Ok(written)
67 }
68 }
69
70 #[allow(clippy::large_enum_variant)]
71 pub(crate) enum CryptoReader<'a, R: Read + ?Sized> {
72 Plaintext(io::Take<&'a mut R>),
73 ZipCrypto(ZipCryptoReaderValid<io::Take<&'a mut R>>),
74 #[cfg(feature = "aes-crypto")]
75 Aes {
76 reader: crate::aes::AesReaderValid<io::Take<&'a mut R>>,
77 vendor_version: AesVendorVersion,
78 },
79 }
80
81 impl<R: Read + ?Sized> core::fmt::Debug for CryptoReader<'_, R> {
82 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
83 match self {
84 CryptoReader::Plaintext(_) => f.write_str("CryptoReader::Plaintext"),
85 CryptoReader::ZipCrypto(_) => f.write_str("CryptoReader::ZipCrypto"),
86 #[cfg(feature = "aes-crypto")]
87 CryptoReader::Aes { vendor_version, .. } => {
88 write!(
89 f,
90 "CryptoReader::Aes {{ vendor_version: {:?} }}",
91 vendor_version
92 )
93 }
94 }
95 }
96 }
97
98 impl<R: Read + ?Sized> Read for CryptoReader<'_, R> {
99 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
100 match self {
101 CryptoReader::Plaintext(r) => r.read(buf),
102 CryptoReader::ZipCrypto(r) => r.read(buf),
103 #[cfg(feature = "aes-crypto")]
104 CryptoReader::Aes { reader: r, .. } => r.read(buf),
105 }
106 }
107
108 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
109 match self {
110 CryptoReader::Plaintext(r) => r.read_to_end(buf),
111 CryptoReader::ZipCrypto(r) => r.read_to_end(buf),
112 #[cfg(feature = "aes-crypto")]
113 CryptoReader::Aes { reader: r, .. } => r.read_to_end(buf),
114 }
115 }
116
117 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
118 match self {
119 CryptoReader::Plaintext(r) => r.read_to_string(buf),
120 CryptoReader::ZipCrypto(r) => r.read_to_string(buf),
121 #[cfg(feature = "aes-crypto")]
122 CryptoReader::Aes { reader: r, .. } => r.read_to_string(buf),
123 }
124 }
125 }
126
127 impl<'a, R: Read + ?Sized> CryptoReader<'a, R> {
128 /// Consumes this decoder, returning the underlying reader.
129 pub fn into_inner(self) -> io::Take<&'a mut R> {
130 match self {
131 CryptoReader::Plaintext(r) => r,
132 CryptoReader::ZipCrypto(r) => r.into_inner(),
133 #[cfg(feature = "aes-crypto")]
134 CryptoReader::Aes { reader: r, .. } => r.into_inner(),
135 }
136 }
137
138 /// Returns `true` if the data is encrypted using AE2.
139 #[cfg(feature = "aes-crypto")]
140 pub const fn is_ae2_encrypted(&self) -> bool {
141 matches!(
142 self,
143 CryptoReader::Aes {
144 vendor_version: AesVendorVersion::Ae2,
145 ..
146 }
147 )
148 }
149
150 /// `false` since the feature `aes-crypto` is not enabled
151 #[cfg(not(feature = "aes-crypto"))]
152 pub const fn is_ae2_encrypted(&self) -> bool {
153 false
154 }
155 }
156
157 macro_rules! invalid_state {
158 ( $( $x:expr ),* ) => {
159 Err(io::Error::other("ZipFileReader was in an invalid state"))
160 };
161 }
162
163 #[derive(Debug)]
164 pub(crate) enum ZipFileReader<'a, R: Read + ?Sized> {
165 NoReader,
166 Raw(io::Take<&'a mut R>),
167 Stored(Box<Crc32Reader<CryptoReader<'a, R>>>),
168 Compressed(Box<Crc32Reader<Decompressor<io::BufReader<CryptoReader<'a, R>>>>>),
169 }
170
171 impl<R: Read + ?Sized> Read for ZipFileReader<'_, R> {
172 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
173 match self {
174 ZipFileReader::NoReader => invalid_state!(),
175 ZipFileReader::Raw(r) => r.read(buf),
176 ZipFileReader::Stored(r) => r.read(buf),
177 ZipFileReader::Compressed(r) => r.read(buf),
178 }
179 }
180
181 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
182 match self {
183 ZipFileReader::NoReader => invalid_state!(),
184 ZipFileReader::Raw(r) => r.read_exact(buf),
185 ZipFileReader::Stored(r) => r.read_exact(buf),
186 ZipFileReader::Compressed(r) => r.read_exact(buf),
187 }
188 }
189
190 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
191 match self {
192 ZipFileReader::NoReader => invalid_state!(),
193 ZipFileReader::Raw(r) => r.read_to_end(buf),
194 ZipFileReader::Stored(r) => r.read_to_end(buf),
195 ZipFileReader::Compressed(r) => r.read_to_end(buf),
196 }
197 }
198
199 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
200 match self {
201 ZipFileReader::NoReader => invalid_state!(),
202 ZipFileReader::Raw(r) => r.read_to_string(buf),
203 ZipFileReader::Stored(r) => r.read_to_string(buf),
204 ZipFileReader::Compressed(r) => r.read_to_string(buf),
205 }
206 }
207 }
208
209 impl<'a, R: Read + ?Sized> ZipFileReader<'a, R> {
210 pub(crate) fn into_inner(self) -> io::Result<io::Take<&'a mut R>> {
211 match self {
212 ZipFileReader::NoReader => invalid_state!(),
213 ZipFileReader::Raw(r) => Ok(r),
214 ZipFileReader::Stored(r) => Ok(r.into_inner().into_inner()),
215 ZipFileReader::Compressed(r) => {
216 Ok(r.into_inner().into_inner()?.into_inner().into_inner())
217 }
218 }
219 }
220 }
221
222 #[allow(clippy::too_many_arguments)]
223 pub(crate) fn make_crypto_reader<'a, R: Read + ?Sized>(
224 data: &ZipFileData,
225 reader: io::Take<&'a mut R>,
226 password: Option<&[u8]>,
227 aes_info: Option<(AesMode, AesVendorVersion, CompressionMethod)>,
228 ) -> ZipResult<CryptoReader<'a, R>> {
229 #[allow(deprecated)]
230 {
231 if let CompressionMethod::Unsupported(id) = data.compression_method {
232 return Err(ZipError::CompressionMethodNotSupported(id));
233 }
234 }
235
236 let reader = match (password, aes_info) {
237 #[cfg(not(feature = "aes-crypto"))]
238 (Some(_), Some(_)) => {
239 return Err(ZipError::UnsupportedArchive(
240 "AES encrypted files cannot be decrypted without the aes-crypto feature.",
241 ));
242 }
243 #[cfg(feature = "aes-crypto")]
244 (Some(password), Some((aes_mode, vendor_version, _))) => CryptoReader::Aes {
245 reader: crate::aes::AesReader::new(reader, aes_mode, data.compressed_size)
246 .validate(password)?,
247 vendor_version,
248 },
249 (Some(password), None) => {
250 let validator = if data.using_data_descriptor {
251 ZipCryptoValidator::InfoZipMsdosTime(
252 data.last_modified_time.map_or(0, |x| x.timepart()),
253 )
254 } else {
255 ZipCryptoValidator::PkzipCrc32(data.crc32)
256 };
257 CryptoReader::ZipCrypto(ZipCryptoReader::new(reader, password).validate(validator)?)
258 }
259 (None, Some(_)) => return Err(ZipError::InvalidPassword),
260 (None, None) => CryptoReader::Plaintext(reader),
261 };
262 Ok(reader)
263 }
264
265 pub(crate) fn make_reader<R: Read + ?Sized>(
266 compression_method: CompressionMethod,
267 uncompressed_size: u64,
268 crc32: Option<u32>,
269 reader: CryptoReader<'_, R>,
270 #[cfg(feature = "legacy-zip")] flags: u16,
271 ) -> ZipResult<ZipFileReader<'_, R>> {
272 // enable the crc32 check when there is a crc32 and the content is not ae2_encrypted
273 let (should_disable, crc32) = if let Some(data_crc32) = crc32 {
274 (reader.is_ae2_encrypted(), data_crc32)
275 } else {
276 (true, 0)
277 };
278 if compression_method == CompressionMethod::Stored {
279 return Ok(ZipFileReader::Stored(Box::new(Crc32Reader::new(
280 reader,
281 crc32,
282 should_disable,
283 ))));
284 }
285 #[cfg(not(feature = "legacy-zip"))]
286 let flags = 0;
287 Ok(ZipFileReader::Compressed(Box::new(Crc32Reader::new(
288 Decompressor::new(
289 io::BufReader::new(reader),
290 compression_method,
291 uncompressed_size,
292 flags,
293 )?,
294 crc32,
295 should_disable,
296 ))))
297 }