Debian Codegraph @

examples/file_extraction.rs

raw symbols SCIP
1 //! Demonstrates how to safely extract everything from a ZIP file.
2 //!
3 //! Extracting zip files from untrusted sources without proper sanitization
4 //! could be exploited by directory traversal attacks.
5 //! <https://en.wikipedia.org/wiki/Directory_traversal_attack#Archives>
6 //!
7 //! This example tries to minimize that risk by following the implementation from
8 //! Python's Standard Library.
9 //! <https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.extract>
10 //! <https://github.com/python/cpython/blob/ac0a19b62ae137c2c9f53fbba8ba3f769acf34dc/Lib/zipfile.py#L1662>
11 //!
12
13 use std::{
14 env::current_dir,
15 path::{Path, PathBuf},
16 };
17
18 use async_zip::base::read::seek::ZipFileReader;
19 use tokio::{
20 fs::{create_dir_all, File, OpenOptions},
21 io::BufReader,
22 };
23 use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
24
25 #[tokio::main]
26 async fn main() {
27 let archive = File::open("example.zip").await.expect("Failed to open zip file");
28 let out_dir = current_dir().expect("Failed to get current working directory");
29 unzip_file(archive, &out_dir).await;
30 }
31
32 /// Returns a relative path without reserved names, redundant separators, ".", or "..".
33 fn sanitize_file_path(path: &str) -> PathBuf {
34 // Replaces backwards slashes
35 path.replace('\\', "/")
36 // Sanitizes each component
37 .split('/')
38 .map(sanitize_filename::sanitize)
39 .collect()
40 }
41
42 /// Extracts everything from the ZIP archive to the output directory
43 async fn unzip_file(archive: File, out_dir: &Path) {
44 let archive = BufReader::new(archive).compat();
45 let mut reader = ZipFileReader::new(archive).await.expect("Failed to read zip file");
46 for index in 0..reader.file().entries().len() {
47 let entry = reader.file().entries().get(index).unwrap();
48 let path = out_dir.join(sanitize_file_path(entry.filename().as_str().unwrap()));
49 // If the filename of the entry ends with '/', it is treated as a directory.
50 // This is implemented by previous versions of this crate and the Python Standard Library.
51 // https://docs.rs/async_zip/0.0.8/src/async_zip/read/mod.rs.html#63-65
52 // https://github.com/python/cpython/blob/820ef62833bd2d84a141adedd9a05998595d6b6d/Lib/zipfile.py#L528
53 let entry_is_dir = entry.dir().unwrap();
54
55 let mut entry_reader = reader.reader_without_entry(index).await.expect("Failed to read ZipEntry");
56
57 if entry_is_dir {
58 // The directory may have been created if iteration is out of order.
59 if !path.exists() {
60 create_dir_all(&path).await.expect("Failed to create extracted directory");
61 }
62 } else {
63 // Creates parent directories. They may not exist if iteration is out of order
64 // or the archive does not contain directory entries.
65 let parent = path.parent().expect("A file entry should have parent directories");
66 if !parent.is_dir() {
67 create_dir_all(parent).await.expect("Failed to create parent directories");
68 }
69 let writer = OpenOptions::new()
70 .write(true)
71 .create_new(true)
72 .open(&path)
73 .await
74 .expect("Failed to create extracted file");
75 futures_lite::io::copy(&mut entry_reader, &mut writer.compat_write())
76 .await
77 .expect("Failed to copy to extracted file");
78
79 // Closes the file and manipulates its metadata here if you wish to preserve its metadata from the archive.
80 }
81 }
82 }