Debian Codegraph @

third_party/rust/zip/src/read/stream.rs

raw
1 use std::fs;
2 use std::io::{self, Read};
3 use std::path::{Path, PathBuf};
4
5 use super::{
6 central_header_to_zip_file_inner, read_zipfile_from_stream, ZipCentralEntryBlock, ZipError,
7 ZipFile, ZipFileData, ZipResult,
8 };
9 use crate::spec::FixedSizeBlock;
10
11 /// Stream decoder for zip.
12 #[derive(Debug)]
13 pub struct ZipStreamReader<R>(R);
14
15 impl<R> ZipStreamReader<R> {
16 /// Create a new ZipStreamReader
17 pub const fn new(reader: R) -> Self {
18 Self(reader)
19 }
20 }
21
22 impl<R: Read> ZipStreamReader<R> {
23 fn parse_central_directory(&mut self) -> ZipResult<ZipStreamFileMetadata> {
24 // Give archive_offset and central_header_start dummy value 0, since
25 // they are not used in the output.
26 let archive_offset = 0;
27 let central_header_start = 0;
28
29 // Parse central header
30 let block = ZipCentralEntryBlock::parse(&mut self.0)?;
31 let file = central_header_to_zip_file_inner(
32 &mut self.0,
33 archive_offset,
34 central_header_start,
35 block,
36 )?;
37 Ok(ZipStreamFileMetadata(file))
38 }
39
40 /// Iterate over the stream and extract all file and their
41 /// metadata.
42 pub fn visit<V: ZipStreamVisitor>(mut self, visitor: &mut V) -> ZipResult<()> {
43 while let Some(mut file) = read_zipfile_from_stream(&mut self.0)? {
44 visitor.visit_file(&mut file)?;
45 }
46
47 while let Ok(metadata) = self.parse_central_directory() {
48 visitor.visit_additional_metadata(&metadata)?;
49 }
50
51 Ok(())
52 }
53
54 /// Extract a Zip archive into a directory, overwriting files if they
55 /// already exist. Paths are sanitized with [`ZipFile::enclosed_name`].
56 ///
57 /// Extraction is not atomic; If an error is encountered, some of the files
58 /// may be left on disk.
59 pub fn extract<P: AsRef<Path>>(self, directory: P) -> ZipResult<()> {
60 struct Extractor<'a>(&'a Path);
61 impl ZipStreamVisitor for Extractor<'_> {
62 fn visit_file(&mut self, file: &mut ZipFile<'_>) -> ZipResult<()> {
63 let filepath = file
64 .enclosed_name()
65 .ok_or(ZipError::InvalidArchive("Invalid file path"))?;
66
67 let outpath = self.0.join(filepath);
68
69 if file.is_dir() {
70 fs::create_dir_all(&outpath)?;
71 } else {
72 if let Some(p) = outpath.parent() {
73 fs::create_dir_all(p)?;
74 }
75 let mut outfile = fs::File::create(&outpath)?;
76 io::copy(file, &mut outfile)?;
77 }
78
79 Ok(())
80 }
81
82 #[allow(unused)]
83 fn visit_additional_metadata(
84 &mut self,
85 metadata: &ZipStreamFileMetadata,
86 ) -> ZipResult<()> {
87 #[cfg(unix)]
88 {
89 let filepath = metadata
90 .enclosed_name()
91 .ok_or(ZipError::InvalidArchive("Invalid file path"))?;
92
93 let outpath = self.0.join(filepath);
94
95 use std::os::unix::fs::PermissionsExt;
96 if let Some(mode) = metadata.unix_mode() {
97 fs::set_permissions(outpath, fs::Permissions::from_mode(mode))?;
98 }
99 }
100
101 Ok(())
102 }
103 }
104
105 self.visit(&mut Extractor(directory.as_ref()))
106 }
107 }
108
109 /// Visitor for ZipStreamReader
110 pub trait ZipStreamVisitor {
111 /// * `file` - contains the content of the file and most of the metadata,
112 /// except:
113 /// - `comment`: set to an empty string
114 /// - `data_start`: set to 0
115 /// - `external_attributes`: `unix_mode()`: will return None
116 fn visit_file(&mut self, file: &mut ZipFile<'_>) -> ZipResult<()>;
117
118 /// This function is guranteed to be called after all `visit_file`s.
119 ///
120 /// * `metadata` - Provides missing metadata in `visit_file`.
121 fn visit_additional_metadata(&mut self, metadata: &ZipStreamFileMetadata) -> ZipResult<()>;
122 }
123
124 /// Additional metadata for the file.
125 #[derive(Debug)]
126 pub struct ZipStreamFileMetadata(ZipFileData);
127
128 impl ZipStreamFileMetadata {
129 /// Get the name of the file
130 ///
131 /// # Warnings
132 ///
133 /// It is dangerous to use this name directly when extracting an archive.
134 /// It may contain an absolute path (`/etc/shadow`), or break out of the
135 /// current directory (`../runtime`). Carelessly writing to these paths
136 /// allows an attacker to craft a ZIP archive that will overwrite critical
137 /// files.
138 ///
139 /// You can use the [`ZipFile::enclosed_name`] method to validate the name
140 /// as a safe path.
141 pub fn name(&self) -> &str {
142 &self.0.file_name
143 }
144
145 /// Get the name of the file, in the raw (internal) byte representation.
146 ///
147 /// The encoding of this data is currently undefined.
148 pub fn name_raw(&self) -> &[u8] {
149 &self.0.file_name_raw
150 }
151
152 /// Rewrite the path, ignoring any path components with special meaning.
153 ///
154 /// - Absolute paths are made relative
155 /// - [std::path::Component::ParentDir]s are ignored
156 /// - Truncates the filename at a NULL byte
157 ///
158 /// This is appropriate if you need to be able to extract *something* from
159 /// any archive, but will easily misrepresent trivial paths like
160 /// `foo/../bar` as `foo/bar` (instead of `bar`). Because of this,
161 /// [`ZipFile::enclosed_name`] is the better option in most scenarios.
162 pub fn mangled_name(&self) -> PathBuf {
163 self.0.file_name_sanitized()
164 }
165
166 /// Ensure the file path is safe to use as a [`Path`].
167 ///
168 /// - It can't contain NULL bytes
169 /// - It can't resolve to a path outside the current directory
170 /// > `foo/../bar` is fine, `foo/../../bar` is not.
171 /// - It can't be an absolute path
172 ///
173 /// This will read well-formed ZIP files correctly, and is resistant
174 /// to path-based exploits. It is recommended over
175 /// [`ZipFile::mangled_name`].
176 pub fn enclosed_name(&self) -> Option<PathBuf> {
177 self.0.enclosed_name()
178 }
179
180 /// Returns whether the file is actually a directory
181 pub fn is_dir(&self) -> bool {
182 self.name()
183 .chars()
184 .next_back()
185 .map_or(false, |c| c == '/' || c == '\\')
186 }
187
188 /// Returns whether the file is a regular file
189 pub fn is_file(&self) -> bool {
190 !self.is_dir()
191 }
192
193 /// Get the comment of the file
194 pub fn comment(&self) -> &str {
195 &self.0.file_comment
196 }
197
198 /// Get the starting offset of the data of the compressed file
199 pub fn data_start(&self) -> u64 {
200 *self.0.data_start.get().unwrap_or(&0)
201 }
202
203 /// Get unix mode for the file
204 pub const fn unix_mode(&self) -> Option<u32> {
205 self.0.unix_mode()
206 }
207 }
208
209 #[cfg(test)]
210 mod test {
211 use super::*;
212 use std::collections::BTreeSet;
213
214 struct DummyVisitor;
215 impl ZipStreamVisitor for DummyVisitor {
216 fn visit_file(&mut self, _file: &mut ZipFile<'_>) -> ZipResult<()> {
217 Ok(())
218 }
219
220 fn visit_additional_metadata(
221 &mut self,
222 _metadata: &ZipStreamFileMetadata,
223 ) -> ZipResult<()> {
224 Ok(())
225 }
226 }
227
228 #[derive(Default, Debug, Eq, PartialEq)]
229 struct CounterVisitor(u64, u64);
230 impl ZipStreamVisitor for CounterVisitor {
231 fn visit_file(&mut self, _file: &mut ZipFile<'_>) -> ZipResult<()> {
232 self.0 += 1;
233 Ok(())
234 }
235
236 fn visit_additional_metadata(
237 &mut self,
238 _metadata: &ZipStreamFileMetadata,
239 ) -> ZipResult<()> {
240 self.1 += 1;
241 Ok(())
242 }
243 }
244
245 #[test]
246 fn invalid_offset() {
247 ZipStreamReader::new(io::Cursor::new(include_bytes!(
248 "../../tests/data/invalid_offset.zip"
249 )))
250 .visit(&mut DummyVisitor)
251 .unwrap_err();
252 }
253
254 #[test]
255 fn invalid_offset2() {
256 ZipStreamReader::new(io::Cursor::new(include_bytes!(
257 "../../tests/data/invalid_offset2.zip"
258 )))
259 .visit(&mut DummyVisitor)
260 .unwrap_err();
261 }
262
263 #[test]
264 fn zip_read_streaming() {
265 let reader = ZipStreamReader::new(io::Cursor::new(include_bytes!(
266 "../../tests/data/mimetype.zip"
267 )));
268
269 #[derive(Default)]
270 struct V {
271 filenames: BTreeSet<Box<str>>,
272 }
273 impl ZipStreamVisitor for V {
274 fn visit_file(&mut self, file: &mut ZipFile<'_>) -> ZipResult<()> {
275 if file.is_file() {
276 self.filenames.insert(file.name().into());
277 }
278
279 Ok(())
280 }
281 fn visit_additional_metadata(
282 &mut self,
283 metadata: &ZipStreamFileMetadata,
284 ) -> ZipResult<()> {
285 if metadata.is_file() {
286 assert!(
287 self.filenames.contains(metadata.name()),
288 "{} is missing its file content",
289 metadata.name()
290 );
291 }
292
293 Ok(())
294 }
295 }
296
297 reader.visit(&mut V::default()).unwrap();
298 }
299
300 #[test]
301 fn file_and_dir_predicates() {
302 let reader = ZipStreamReader::new(io::Cursor::new(include_bytes!(
303 "../../tests/data/files_and_dirs.zip"
304 )));
305
306 #[derive(Default)]
307 struct V {
308 filenames: BTreeSet<Box<str>>,
309 }
310 impl ZipStreamVisitor for V {
311 fn visit_file(&mut self, file: &mut ZipFile<'_>) -> ZipResult<()> {
312 let full_name = file.enclosed_name().unwrap();
313 let file_name = full_name.file_name().unwrap().to_str().unwrap();
314 assert!(
315 (file_name.starts_with("dir") && file.is_dir())
316 || (file_name.starts_with("file") && file.is_file())
317 );
318
319 if file.is_file() {
320 self.filenames.insert(file.name().into());
321 }
322
323 Ok(())
324 }
325 fn visit_additional_metadata(
326 &mut self,
327 metadata: &ZipStreamFileMetadata,
328 ) -> ZipResult<()> {
329 if metadata.is_file() {
330 assert!(
331 self.filenames.contains(metadata.name()),
332 "{} is missing its file content",
333 metadata.name()
334 );
335 }
336
337 Ok(())
338 }
339 }
340
341 reader.visit(&mut V::default()).unwrap();
342 }
343
344 /// test case to ensure we don't preemptively over allocate based on the
345 /// declared number of files in the CDE of an invalid zip when the number of
346 /// files declared is more than the alleged offset in the CDE
347 #[test]
348 fn invalid_cde_number_of_files_allocation_smaller_offset() {
349 ZipStreamReader::new(io::Cursor::new(include_bytes!(
350 "../../tests/data/invalid_cde_number_of_files_allocation_smaller_offset.zip"
351 )))
352 .visit(&mut DummyVisitor)
353 .unwrap_err();
354 }
355
356 /// test case to ensure we don't preemptively over allocate based on the
357 /// declared number of files in the CDE of an invalid zip when the number of
358 /// files declared is less than the alleged offset in the CDE
359 #[test]
360 fn invalid_cde_number_of_files_allocation_greater_offset() {
361 ZipStreamReader::new(io::Cursor::new(include_bytes!(
362 "../../tests/data/invalid_cde_number_of_files_allocation_greater_offset.zip"
363 )))
364 .visit(&mut DummyVisitor)
365 .unwrap_err();
366 }
367 }