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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::{
io::Write,
path::{Component, Path, PathBuf},
};
use async_zip::read::stream::{Reading, ZipFileReader};
use bytes::{Bytes, BytesMut};
use futures_lite::future::try_zip as try_join;
use thiserror::Error as ThisError;
use tokio::{
io::{AsyncRead, AsyncReadExt, Take},
sync::mpsc,
};
use super::{DownloadError, ExtractedFiles};
use crate::utils::asyncify;
#[derive(Debug, ThisError)]
enum ZipErrorInner {
#[error(transparent)]
Inner(#[from] async_zip::error::ZipError),
#[error("Invalid file path: {0}")]
InvalidFilePath(Box<str>),
}
#[derive(Debug, ThisError)]
#[error(transparent)]
pub struct ZipError(#[from] ZipErrorInner);
impl ZipError {
pub(super) fn from_inner(err: async_zip::error::ZipError) -> Self {
Self(ZipErrorInner::Inner(err))
}
}
pub(super) async fn extract_zip_entry<R>(
zip_reader: &mut ZipFileReader<Reading<'_, Take<R>>>,
path: &Path,
buf: &mut BytesMut,
extracted_files: &mut ExtractedFiles,
) -> Result<(), DownloadError>
where
R: AsyncRead + Unpin + Send + Sync,
{
let raw_filename = zip_reader.entry().filename();
let filename = check_filename_and_normalize(raw_filename)
.ok_or_else(|| ZipError(ZipErrorInner::InvalidFilePath(raw_filename.into())))?;
let outpath = path.join(&filename);
#[cfg_attr(not(unix), allow(unused_mut))]
let mut perms = None;
let is_dir = raw_filename.ends_with('/');
#[cfg(unix)]
{
use std::{fs::Permissions, os::unix::fs::PermissionsExt};
if let Some(mode) = zip_reader.entry().unix_permissions() {
let mode: u16 = mode | if is_dir { 0o700 } else { 0o400 };
perms = Some(Permissions::from_mode(mode as u32));
}
}
if is_dir {
extracted_files.add_dir(&filename);
asyncify(move || {
std::fs::create_dir_all(&outpath)?;
if let Some(perms) = perms {
std::fs::set_permissions(&outpath, perms)?;
}
Ok(())
})
.await?;
} else {
extracted_files.add_file(&filename);
let (tx, mut rx) = mpsc::channel::<Bytes>(5);
let write_task = asyncify(move || {
if let Some(p) = outpath.parent() {
std::fs::create_dir_all(p)?;
}
let mut outfile = std::fs::File::create(&outpath)?;
while let Some(bytes) = rx.blocking_recv() {
outfile.write_all(&bytes)?;
}
outfile.flush()?;
if let Some(perms) = perms {
outfile.set_permissions(perms)?;
}
Ok(())
});
let read_task = copy_file_to_mpsc(zip_reader.reader(), tx, buf);
try_join(
async move { write_task.await.map_err(From::from) },
async move {
read_task
.await
.map_err(ZipError::from_inner)
.map_err(DownloadError::from)
},
)
.await?;
}
Ok(())
}
async fn copy_file_to_mpsc<R: AsyncRead>(
entry_reader: &mut R,
tx: mpsc::Sender<Bytes>,
buf: &mut BytesMut,
) -> Result<(), async_zip::error::ZipError>
where
R: AsyncRead + Unpin + Send + Sync,
{
while entry_reader.read_buf(buf).await? != 0 {
buf.reserve(4096);
if tx.send(buf.split().freeze()).await.is_err() {
break;
}
}
Ok(())
}
fn check_filename_and_normalize(filename: &str) -> Option<PathBuf> {
if filename.contains('\0') {
return None;
}
let mut path = PathBuf::new();
for component in Path::new(filename).components() {
match component {
Component::Prefix(_) | Component::RootDir => return None,
Component::CurDir => (),
Component::ParentDir => {
if !path.pop() {
return None;
}
}
Component::Normal(c) => path.push(c),
}
}
Some(path)
}