use std::{ io::{BufReader, Cursor}, path::{Path, PathBuf}, time::{Duration, SystemTime}, }; use bitcode::Encode; use common::{ constant::{ ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, AVATAR_SIZE, MAXIMUM_AVATAR_BYTES, THUMBNAIL_SIZE, }, error::{Error as CommonError, Field, Problem}, frame::{self, DOWN_MAX, Sending}, model::{Attachment, AttachmentKind, Id, ServerSettings, User}, open::{Blob, Upload}, permission, time::{HOUR_MILLIS, now_ms}, validate::{validate_attachment_name, validate_attachment_size, validate_avatar_size}, }; use image::{ImageFormat, ImageReader, Limits}; use quinn::{RecvStream, VarInt}; use tokio::{ fs::File, io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, }; use tracing::error; use crate::{ authentication::random_bytes, backup, db::{self, Db}, error::{ServerError, ensure, ensure_with}, }; const COLLECT_INTERVAL: Duration = Duration::from_secs(600); const MAXIMUM_IMAGE_SIDE: u32 = 16384; const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024; const THUMB_SUFFIX: &str = ".thumb"; const FILE_NAME_BYTES: usize = 16; fn thumb_path(directory: &Path, file: &str) -> PathBuf { directory.join(format!("{file}{THUMB_SUFFIX}")) } fn remove_files(directory: &Path, file: &str) { let _ = std::fs::remove_file(directory.join(file)); let _ = std::fs::remove_file(thumb_path(directory, file)); } fn media_kind(head: &[u8]) -> AttachmentKind { if is_video(head) { AttachmentKind::Video } else if is_audio(head) { AttachmentKind::Audio } else { AttachmentKind::File } } fn is_image(head: &[u8]) -> bool { matches!( image::guess_format(head), Ok(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP) ) } fn is_video(head: &[u8]) -> bool { head.get(4..8) == Some(b"ftyp") || head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) } fn is_audio(head: &[u8]) -> bool { head.starts_with(b"OggS") || head.starts_with(b"fLaC") || head.starts_with(b"ID3") || head.starts_with(&[0xFF, 0xFB]) || head.starts_with(&[0xFF, 0xF3]) || head.starts_with(&[0xFF, 0xF2]) || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WAVE")) } fn decode_thumbnail(source: &Path, thumbnail: &Path) -> Option<(u32, u32)> { let mut reader = ImageReader::new(BufReader::new(std::fs::File::open(source).ok()?)) .with_guessed_format() .ok()?; let mut limits = Limits::default(); limits.max_image_width = Some(MAXIMUM_IMAGE_SIDE); limits.max_image_height = Some(MAXIMUM_IMAGE_SIDE); limits.max_alloc = Some(MAXIMUM_DECODE_BYTES); reader.limits(limits); let image = reader.decode().ok()?; let (width, height) = (image.width(), image.height()); let fitted = if width > THUMBNAIL_SIZE || height > THUMBNAIL_SIZE { image.thumbnail(THUMBNAIL_SIZE, THUMBNAIL_SIZE) } else { image }; let mut bytes = Cursor::new(Vec::new()); fitted .to_rgb8() .write_to(&mut bytes, ImageFormat::Jpeg) .ok()?; std::fs::write(thumbnail, bytes.into_inner()).ok()?; Some((width, height)) } pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> { validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| { CommonError::Invalid { field: Field::Avatar, problem: Problem::NotJpeg, } })?; if image.width() != image.height() || image.width() > AVATAR_SIZE { return Err(CommonError::Invalid { field: Field::Avatar, problem: Problem::Dimensions { expected: AVATAR_SIZE, }, } .into()); } Ok(()) } async fn receive_body( reader: &mut R, path: &Path, size: u64, ) -> Result, ServerError> { let mismatch = |actual: u64| CommonError::Invalid { field: Field::Attachment, problem: Problem::Length { min: size, max: size, actual, }, }; let mut file = File::create(path).await?; let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize]; reader.read_exact(&mut head).await?; file.write_all(&head).await?; let mut received = head.len() as u64; let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; loop { let read = reader.read(&mut buffer).await?; if read == 0 { break; } received += read as u64; if received > size { return Err(mismatch(received).into()); } file.write_all(&buffer[..read]).await?; } if received != size { return Err(mismatch(received).into()); } file.flush().await?; Ok(head) } async fn ensure_quota( user_id: Id, community_id: Id, size: u64, settings: &ServerSettings, db: &db::Connection, ) -> Result<(), ServerError> { let (user_used, community_used) = db::attachment::quota(user_id, community_id, db).await?; let over = |used: u64, limit: u64| limit != 0 && used.saturating_add(size) > limit; ensure_with( !over(user_used, settings.user_quota_bytes) && !over(community_used, settings.community_quota_bytes), CommonError::QuotaExceeded, ) } async fn write_file( reader: &mut (impl AsyncRead + Unpin), header: &Upload, path: &Path, thumbnail: PathBuf, ) -> Result<(AttachmentKind, Option, Option), ServerError> { let head = receive_body(reader, path, header.size).await?; let described = if is_image(&head) { let source = path.to_path_buf(); tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail)).await? } else { None }; Ok(match described { Some((width, height)) => (AttachmentKind::Image, Some(width), Some(height)), None => (media_kind(&head), None, None), }) } pub async fn store( user: &User, header: &Upload, reader: &mut R, db: &Db, directory: &Path, ) -> Result { let settings = db .run(async |conn| { let rank = permission::effective_rank( user.role, db::member::rank(user.id, header.community_id, conn).await?, ); ensure(permission::is_member(rank))?; validate_attachment_name(&header.name)?; let settings = db::settings::read(conn).await?; validate_attachment_size(header.size, settings.max_attachment_bytes)?; ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?; Ok(settings) }) .await?; let file: String = random_bytes::()? .iter() .map(|byte| format!("{byte:02x}")) .collect(); let path = directory.join(&file); let (kind, width, height) = match write_file(reader, header, &path, thumb_path(directory, &file)).await { Ok(described) => described, Err(error) => { remove_files(directory, &file); return Err(error); } }; let stored = db .run(async |conn| { ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?; db::attachment::insert( user.id, header.community_id, &file, &header.name, header.size, kind, width, height, conn, ) .await }) .await; if stored.is_err() { remove_files(directory, &file); } stored } pub(crate) async fn reply_upload( result: Result, mut send_stream: Sending, mut receive_stream: RecvStream, ) -> Result<(), ServerError> { let rejected = result.is_err(); let reply = result.map_err(CommonError::from); frame::write(&mut send_stream, &reply, DOWN_MAX).await?; send_stream.finish()?; if rejected { let _ = receive_stream.stop(VarInt::from_u32(0)); } Ok(()) } pub async fn upload( user: Option<&User>, header: Upload, mut receive_stream: RecvStream, send_stream: Sending, db: &Db, directory: &Path, ) -> Result<(), ServerError> { let stored = match user { Some(user) => store(user, &header, &mut receive_stream, db, directory).await, None => Err(CommonError::Unauthenticated.into()), }; reply_upload(stored, send_stream, receive_stream).await } async fn locate( user: Option<&User>, attachment_id: Id, thumbnail: bool, db: &Db, directory: &Path, ) -> Result<(PathBuf, u64), ServerError> { let user = user.ok_or(CommonError::Unauthenticated)?; let stored = db .run(async |conn| { let stored = db::attachment::read(attachment_id, conn).await?; let rank = permission::effective_rank( user.role, db::member::rank(user.id, stored.community_id, conn).await?, ); ensure(permission::is_member(rank))?; ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; Ok(stored) }) .await?; let path = if thumbnail { thumb_path(directory, &stored.file) } else { directory.join(&stored.file) }; let length = tokio::fs::metadata(&path) .await .map_err(|_| CommonError::NotFound)? .len(); Ok((path, length)) } pub async fn fetch( user: Option<&User>, blob: Blob, mut send_stream: Sending, db: &Db, directory: &Path, backups: &Path, ) -> Result<(), ServerError> { let located = match &blob { Blob::Attachment(id) => locate(user, *id, false, db, directory).await, Blob::Thumbnail(id) => locate(user, *id, true, db, directory).await, Blob::Backup(name) => backup::locate(user, name, db, backups).await, }; let located = located.map_err(CommonError::from); let reply = located .as_ref() .map(|(_, length)| *length) .map_err(Clone::clone); frame::write(&mut send_stream, &reply, DOWN_MAX).await?; if let Ok((path, _)) = located { let mut file = File::open(path).await?; tokio::io::copy(&mut file, send_stream.get()).await?; } send_stream.finish()?; Ok(()) } pub async fn collect(db: Db, directory: PathBuf) { let mut interval = tokio::time::interval(COLLECT_INTERVAL); loop { interval.tick().await; if let Err(error) = sweep(&db, &directory).await { error!("attachment sweep: {error}"); } } } async fn sweep(db: &Db, directory: &Path) -> Result<(), ServerError> { let stale_ms = now_ms().saturating_sub(HOUR_MILLIS); let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); let files = db .run(async |conn| { db::attachment::delete_stale_unbound(stale_ms, conn).await?; db::attachment::files(conn).await }) .await?; for entry in std::fs::read_dir(directory)? { let Ok(entry) = entry else { continue }; let name = entry.file_name().to_string_lossy().into_owned(); let file = name.strip_suffix(THUMB_SUFFIX).unwrap_or(&name); let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else { continue; }; if modified < stale_at && !files.contains(file) { let _ = std::fs::remove_file(entry.path()); } } Ok(()) } #[cfg(test)] mod tests { use std::io::Cursor; use common::{ constant::AVATAR_SIZE, error::{Error as CommonError, Field}, model::{AttachmentKind, Rank, Role}, open::Upload, }; use image::{ImageFormat, RgbImage}; use super::{check_avatar, store, thumb_path}; use crate::{db, error::ServerError, test}; fn jpeg(size: u32) -> Vec { let mut bytes = Cursor::new(Vec::new()); RgbImage::new(size, size) .write_to(&mut bytes, ImageFormat::Jpeg) .unwrap(); bytes.into_inner() } #[test] fn avatar_checks_jpeg_size() { let large = check_avatar(&jpeg(AVATAR_SIZE * 2)); let not_jpeg = check_avatar(b"not a jpeg"); assert!(matches!( large, Err(ServerError::Wire(CommonError::Invalid { field: Field::Avatar, .. })) )); assert!(matches!( not_jpeg, Err(ServerError::Wire(CommonError::Invalid { field: Field::Avatar, .. })) )); assert!(check_avatar(&jpeg(AVATAR_SIZE)).is_ok()); assert!(check_avatar(&jpeg(AVATAR_SIZE / 2)).is_ok()); } #[tokio::test] async fn upload_then_read_in_message() { let db = test::db().await; let (user, community) = { let conn = db.lock().await.unwrap(); let user = db::user::create("Tahinli", "hash", Role::User, &conn) .await .unwrap(); let community_id = db::community::create(db::community::Kind::Group, "Tahinli", &conn) .await .unwrap(); db::member::join(user.id, community_id, Rank::Member, &conn) .await .unwrap(); (user, community_id) }; let mut png = Cursor::new(Vec::new()); RgbImage::new(2, 3) .write_to(&mut png, ImageFormat::Png) .unwrap(); let png = png.into_inner(); let directory = test::directory(); let header = Upload { community_id: community, name: "pixel.png".to_string(), size: png.len() as u64, }; let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory) .await .unwrap(); let conn = db.lock().await.unwrap(); db::message::create(user.id, community, "", &[attachment.id], None, &conn) .await .unwrap(); let messages = db::message::read_page(community, None, false, &conn) .await .unwrap(); assert_eq!(vec![attachment.clone()], messages[0].attachments); assert_eq!(AttachmentKind::Image, attachment.kind); assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); let file = db::attachment::read(attachment.id, &conn) .await .unwrap() .file; std::fs::remove_file(directory.join(&file)).unwrap(); std::fs::remove_file(thumb_path(&directory, &file)).unwrap(); } }