Skip to main content

zaun_client/
files.rs

1//! Attachment files on this side: staging an upload inside the SimpleX folder (it only sends
2//! files from there), measuring, and delivering a checked download under a safe name.
3#![cfg_attr(
4    target_arch = "wasm32",
5    allow(dead_code, reason = "attachments are native-only for now")
6)]
7
8use std::fs::{self, File};
9use std::io::{self, Read};
10use std::path::{Path, PathBuf};
11
12use simplex_client::types::has_file_servers;
13use simplex_client::xftp::{XftpServer, preset_servers};
14use zaun_community_protocol::command::object::{Attachment, UploadFailure};
15use zaun_community_protocol::command::session::HostAttachments;
16use zaun_community_protocol::crypto::{Sha3Hasher, content_hash};
17
18use crate::error::{Error, Result};
19
20/// The XFTP servers `simplex-client` uploads to for `relays`: the `xftp://` ones, else the
21/// official ones when no `smp://` relay is named, else none (its `servers_of`).
22#[must_use]
23pub(crate) fn upload_servers(relays: &[String]) -> Vec<XftpServer> {
24    let own: Vec<XftpServer> = relays
25        .iter()
26        .filter(|r| r.starts_with("xftp://"))
27        .filter_map(|r| r.parse().ok())
28        .collect();
29    if own.is_empty() && has_file_servers(relays) {
30        preset_servers()
31    } else {
32        own
33    }
34}
35
36/// Refuses an upload the host would never receive: larger than it takes, or bound for a
37/// file server it does not download from. Each chunk goes to any of `ours`, so every one of
38/// them must be in the host's list (compared as file descriptions name them: no password).
39pub(crate) fn check_upload(ours: &[XftpServer], host: &HostAttachments, size: u64) -> Result<()> {
40    if size > host.max_bytes {
41        return Err(Error::Transfer("the file is larger than the host takes"));
42    }
43    let theirs: Vec<XftpServer> = host
44        .file_servers
45        .iter()
46        .filter_map(|s| s.parse::<XftpServer>().ok())
47        .map(|s| s.without_auth())
48        .collect();
49    if ours.is_empty() || !ours.iter().all(|s| theirs.contains(&s.without_auth())) {
50        return Err(Error::Transfer(
51            "this client uploads to file servers the host does not download from",
52        ));
53    }
54    Ok(())
55}
56
57/// What an upload's `failure` means for the uploader.
58#[must_use]
59pub(crate) const fn failure_text(failure: Option<UploadFailure>) -> &'static str {
60    match failure {
61        Some(UploadFailure::FileServer) => {
62            "the host does not download from the file server the upload went to"
63        }
64        Some(UploadFailure::Transfer) => "the host could not fetch the file",
65        Some(UploadFailure::Mismatch) => "the host received different bytes than declared",
66        Some(UploadFailure::NotReceived) => "the file did not reach the host in time",
67        None => "the host did not keep the file",
68    }
69}
70
71/// The staging folder under the client's directory.
72pub(crate) const UPLOADS: &str = "zaun-uploads";
73
74/// The size and SHA3-256 of the file at `path`.
75///
76/// # Errors
77/// I/O errors.
78pub fn measure(path: &Path) -> io::Result<(u64, [u8; 32])> {
79    let mut file = File::open(path)?;
80    let mut hasher = Sha3Hasher::new();
81    let mut buf = vec![0u8; 64 * 1024];
82    let mut size = 0u64;
83    loop {
84        let n = file.read(&mut buf)?;
85        if n == 0 {
86            break;
87        }
88        hasher.update(&buf[..n]);
89        size += n as u64;
90    }
91    Ok((size, hasher.finalize()))
92}
93
94/// Copies `from` into `<dir>/zaun-uploads/` (mode 0700) and measures the copy, so what is
95/// declared is exactly what is sent.
96pub(crate) fn stage(dir: &Path, from: &Path) -> Result<(PathBuf, u64, [u8; 32])> {
97    let staged = staging_path(dir)?;
98    fs::copy(from, &staged).map_err(store)?;
99    match measure(&staged) {
100        Ok((size, hash)) => Ok((staged, size, hash)),
101        Err(e) => {
102            discard(&staged);
103            Err(store(e))
104        }
105    }
106}
107
108/// Writes `data` into `<dir>/zaun-uploads/` (mode 0700) and measures it, as [`stage`] does
109/// for a file.
110pub(crate) fn stage_bytes(dir: &Path, data: &[u8]) -> Result<(PathBuf, u64, [u8; 32])> {
111    let staged = staging_path(dir)?;
112    fs::write(&staged, data).map_err(store)?;
113    Ok((staged, data.len() as u64, content_hash(data)))
114}
115
116/// A fresh path in `<dir>/zaun-uploads/`, the folder made (mode 0700) when missing.
117fn staging_path(dir: &Path) -> Result<PathBuf> {
118    let folder = dir.join(UPLOADS);
119    let mut builder = fs::DirBuilder::new();
120    builder.recursive(true);
121    #[cfg(unix)]
122    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
123    builder.create(&folder).map_err(store)?;
124    let name = zaun_community_protocol::ids::AttachmentId::random()
125        .map_err(|_| Error::Protocol("no randomness".into()))?;
126    Ok(folder.join(name.to_b64()))
127}
128
129/// Deletes a staged or received file; gone already is fine.
130pub(crate) fn discard(path: &Path) {
131    let _ = fs::remove_file(path);
132}
133
134fn store(e: io::Error) -> Error {
135    Error::Store(format!("attachment file: {}", e.kind()))
136}
137
138/// A name for `name` that is safe as one path component: no separators, no control
139/// characters, no leading dots; `attachment` when nothing is left.
140#[must_use]
141pub fn safe_name(name: &str) -> String {
142    let cleaned: String = name
143        .chars()
144        .filter(|c| !c.is_control() && !matches!(c, '/' | '\\' | ':'))
145        .collect();
146    let trimmed = cleaned.trim().trim_start_matches('.');
147    if trimmed.is_empty() {
148        "attachment".to_owned()
149    } else {
150        trimmed.chars().take(200).collect()
151    }
152}
153
154/// Checks a received file against its attachment and moves it into `dest` under its safe
155/// name (prefixed with the attachment id when that name is taken). The received file never
156/// stays where it arrived.
157pub(crate) fn deliver(received: &Path, a: &Attachment, dest: &Path) -> Result<PathBuf> {
158    let checked = match measure(received) {
159        Ok((size, hash)) if size == a.size && hash.as_slice() == a.sha3_256.as_slice() => Ok(()),
160        Ok(_) => Err(Error::Transfer(
161            "the file does not match the attachment's size and hash",
162        )),
163        Err(e) => Err(store(e)),
164    };
165    if let Err(e) = checked {
166        discard(received);
167        return Err(e);
168    }
169    let name = safe_name(&a.name);
170    let mut to = dest.join(&name);
171    if to.exists() {
172        to = dest.join(format!("{}-{name}", a.attachment_id.to_b64()));
173    }
174    let moved = fs::rename(received, &to).or_else(|_| fs::copy(received, &to).map(|_| ()));
175    discard(received);
176    moved.map_err(store)?;
177    Ok(to)
178}
179
180/// A media type from a file name's extension; `application/octet-stream` otherwise.
181#[must_use]
182pub fn guess_mime(name: &str) -> &'static str {
183    let ext = name
184        .rsplit_once('.')
185        .map(|(_, e)| e.to_ascii_lowercase())
186        .unwrap_or_default();
187    match ext.as_str() {
188        "png" => "image/png",
189        "jpg" | "jpeg" => "image/jpeg",
190        "gif" => "image/gif",
191        "webp" => "image/webp",
192        "svg" => "image/svg+xml",
193        "mp4" => "video/mp4",
194        "webm" => "video/webm",
195        "mov" => "video/quicktime",
196        "mp3" => "audio/mpeg",
197        "ogg" | "oga" => "audio/ogg",
198        "wav" => "audio/wav",
199        "flac" => "audio/flac",
200        "pdf" => "application/pdf",
201        "zip" => "application/zip",
202        "json" => "application/json",
203        "txt" | "md" | "log" => "text/plain",
204        _ => "application/octet-stream",
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    const XFTP_A: &str = "xftp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=@a.example.org:5443";
213    const XFTP_B: &str = "xftp://hpq7_4gGJiilmz5Rf-CswuU5kZGkm_zOIooSw6yALRg=@b.example.org";
214    const SMP: &str = "smp://hpq7_4gGJiilmz5Rf-CswuU5kZGkm_zOIooSw6yALRg=@smp.example.org";
215
216    fn host(servers: &[&str]) -> HostAttachments {
217        HostAttachments {
218            max_bytes: 100,
219            file_servers: servers.iter().map(|s| (*s).to_owned()).collect(),
220        }
221    }
222
223    #[test]
224    fn uploads_go_to_the_named_file_servers_else_the_presets_else_none() {
225        assert_eq!(upload_servers(&[]), preset_servers());
226        assert_eq!(upload_servers(&[SMP.to_owned()]), []);
227        let named = upload_servers(&[SMP.to_owned(), XFTP_A.to_owned()]);
228        assert_eq!(named, [XFTP_A.parse::<XftpServer>().unwrap()]);
229    }
230
231    #[test]
232    fn an_upload_is_checked_against_the_hosts_servers_and_size() {
233        let ours = upload_servers(&[XFTP_A.to_owned()]);
234        assert!(check_upload(&ours, &host(&[XFTP_A, XFTP_B]), 100).is_ok());
235        assert!(check_upload(&ours, &host(&[XFTP_A]), 101).is_err());
236        assert!(check_upload(&ours, &host(&[XFTP_B]), 1).is_err());
237        assert!(check_upload(&[], &host(&[XFTP_A]), 1).is_err());
238        // A password on our side is for creating files; the host compares without it.
239        let with_auth =
240            "xftp://LcJUMfVhwD8yxjAiSaDzzGF3-kLG4Uh0Fl_ZIjrRwjI=:secret@a.example.org:5443";
241        let ours = upload_servers(&[with_auth.to_owned()]);
242        assert!(check_upload(&ours, &host(&[XFTP_A]), 1).is_ok());
243        // The official servers on both sides: every preset is listed.
244        let presets: Vec<String> = preset_servers().iter().map(ToString::to_string).collect();
245        let theirs = HostAttachments {
246            max_bytes: 100,
247            file_servers: presets,
248        };
249        assert!(check_upload(&upload_servers(&[]), &theirs, 1).is_ok());
250        // Only some presets on the host's side: one of ours could be refused.
251        assert!(check_upload(&upload_servers(&[]), &host(&[XFTP_A]), 1).is_err());
252    }
253
254    use zaun_community_protocol::command::object::Availability;
255    use zaun_community_protocol::ids::AttachmentId;
256
257    fn attachment(name: &str, bytes: &[u8]) -> Attachment {
258        Attachment {
259            attachment_id: AttachmentId::from_bytes([3; 16]),
260            name: name.into(),
261            size: bytes.len() as u64,
262            mime: "text/plain".into(),
263            sha3_256: content_hash(bytes).to_vec(),
264            availability: Availability::Stored,
265            failure: None,
266        }
267    }
268
269    #[test]
270    fn names_are_made_safe() {
271        assert_eq!(safe_name("../../etc/passwd"), "etcpasswd");
272        assert_eq!(safe_name("..."), "attachment");
273        assert_eq!(safe_name("a\u{0}b.txt"), "ab.txt");
274        assert_eq!(safe_name(" cat.png "), "cat.png");
275    }
276
277    #[test]
278    fn a_matching_download_is_delivered_and_a_wrong_one_dropped() {
279        let dir = tempfile::tempdir().unwrap();
280        let got = dir.path().join("in");
281        fs::write(&got, b"hello").unwrap();
282        let out = deliver(&got, &attachment("../hi.txt", b"hello"), dir.path()).unwrap();
283        assert_eq!(out, dir.path().join("hi.txt"));
284        assert_eq!(fs::read(&out).unwrap(), b"hello");
285        assert!(!got.exists());
286
287        fs::write(&got, b"hello").unwrap();
288        let again = deliver(&got, &attachment("hi.txt", b"hello"), dir.path()).unwrap();
289        assert!(
290            again
291                .file_name()
292                .unwrap()
293                .to_str()
294                .unwrap()
295                .ends_with("-hi.txt")
296        );
297
298        fs::write(&got, b"tampered").unwrap();
299        let bad = deliver(&got, &attachment("x.txt", b"hello"), dir.path());
300        assert!(matches!(bad, Err(Error::Transfer(_))));
301        assert!(!got.exists());
302        assert!(!dir.path().join("x.txt").exists());
303    }
304
305    #[test]
306    fn staging_copies_and_measures() {
307        let dir = tempfile::tempdir().unwrap();
308        let src = dir.path().join("cat.png");
309        fs::write(&src, b"meow").unwrap();
310        let (staged, size, hash) = stage(dir.path(), &src).unwrap();
311        assert!(staged.starts_with(dir.path().join(UPLOADS)));
312        assert_eq!((size, hash), (4, content_hash(b"meow")));
313        assert!(src.exists());
314        assert_eq!(guess_mime("CAT.PNG"), "image/png");
315        assert_eq!(guess_mime("noext"), "application/octet-stream");
316        let (staged, size, hash) = stage_bytes(dir.path(), b"purr").unwrap();
317        assert!(staged.starts_with(dir.path().join(UPLOADS)));
318        assert_eq!((size, hash), (4, content_hash(b"purr")));
319        assert_eq!(fs::read(&staged).unwrap(), b"purr");
320    }
321}