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> {
253 let mut out = BTreeSet::new();
254 for part in state.parts.iter() {
255 out.extend(part.attachments.iter().map(|a| a.sha256.clone()));
256 for revision in &part.revisions {
257 out.extend(revision.attachments.iter().map(|a| a.sha256.clone()));
258 out.extend(revision.thumbnail.iter().map(|t| t.sha256.clone()));
259 }
260 }
261 for entry in state.workspace.iter() {
262 out.extend(entry.versions.iter().map(|v| v.sha256.clone()));
263 }
264 out
265}
266
267pub fn remove_if_unreferenced(state: &State, root: &Path, sha256: &str) -> Result<(), Error> {
270 if !is_sha256(sha256) || referenced(state).contains(sha256) {
271 return Ok(());
272 }
273 match std::fs::remove_file(blob_path(root, sha256)) {
274 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(Error::internal(error)),
275 _ => Ok(()),
276 }
277}
278
279pub fn place(root: &Path, staged: &Staged) -> Result<(), Error> {
282 let target = blob_path(root, &staged.sha256);
283 if !target.exists() {
284 std::fs::create_dir_all(target.parent().expect("a blob has a directory")).map_err(Error::internal)?;
285 std::fs::rename(&staged.path, &target).map_err(Error::internal)?;
286 }
287 Ok(())
288}
289
290fn revision_writable(state: &State, user: &User, part: &Part, revision_id: &str) -> Result<(), Error> {
293 let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
294 if !revision.lifecycle.is_editable() {
295 return Err(Error::conflict(format!(
296 "{} revision {} is {} — its files are frozen with it; attach to a new revision",
297 part.number,
298 revision.label,
299 revision.lifecycle.as_str()
300 )));
301 }
302 if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user.id) {
303 let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
304 return Err(Error::conflict(format!(
305 "{} revision {} is checked out by {holder}",
306 part.number, revision.label
307 )));
308 }
309 Ok(())
310}
311
312impl Db {
313 pub fn blob_path(&self, sha256: &str) -> PathBuf {
315 blob_path(self.root(), sha256)
316 }
317
318 pub fn start_upload(&self) -> Result<Upload, Error> {
320 Upload::start(self.root(), self.security().config.attachment_limit()).map_err(Error::internal)
321 }
322
323 pub fn attach(
326 &self,
327 user: &User,
328 part_key: &str,
329 revision_key: &str,
330 staged: Staged,
331 describe: &Describe,
332 ) -> Result<Attachment, Error> {
333 let (sha256, size) = (staged.sha256.clone(), staged.size);
334 self.attach_blob(user, part_key, revision_key, &sha256, size, Some(staged), describe, |_| Ok(()))
335 }
336
337 #[allow(clippy::too_many_arguments)]
342 pub fn attach_blob(
343 &self,
344 user: &User,
345 part_key: &str,
346 revision_key: &str,
347 sha256: &str,
348 size: u64,
349 staged: Option<Staged>,
350 describe: &Describe,
351 check: impl FnOnce(&State) -> Result<(), Error>,
352 ) -> Result<Attachment, Error> {
353 if !user.can_author() {
354 return Err(Error::forbidden("attaching a file needs the author group"));
355 }
356 let name = clean_name(&describe.name)?;
357 let media_type = clean_media_type(&describe.media_type);
358 let kind = clean_kind(&describe.kind, &media_type)?;
359 let note = describe.note.trim().to_string();
360 if note.chars().count() > MAX_NOTE {
361 return Err(Error::bad_request(format!("a note is at most {MAX_NOTE} characters")));
362 }
363 if !is_sha256(sha256) {
364 return Err(Error::internal("an attachment names no valid blob"));
365 }
366 let root = self.root().to_path_buf();
367 let user_id = user.id.clone();
368 let user = user.clone();
369 self.mutate(move |state| {
370 check(state)?;
371 let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
372 let part_id = part.id.clone();
373 let revision_id = if revision_key.trim().is_empty() {
374 None
375 } else {
376 let r = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
377 Some(r.id.clone())
378 };
379 if let Some(revision_id) = &revision_id {
380 revision_writable(state, &user, part, revision_id)?;
381 }
382 let attachment = Attachment {
383 id: crate::auth::new_id(),
384 name,
385 media_type,
386 size,
387 sha256: sha256.to_string(),
388 kind,
389 note,
390 uploaded_by: user_id,
391 uploaded_at: now(),
392 };
393 match &staged {
396 Some(staged) => place(&root, staged)?,
397 None if !blob_path(&root, sha256).exists() => {
398 return Err(Error::internal(format!("the stored file {sha256} is missing")))
399 }
400 None => {}
401 }
402 let part = state.parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
403 match &revision_id {
404 None => part.attachments.push(attachment.clone()),
405 Some(id) => {
406 let revision = part.revision_mut(id).ok_or_else(|| Error::not_found("revision"))?;
407 revision.attachments.push(attachment.clone());
408 revision.modified_at = now();
409 }
410 }
411 Ok(attachment)
412 })
413 }
414
415 pub fn replace_attachment(&self, user: &User, id: &str, part: &str, revision: &str,
418 expected_hash: &str, staged: Staged) -> Result<Located, Error> {
419 let root = self.root().to_path_buf();
420 self.mutate(|state| {
421 let found = locate_scoped(state, id, part, revision).ok_or_else(|| Error::not_found("attachment"))?;
422 attachment_writable(state, user, &found)?;
423 if found.attachment.sha256 != expected_hash { return Err(Error::conflict("This file changed since you opened it. Reopen it before saving.")); }
424 let mut changed = found.clone();
425 changed.attachment.id = crate::auth::new_id();
426 changed.attachment.sha256 = staged.sha256.clone();changed.attachment.size = staged.size;
427 changed.attachment.uploaded_by = user.id.clone();changed.attachment.uploaded_at = now();
428 place(&root, &staged)?;
429 let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
430 let files = if found.revision_id.is_empty() { &mut part.attachments } else {
431 let r = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
432 r.modified_at = now();&mut r.attachments
433 };
434 let file = files.iter_mut().find(|a| a.id == id).ok_or_else(|| Error::not_found("attachment"))?;
435 *file = changed.attachment.clone();
436 remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
437 Ok(changed)
438 })
439 }
440
441 pub fn detach(&self, user: &User, id: &str) -> Result<Located, Error> {
443 if !user.can_author() {
444 return Err(Error::forbidden("removing a file needs the author group"));
445 }
446 let root = self.root().to_path_buf();
447 let user = user.clone();
448 self.mutate(move |state| {
449 let found = locate(state, id).ok_or_else(|| Error::not_found("attachment"))?;
450 let part = state.part(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
451 if !found.revision_id.is_empty() {
452 revision_writable(state, &user, part, &found.revision_id)?;
453 }
454 let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
455 if found.revision_id.is_empty() {
456 part.attachments.retain(|a| a.id != id);
457 } else {
458 let revision = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
459 revision.attachments.retain(|a| a.id != id);
460 revision.modified_at = now();
461 }
462 remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
463 Ok(found)
464 })
465 }
466
467 pub fn attachment(&self, id: &str) -> Option<Located> {
469 self.read(|state| locate(state, id))
470 }
471
472 pub fn sweep_blobs(&self) -> io::Result<usize> {
477 let root = blob_root(self.root());
478 if !root.exists() {
479 return Ok(0);
480 }
481 let keep = self.read(referenced);
482 let staging = staging_dir(self.root());
483 let mut removed = 0;
484 if staging.exists() {
485 for entry in std::fs::read_dir(&staging)? {
486 std::fs::remove_file(entry?.path())?;
487 removed += 1;
488 }
489 }
490 for shard in std::fs::read_dir(&root)? {
491 let shard = shard?.path();
492 if !shard.is_dir() || shard == staging {
493 continue;
494 }
495 for entry in std::fs::read_dir(&shard)? {
496 let path = entry?.path();
497 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
498 if is_sha256(&name) && !keep.contains(&name) {
499 std::fs::remove_file(&path)?;
500 removed += 1;
501 }
502 }
503 }
504 Ok(removed)
505 }
506}