forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

files.rs498 lines, 14.6 KiBHistoryRawDownload
1use std::{
2 io::{BufReader, Cursor},
3 path::{Path, PathBuf},
4 time::{Duration, SystemTime},
5};
6
7use common::{
8 constant::{
9 ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, AVATAR_SIZE, MAXIMUM_AVATAR_BYTES,
10 THUMBNAIL_SIZE,
11 },
12 error::{Error as CommonError, Field, Problem},
13 frame::{self, DOWN_MAX, Sending},
14 model::{Attachment, AttachmentKind, Id, ServerSettings, User},
15 open::{Blob, Upload},
16 permission,
17 time::{HOUR_MILLIS, now_ms},
18 validate::{validate_attachment_name, validate_attachment_size, validate_avatar_size},
19};
20use image::{ImageFormat, ImageReader, Limits};
21use quinn::{RecvStream, VarInt};
22use tokio::{
23 fs::File,
24 io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
25};
26use tracing::error;
27
28use crate::{
29 authentication::random_bytes,
30 backup,
31 db::{self, Db},
32 error::{ServerError, ensure, ensure_with},
33};
34
35const COLLECT_INTERVAL: Duration = Duration::from_secs(600);
36const MAXIMUM_IMAGE_SIDE: u32 = 16384;
37const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024;
38const THUMB_SUFFIX: &str = ".thumb";
39const FILE_NAME_BYTES: usize = 16;
40
41fn thumb_path(directory: &Path, file: &str) -> PathBuf {
42 directory.join(format!("{file}{THUMB_SUFFIX}"))
43}
44
45fn remove_files(directory: &Path, file: &str) {
46 let _ = std::fs::remove_file(directory.join(file));
47 let _ = std::fs::remove_file(thumb_path(directory, file));
48}
49
50fn media_kind(head: &[u8]) -> AttachmentKind {
51 if is_video(head) {
52 AttachmentKind::Video
53 } else if is_audio(head) {
54 AttachmentKind::Audio
55 } else {
56 AttachmentKind::File
57 }
58}
59
60fn is_image(head: &[u8]) -> bool {
61 matches!(
62 image::guess_format(head),
63 Ok(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP)
64 )
65}
66
67fn is_video(head: &[u8]) -> bool {
68 head.get(4..8) == Some(b"ftyp") || head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3])
69}
70
71fn is_audio(head: &[u8]) -> bool {
72 head.starts_with(b"OggS")
73 || head.starts_with(b"fLaC")
74 || head.starts_with(b"ID3")
75 || head.starts_with(&[0xFF, 0xFB])
76 || head.starts_with(&[0xFF, 0xF3])
77 || head.starts_with(&[0xFF, 0xF2])
78 || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WAVE"))
79}
80
81fn decode_thumbnail(source: &Path, thumbnail: &Path) -> Option<(u32, u32)> {
82 let mut reader = ImageReader::new(BufReader::new(std::fs::File::open(source).ok()?))
83 .with_guessed_format()
84 .ok()?;
85 let mut limits = Limits::default();
86 limits.max_image_width = Some(MAXIMUM_IMAGE_SIDE);
87 limits.max_image_height = Some(MAXIMUM_IMAGE_SIDE);
88 limits.max_alloc = Some(MAXIMUM_DECODE_BYTES);
89 reader.limits(limits);
90 let image = reader.decode().ok()?;
91 let (width, height) = (image.width(), image.height());
92
93 let fitted = if width > THUMBNAIL_SIZE || height > THUMBNAIL_SIZE {
94 image.thumbnail(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
95 } else {
96 image
97 };
98 let mut bytes = Cursor::new(Vec::new());
99 fitted
100 .to_rgb8()
101 .write_to(&mut bytes, ImageFormat::Jpeg)
102 .ok()?;
103 std::fs::write(thumbnail, bytes.into_inner()).ok()?;
104
105 Some((width, height))
106}
107
108pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> {
109 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
110 let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| {
111 CommonError::Invalid {
112 field: Field::Avatar,
113 problem: Problem::NotJpeg,
114 }
115 })?;
116 if image.width() != image.height() || image.width() > AVATAR_SIZE {
117 return Err(CommonError::Invalid {
118 field: Field::Avatar,
119 problem: Problem::Dimensions {
120 expected: AVATAR_SIZE,
121 },
122 }
123 .into());
124 }
125
126 Ok(())
127}
128
129async fn receive_body<R: AsyncRead + Unpin>(
130 reader: &mut R,
131 path: &Path,
132 size: u64,
133) -> Result<Vec<u8>, ServerError> {
134 let mismatch = |actual: u64| CommonError::Invalid {
135 field: Field::Attachment,
136 problem: Problem::Length {
137 min: size,
138 max: size,
139 actual,
140 },
141 };
142 let mut file = File::create(path).await?;
143
144 let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize];
145 reader.read_exact(&mut head).await?;
146 file.write_all(&head).await?;
147
148 let mut received = head.len() as u64;
149 let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
150 loop {
151 let read = reader.read(&mut buffer).await?;
152 if read == 0 {
153 break;
154 }
155
156 received += read as u64;
157 if received > size {
158 return Err(mismatch(received).into());
159 }
160 file.write_all(&buffer[..read]).await?;
161 }
162
163 if received != size {
164 return Err(mismatch(received).into());
165 }
166 file.flush().await?;
167
168 Ok(head)
169}
170
171async fn ensure_quota(
172 user_id: Id,
173 community_id: Id,
174 size: u64,
175 settings: &ServerSettings,
176 db: &db::Connection,
177) -> Result<(), ServerError> {
178 let (user_used, community_used) = db::attachment::quota(user_id, community_id, db).await?;
179 let over = |used: u64, limit: u64| limit != 0 && used.saturating_add(size) > limit;
180 ensure_with(
181 !over(user_used, settings.user_quota_bytes)
182 && !over(community_used, settings.community_quota_bytes),
183 CommonError::QuotaExceeded,
184 )
185}
186
187async fn write_file(
188 reader: &mut (impl AsyncRead + Unpin),
189 header: &Upload,
190 path: &Path,
191 thumbnail: PathBuf,
192) -> Result<(AttachmentKind, Option<u32>, Option<u32>), ServerError> {
193 let head = receive_body(reader, path, header.size).await?;
194 let described = if is_image(&head) {
195 let source = path.to_path_buf();
196 tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail)).await?
197 } else {
198 None
199 };
200
201 Ok(match described {
202 Some((width, height)) => (AttachmentKind::Image, Some(width), Some(height)),
203 None => (media_kind(&head), None, None),
204 })
205}
206
207pub async fn store<R: AsyncRead + Unpin>(
208 user: &User,
209 header: &Upload,
210 reader: &mut R,
211 db: &Db,
212 directory: &Path,
213) -> Result<Attachment, ServerError> {
214 let settings = db
215 .run(async |conn| {
216 let rank = permission::effective_rank(
217 user.role,
218 db::member::rank(user.id, header.community_id, conn).await?,
219 );
220 ensure(permission::can_post(rank))?;
221 validate_attachment_name(&header.name)?;
222 let settings = db::settings::read(conn).await?;
223 validate_attachment_size(header.size, settings.max_attachment_bytes)?;
224 ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?;
225
226 Ok(settings)
227 })
228 .await?;
229
230 let file: String = random_bytes::<FILE_NAME_BYTES>()?
231 .iter()
232 .map(|byte| format!("{byte:02x}"))
233 .collect();
234 let path = directory.join(&file);
235 let (kind, width, height) =
236 match write_file(reader, header, &path, thumb_path(directory, &file)).await {
237 Ok(described) => described,
238 Err(error) => {
239 remove_files(directory, &file);
240 return Err(error);
241 }
242 };
243
244 let stored = db
245 .run(async |conn| {
246 ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?;
247 db::attachment::insert(
248 user.id,
249 header.community_id,
250 &file,
251 &header.name,
252 header.size,
253 kind,
254 width,
255 height,
256 conn,
257 )
258 .await
259 })
260 .await;
261 if stored.is_err() {
262 remove_files(directory, &file);
263 }
264
265 stored
266}
267
268pub async fn upload(
269 user: Option<&User>,
270 header: Upload,
271 mut receive_stream: RecvStream,
272 mut send_stream: Sending,
273 db: &Db,
274 directory: &Path,
275) -> Result<(), ServerError> {
276 let stored = match user {
277 Some(user) => store(user, &header, &mut receive_stream, db, directory).await,
278 None => Err(CommonError::Unauthenticated.into()),
279 };
280 let rejected = stored.is_err();
281 let reply = stored.map_err(CommonError::from);
282
283 frame::write(&mut send_stream, &reply, DOWN_MAX).await?;
284 send_stream.finish()?;
285 if rejected {
286 let _ = receive_stream.stop(VarInt::from_u32(0));
287 }
288
289 Ok(())
290}
291
292async fn locate(
293 user: Option<&User>,
294 attachment_id: Id,
295 thumbnail: bool,
296 db: &Db,
297 directory: &Path,
298) -> Result<(PathBuf, u64), ServerError> {
299 let user = user.ok_or(CommonError::Unauthenticated)?;
300 let stored = db
301 .run(async |conn| {
302 let stored = db::attachment::read(attachment_id, conn).await?;
303 let rank = permission::effective_rank(
304 user.role,
305 db::member::rank(user.id, stored.community_id, conn).await?,
306 );
307 ensure(permission::can_read(rank))?;
308 ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?;
309
310 Ok(stored)
311 })
312 .await?;
313
314 let path = if thumbnail {
315 thumb_path(directory, &stored.file)
316 } else {
317 directory.join(&stored.file)
318 };
319 let length = tokio::fs::metadata(&path)
320 .await
321 .map_err(|_| CommonError::NotFound)?
322 .len();
323
324 Ok((path, length))
325}
326
327pub async fn fetch(
328 user: Option<&User>,
329 blob: Blob,
330 mut send_stream: Sending,
331 db: &Db,
332 directory: &Path,
333 backups: &Path,
334) -> Result<(), ServerError> {
335 let located = match &blob {
336 Blob::Attachment(id) => locate(user, *id, false, db, directory).await,
337 Blob::Thumbnail(id) => locate(user, *id, true, db, directory).await,
338 Blob::Backup(name) => backup::locate(user, name, db, backups).await,
339 };
340 let located = located.map_err(CommonError::from);
341 let reply = located
342 .as_ref()
343 .map(|(_, length)| *length)
344 .map_err(Clone::clone);
345 frame::write(&mut send_stream, &reply, DOWN_MAX).await?;
346
347 if let Ok((path, _)) = located {
348 let mut file = File::open(path).await?;
349 let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
350 loop {
351 let read = file.read(&mut buffer).await?;
352 if read == 0 {
353 break;
354 }
355 send_stream.get().write_all(&buffer[..read]).await?;
356 }
357 }
358 send_stream.finish()?;
359
360 Ok(())
361}
362
363pub async fn collect(db: Db, directory: PathBuf) {
364 let mut interval = tokio::time::interval(COLLECT_INTERVAL);
365 loop {
366 interval.tick().await;
367 if let Err(error) = sweep(&db, &directory).await {
368 error!("attachment sweep: {error}");
369 }
370 }
371}
372
373async fn sweep(db: &Db, directory: &Path) -> Result<(), ServerError> {
374 let stale_ms = now_ms().saturating_sub(HOUR_MILLIS);
375 let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms);
376
377 let files = db
378 .run(async |conn| {
379 db::attachment::delete_stale_unbound(stale_ms, conn).await?;
380 db::attachment::files(conn).await
381 })
382 .await?;
383
384 for entry in std::fs::read_dir(directory)? {
385 let Ok(entry) = entry else { continue };
386 let name = entry.file_name().to_string_lossy().into_owned();
387 let file = name.strip_suffix(THUMB_SUFFIX).unwrap_or(&name);
388 let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else {
389 continue;
390 };
391
392 if modified < stale_at && !files.contains(file) {
393 let _ = std::fs::remove_file(entry.path());
394 }
395 }
396
397 Ok(())
398}
399
400#[cfg(test)]
401mod tests {
402 use std::io::Cursor;
403
404 use common::{
405 constant::AVATAR_SIZE,
406 error::{Error as CommonError, Field},
407 model::{AttachmentKind, Rank, Role},
408 open::Upload,
409 };
410 use image::{ImageFormat, RgbImage};
411
412 use super::{check_avatar, store, thumb_path};
413 use crate::{db, error::ServerError, test};
414
415 fn jpeg(size: u32) -> Vec<u8> {
416 let mut bytes = Cursor::new(Vec::new());
417 RgbImage::new(size, size)
418 .write_to(&mut bytes, ImageFormat::Jpeg)
419 .unwrap();
420
421 bytes.into_inner()
422 }
423
424 #[test]
425 fn avatar_checks_jpeg_size() {
426 let large = check_avatar(&jpeg(AVATAR_SIZE * 2));
427 let not_jpeg = check_avatar(b"not a jpeg");
428
429 assert!(matches!(
430 large,
431 Err(ServerError::Wire(CommonError::Invalid {
432 field: Field::Avatar,
433 ..
434 }))
435 ));
436 assert!(matches!(
437 not_jpeg,
438 Err(ServerError::Wire(CommonError::Invalid {
439 field: Field::Avatar,
440 ..
441 }))
442 ));
443 assert!(check_avatar(&jpeg(AVATAR_SIZE)).is_ok());
444 assert!(check_avatar(&jpeg(AVATAR_SIZE / 2)).is_ok());
445 }
446
447 #[tokio::test]
448 async fn upload_then_read_in_message() {
449 let db = test::db().await;
450 let (user, community) = {
451 let conn = db.lock().await.unwrap();
452 let user = db::user::create("Tahinli", "hash", Role::User, &conn)
453 .await
454 .unwrap();
455 let community_id = db::community::create(db::community::Kind::Group, "Tahinli", &conn)
456 .await
457 .unwrap();
458 db::member::join(user.id, community_id, Rank::Member, &conn)
459 .await
460 .unwrap();
461
462 (user, community_id)
463 };
464
465 let mut png = Cursor::new(Vec::new());
466 RgbImage::new(2, 3)
467 .write_to(&mut png, ImageFormat::Png)
468 .unwrap();
469 let png = png.into_inner();
470 let directory = test::directory();
471 let header = Upload {
472 community_id: community,
473 name: "pixel.png".to_string(),
474 size: png.len() as u64,
475 };
476 let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory)
477 .await
478 .unwrap();
479
480 let conn = db.lock().await.unwrap();
481 db::message::create(user.id, community, "", &[attachment.id], None, &conn)
482 .await
483 .unwrap();
484 let messages = db::message::read_page(community, None, false, &conn)
485 .await
486 .unwrap();
487 assert_eq!(vec![attachment.clone()], messages[0].attachments);
488 assert_eq!(AttachmentKind::Image, attachment.kind);
489 assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height));
490
491 let file = db::attachment::read(attachment.id, &conn)
492 .await
493 .unwrap()
494 .file;
495 std::fs::remove_file(directory.join(&file)).unwrap();
496 std::fs::remove_file(thumb_path(&directory, &file)).unwrap();
497 }
498}