forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

export.rs252 lines, 9.1 KiBHistoryRawDownload
1//! `in export --member <sub> --out <dir>`: copies one person's live files into a plain folder tree.
2//!
3//! The tree uses the names people gave their folders and files, so it needs no `in` to read. Every
4//! destination is built from one sanitized name per path component, so no name can climb out of the
5//! output directory: a separator or control character becomes `_`, and `.` and `..` are never used as
6//! a name. Each file is created with `create_new`, so an existing file or a planted symlink is never
7//! written through. Bytes are hashed while they are copied and checked against the database row; a
8//! mismatch removes the partial file and is reported. Trashed items are not exported. Folders are made
9//! with mode 0700 and files with mode 0600, so the copy is private whatever the umask says.
10
11use std::io::Write;
12use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
13use std::path::{Path, PathBuf};
14
15use futures_util::StreamExt;
16use sha2::{Digest, Sha256};
17
18use crate::blob::BlobStore;
19use crate::error::{Error, Result};
20use crate::names;
21use crate::store::Store;
22use crate::store::folders::Folder;
23
24/// Longest name written, in bytes. Longer names are cut at a character boundary.
25const MAX_NAME_BYTES: usize = 200;
26
27/// What an export wrote, and what it could not.
28#[derive(Debug, Default, Clone, PartialEq, Eq)]
29pub struct ExportReport {
30 /// Folders created.
31 pub folders: u64,
32 /// Files written and verified.
33 pub files: u64,
34 /// Bytes written.
35 pub bytes: u64,
36 /// Files whose bytes did not match their row, or whose blob was missing. Each is named.
37 pub failed: Vec<String>,
38}
39
40/// One path component made safe to write: no separators, no control characters, not `.` or `..`, not empty,
41/// and at most [`MAX_NAME_BYTES`] bytes. The result is always a single component.
42pub fn safe_component(name: &str) -> String {
43 let replaced: String = name
44 .chars()
45 .map(|c| {
46 if c == '/' || c == '\\' || c.is_control() {
47 '_'
48 } else {
49 c
50 }
51 })
52 .collect();
53 let trimmed = replaced.trim();
54 let mut out = match trimmed {
55 "" => "Untitled".to_owned(),
56 "." | ".." => format!("_{trimmed}"),
57 other => other.to_owned(),
58 };
59 while out.len() > MAX_NAME_BYTES {
60 out.pop();
61 }
62 out
63}
64
65/// A path under `dir` named `name` that does not exist yet. Clashes get ` (2)`, ` (3)` and so on before
66/// the extension, as the drive does. `is_file` tells the postfix rule where the extension starts.
67fn free_path(dir: &Path, name: &str, is_file: bool) -> Result<PathBuf> {
68 let mut candidate = dir.join(name);
69 let mut n = 2u32;
70 while std::fs::symlink_metadata(&candidate).is_ok() {
71 if n > crate::store::MAX_POSTFIX_TRIES {
72 return Err(Error::Conflict("too_many_names".into()));
73 }
74 candidate = dir.join(safe_component(&names::postfix(name, n, is_file)));
75 n += 1;
76 }
77 Ok(candidate)
78}
79
80/// Exports every live file and folder of `sub` under `out`. `out` is created if needed. Returns what was
81/// written. A failed file is reported, not fatal, so one bad blob does not stop the rest.
82pub async fn export_member(
83 store: &Store,
84 blobs: &dyn BlobStore,
85 sub: &str,
86 out: &Path,
87) -> Result<ExportReport> {
88 std::fs::DirBuilder::new()
89 .recursive(true)
90 .mode(0o700)
91 .create(out)?;
92 let root = std::fs::canonicalize(out)?;
93 let mut report = ExportReport::default();
94 // Work list of (folder id, the directory it goes into).
95 let mut pending: Vec<(Option<String>, PathBuf)> = vec![(None, root.clone())];
96 while let Some((folder, dir)) = pending.pop() {
97 let listing = store.list_children(sub, folder.as_deref()).await?;
98 for Folder { id, name, .. } in listing.folders {
99 let path = free_path(&dir, &safe_component(&name), false)?;
100 std::fs::DirBuilder::new().mode(0o700).create(&path)?;
101 ensure_inside(&root, &path)?;
102 report.folders += 1;
103 pending.push((Some(id), path));
104 }
105 for file in listing.files {
106 let path = free_path(&dir, &safe_component(&file.name), true)?;
107 ensure_inside(&root, &path)?;
108 match copy_file(blobs, &file.blob_key, &file.sha256, file.size, &path).await {
109 Ok(bytes) => {
110 report.files += 1;
111 report.bytes += bytes;
112 }
113 Err(reason) => {
114 tracing::warn!(file = %file.id, reason = %reason, "export: a file did not verify");
115 report.failed.push(file.id.clone());
116 }
117 }
118 }
119 }
120 Ok(report)
121}
122
123/// Refuses a destination that is not inside the output directory. Every path is built from safe
124/// components, so this is a second, independent check.
125fn ensure_inside(root: &Path, path: &Path) -> Result<()> {
126 let parent = path
127 .parent()
128 .ok_or_else(|| Error::Invalid("export_path".into()))?;
129 let parent = std::fs::canonicalize(parent)?;
130 if !parent.starts_with(root) {
131 return Err(Error::Forbidden("export_path".into()));
132 }
133 Ok(())
134}
135
136/// Copies one blob to a new file at `path` and checks its size and hash. Returns the bytes written, or
137/// the reason it failed (the file is then removed).
138async fn copy_file(
139 blobs: &dyn BlobStore,
140 key: &str,
141 sha256: &str,
142 size: i64,
143 path: &Path,
144) -> std::result::Result<u64, String> {
145 let size = u64::try_from(size).map_err(|_| "negative size".to_owned())?;
146 let stored = blobs
147 .size(key)
148 .await
149 .map_err(|e| e.to_string())?
150 .ok_or_else(|| "blob missing".to_owned())?;
151 if stored != size {
152 return Err("blob size differs from the row".into());
153 }
154 let mut file = std::fs::OpenOptions::new()
155 .write(true)
156 .create_new(true)
157 .mode(0o600)
158 .open(path)
159 .map_err(|e| e.to_string())?;
160 let outcome = write_verified(blobs, key, size, sha256, &mut file).await;
161 match outcome {
162 Ok(()) => {
163 file.sync_all().map_err(|e| e.to_string())?;
164 Ok(size)
165 }
166 Err(reason) => {
167 drop(file);
168 // The file was created by this call, so removing it touches nothing else.
169 let _ = std::fs::remove_file(path);
170 Err(reason)
171 }
172 }
173}
174
175/// Streams the blob into `file` while hashing it, and fails when the hash differs from `sha256`.
176async fn write_verified(
177 blobs: &dyn BlobStore,
178 key: &str,
179 size: u64,
180 sha256: &str,
181 file: &mut std::fs::File,
182) -> std::result::Result<(), String> {
183 let mut stream = blobs
184 .open_range(key, 0, size)
185 .await
186 .map_err(|e| e.to_string())?;
187 let mut hasher = Sha256::new();
188 while let Some(frame) = stream.next().await {
189 let frame = frame.map_err(|e| e.to_string())?;
190 hasher.update(&frame);
191 file.write_all(&frame).map_err(|e| e.to_string())?;
192 }
193 if hex::encode(hasher.finalize()) != sha256 {
194 return Err("hash differs from the row".into());
195 }
196 Ok(())
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202 use crate::blob::local::LocalBlobs;
203 use crate::store::files::{NewFile, files_blob_key};
204 use crate::store::test_support::store_with_member;
205
206 #[test]
207 fn components_never_contain_separators_or_dot_names() {
208 assert_eq!(safe_component("../../evil"), ".._.._evil");
209 assert_eq!(safe_component(".."), "_..");
210 assert_eq!(safe_component("."), "_.");
211 assert_eq!(safe_component(""), "Untitled");
212 assert_eq!(safe_component("a\0b\nc"), "a_b_c");
213 assert!(!safe_component("x/y\\z").contains(['/', '\\']));
214 assert!(safe_component(&"é".repeat(300)).len() <= MAX_NAME_BYTES);
215 }
216
217 #[tokio::test]
218 async fn export_never_writes_outside_the_output_directory() {
219 let (dir, store) = store_with_member("ann").await;
220 let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap();
221 let src = dir.path().join("src.bin");
222 std::fs::write(&src, b"hello").unwrap();
223 let id = "01hzexportfile0000000000001".to_owned();
224 blobs.put_file(&files_blob_key(&id), &src).await.unwrap();
225 let sha = hex::encode(Sha256::digest(b"hello"));
226 store
227 .insert_file(NewFile {
228 id,
229 owner: "ann".into(),
230 folder: None,
231 name: "../../evil".into(),
232 mime: "text/plain".into(),
233 size: 5,
234 sha256: sha,
235 staged_claims: 0,
236 })
237 .await
238 .unwrap();
239
240 let out = dir.path().join("out");
241 let report = export_member(&store, &blobs, "ann", &out).await.unwrap();
242 assert_eq!(report.files, 1);
243 assert!(report.failed.is_empty());
244 // The drive's name rules already reduced `../../evil` to `evil`; the export must keep it inside `out`.
245 assert!(!dir.path().join("evil").exists());
246 let written: Vec<_> = std::fs::read_dir(&out)
247 .unwrap()
248 .map(|e| e.unwrap().file_name())
249 .collect();
250 assert_eq!(written, vec![std::ffi::OsString::from("evil")]);
251 }
252}