Debian Codegraph @

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

raw
1 //! Code related to stream reading
2
3 use crate::read::parse_extra_field;
4 use crate::read::readers::{make_crypto_reader, make_reader};
5 use crate::read::{
6 ZipFile, ZipFileData, ZipResult, central_header_to_zip_file_inner, make_symlink,
7 };
8 use crate::result::ZipError;
9 use crate::spec::{FixedSizeBlock, Magic, Pod, ZipCentralEntryBlock, ZipLocalEntryBlock, is_dir};
10 use indexmap::IndexMap;
11 use std::borrow::Cow;
12 use std::io::{self, Read};
13 use std::path::{Path, PathBuf};
14
15 /// Stream decoder for zip.
16 #[derive(Debug)]
17 pub struct ZipStreamReader<R>(R);
18
19 impl<R> ZipStreamReader<R> {
20 /// Create a new `ZipStreamReader`
21 pub const fn new(reader: R) -> Self {
22 Self(reader)
23 }
24 }
25
26 impl<R: Read> ZipStreamReader<R> {
27 fn parse_central_directory(&mut self) -> ZipResult<ZipStreamFileMetadata> {
28 // Give archive_offset and central_header_start dummy value 0, since
29 // they are not used in the output.
30 let archive_offset = 0;
31 let central_header_start = 0;
32
33 // Parse central header
34 let block = ZipCentralEntryBlock::parse(&mut self.0)?;
35 let file = central_header_to_zip_file_inner(
36 &mut self.0,
37 archive_offset,
38 central_header_start,
39 block,
40 )?;
41 Ok(ZipStreamFileMetadata(file))
42 }
43
44 /// Iterate over the stream and extract all file and their
45 /// metadata.
46 pub fn visit<V: ZipStreamVisitor>(mut self, visitor: &mut V) -> ZipResult<()> {
47 while let Some(mut file) = read_zipfile_from_stream(&mut self.0)? {
48 visitor.visit_file(&mut file)?;
49 }
50
51 while let Ok(metadata) = self.parse_central_directory() {
52 visitor.visit_additional_metadata(&metadata)?;
53 }
54
55 Ok(())
56 }
57
58 /// Extract a Zip archive into a directory, overwriting files if they
59 /// already exist. Paths are sanitized with [`ZipFile::enclosed_name`].
60 ///
61 /// Extraction is not atomic; If an error is encountered, some of the files
62 /// may be left on disk.
63 pub fn extract<P: AsRef<Path>>(self, directory: P) -> ZipResult<()> {
64 struct Extractor(PathBuf, IndexMap<Box<[u8]>, ()>);
65 impl ZipStreamVisitor for Extractor {
66 fn visit_file<R: Read>(&mut self, file: &mut ZipFile<'_, R>) -> ZipResult<()> {
67 self.1.insert(file.name_raw().into(), ());
68 let mut outpath = self.0.clone();
69 file.safe_prepare_path(&self.0, &mut outpath, None::<&(_, fn(&Path) -> bool)>)?;
70
71 if file.is_symlink() {
72 let mut target = Vec::with_capacity(file.size() as usize);
73 file.read_to_end(&mut target)?;
74 make_symlink(&outpath, &target, &self.1)?;
75 return Ok(());
76 }
77
78 if file.is_dir() {
79 fs::create_dir_all(&outpath)?;
80 } else {
81 let mut outfile = fs::File::create(&outpath)?;
82 io::copy(file, &mut outfile)?;
83 }
84
85 Ok(())
86 }
87
88 #[allow(unused)]
89 fn visit_additional_metadata(
90 &mut self,
91 metadata: &ZipStreamFileMetadata,
92 ) -> ZipResult<()> {
93 #[cfg(unix)]
94 {
95 use super::ZipError;
96 use std::os::unix::fs::PermissionsExt;
97 let filepath = metadata
98 .enclosed_name()
99 .ok_or(crate::result::invalid!("Invalid file path"))?;
100
101 let outpath = self.0.join(filepath);
102
103 if let Some(mode) = metadata.unix_mode() {
104 fs::set_permissions(outpath, fs::Permissions::from_mode(mode))?;
105 }
106 }
107
108 Ok(())
109 }
110 }
111 use std::fs;
112 fs::create_dir_all(&directory)?;
113 let directory = directory.as_ref().canonicalize()?;
114
115 self.visit(&mut Extractor(directory, IndexMap::new()))
116 }
117 }
118
119 /// Visitor for `ZipStreamReader`
120 pub trait ZipStreamVisitor {
121 /// * `file` - contains the content of the file and most of the metadata,
122 /// except:
123 /// - `comment`: set to an empty string
124 /// - `data_start`: set to 0
125 /// - `external_attributes`: `unix_mode()`: will return None
126 fn visit_file<R: Read>(&mut self, file: &mut ZipFile<'_, R>) -> ZipResult<()>;
127
128 /// This function is guaranteed to be called after all `visit_file`s.
129 ///
130 /// * `metadata` - Provides missing metadata in `visit_file`.
131 fn visit_additional_metadata(&mut self, metadata: &ZipStreamFileMetadata) -> ZipResult<()>;
132 }
133
134 /// Additional metadata for the file.
135 #[derive(Debug)]
136 pub struct ZipStreamFileMetadata(ZipFileData);
137
138 impl ZipStreamFileMetadata {
139 /// Get the name of the file
140 ///
141 /// # Warnings
142 ///
143 /// It is dangerous to use this name directly when extracting an archive.
144 /// It may contain an absolute path (`/etc/shadow`), or break out of the
145 /// current directory (`../runtime`). Carelessly writing to these paths
146 /// allows an attacker to craft a ZIP archive that will overwrite critical
147 /// files.
148 ///
149 /// You can use the [`ZipFile::enclosed_name`] method to validate the name
150 /// as a safe path.
151 pub fn name(&self) -> &str {
152 &self.0.file_name
153 }
154
155 /// Get the name of the file, in the raw (internal) byte representation.
156 ///
157 /// The encoding of this data is currently undefined.
158 pub fn name_raw(&self) -> &[u8] {
159 &self.0.file_name_raw
160 }
161
162 /// Rewrite the path, ignoring any path components with special meaning.
163 ///
164 /// - Absolute paths are made relative
165 /// - [`std::path::Component::ParentDir`]s are ignored
166 /// - Truncates the filename at a NULL byte
167 ///
168 /// This is appropriate if you need to be able to extract *something* from
169 /// any archive, but will easily misrepresent trivial paths like
170 /// `foo/../bar` as `foo/bar` (instead of `bar`). Because of this,
171 /// [`ZipFile::enclosed_name`] is the better option in most scenarios.
172 pub fn mangled_name(&self) -> PathBuf {
173 self.0.file_name_sanitized()
174 }
175
176 /// Ensure the file path is safe to use as a [`Path`].
177 ///
178 /// - It can't contain NULL bytes
179 /// - It can't resolve to a path outside the current directory
180 /// > `foo/../bar` is fine, `foo/../../bar` is not.
181 /// - It can't be an absolute path
182 ///
183 /// This will read well-formed ZIP files correctly, and is resistant
184 /// to path-based exploits. It is recommended over
185 /// [`ZipFile::mangled_name`].
186 pub fn enclosed_name(&self) -> Option<PathBuf> {
187 self.0.enclosed_name()
188 }
189
190 /// Returns whether the file is actually a directory
191 pub fn is_dir(&self) -> bool {
192 is_dir(self.name())
193 }
194
195 /// Returns whether the file is a regular file
196 pub fn is_file(&self) -> bool {
197 !self.is_dir()
198 }
199
200 /// Get the comment of the file
201 pub fn comment(&self) -> &str {
202 &self.0.file_comment
203 }
204
205 /// Get unix mode for the file
206 pub const fn unix_mode(&self) -> Option<u32> {
207 self.0.unix_mode()
208 }
209 }
210
211 /// Read `ZipFile` structures from a non-seekable reader.
212 ///
213 /// This is an alternative method to read a zip file. If possible, use the `ZipArchive` functions
214 /// as some information will be missing when reading this manner.
215 ///
216 /// Reads a file header from the start of the stream. Will return `Ok(Some(..))` if a file is
217 /// present at the start of the stream. Returns `Ok(None)` if the start of the central directory
218 /// is encountered. No more files should be read after this.
219 ///
220 /// The Drop implementation of `ZipFile` ensures that the reader will be correctly positioned after
221 /// the structure is done.
222 ///
223 /// Missing fields are:
224 /// * `comment`: set to an empty string
225 /// * `data_start`: set to 0
226 /// * `external_attributes`: `unix_mode()`: will return None
227 pub fn read_zipfile_from_stream<R: Read>(reader: &mut R) -> ZipResult<Option<ZipFile<'_, R>>> {
228 // We can't use the typical [`ZipLocalEntryBlock::parse`] method, as we follow separate code paths depending on the
229 // "magic" value (since the magic value will be from the central directory header if we've
230 // finished iterating over all the actual files).
231 /* TODO: smallvec? */
232
233 let mut magic_buf = [0; size_of::<u32>()];
234 reader.read_exact(&mut magic_buf)?;
235
236 match Magic::from_le_bytes(magic_buf) {
237 Magic::LOCAL_FILE_HEADER_SIGNATURE => (),
238 Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE => return Ok(None),
239 _ => return Err(ZipLocalEntryBlock::WRONG_MAGIC_ERROR),
240 }
241
242 let mut block = ZipLocalEntryBlock::zeroed();
243 reader.read_exact(block.as_bytes_mut())?;
244
245 let block = block.from_le();
246
247 let mut result = ZipFileData::from_local_block(block, reader)?;
248
249 match parse_extra_field(&mut result) {
250 Ok(..) | Err(ZipError::Io(..)) => {}
251 Err(e) => return Err(e),
252 }
253
254 let limit_reader = reader.take(result.compressed_size);
255 let crypto_reader = make_crypto_reader(&result, limit_reader, None, None)?;
256 let ZipFileData {
257 crc32,
258 uncompressed_size,
259 compression_method,
260 #[cfg(feature = "legacy-zip")]
261 flags,
262 ..
263 } = result;
264
265 Ok(Some(ZipFile {
266 data: Cow::Owned(result),
267 reader: make_reader(
268 compression_method,
269 uncompressed_size,
270 Some(crc32),
271 crypto_reader,
272 #[cfg(feature = "legacy-zip")]
273 flags,
274 )?,
275 }))
276 }
277
278 /// Read `ZipFile` from a non-seekable reader like [`read_zipfile_from_stream`] does, but assume the
279 /// given compressed size and don't read any further ahead than that.
280 pub fn read_zipfile_from_stream_with_compressed_size<R: io::Read>(
281 reader: &mut R,
282 compressed_size: u64,
283 ) -> ZipResult<Option<ZipFile<'_, R>>> {
284 let mut magic_buf = [0; size_of::<u32>()];
285 reader.read_exact(&mut magic_buf)?;
286
287 match Magic::from_le_bytes(magic_buf) {
288 Magic::LOCAL_FILE_HEADER_SIGNATURE => (),
289 Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE => return Ok(None),
290 _ => return Err(ZipLocalEntryBlock::WRONG_MAGIC_ERROR),
291 }
292
293 let mut block = ZipLocalEntryBlock::zeroed();
294 reader.read_exact(block.as_bytes_mut())?;
295
296 let block = block.from_le();
297
298 let mut result = ZipFileData::from_local_block(block, reader)?;
299 result.compressed_size = compressed_size;
300
301 if result.encrypted {
302 return Err(ZipError::UnsupportedArchive(
303 "Encrypted files are not supported",
304 ));
305 }
306
307 let limit_reader = reader.take(result.compressed_size);
308 let crypto_reader = make_crypto_reader(&result, limit_reader, None, None)?;
309 let ZipFileData {
310 crc32,
311 compression_method,
312 uncompressed_size,
313 #[cfg(feature = "legacy-zip")]
314 flags,
315 ..
316 } = result;
317
318 Ok(Some(ZipFile {
319 data: Cow::Owned(result),
320 reader: make_reader(
321 compression_method,
322 uncompressed_size,
323 Some(crc32),
324 crypto_reader,
325 #[cfg(feature = "legacy-zip")]
326 flags,
327 )?,
328 }))
329 }
330
331 #[cfg(test)]
332 mod tests {
333
334 use crate::read::ZipFile;
335 use crate::read::stream::{ZipStreamFileMetadata, ZipStreamReader, ZipStreamVisitor};
336 use crate::result::ZipResult;
337 use std::collections::BTreeSet;
338 use std::io::{Cursor, Read};
339
340 struct DummyVisitor;
341 impl ZipStreamVisitor for DummyVisitor {
342 fn visit_file<R: Read>(&mut self, _file: &mut ZipFile<'_, R>) -> ZipResult<()> {
343 Ok(())
344 }
345
346 fn visit_additional_metadata(
347 &mut self,
348 _metadata: &ZipStreamFileMetadata,
349 ) -> ZipResult<()> {
350 Ok(())
351 }
352 }
353
354 #[allow(dead_code)]
355 #[derive(Default, Debug, Eq, PartialEq)]
356 struct CounterVisitor(u64, u64);
357 impl ZipStreamVisitor for CounterVisitor {
358 fn visit_file<R: Read>(&mut self, _file: &mut ZipFile<'_, R>) -> ZipResult<()> {
359 self.0 += 1;
360 Ok(())
361 }
362
363 fn visit_additional_metadata(
364 &mut self,
365 _metadata: &ZipStreamFileMetadata,
366 ) -> ZipResult<()> {
367 self.1 += 1;
368 Ok(())
369 }
370 }
371
372 #[test]
373 fn invalid_offset() {
374 ZipStreamReader::new(Cursor::new(include_bytes!(
375 "../../tests/data/invalid_offset.zip"
376 )))
377 .visit(&mut DummyVisitor)
378 .unwrap_err();
379 }
380
381 #[test]
382 fn invalid_offset2() {
383 ZipStreamReader::new(Cursor::new(include_bytes!(
384 "../../tests/data/invalid_offset2.zip"
385 )))
386 .visit(&mut DummyVisitor)
387 .unwrap_err();
388 }
389
390 #[test]
391 fn zip_read_streaming_visitor() {
392 let reader =
393 ZipStreamReader::new(Cursor::new(include_bytes!("../../tests/data/mimetype.zip")));
394
395 #[derive(Default)]
396 struct V {
397 filenames: BTreeSet<Box<str>>,
398 }
399 impl ZipStreamVisitor for V {
400 fn visit_file<R: Read>(&mut self, file: &mut ZipFile<'_, R>) -> ZipResult<()> {
401 if file.is_file() {
402 self.filenames.insert(file.name().into());
403 }
404
405 Ok(())
406 }
407 fn visit_additional_metadata(
408 &mut self,
409 metadata: &ZipStreamFileMetadata,
410 ) -> ZipResult<()> {
411 if metadata.is_file() {
412 assert!(
413 self.filenames.contains(metadata.name()),
414 "{} is missing its file content",
415 metadata.name()
416 );
417 }
418
419 Ok(())
420 }
421 }
422
423 reader.visit(&mut V::default()).unwrap();
424 }
425
426 #[test]
427 fn file_and_dir_predicates() {
428 let reader = ZipStreamReader::new(Cursor::new(include_bytes!(
429 "../../tests/data/files_and_dirs.zip"
430 )));
431
432 #[derive(Default)]
433 struct V {
434 filenames: BTreeSet<Box<str>>,
435 }
436 impl ZipStreamVisitor for V {
437 fn visit_file<R: Read>(&mut self, file: &mut ZipFile<'_, R>) -> ZipResult<()> {
438 let full_name = file.enclosed_name().unwrap();
439 let file_name = full_name.file_name().unwrap().to_str().unwrap();
440 assert!(
441 (file_name.starts_with("dir") && file.is_dir())
442 || (file_name.starts_with("file") && file.is_file())
443 );
444
445 if file.is_file() {
446 self.filenames.insert(file.name().into());
447 }
448
449 Ok(())
450 }
451 fn visit_additional_metadata(
452 &mut self,
453 metadata: &ZipStreamFileMetadata,
454 ) -> ZipResult<()> {
455 if metadata.is_file() {
456 assert!(
457 self.filenames.contains(metadata.name()),
458 "{} is missing its file content",
459 metadata.name()
460 );
461 }
462
463 Ok(())
464 }
465 }
466
467 reader.visit(&mut V::default()).unwrap();
468 }
469
470 /// test case to ensure we don't preemptively over allocate based on the
471 /// declared number of files in the CDE of an invalid zip when the number of
472 /// files declared is more than the alleged offset in the CDE
473 #[test]
474 fn invalid_cde_number_of_files_allocation_smaller_offset() {
475 ZipStreamReader::new(Cursor::new(include_bytes!(
476 "../../tests/data/invalid_cde_number_of_files_allocation_smaller_offset.zip"
477 )))
478 .visit(&mut DummyVisitor)
479 .unwrap_err();
480 }
481
482 /// test case to ensure we don't preemptively over allocate based on the
483 /// declared number of files in the CDE of an invalid zip when the number of
484 /// files declared is less than the alleged offset in the CDE
485 #[test]
486 fn invalid_cde_number_of_files_allocation_greater_offset() {
487 ZipStreamReader::new(Cursor::new(include_bytes!(
488 "../../tests/data/invalid_cde_number_of_files_allocation_greater_offset.zip"
489 )))
490 .visit(&mut DummyVisitor)
491 .unwrap_err();
492 }
493
494 /// Symlinks being extracted shouldn't be followed out of the destination directory.
495 /// Only on little endian because we cannot use fs with miri CI
496 #[cfg(all(target_endian = "little", not(miri)))]
497 #[test]
498 fn test_cannot_symlink_outside_destination() -> ZipResult<()> {
499 use crate::ZipWriter;
500 use crate::write::SimpleFileOptions;
501 use std::fs::create_dir;
502 use tempfile::TempDir;
503
504 let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
505 writer.add_symlink("symlink/", "../dest-sibling/", SimpleFileOptions::default())?;
506 writer.start_file("symlink/dest-file", SimpleFileOptions::default())?;
507 let reader = ZipStreamReader::new(writer.finish()?);
508 let dest_parent = TempDir::with_prefix("stream__cannot_symlink_outside_destination")?;
509 let dest_sibling = dest_parent.path().join("dest-sibling");
510 create_dir(&dest_sibling)?;
511 let dest = dest_parent.path().join("dest");
512 create_dir(&dest)?;
513 assert!(reader.extract(dest).is_err());
514 assert!(!dest_sibling.join("dest-file").exists());
515 Ok(())
516 }
517
518 /// Only on little endian because we cannot use fs with miri CI
519 #[cfg(all(target_endian = "little", not(miri)))]
520 #[test]
521 fn test_can_create_destination() -> ZipResult<()> {
522 use tempfile::TempDir;
523
524 let v = include_bytes!("../../tests/data/mimetype.zip");
525 let reader = ZipStreamReader::new(v.as_ref());
526 let dest = TempDir::with_prefix("stream_test_can_create_destination").unwrap();
527 reader.extract(&dest)?;
528 assert!(dest.path().join("mimetype").exists());
529 Ok(())
530 }
531
532 #[test]
533 fn zip_read_streaming() {
534 use super::read_zipfile_from_stream;
535
536 let mut reader = Cursor::new(include_bytes!("../../tests/data/mimetype.zip"));
537 loop {
538 if read_zipfile_from_stream(&mut reader).unwrap().is_none() {
539 break;
540 }
541 }
542 }
543
544 #[test]
545 #[cfg(feature = "deflate")]
546 fn zip_read_streaming_compressed() {
547 use super::read_zipfile_from_stream_with_compressed_size;
548 use crate::ZipWriter;
549 use crate::write::SimpleFileOptions;
550 use std::io::Write;
551
552 let compression_method = crate::CompressionMethod::Deflated;
553 let options = SimpleFileOptions::default()
554 .compression_method(compression_method)
555 .unix_permissions(0o755);
556
557 let mut bytes = Vec::new();
558 let mut writer = ZipWriter::new(std::io::Cursor::new(&mut bytes));
559 writer.start_file("file.txt", options).unwrap();
560 write!(&mut writer, "{}", "test-".repeat(100)).unwrap();
561 writer.finish().unwrap();
562
563 let compressed_size = u32::from_le_bytes(bytes[18..22].try_into().unwrap());
564 let uncompressed_size = u32::from_le_bytes(bytes[22..26].try_into().unwrap());
565
566 assert_eq!(compressed_size, 14);
567 assert_eq!(uncompressed_size as usize, "test-".len() * 100);
568
569 let mut reader = Cursor::new(bytes);
570 loop {
571 if read_zipfile_from_stream_with_compressed_size(&mut reader, compressed_size as u64)
572 .unwrap()
573 .is_none()
574 {
575 break;
576 }
577 }
578 }
579 }