1use std::collections::BTreeSet;
27use std::io;
28use std::path::{Path, PathBuf};
29
30use serde::Serialize;
31use sha2::{Digest, Sha256};
32
33use crate::db::{now, Db, State};
34use crate::model::{Attachment, Part, User};
35use crate::Error;
36
37pub const KINDS: [&str; 5] = ["datasheet", "drawing", "spec", "image", "other"];
39
40pub const INLINE_TYPES: [&str; 5] = ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
43
44const MAX_NAME: usize = 200;
45const MAX_NOTE: usize = 500;
46
47pub fn blob_root(data: &Path) -> PathBuf {
49 data.join("blobs")
50}
51
52pub fn blob_path(data: &Path, sha256: &str) -> PathBuf {
54 blob_root(data).join(&sha256[..2]).join(sha256)
55}
56
57pub fn staging_dir(data: &Path) -> PathBuf {
59 blob_root(data).join("tmp")
60}
61
62pub fn is_sha256(text: &str) -> bool {
64 text.len() == 64 && text.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
65}
66
67#[derive(Debug)]
71pub struct Staged {
72 pub path: PathBuf,
73 pub sha256: String,
74 pub size: u64,
75}
76
77impl Drop for Staged {
78 fn drop(&mut self) {
79 let _ = std::fs::remove_file(&self.path);
80 }
81}
82
83pub struct Upload {
85 file: std::fs::File,
86 path: PathBuf,
87 hasher: Sha256,
88 size: u64,
89 limit: u64,
90 done: bool,
91}
92
93impl Upload {
94 pub fn start(data: &Path, limit: u64) -> io::Result<Upload> {
95 let dir = staging_dir(data);
96 std::fs::create_dir_all(&dir)?;
97 let path = dir.join(format!("{}.part", crate::auth::new_id()));
98 let file = std::fs::File::create(&path)?;
99 Ok(Upload { file, path, hasher: Sha256::new(), size: 0, limit, done: false })
100 }
101
102 pub fn write(&mut self, chunk: &[u8]) -> Result<(), Error> {
104 use std::io::Write;
105 self.size += chunk.len() as u64;
106 if self.size > self.limit {
107 return Err(Error {
108 status: axum::http::StatusCode::PAYLOAD_TOO_LARGE,
109 message: format!("the file is over the {} MB attachment limit", self.limit / (1024 * 1024)),
110 });
111 }
112 self.hasher.update(chunk);
113 self.file.write_all(chunk).map_err(Error::internal)
114 }
115
116 pub fn finish(self) -> Result<Staged, Error> { self.finish_with_empty(false) }
118
119 pub(crate) fn finish_with_empty(mut self, allow_empty: bool) -> Result<Staged, Error> {
120 if self.size == 0 && !allow_empty {
121 return Err(Error::bad_request("the file is empty"));
122 }
123 self.file.sync_all().map_err(Error::internal)?;
124 self.done = true;
125 let sha256 = format!("{:x}", std::mem::take(&mut self.hasher).finalize());
126 Ok(Staged { path: std::mem::take(&mut self.path), sha256, size: self.size })
127 }
128}
129
130impl Drop for Upload {
131 fn drop(&mut self) {
132 if !self.done {
133 let _ = std::fs::remove_file(&self.path);
134 }
135 }
136}
137
138#[derive(Debug, Clone, Default)]
140pub struct Describe {
141 pub name: String,
142 pub media_type: String,
143 pub kind: String,
144 pub note: String,
145}
146
147pub fn clean_name(raw: &str) -> Result<String, Error> {
150 let last = raw.rsplit(['/', '\\']).next().unwrap_or("").trim();
151 let name: String = last.chars().filter(|c| !c.is_control() && *c != '"').collect();
152 let name = name.trim().to_string();
153 if name.is_empty() || name == "." || name == ".." {
154 return Err(Error::bad_request("an attachment needs a file name"));
155 }
156 if name.chars().count() > MAX_NAME {
157 return Err(Error::bad_request(format!("a file name is at most {MAX_NAME} characters")));
158 }
159 Ok(name)
160}
161
162pub fn clean_media_type(raw: &str) -> String {
165 let base = raw.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
166 let ok = |part: &str| {
167 !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&b))
168 };
169 match base.split_once('/') {
170 Some((a, b)) if ok(a) && ok(b) => base,
171 _ => "application/octet-stream".to_string(),
172 }
173}
174
175fn clean_kind(raw: &str, media_type: &str) -> Result<String, Error> {
176 let kind = raw.trim().to_ascii_lowercase();
177 if kind.is_empty() {
178 return Ok(if media_type.starts_with("image/") { "image" } else { "other" }.to_string());
179 }
180 if KINDS.contains(&kind.as_str()) {
181 Ok(kind)
182 } else {
183 Err(Error::bad_request(format!("'{kind}' is not a kind of attachment — {}", KINDS.join(", "))))
184 }
185}
186
187pub fn inline_ok(media_type: &str) -> bool {
189 INLINE_TYPES.contains(&media_type)
190}
191
192#[derive(Debug, Clone, Serialize)]
194pub struct Located {
195 pub attachment: Attachment,
196 pub part_id: String,
197 pub number: String,
198 pub revision_id: String,
200 pub revision_label: String,
201}
202
203pub fn locate(state: &State, id: &str) -> Option<Located> {
205 for part in state.parts.iter() {
206 if let Some(a) = part.attachments.iter().find(|a| a.id == id) {
207 return Some(Located {
208 attachment: a.clone(),
209 part_id: part.id.clone(),
210 number: part.number.clone(),
211 revision_id: String::new(),
212 revision_label: String::new(),
213 });
214 }
215 for revision in &part.revisions {
216 if let Some(a) = revision.attachments.iter().find(|a| a.id == id) {
217 return Some(Located {
218 attachment: a.clone(),
219 part_id: part.id.clone(),
220 number: part.number.clone(),
221 revision_id: revision.id.clone(),
222 revision_label: revision.label.clone(),
223 });
224 }
225 }
226 }
227 None
228}
229
230pub fn locate_scoped(state: &State, id: &str, part_key: &str, revision_key: &str) -> Option<Located> {
232 if part_key.is_empty() { return locate(state, id); }
233 let part = state.part_by_id_or_number(part_key)?;
234 let revision = if revision_key.is_empty() { None } else { Some(crate::bom::find_revision(part, revision_key)?) };
235 let files = revision.map(|r| &r.attachments).unwrap_or(&part.attachments);
236 let attachment = files.iter().find(|a| a.id == id)?.clone();
237 Some(Located { attachment, part_id: part.id.clone(), number: part.number.clone(),
238 revision_id: revision.map(|r| r.id.clone()).unwrap_or_default(),
239 revision_label: revision.map(|r| r.label.clone()).unwrap_or_default() })
240}
241
242pub fn attachment_writable(state: &State, user: &User, found: &Located) -> Result<(), Error> {
243 if !user.can_author() { return Err(Error::forbidden("editing an attachment needs the author group")); }
244 let part = state.part(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
245 if !found.revision_id.is_empty() { revision_writable(state, user, part, &found.revision_id)?; }
246 Ok(())
247}
248
249pub fn referenced(state: &State) -> BTreeSet<String> {
254 let mut out = BTreeSet::new();
255 for part in state.parts.iter() {
256 out.extend(part.attachments.iter().map(|a| a.sha256.clone()));
257 for revision in &part.revisions {
258 out.extend(revision.attachments.iter().map(|a| a.sha256.clone()));
259 out.extend(revision.thumbnail.iter().map(|t| t.sha256.clone()));
260 out.extend(revision.player.iter().map(|p| p.sha256.clone()));
261 }
262 }
263 for entry in state.workspace.iter() {
264 out.extend(entry.versions.iter().map(|v| v.sha256.clone()));
265 }
266 out.extend(crate::tools::pictures(state).map(str::to_string));
267 out
268}
269
270static HELD: std::sync::Mutex<Vec<(std::path::PathBuf, Vec<String>)>> = std::sync::Mutex::new(Vec::new());
276
277pub struct BlobsHeld(std::path::PathBuf);
280
281impl BlobsHeld {
282 pub fn new(root: &Path) -> Self {
283 HELD.lock().unwrap_or_else(|e| e.into_inner()).push((root.to_path_buf(), Vec::new()));
284 Self(root.to_path_buf())
285 }
286
287 pub fn release(self, db: &crate::db::Db) -> Result<(), Error> {
290 let held = take_held(&self.0);
291 db.read(|state| held.iter().try_for_each(|sha| remove_if_unreferenced(state, &self.0, sha)))
292 }
293}
294
295impl Drop for BlobsHeld {
296 fn drop(&mut self) {
297 take_held(&self.0);
300 }
301}
302
303fn take_held(root: &Path) -> Vec<String> {
304 let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner());
305 match held.iter().position(|(r, _)| r == root) {
306 Some(i) => held.remove(i).1,
307 None => Vec::new(),
308 }
309}
310
311pub fn remove_if_unreferenced(state: &State, root: &Path, sha256: &str) -> Result<(), Error> {
315 if !is_sha256(sha256) || referenced(state).contains(sha256) {
316 return Ok(());
317 }
318 {
319 let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner());
320 if let Some((_, waiting)) = held.iter_mut().find(|(r, _)| r == root) {
321 waiting.push(sha256.to_string());
322 return Ok(());
323 }
324 }
325 match std::fs::remove_file(blob_path(root, sha256)) {
326 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(Error::internal(error)),
327 _ => Ok(()),
328 }
329}
330
331pub fn place(root: &Path, staged: &Staged) -> Result<(), Error> {
334 let target = blob_path(root, &staged.sha256);
335 if !target.exists() {
336 std::fs::create_dir_all(target.parent().expect("a blob has a directory")).map_err(Error::internal)?;
337 std::fs::rename(&staged.path, &target).map_err(Error::internal)?;
338 }
339 Ok(())
340}
341
342fn revision_writable(state: &State, user: &User, part: &Part, revision_id: &str) -> Result<(), Error> {
345 let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
346 if !revision.lifecycle.is_editable() {
347 return Err(Error::conflict(format!(
348 "{} revision {} is {} — its files are frozen with it; attach to a new revision",
349 part.number,
350 revision.label,
351 revision.lifecycle.as_str()
352 )));
353 }
354 if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user.id) {
355 let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
356 return Err(Error::conflict(format!(
357 "{} revision {} is checked out by {holder}",
358 part.number, revision.label
359 )));
360 }
361 Ok(())
362}
363
364impl Db {
365 pub fn blob_path(&self, sha256: &str) -> PathBuf {
367 blob_path(self.root(), sha256)
368 }
369
370 pub fn start_upload(&self) -> Result<Upload, Error> {
372 Upload::start(self.root(), self.security().config.attachment_limit()).map_err(Error::internal)
373 }
374
375 pub fn attach(
378 &self,
379 user: &User,
380 part_key: &str,
381 revision_key: &str,
382 staged: Staged,
383 describe: &Describe,
384 ) -> Result<Attachment, Error> {
385 let (sha256, size) = (staged.sha256.clone(), staged.size);
386 self.attach_blob(user, part_key, revision_key, &sha256, size, Some(staged), describe, |_| Ok(()))
387 }
388
389 #[allow(clippy::too_many_arguments)]
394 pub fn attach_blob(
395 &self,
396 user: &User,
397 part_key: &str,
398 revision_key: &str,
399 sha256: &str,
400 size: u64,
401 staged: Option<Staged>,
402 describe: &Describe,
403 check: impl FnOnce(&State) -> Result<(), Error>,
404 ) -> Result<Attachment, Error> {
405 if !user.can_author() {
406 return Err(Error::forbidden("attaching a file needs the author group"));
407 }
408 let name = clean_name(&describe.name)?;
409 let media_type = clean_media_type(&describe.media_type);
410 let kind = clean_kind(&describe.kind, &media_type)?;
411 let note = describe.note.trim().to_string();
412 if note.chars().count() > MAX_NOTE {
413 return Err(Error::bad_request(format!("a note is at most {MAX_NOTE} characters")));
414 }
415 if !is_sha256(sha256) {
416 return Err(Error::internal("an attachment names no valid blob"));
417 }
418 let root = self.root().to_path_buf();
419 let user_id = user.id.clone();
420 let user = user.clone();
421 self.mutate(move |state| {
422 check(state)?;
423 let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
424 let part_id = part.id.clone();
425 let revision_id = if revision_key.trim().is_empty() {
426 None
427 } else {
428 let r = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
429 Some(r.id.clone())
430 };
431 if let Some(revision_id) = &revision_id {
432 revision_writable(state, &user, part, revision_id)?;
433 }
434 let attachment = Attachment {
435 id: crate::auth::new_id(),
436 name,
437 media_type,
438 size,
439 sha256: sha256.to_string(),
440 kind,
441 note,
442 uploaded_by: user_id,
443 uploaded_at: now(),
444 };
445 match &staged {
448 Some(staged) => place(&root, staged)?,
449 None if !blob_path(&root, sha256).exists() => {
450 return Err(Error::internal(format!("the stored file {sha256} is missing")))
451 }
452 None => {}
453 }
454 let part = state.parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
455 match &revision_id {
456 None => part.attachments.push(attachment.clone()),
457 Some(id) => {
458 let revision = part.revision_mut(id).ok_or_else(|| Error::not_found("revision"))?;
459 revision.attachments.push(attachment.clone());
460 revision.modified_at = now();
461 }
462 }
463 Ok(attachment)
464 })
465 }
466
467 pub fn replace_attachment(&self, user: &User, id: &str, part: &str, revision: &str,
470 expected_hash: &str, staged: Staged) -> Result<Located, Error> {
471 let root = self.root().to_path_buf();
472 self.mutate(|state| {
473 let found = locate_scoped(state, id, part, revision).ok_or_else(|| Error::not_found("attachment"))?;
474 attachment_writable(state, user, &found)?;
475 if found.attachment.sha256 != expected_hash { return Err(Error::conflict("This file changed since you opened it. Reopen it before saving.")); }
476 let mut changed = found.clone();
477 changed.attachment.id = crate::auth::new_id();
478 changed.attachment.sha256 = staged.sha256.clone();changed.attachment.size = staged.size;
479 changed.attachment.uploaded_by = user.id.clone();changed.attachment.uploaded_at = now();
480 place(&root, &staged)?;
481 let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
482 let files = if found.revision_id.is_empty() { &mut part.attachments } else {
483 let r = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
484 r.modified_at = now();&mut r.attachments
485 };
486 let file = files.iter_mut().find(|a| a.id == id).ok_or_else(|| Error::not_found("attachment"))?;
487 *file = changed.attachment.clone();
488 remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
489 Ok(changed)
490 })
491 }
492
493 pub fn detach(&self, user: &User, id: &str) -> Result<Located, Error> {
495 if !user.can_author() {
496 return Err(Error::forbidden("removing a file needs the author group"));
497 }
498 let root = self.root().to_path_buf();
499 let user = user.clone();
500 self.mutate(move |state| {
501 let found = locate(state, id).ok_or_else(|| Error::not_found("attachment"))?;
502 let part = state.part(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
503 if !found.revision_id.is_empty() {
504 revision_writable(state, &user, part, &found.revision_id)?;
505 }
506 let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
507 if found.revision_id.is_empty() {
508 part.attachments.retain(|a| a.id != id);
509 } else {
510 let revision = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
511 revision.attachments.retain(|a| a.id != id);
512 revision.modified_at = now();
513 }
514 remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
515 Ok(found)
516 })
517 }
518
519 pub fn attachment(&self, id: &str) -> Option<Located> {
521 self.read(|state| locate(state, id))
522 }
523
524 pub fn sweep_blobs(&self) -> io::Result<usize> {
529 let root = blob_root(self.root());
530 if !root.exists() {
531 return Ok(0);
532 }
533 let keep = self.read(referenced);
534 let staging = staging_dir(self.root());
535 let mut removed = 0;
536 if staging.exists() {
537 for entry in std::fs::read_dir(&staging)? {
538 std::fs::remove_file(entry?.path())?;
539 removed += 1;
540 }
541 }
542 for shard in std::fs::read_dir(&root)? {
543 let shard = shard?.path();
544 if !shard.is_dir() || shard == staging {
545 continue;
546 }
547 for entry in std::fs::read_dir(&shard)? {
548 let path = entry?.path();
549 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
550 if is_sha256(&name) && !keep.contains(&name) {
551 std::fs::remove_file(&path)?;
552 removed += 1;
553 }
554 }
555 }
556 Ok(removed)
557 }
558}