1use serde::{Deserialize, Serialize};
2use std::fs::{self, File, OpenOptions};
3use std::io::{ErrorKind, Write};
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::Mutex;
7
8pub const MAX_ATTACHMENT_BYTES: usize = 10 * 1024 * 1024;
9const ATTACHMENTS_SUBDIR: &str = "attachments";
10
11static STORE_LOCK: Mutex<()> = Mutex::new(());
12static TMP_COUNTER: AtomicU64 = AtomicU64::new(1);
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct Meta {
16 pub id: String,
17 pub name: String,
18 pub mime_type: String,
19 pub size: u64,
20 pub image: bool,
21}
22
23pub fn detect_image(bytes: &[u8]) -> Option<&'static str> {
24 if bytes.len() >= 8 && bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
25 return Some("image/png");
26 }
27 if bytes.len() >= 3 && bytes.starts_with(&[0xff, 0xd8, 0xff]) {
28 return Some("image/jpeg");
29 }
30 if bytes.len() >= 6 && (bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a")) {
31 return Some("image/gif");
32 }
33 if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
34 return Some("image/webp");
35 }
36 None
37}
38
39pub fn mime_type_for(bytes: &[u8]) -> (&'static str, bool) {
40 match detect_image(bytes) {
41 Some(mime) => (mime, true),
42 None => ("application/octet-stream", false),
43 }
44}
45
46pub fn sanitise_name(raw: &str) -> Result<String, String> {
47 let component = raw.rsplit(['/', '\\']).next().unwrap_or("");
48 if component.trim().is_empty() {
49 return Err("attachment name is empty".to_string());
50 }
51 let sanitised: String = component
52 .chars()
53 .map(|c| {
54 if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
55 c
56 } else {
57 '_'
58 }
59 })
60 .collect();
61 if sanitised.is_empty() || sanitised == "." || sanitised == ".." {
62 return Err("attachment name is empty".to_string());
63 }
64 Ok(sanitised)
65}
66
67pub fn attachments_dir(record_dir: &Path) -> PathBuf {
68 record_dir.join(ATTACHMENTS_SUBDIR)
69}
70
71pub fn store(dir: &Path, name: &str, bytes: &[u8]) -> Result<Meta, String> {
72 store_with_lock(&STORE_LOCK, dir, name, bytes)
73}
74
75fn store_with_lock(lock: &Mutex<()>, dir: &Path, name: &str, bytes: &[u8]) -> Result<Meta, String> {
76 let sanitised = sanitise_name(name)?;
77 if bytes.is_empty() {
78 return Err(format!("{sanitised} is empty"));
79 }
80 if bytes.len() > MAX_ATTACHMENT_BYTES {
81 return Err(format!(
82 "{sanitised} is larger than the 10 MiB limit for one file"
83 ));
84 }
85
86 let _guard = lock
87 .lock()
88 .map_err(|_| format!("attachment store lock is poisoned while storing {sanitised}"))?;
89 let dest_dir = attachments_dir(dir);
90 fs::create_dir_all(&dest_dir)
91 .map_err(|e| format!("failed to create {}: {e}", dest_dir.display()))?;
92
93 let next_num = highest_id_in(&dest_dir)? + 1;
94 let id = format!("a{next_num}");
95 let final_path = dest_dir.join(format!("{id}-{sanitised}"));
96 let tmp_name = format!(
97 ".tmp-{}-{}-{}",
98 id,
99 std::process::id(),
100 TMP_COUNTER.fetch_add(1, Ordering::Relaxed)
101 );
102 let tmp_path = dest_dir.join(tmp_name);
103
104 let write_res = (|| -> std::io::Result<()> {
105 let mut file = OpenOptions::new()
106 .write(true)
107 .create_new(true)
108 .open(&tmp_path)?;
109 file.write_all(bytes)?;
110 file.sync_all()?;
111 Ok(())
112 })();
113 if let Err(e) = write_res {
114 let _ = fs::remove_file(&tmp_path);
115 return Err(format!("failed to write {}: {e}", tmp_path.display()));
116 }
117 if let Err(e) = fs::rename(&tmp_path, &final_path) {
118 let _ = fs::remove_file(&tmp_path);
119 return Err(format!(
120 "failed to move {} to {}: {e}",
121 tmp_path.display(),
122 final_path.display()
123 ));
124 }
125
126 let (mime_type, image) = mime_type_for(bytes);
127 Ok(Meta {
128 id,
129 name: sanitised,
130 mime_type: mime_type.to_string(),
131 size: bytes.len() as u64,
132 image,
133 })
134}
135
136pub fn load(dir: &Path, id: &str) -> Result<(Meta, Vec<u8>), String> {
137 let (meta, _, bytes) = load_with_path(dir, id)?;
138 Ok((meta, bytes))
139}
140
141pub fn load_with_path(dir: &Path, id: &str) -> Result<(Meta, PathBuf, Vec<u8>), String> {
142 if !is_valid_id(id) {
143 return Err(format!("unknown attachment id: {id}"));
144 }
145 let dest_dir = attachments_dir(dir);
146 let prefix = format!("{id}-");
147 let entries = match fs::read_dir(&dest_dir) {
148 Ok(rd) => rd,
149 Err(e) if e.kind() == ErrorKind::NotFound => {
150 return Err(format!("unknown attachment id: {id}"));
151 }
152 Err(e) => {
153 return Err(format!(
154 "failed to read attachments directory {}: {e}",
155 dest_dir.display()
156 ));
157 }
158 };
159
160 let mut matched: Option<(String, PathBuf)> = None;
161 for entry in entries {
162 let entry = entry.map_err(|e| format!("failed to inspect attachment {id}: {e}"))?;
163 let file_name = entry.file_name();
164 let Some(name_str) = file_name.to_str() else {
165 continue;
166 };
167 if let Some(rest) = name_str.strip_prefix(&prefix) {
168 if !rest.is_empty() {
169 matched = Some((rest.to_string(), entry.path()));
170 break;
171 }
172 }
173 }
174
175 let Some((name, path)) = matched else {
176 return Err(format!("unknown attachment id: {id}"));
177 };
178 let abs_path = fs::canonicalize(&path).map_err(|e| {
179 format!(
180 "failed to canonicalize attachment {id} at {}: {e}",
181 path.display()
182 )
183 })?;
184 let bytes = match File::open(&abs_path).and_then(|mut f| {
185 let mut buf = Vec::new();
186 std::io::Read::read_to_end(&mut f, &mut buf)?;
187 Ok(buf)
188 }) {
189 Ok(b) => b,
190 Err(e) => return Err(format!("attachment {id} is missing or unreadable: {e}")),
191 };
192 let (mime_type, image) = mime_type_for(&bytes);
193 let meta = Meta {
194 id: id.to_string(),
195 name,
196 mime_type: mime_type.to_string(),
197 size: bytes.len() as u64,
198 image,
199 };
200 Ok((meta, abs_path, bytes))
201}
202
203fn is_valid_id(id: &str) -> bool {
204 match id.strip_prefix('a') {
205 Some(digits) if !digits.is_empty() => digits.bytes().all(|b| b.is_ascii_digit()),
206 _ => false,
207 }
208}
209
210fn highest_id_in(dir: &Path) -> Result<u64, String> {
211 let entries = match fs::read_dir(dir) {
212 Ok(rd) => rd,
213 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(0),
214 Err(e) => return Err(format!("failed to read {}: {e}", dir.display())),
215 };
216 let mut highest = 0u64;
217 for entry in entries {
218 let entry = entry.map_err(|e| format!("failed to read {}: {e}", dir.display()))?;
219 let file_name = entry.file_name();
220 let Some(name_str) = file_name.to_str() else {
221 continue;
222 };
223 if name_str.starts_with('.') {
224 continue;
225 }
226 if let Some((prefix, _)) = name_str.split_once('-') {
227 if let Some(digits) = prefix.strip_prefix('a') {
228 if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) {
229 if let Ok(n) = digits.parse::<u64>() {
230 if n > highest {
231 highest = n;
232 }
233 }
234 }
235 }
236 }
237 }
238 Ok(highest)
239}
240
241pub fn base64_encode(bytes: &[u8]) -> String {
242 const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
243 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
244 let (chunks, rem) = bytes.as_chunks::<3>();
245 for chunk in chunks {
246 let n = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32);
247 out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
248 out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
249 out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
250 out.push(TABLE[(n & 0x3f) as usize] as char);
251 }
252 match rem.len() {
253 1 => {
254 let n = (rem[0] as u32) << 16;
255 out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
256 out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
257 out.push('=');
258 out.push('=');
259 }
260 2 => {
261 let n = ((rem[0] as u32) << 16) | ((rem[1] as u32) << 8);
262 out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
263 out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
264 out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
265 out.push('=');
266 }
267 _ => {}
268 }
269 out
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 #[test]
277 fn base64_matches_rfc_4648_vectors() {
278 assert_eq!(base64_encode(b""), "");
279 assert_eq!(base64_encode(b"f"), "Zg==");
280 assert_eq!(base64_encode(b"fo"), "Zm8=");
281 assert_eq!(base64_encode(b"foo"), "Zm9v");
282 assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
283 assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
284 assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
285 assert_eq!(base64_encode(&[0xff, 0xee, 0xdd]), "/+7d");
286 }
287
288 #[test]
289 fn detect_image_recognises_the_four_formats() {
290 assert_eq!(
291 detect_image(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0]),
292 Some("image/png")
293 );
294 assert_eq!(detect_image(&[0xff, 0xd8, 0xff, 0xe0]), Some("image/jpeg"));
295 assert_eq!(detect_image(b"GIF87a..."), Some("image/gif"));
296 assert_eq!(detect_image(b"GIF89a..."), Some("image/gif"));
297 assert_eq!(
298 detect_image(b"RIFF\x12\x00\x00\x00WEBP"),
299 Some("image/webp")
300 );
301 assert_eq!(detect_image(b"RIFF\x12\x00\x00\x00WAVE"), None);
302 assert_eq!(detect_image(b"plain text"), None);
303 assert_eq!(detect_image(b""), None);
304 }
305
306 #[test]
307 fn sanitise_name_strips_paths_and_replaces_other_chars() {
308 assert_eq!(sanitise_name("../../x y.png").unwrap(), "x_y.png");
309 assert_eq!(sanitise_name(r"C:\tmp\a+b (1).txt").unwrap(), "a_b__1_.txt");
310 assert!(sanitise_name("").is_err());
311 assert!(sanitise_name(" ").is_err());
312 assert!(sanitise_name("..").is_err());
313 assert!(sanitise_name("dir/").is_err());
314 }
315
316 #[test]
317 fn store_continues_after_highest_existing_id() {
318 let dir = tempfile::tempdir().unwrap();
319 let m1 = store(dir.path(), "first.txt", b"one").unwrap();
320 assert_eq!(m1.id, "a1");
321 let m2 = store(dir.path(), "second.txt", b"two").unwrap();
322 assert_eq!(m2.id, "a2");
323 fs::write(attachments_dir(dir.path()).join("a9-manual.txt"), b"nine").unwrap();
324 let m3 = store(dir.path(), "third.txt", b"three").unwrap();
325 assert_eq!(m3.id, "a10");
326 let (loaded, bytes) = load(dir.path(), "a10").unwrap();
327 assert_eq!(loaded, m3);
328 assert_eq!(bytes, b"three");
329 }
330
331 #[test]
332 fn store_errors_when_lock_is_poisoned() {
333 let dir = tempfile::tempdir().unwrap();
334 let lock = std::sync::Arc::new(Mutex::new(()));
335 let lock_bg = std::sync::Arc::clone(&lock);
336 let _ = std::thread::spawn(move || {
337 let _guard = lock_bg.lock().unwrap();
338 panic!("poison test lock");
339 })
340 .join();
341 let err = store_with_lock(&lock, dir.path(), "note.txt", b"hello").unwrap_err();
342 assert!(err.contains("poisoned"), "unexpected error: {err}");
343 assert!(err.contains("note.txt"), "unexpected error: {err}");
344 }
345
346 #[cfg(unix)]
347 #[test]
348 fn load_with_path_errors_when_canonicalize_fails() {
349 let dir = tempfile::tempdir().unwrap();
350 let dest = attachments_dir(dir.path());
351 fs::create_dir_all(&dest).unwrap();
352 let dangling = dest.join("a1-dangling.txt");
353 std::os::unix::fs::symlink(dir.path().join("does-not-exist.txt"), &dangling).unwrap();
354 let err = load_with_path(dir.path(), "a1").unwrap_err();
355 assert!(err.contains("a1"), "unexpected error: {err}");
356 assert!(err.contains("canonicalize"), "unexpected error: {err}");
357 }
358}