archive.rs
⎇
Raw
1//! Streaming archive builders (zip / tar / tar.gz / tar.zst).
2//!
3//! Everything writes directly into an `impl std::io::Write` sink — no temp
4//! files, no full in-memory buffering. The sink is typically a channel that
5//! feeds the HTTP response body, so bytes reach the client while the tree is
6//! still being walked.
7
8use std::io::{self, Write};
9use std::path::{Path, PathBuf};
10
11/// The archive formats offered for folder downloads.
12#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13pub enum ArchiveFormat {
14 Zip,
15 Tar,
16 TarGz,
17 TarZst,
18}
19
20impl ArchiveFormat {
21 /// Parse the `format` query parameter. Unknown values are rejected.
22 pub fn parse(s: &str) -> Option<Self> {
23 match s {
24 "zip" => Some(Self::Zip),
25 "tar" => Some(Self::Tar),
26 "tar.gz" | "tgz" => Some(Self::TarGz),
27 "tar.zst" | "tzst" => Some(Self::TarZst),
28 _ => None,
29 }
30 }
31
32 /// The file-name suffix for the produced archive.
33 pub fn extension(self) -> &'static str {
34 match self {
35 Self::Zip => "zip",
36 Self::Tar => "tar",
37 Self::TarGz => "tar.gz",
38 Self::TarZst => "tar.zst",
39 }
40 }
41
42 /// MIME type for the produced archive.
43 pub fn mime(self) -> &'static str {
44 match self {
45 Self::Zip => "application/zip",
46 Self::Tar => "application/x-tar",
47 Self::TarGz => "application/gzip",
48 Self::TarZst => "application/zstd",
49 }
50 }
51}
52
53/// Build `dir` (top-level entry named `top_name`) as `format`, streaming into
54/// `sink`. Blocking — call from `spawn_blocking`.
55pub fn build(
56 format: ArchiveFormat,
57 dir: &Path,
58 top_name: &str,
59 sink: impl Write,
60) -> io::Result<()> {
61 match format {
62 ArchiveFormat::Tar => build_tar(dir, top_name, sink).map(|_| ()),
63 ArchiveFormat::TarGz => {
64 // Level 1: the archive is streamed, so throughput beats ratio.
65 let enc = flate2::write::GzEncoder::new(sink, flate2::Compression::new(1));
66 build_tar(dir, top_name, enc)?.finish().map(|_| ())
67 }
68 ArchiveFormat::TarZst => {
69 let enc = zstd::stream::write::Encoder::new(sink, 3)?;
70 build_tar(dir, top_name, enc)?.finish().map(|_| ())
71 }
72 ArchiveFormat::Zip => build_zip(dir, top_name, sink),
73 }
74}
75
76fn mtime_secs(m: &std::fs::Metadata) -> u64 {
77 crate::fs::mtime_secs(m).unwrap_or(0).max(0) as u64
78}
79
80/// Cycle guard: a symlink loop would otherwise recurse forever. Real trees
81/// this deep are not worth archiving, so deeper levels are dropped.
82const MAX_DEPTH: usize = 64;
83
84/// Depth-first walk. Invokes `f(entry_name, abs_path, is_dir)` for the
85/// directory itself and every descendant. Directory entry names carry no
86/// trailing slash; each format appends it as needed. Deterministic order
87/// (case-insensitive name) so archives are reproducible.
88fn walk<F: FnMut(&str, &Path, bool) -> io::Result<()>>(
89 abs_dir: &Path,
90 entry_prefix: &str,
91 f: &mut F,
92) -> io::Result<()> {
93 // The canonical top directory is the containment boundary for the whole
94 // walk. Unlike browse and upload, nothing else re-checks it here.
95 let base = abs_dir.canonicalize()?;
96 walk_in(&base, &base, entry_prefix, 0, f)
97}
98
99fn walk_in<F: FnMut(&str, &Path, bool) -> io::Result<()>>(
100 base: &Path,
101 abs_dir: &Path,
102 entry_prefix: &str,
103 depth: usize,
104 f: &mut F,
105) -> io::Result<()> {
106 f(entry_prefix, abs_dir, true)?;
107 if depth >= MAX_DEPTH {
108 tracing::warn!(path = %abs_dir.display(), "archive: depth limit reached, subtree skipped");
109 return Ok(());
110 }
111 let rd = std::fs::read_dir(abs_dir)?;
112 let mut children: Vec<(String, PathBuf, bool)> = Vec::new();
113 for e in rd.flatten() {
114 let name = e.file_name().to_string_lossy().into_owned();
115 // Resolve symlinks: a link inside the tree may point outside it, and
116 // its contents must not end up in the archive. One bad entry is
117 // skipped instead of failing the whole download.
118 let Ok(p) = e.path().canonicalize() else {
119 tracing::warn!(path = %e.path().display(), "archive: unreadable entry skipped");
120 continue;
121 };
122 if !crate::fs::is_within_or_eq(base, &p) {
123 tracing::warn!(path = %e.path().display(), "archive: entry outside the archive root skipped");
124 continue;
125 }
126 let is_dir = p.is_dir();
127 children.push((name, p, is_dir));
128 }
129 children.sort_by_key(|c| c.0.to_lowercase());
130 for (name, p, is_dir) in children {
131 let child = format!("{entry_prefix}/{name}");
132 if is_dir {
133 walk_in(base, &p, &child, depth + 1, f)?;
134 } else {
135 f(&child, &p, false)?;
136 }
137 }
138 Ok(())
139}
140
141// ---------------------------------------------------------------------------
142// tar
143// ---------------------------------------------------------------------------
144
145fn tar_add<W: Write>(
146 tar: &mut tar::Builder<W>,
147 entry: &str,
148 abs: &Path,
149 is_dir: bool,
150) -> io::Result<()> {
151 let mut header = tar::Header::new_gnu();
152 let meta = std::fs::metadata(abs)?;
153 header.set_mode(if is_dir { 0o755 } else { 0o644 });
154 header.set_mtime(mtime_secs(&meta));
155 let name = if is_dir {
156 format!("{entry}/")
157 } else {
158 entry.to_string()
159 };
160 if is_dir {
161 header.set_entry_type(tar::EntryType::Directory);
162 header.set_size(0);
163 tar.append_data(&mut header, name, io::empty())?;
164 } else {
165 header.set_entry_type(tar::EntryType::Regular);
166 header.set_size(meta.len());
167 let f = std::fs::File::open(abs)?;
168 tar.append_data(&mut header, name, f)?;
169 }
170 Ok(())
171}
172
173/// Write the tar stream into `sink` and hand `sink` back, so a caller that
174/// wrapped it in a compressor can finish that compressor.
175fn build_tar<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<W> {
176 let mut tar = tar::Builder::new(sink);
177 let mut add = |entry: &str, abs: &Path, is_dir: bool| -> io::Result<()> {
178 tar_add(&mut tar, entry, abs, is_dir)
179 };
180 walk(dir, top, &mut add)?;
181 tar.finish()?;
182 tar.into_inner()
183}
184
185// ---------------------------------------------------------------------------
186// zip
187// ---------------------------------------------------------------------------
188
189fn build_zip<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<()> {
190 // Streaming mode: no `Seek` needed, entries use data descriptors.
191 let mut zip = zip::write::ZipWriter::new_stream(sink);
192 let mut add = |entry: &str, abs: &Path, is_dir: bool| -> io::Result<()> {
193 let opts = zip::write::SimpleFileOptions::default();
194 let name = if is_dir {
195 format!("{entry}/")
196 } else {
197 entry.to_string()
198 };
199 if is_dir {
200 zip.add_directory(&name, opts)?;
201 } else {
202 zip.start_file(&name, opts)?;
203 let mut f = std::fs::File::open(abs)?;
204 io::copy(&mut f, &mut zip)?;
205 }
206 Ok(())
207 };
208 walk(dir, top, &mut add)?;
209 zip.finish()?;
210 Ok(())
211}
212
213// ---------------------------------------------------------------------------
214// Tests
215// ---------------------------------------------------------------------------
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use std::collections::BTreeMap;
221 use std::io::Read as _;
222
223 fn sample_dir() -> (tempfile::TempDir, PathBuf) {
224 let tmp = tempfile::tempdir().unwrap();
225 let dir = tmp.path().to_path_buf();
226 std::fs::write(dir.join("alpha.txt"), "alpha content").unwrap();
227 std::fs::create_dir_all(dir.join("sub/deep")).unwrap();
228 std::fs::create_dir(dir.join("empty-dir")).unwrap();
229 std::fs::write(dir.join("sub/beta.txt"), "beta").unwrap();
230 std::fs::write(
231 dir.join("sub/deep/gamma.bin"),
232 (0u8..=255).collect::<Vec<_>>(),
233 )
234 .unwrap();
235 (tmp, dir)
236 }
237
238 fn build_to_mem(fmt: ArchiveFormat, dir: &Path) -> Vec<u8> {
239 let mut out: Vec<u8> = Vec::new();
240 build(fmt, dir, "top", &mut out).unwrap();
241 out
242 }
243
244 #[test]
245 fn format_parsing() {
246 assert_eq!(ArchiveFormat::parse("zip"), Some(ArchiveFormat::Zip));
247 assert_eq!(ArchiveFormat::parse("tar"), Some(ArchiveFormat::Tar));
248 assert_eq!(ArchiveFormat::parse("tar.gz"), Some(ArchiveFormat::TarGz));
249 assert_eq!(ArchiveFormat::parse("tgz"), Some(ArchiveFormat::TarGz));
250 assert_eq!(ArchiveFormat::parse("tar.zst"), Some(ArchiveFormat::TarZst));
251 assert_eq!(ArchiveFormat::parse("tzst"), Some(ArchiveFormat::TarZst));
252 for bad in [
253 "", "ZIP", "gzip", "rar", "7z", "tar.bz2", "tar.xz", "tar.zstx", "tar.gz ",
254 ] {
255 assert_eq!(ArchiveFormat::parse(bad), None, "{bad:?}");
256 }
257 }
258
259 #[test]
260 fn format_metadata() {
261 assert_eq!(ArchiveFormat::Zip.extension(), "zip");
262 assert_eq!(ArchiveFormat::Zip.mime(), "application/zip");
263 assert_eq!(ArchiveFormat::Tar.extension(), "tar");
264 assert_eq!(ArchiveFormat::Tar.mime(), "application/x-tar");
265 assert_eq!(ArchiveFormat::TarGz.extension(), "tar.gz");
266 assert_eq!(ArchiveFormat::TarGz.mime(), "application/gzip");
267 assert_eq!(ArchiveFormat::TarZst.extension(), "tar.zst");
268 assert_eq!(ArchiveFormat::TarZst.mime(), "application/zstd");
269 }
270
271 /// Read a tar stream into a name → content map (files only).
272 fn tar_map<R: std::io::Read>(r: R) -> BTreeMap<String, Vec<u8>> {
273 let mut map = BTreeMap::new();
274 for entry in tar::Archive::new(r).entries().unwrap() {
275 let mut e = entry.unwrap();
276 if !e.header().entry_type().is_file() {
277 continue;
278 }
279 let name = e.path().unwrap().to_string_lossy().into_owned();
280 let mut buf = Vec::new();
281 e.read_to_end(&mut buf).unwrap();
282 map.insert(name, buf);
283 }
284 map
285 }
286 fn expected_map() -> BTreeMap<String, Vec<u8>> {
287 let mut m = BTreeMap::new();
288 m.insert("top/alpha.txt".to_string(), b"alpha content".to_vec());
289 m.insert("top/sub/beta.txt".to_string(), b"beta".to_vec());
290 m.insert("top/sub/deep/gamma.bin".to_string(), (0u8..=255).collect());
291 m
292 }
293
294 #[test]
295 fn zip_round_trip() {
296 let (_tmp, dir) = sample_dir();
297 let bytes = build_to_mem(ArchiveFormat::Zip, &dir);
298 let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
299
300 let mut map = BTreeMap::new();
301 for i in 0..zip.len() {
302 let mut f = zip.by_index(i).unwrap();
303 let name = f.name().unwrap().to_string();
304 if name.ends_with('/') {
305 continue; // directory entry
306 }
307 let mut buf = Vec::new();
308 f.read_to_end(&mut buf).unwrap();
309 map.insert(name, buf);
310 }
311 assert_eq!(map, expected_map());
312
313 // Directory entries are present and the order is deterministic.
314 let names: Vec<String> = zip.file_names().map(|n| n.unwrap().to_string()).collect();
315 let has = |n: &str| names.iter().any(|x| x == n);
316 assert!(has("top/"));
317 assert!(has("top/sub/"));
318 assert!(has("top/sub/deep/"));
319 assert!(has("top/empty-dir/"));
320 let mut sorted = names.clone();
321 sorted.sort_unstable();
322 assert_eq!(names, sorted);
323 }
324
325 #[test]
326 fn tar_round_trip() {
327 let (_tmp, dir) = sample_dir();
328 let bytes = build_to_mem(ArchiveFormat::Tar, &dir);
329 let map = tar_map(std::io::Cursor::new(bytes));
330 assert_eq!(map, expected_map());
331 }
332
333 #[test]
334 fn tar_gz_round_trip() {
335 let (_tmp, dir) = sample_dir();
336 let bytes = build_to_mem(ArchiveFormat::TarGz, &dir);
337 let gz = flate2::read::GzDecoder::new(std::io::Cursor::new(bytes));
338 let map = tar_map(gz);
339 assert_eq!(map, expected_map());
340 }
341
342 #[test]
343 fn tar_zst_round_trip() {
344 let (_tmp, dir) = sample_dir();
345 let bytes = build_to_mem(ArchiveFormat::TarZst, &dir);
346 let dec = zstd::stream::read::Decoder::new(std::io::Cursor::new(bytes)).unwrap();
347 let map = tar_map(dec);
348 assert_eq!(map, expected_map());
349 }
350
351 #[test]
352 fn walk_is_sorted_case_insensitively() {
353 let tmp = tempfile::tempdir().unwrap();
354 let dir = tmp.path();
355 for name in ["Zeta", "alpha", "Beta", "a.txt", "B.txt"] {
356 if name.ends_with(".txt") {
357 std::fs::write(dir.join(name), name).unwrap();
358 } else {
359 std::fs::create_dir(dir.join(name)).unwrap();
360 }
361 }
362 let mut order = Vec::new();
363 walk(dir, "top", &mut |name, _p, _is_dir| {
364 order.push(name.to_string());
365 Ok(())
366 })
367 .unwrap();
368 assert_eq!(
369 order,
370 vec![
371 "top",
372 "top/a.txt",
373 "top/alpha",
374 "top/B.txt",
375 "top/Beta",
376 "top/Zeta"
377 ]
378 );
379 }
380
381 #[test]
382 fn build_fails_on_missing_dir() {
383 let mut out = Vec::new();
384 let r = build(
385 ArchiveFormat::Zip,
386 Path::new("/nonexistent-filebrowser-ng-test-dir"),
387 "top",
388 &mut out,
389 );
390 assert!(r.is_err());
391 // The tar path fails too.
392 let mut out = Vec::new();
393 let r = build(
394 ArchiveFormat::Tar,
395 Path::new("/nonexistent-filebrowser-ng-test-dir"),
396 "top",
397 &mut out,
398 );
399 assert!(r.is_err());
400 }
401}
402