//! `in export --member --out `: copies one person's live files into a plain folder tree. //! //! The tree uses the names people gave their folders and files, so it needs no `in` to read. Every //! destination is built from one sanitized name per path component, so no name can climb out of the //! output directory: a separator or control character becomes `_`, and `.` and `..` are never used as //! a name. Each file is created with `create_new`, so an existing file or a planted symlink is never //! written through. Bytes are hashed while they are copied and checked against the database row; a //! mismatch removes the partial file and is reported. Trashed items are not exported. Folders are made //! with mode 0700 and files with mode 0600, so the copy is private whatever the umask says. use std::io::Write; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use futures_util::StreamExt; use sha2::{Digest, Sha256}; use crate::blob::BlobStore; use crate::error::{Error, Result}; use crate::names; use crate::store::Store; use crate::store::folders::Folder; /// Longest name written, in bytes. Longer names are cut at a character boundary. const MAX_NAME_BYTES: usize = 200; /// What an export wrote, and what it could not. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct ExportReport { /// Folders created. pub folders: u64, /// Files written and verified. pub files: u64, /// Bytes written. pub bytes: u64, /// Files whose bytes did not match their row, or whose blob was missing. Each is named. pub failed: Vec, } /// One path component made safe to write: no separators, no control characters, not `.` or `..`, not empty, /// and at most [`MAX_NAME_BYTES`] bytes. The result is always a single component. pub fn safe_component(name: &str) -> String { let replaced: String = name .chars() .map(|c| { if c == '/' || c == '\\' || c.is_control() { '_' } else { c } }) .collect(); let trimmed = replaced.trim(); let mut out = match trimmed { "" => "Untitled".to_owned(), "." | ".." => format!("_{trimmed}"), other => other.to_owned(), }; while out.len() > MAX_NAME_BYTES { out.pop(); } out } /// A path under `dir` named `name` that does not exist yet. Clashes get ` (2)`, ` (3)` and so on before /// the extension, as the drive does. `is_file` tells the postfix rule where the extension starts. fn free_path(dir: &Path, name: &str, is_file: bool) -> Result { let mut candidate = dir.join(name); let mut n = 2u32; while std::fs::symlink_metadata(&candidate).is_ok() { if n > crate::store::MAX_POSTFIX_TRIES { return Err(Error::Conflict("too_many_names".into())); } candidate = dir.join(safe_component(&names::postfix(name, n, is_file))); n += 1; } Ok(candidate) } /// Exports every live file and folder of `sub` under `out`. `out` is created if needed. Returns what was /// written. A failed file is reported, not fatal, so one bad blob does not stop the rest. pub async fn export_member( store: &Store, blobs: &dyn BlobStore, sub: &str, out: &Path, ) -> Result { std::fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(out)?; let root = std::fs::canonicalize(out)?; let mut report = ExportReport::default(); // Work list of (folder id, the directory it goes into). let mut pending: Vec<(Option, PathBuf)> = vec![(None, root.clone())]; while let Some((folder, dir)) = pending.pop() { let listing = store.list_children(sub, folder.as_deref()).await?; for Folder { id, name, .. } in listing.folders { let path = free_path(&dir, &safe_component(&name), false)?; std::fs::DirBuilder::new().mode(0o700).create(&path)?; ensure_inside(&root, &path)?; report.folders += 1; pending.push((Some(id), path)); } for file in listing.files { let path = free_path(&dir, &safe_component(&file.name), true)?; ensure_inside(&root, &path)?; match copy_file(blobs, &file.blob_key, &file.sha256, file.size, &path).await { Ok(bytes) => { report.files += 1; report.bytes += bytes; } Err(reason) => { tracing::warn!(file = %file.id, reason = %reason, "export: a file did not verify"); report.failed.push(file.id.clone()); } } } } Ok(report) } /// Refuses a destination that is not inside the output directory. Every path is built from safe /// components, so this is a second, independent check. fn ensure_inside(root: &Path, path: &Path) -> Result<()> { let parent = path .parent() .ok_or_else(|| Error::Invalid("export_path".into()))?; let parent = std::fs::canonicalize(parent)?; if !parent.starts_with(root) { return Err(Error::Forbidden("export_path".into())); } Ok(()) } /// Copies one blob to a new file at `path` and checks its size and hash. Returns the bytes written, or /// the reason it failed (the file is then removed). async fn copy_file( blobs: &dyn BlobStore, key: &str, sha256: &str, size: i64, path: &Path, ) -> std::result::Result { let size = u64::try_from(size).map_err(|_| "negative size".to_owned())?; let stored = blobs .size(key) .await .map_err(|e| e.to_string())? .ok_or_else(|| "blob missing".to_owned())?; if stored != size { return Err("blob size differs from the row".into()); } let mut file = std::fs::OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(path) .map_err(|e| e.to_string())?; let outcome = write_verified(blobs, key, size, sha256, &mut file).await; match outcome { Ok(()) => { file.sync_all().map_err(|e| e.to_string())?; Ok(size) } Err(reason) => { drop(file); // The file was created by this call, so removing it touches nothing else. let _ = std::fs::remove_file(path); Err(reason) } } } /// Streams the blob into `file` while hashing it, and fails when the hash differs from `sha256`. async fn write_verified( blobs: &dyn BlobStore, key: &str, size: u64, sha256: &str, file: &mut std::fs::File, ) -> std::result::Result<(), String> { let mut stream = blobs .open_range(key, 0, size) .await .map_err(|e| e.to_string())?; let mut hasher = Sha256::new(); while let Some(frame) = stream.next().await { let frame = frame.map_err(|e| e.to_string())?; hasher.update(&frame); file.write_all(&frame).map_err(|e| e.to_string())?; } if hex::encode(hasher.finalize()) != sha256 { return Err("hash differs from the row".into()); } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::blob::local::LocalBlobs; use crate::store::files::{NewFile, files_blob_key}; use crate::store::test_support::store_with_member; #[test] fn components_never_contain_separators_or_dot_names() { assert_eq!(safe_component("../../evil"), ".._.._evil"); assert_eq!(safe_component(".."), "_.."); assert_eq!(safe_component("."), "_."); assert_eq!(safe_component(""), "Untitled"); assert_eq!(safe_component("a\0b\nc"), "a_b_c"); assert!(!safe_component("x/y\\z").contains(['/', '\\'])); assert!(safe_component(&"é".repeat(300)).len() <= MAX_NAME_BYTES); } #[tokio::test] async fn export_never_writes_outside_the_output_directory() { let (dir, store) = store_with_member("ann").await; let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); let src = dir.path().join("src.bin"); std::fs::write(&src, b"hello").unwrap(); let id = "01hzexportfile0000000000001".to_owned(); blobs.put_file(&files_blob_key(&id), &src).await.unwrap(); let sha = hex::encode(Sha256::digest(b"hello")); store .insert_file(NewFile { id, owner: "ann".into(), folder: None, name: "../../evil".into(), mime: "text/plain".into(), size: 5, sha256: sha, staged_claims: 0, }) .await .unwrap(); let out = dir.path().join("out"); let report = export_member(&store, &blobs, "ann", &out).await.unwrap(); assert_eq!(report.files, 1); assert!(report.failed.is_empty()); // The drive's name rules already reduced `../../evil` to `evil`; the export must keep it inside `out`. assert!(!dir.path().join("evil").exists()); let written: Vec<_> = std::fs::read_dir(&out) .unwrap() .map(|e| e.unwrap().file_name()) .collect(); assert_eq!(written, vec![std::ffi::OsString::from("evil")]); } }