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 if is_dir {
156 header.set_entry_type(tar::EntryType::Directory);
157 header.set_size(0);
158 tar.append_data(&mut header, format!("{entry}/"), io::empty())
159 } else {
160 header.set_entry_type(tar::EntryType::Regular);
161 header.set_size(meta.len());
162 tar.append_data(&mut header, entry, std::fs::File::open(abs)?)
163 }
164}
165
166/// Write the tar stream into `sink` and hand `sink` back, so a caller that
167/// wrapped it in a compressor can finish that compressor.
168fn build_tar<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<W> {
169 let mut tar = tar::Builder::new(sink);
170 walk(dir, top, &mut |entry: &str, abs: &Path, is_dir: bool| {
171 tar_add(&mut tar, entry, abs, is_dir)
172 })?;
173 tar.finish()?;
174 tar.into_inner()
175}
176
177// ---------------------------------------------------------------------------
178// zip
179// ---------------------------------------------------------------------------
180
181fn build_zip<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<()> {
182 // Streaming mode: no `Seek` needed, entries use data descriptors.
183 let mut zip = zip::write::ZipWriter::new_stream(sink);
184 let mut add = |entry: &str, abs: &Path, is_dir: bool| -> io::Result<()> {
185 let opts = zip::write::SimpleFileOptions::default();
186 let name = if is_dir {
187 format!("{entry}/")
188 } else {
189 entry.to_string()
190 };
191 if is_dir {
192 zip.add_directory(&name, opts)?;
193 } else {
194 zip.start_file(&name, opts)?;
195 let mut f = std::fs::File::open(abs)?;
196 io::copy(&mut f, &mut zip)?;
197 }
198 Ok(())
199 };
200 walk(dir, top, &mut add)?;
201 zip.finish()?;
202 Ok(())
203}
204
205// ---------------------------------------------------------------------------
206// Tests
207// ---------------------------------------------------------------------------
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212 use std::collections::BTreeMap;
213 use std::io::Read as _;
214
215 fn sample_dir() -> (tempfile::TempDir, PathBuf) {
216 let tmp = tempfile::tempdir().unwrap();
217 let dir = tmp.path().to_path_buf();
218 std::fs::write(dir.join("alpha.txt"), "alpha content").unwrap();
219 std::fs::create_dir_all(dir.join("sub/deep")).unwrap();
220 std::fs::create_dir(dir.join("empty-dir")).unwrap();
221 std::fs::write(dir.join("sub/beta.txt"), "beta").unwrap();
222 std::fs::write(
223 dir.join("sub/deep/gamma.bin"),
224 (0u8..=255).collect::<Vec<_>>(),
225 )
226 .unwrap();
227 (tmp, dir)
228 }
229
230 fn build_to_mem(fmt: ArchiveFormat, dir: &Path) -> Vec<u8> {
231 let mut out: Vec<u8> = Vec::new();
232 build(fmt, dir, "top", &mut out).unwrap();
233 out
234 }
235
236 #[test]
237 fn format_parsing() {
238 assert_eq!(ArchiveFormat::parse("zip"), Some(ArchiveFormat::Zip));
239 assert_eq!(ArchiveFormat::parse("tar"), Some(ArchiveFormat::Tar));
240 assert_eq!(ArchiveFormat::parse("tar.gz"), Some(ArchiveFormat::TarGz));
241 assert_eq!(ArchiveFormat::parse("tgz"), Some(ArchiveFormat::TarGz));
242 assert_eq!(ArchiveFormat::parse("tar.zst"), Some(ArchiveFormat::TarZst));
243 assert_eq!(ArchiveFormat::parse("tzst"), Some(ArchiveFormat::TarZst));
244 for bad in [
245 "", "ZIP", "gzip", "rar", "7z", "tar.bz2", "tar.xz", "tar.zstx", "tar.gz ",
246 ] {
247 assert_eq!(ArchiveFormat::parse(bad), None, "{bad:?}");
248 }
249 }
250
251 #[test]
252 fn format_metadata() {
253 assert_eq!(ArchiveFormat::Zip.extension(), "zip");
254 assert_eq!(ArchiveFormat::Zip.mime(), "application/zip");
255 assert_eq!(ArchiveFormat::Tar.extension(), "tar");
256 assert_eq!(ArchiveFormat::Tar.mime(), "application/x-tar");
257 assert_eq!(ArchiveFormat::TarGz.extension(), "tar.gz");
258 assert_eq!(ArchiveFormat::TarGz.mime(), "application/gzip");
259 assert_eq!(ArchiveFormat::TarZst.extension(), "tar.zst");
260 assert_eq!(ArchiveFormat::TarZst.mime(), "application/zstd");
261 }
262
263 /// Read a tar stream into a name → content map (files only).
264 fn tar_map<R: std::io::Read>(r: R) -> BTreeMap<String, Vec<u8>> {
265 let mut map = BTreeMap::new();
266 for entry in tar::Archive::new(r).entries().unwrap() {
267 let mut e = entry.unwrap();
268 if !e.header().entry_type().is_file() {
269 continue;
270 }
271 let name = e.path().unwrap().to_string_lossy().into_owned();
272 let mut buf = Vec::new();
273 e.read_to_end(&mut buf).unwrap();
274 map.insert(name, buf);
275 }
276 map
277 }
278 fn expected_map() -> BTreeMap<String, Vec<u8>> {
279 let mut m = BTreeMap::new();
280 m.insert("top/alpha.txt".to_string(), b"alpha content".to_vec());
281 m.insert("top/sub/beta.txt".to_string(), b"beta".to_vec());
282 m.insert("top/sub/deep/gamma.bin".to_string(), (0u8..=255).collect());
283 m
284 }
285
286 #[test]
287 fn zip_round_trip() {
288 let (_tmp, dir) = sample_dir();
289 let bytes = build_to_mem(ArchiveFormat::Zip, &dir);
290 let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
291
292 let mut map = BTreeMap::new();
293 for i in 0..zip.len() {
294 let mut f = zip.by_index(i).unwrap();
295 let name = f.name().unwrap().to_string();
296 if name.ends_with('/') {
297 continue; // directory entry
298 }
299 let mut buf = Vec::new();
300 f.read_to_end(&mut buf).unwrap();
301 map.insert(name, buf);
302 }
303 assert_eq!(map, expected_map());
304
305 // Directory entries are present and the order is deterministic.
306 let names: Vec<String> = zip.file_names().map(|n| n.unwrap().to_string()).collect();
307 let has = |n: &str| names.iter().any(|x| x == n);
308 assert!(has("top/"));
309 assert!(has("top/sub/"));
310 assert!(has("top/sub/deep/"));
311 assert!(has("top/empty-dir/"));
312 let mut sorted = names.clone();
313 sorted.sort_unstable();
314 assert_eq!(names, sorted);
315 }
316
317 #[test]
318 fn tar_round_trip() {
319 let (_tmp, dir) = sample_dir();
320 let bytes = build_to_mem(ArchiveFormat::Tar, &dir);
321 let map = tar_map(std::io::Cursor::new(bytes));
322 assert_eq!(map, expected_map());
323 }
324
325 #[test]
326 fn tar_gz_round_trip() {
327 let (_tmp, dir) = sample_dir();
328 let bytes = build_to_mem(ArchiveFormat::TarGz, &dir);
329 let gz = flate2::read::GzDecoder::new(std::io::Cursor::new(bytes));
330 let map = tar_map(gz);
331 assert_eq!(map, expected_map());
332 }
333
334 #[test]
335 fn tar_zst_round_trip() {
336 let (_tmp, dir) = sample_dir();
337 let bytes = build_to_mem(ArchiveFormat::TarZst, &dir);
338 let dec = zstd::stream::read::Decoder::new(std::io::Cursor::new(bytes)).unwrap();
339 let map = tar_map(dec);
340 assert_eq!(map, expected_map());
341 }
342
343 #[test]
344 fn walk_is_sorted_case_insensitively() {
345 let tmp = tempfile::tempdir().unwrap();
346 let dir = tmp.path();
347 for name in ["Zeta", "alpha", "Beta", "a.txt", "B.txt"] {
348 if name.ends_with(".txt") {
349 std::fs::write(dir.join(name), name).unwrap();
350 } else {
351 std::fs::create_dir(dir.join(name)).unwrap();
352 }
353 }
354 let mut order = Vec::new();
355 walk(dir, "top", &mut |name, _p, _is_dir| {
356 order.push(name.to_string());
357 Ok(())
358 })
359 .unwrap();
360 assert_eq!(
361 order,
362 vec![
363 "top",
364 "top/a.txt",
365 "top/alpha",
366 "top/B.txt",
367 "top/Beta",
368 "top/Zeta"
369 ]
370 );
371 }
372
373 #[test]
374 fn build_fails_on_missing_dir() {
375 let mut out = Vec::new();
376 let r = build(
377 ArchiveFormat::Zip,
378 Path::new("/nonexistent-filebrowser-ng-test-dir"),
379 "top",
380 &mut out,
381 );
382 assert!(r.is_err());
383 // The tar path fails too.
384 let mut out = Vec::new();
385 let r = build(
386 ArchiveFormat::Tar,
387 Path::new("/nonexistent-filebrowser-ng-test-dir"),
388 "top",
389 &mut out,
390 );
391 assert!(r.is_err());
392 }
393}
394