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