diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index ddc6b03..3b61f4f 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -9,7 +9,7 @@ pixel.workspace = true spectrum.workspace = true reed-solomon-simd = "3.1.0" tokio.workspace = true -quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } +quinn = { workspace = true, features = ["rustls-ring"] } gpui-kit = { version = "0.11.0", features = ["syntect"] } ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } @@ -31,6 +31,8 @@ jiff = "1.0.2" dirs = "7.0.0" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } rtrb = "0.4.1" +gethostname = "1.1.0" +rustls-platform-verifier = "0.7.1" [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } diff --git a/crates/client/src/avatar.rs b/crates/client/src/avatar.rs index 5309e00..773238d 100644 --- a/crates/client/src/avatar.rs +++ b/crates/client/src/avatar.rs @@ -1,12 +1,13 @@ +use crate::net::Fail; use common::{ constant::AVATAR_SIZE, - error::{Error, Field, InvalidInput}, + error::{Error, Field, Problem}, }; use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType}; const QUALITIES: [u8; 3] = [85, 60, 40]; -pub fn prepare(bytes: &[u8], maximum: u64) -> Result, Error> { +pub fn prepare(bytes: &[u8], maximum: u64) -> Result, Fail> { let image = image::load_from_memory(bytes).map_err(image_error)?; let square = center_square(image) .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3) @@ -22,11 +23,13 @@ pub fn prepare(bytes: &[u8], maximum: u64) -> Result, Error> { Err(Error::Invalid { field: Field::Avatar, - input: InvalidInput::TooLarge { - maximum, + problem: Problem::Length { + min: 0, + max: maximum, actual: encoded.len() as u64, }, - }) + } + .into()) } fn center_square(image: DynamicImage) -> DynamicImage { @@ -37,7 +40,7 @@ fn center_square(image: DynamicImage) -> DynamicImage { image.crop_imm(x, y, side, side) } -fn encode(image: &RgbImage, quality: u8) -> Result, Error> { +fn encode(image: &RgbImage, quality: u8) -> Result, Fail> { let mut bytes = Vec::new(); JpegEncoder::new_with_quality(&mut bytes, quality) .encode_image(image) @@ -46,8 +49,8 @@ fn encode(image: &RgbImage, quality: u8) -> Result, Error> { Ok(bytes) } -fn image_error(error: image::ImageError) -> Error { - Error::Decode(error.to_string()) +fn image_error(error: image::ImageError) -> Fail { + Fail::Io(error.to_string()) } const HUE_BINS: usize = 24; diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index c8f78b0..e1b3cb5 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -37,7 +37,7 @@ use tokio::sync::mpsc; use crate::{ accounts::{self, Accounts}, mutes, - network::{NetworkEvent, NetworkHandle}, + net::{Fail, LinkError, NetworkEvent, NetworkHandle}, settings::{Look, Scale, Settings, ThemeChoice}, }; @@ -540,32 +540,18 @@ impl Connection { matches!(self, Self::Connected) } - fn lost(&mut self, error: &Error) { + fn lost(&mut self, error: &LinkError) { let attempts = match self { Self::Lost { attempts, .. } => *attempts + 1, _ => 1, }; *self = Self::Lost { - error: reason(error), + error: error.to_string(), attempts, }; } } -fn reason(error: &Error) -> String { - let text = error.to_string(); - let lower = text.to_lowercase(); - if lower.contains("timed out") || lower.contains("unreachable") { - "Server unreachable".into() - } else if lower.contains("certificate") || lower.contains("tls") { - "Certificate error".into() - } else if lower.contains("refused") { - "Connection refused".into() - } else { - text - } -} - fn connection_notice(connection: &Connection, palette: Palette) -> Option
{ let (label, color) = match connection { Connection::Connecting => ("Connecting…".to_string(), palette.muted), @@ -755,7 +741,7 @@ impl Yumush { let result = network.resume(&account.token).await; let _ = this.update_in(cx, |yumush, window, cx| match result { Ok((user, token)) => yumush.enter_session(user, token, window, cx), - Err(error @ (Error::NotFound | Error::Unauthenticated)) => { + Err(error @ Fail::Server(Error::NotFound | Error::Unauthenticated)) => { yumush.accounts.forget(&account.user_id); window.push_notification(Notification::error(error.to_string()), cx); cx.notify(); diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 8e0d36b..777eb8d 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -32,7 +32,7 @@ use super::{ Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header, text, widget::search_text, }; -use crate::network::NetworkHandle; +use crate::net::NetworkHandle; pub(super) fn save_directory() -> PathBuf { dirs::download_dir().unwrap_or_else(std::env::temp_dir) diff --git a/crates/client/src/gui/builder/overview.rs b/crates/client/src/gui/builder/overview.rs index 8604292..d1d3864 100644 --- a/crates/client/src/gui/builder/overview.rs +++ b/crates/client/src/gui/builder/overview.rs @@ -1,4 +1,5 @@ -use common::{error::Error, model::DayStat, time::DAY_MILLIS}; +use crate::net::Fail; +use common::{model::DayStat, time::DAY_MILLIS}; use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px}; use jiff::Timestamp; @@ -107,7 +108,7 @@ impl Yumush { window, cx, |network| async move { - Ok::<_, Error>((network.overview().await?, network.daily_stats(30).await?)) + Ok::<_, Fail>((network.overview().await?, network.daily_stats(30).await?)) }, |yumush, (overview, stats), cx| { yumush.chat.builder_overview = Some(overview); diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs index 3df4a00..c960041 100644 --- a/crates/client/src/gui/builder/reports.rs +++ b/crates/client/src/gui/builder/reports.rs @@ -1,9 +1,6 @@ use std::future::Future; -use common::{ - error::Error, - model::{BanScope, Report, ReportStatus}, -}; +use common::model::{BanScope, Report, ReportStatus}; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window, div, px, @@ -20,7 +17,7 @@ use crate::{ settings_page::{segment, segment_track}, text, }, - network::NetworkHandle, + net::{Fail, NetworkHandle}, }; const REPORT_FILTERS: [Option; 4] = [ @@ -91,7 +88,7 @@ impl Yumush { cx: &mut Context, action: impl FnOnce(NetworkHandle) -> Fut + 'static, ) where - Fut: Future> + 'static, + Fut: Future> + 'static, { let network = self.network.clone(); diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index 286ac01..8a431c9 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -1,7 +1,6 @@ use std::future::Future; use common::{ - error::Error, model::{Account, BanScope, Role, SessionInfo, User}, permission, time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}, @@ -26,7 +25,7 @@ use crate::{ text, widget::{field, search_text}, }, - network::NetworkHandle, + net::{Fail, NetworkHandle}, }; const MINUTES_PER_HOUR: u64 = HOUR_MILLIS / MINUTE_MILLIS; @@ -143,7 +142,7 @@ impl Yumush { cx: &mut Context, action: impl FnOnce(NetworkHandle) -> Fut + 'static, ) where - Fut: Future> + 'static, + Fut: Future> + 'static, { let network = self.network.clone(); diff --git a/crates/client/src/gui/builder/voice.rs b/crates/client/src/gui/builder/voice.rs index abb75cb..89bb82a 100644 --- a/crates/client/src/gui/builder/voice.rs +++ b/crates/client/src/gui/builder/voice.rs @@ -1,9 +1,6 @@ use std::future::Future; -use common::{ - error::Error, - model::{User, VoiceRoom}, -}; +use common::model::{User, VoiceRoom}; use gpui_kit::{ AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, div, px, @@ -12,7 +9,7 @@ use gpui_kit::{ use super::ui::{card, card_header, icon_button, list_card, pill, rows_body}; use crate::{ gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text}, - network::NetworkHandle, + net::{Fail, NetworkHandle}, }; impl Yumush { @@ -34,7 +31,7 @@ impl Yumush { cx: &mut Context, action: impl FnOnce(NetworkHandle) -> Fut + 'static, ) where - Fut: Future> + 'static, + Fut: Future> + 'static, { let network = self.network.clone(); diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index bb63dd1..7e44a05 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -28,7 +28,7 @@ use crate::gui::{ voice_note::{self, VoiceNote}, widget::{icon_button, ok_or_notify, search_text, spawn_done}, }; -use crate::network::Levels; +use crate::net::Levels; use crate::settings::VOLUME; use crate::share::session::ShareSample; use crate::voice::VoiceSample; diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index cf5c887..a045164 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -1,7 +1,7 @@ use std::{collections::HashMap, sync::Arc}; +use crate::net::Fail; use common::{ - error::Error, model::{Ban, Community, LogAction, LogEntry, User}, permission, validate::validate_community_name, @@ -56,7 +56,7 @@ const LOG_SORTS: [(LogSort, &str); 2] = [(LogSort::Newest, "Newest"), (LogSort:: fn apply_community( this: &WeakEntity, cx: &mut AsyncWindowContext, - result: Result, + result: Result, ) { match result { Ok(community) => { @@ -225,7 +225,14 @@ impl Yumush { let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; - let name = self.chat.community_name_input.read(cx).text().to_string().trim().to_string(); + let name = self + .chat + .community_name_input + .read(cx) + .text() + .to_string() + .trim() + .to_string(); if let Err(error) = validate_community_name(&name) { window.push_notification(Notification::error(error.to_string()), cx); diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index bab62fc..ccc721a 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -2,6 +2,7 @@ use super::text; use super::widget::{compact_field, icon_button, panel, spawn_done}; use std::time::{Duration, Instant}; +use crate::net::Fail; use common::{ constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS}, error::Error, @@ -275,19 +276,12 @@ impl Yumush { .await { Ok(_) => {} - Err(Error::RateLimited { + Err(Fail::Server(Error::RateLimited { retry_after_seconds, - }) => { + })) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.slow_down( - retry_after_seconds, - &restore, - &community_id, - body, - pending, - window, - cx, - ) + yumush.restore_message(&restore, &community_id, body, pending, window, cx); + yumush.slow_down(retry_after_seconds, window, cx) }); } Err(error) => { @@ -330,14 +324,9 @@ impl Yumush { fn slow_down( &mut self, seconds: u64, - input: &Entity, - community_id: &str, - body: String, - pending: Vec, window: &mut Window, cx: &mut Context, ) { - self.restore_message(input, community_id, body, pending, window, cx); self.chat.slowed_until = Some(now_ms() + seconds * 1000); cx.spawn_in(window, async move |this, cx| { diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index f9c12bf..9600ed4 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -29,7 +29,7 @@ use super::{ use crate::{ embed::{self, Embed, EmbedKind}, media::{Player, voice_note as note}, - network::NetworkHandle, + net::{Fail, NetworkHandle}, }; const FRAME_TICK: Duration = Duration::from_millis(16); @@ -152,7 +152,7 @@ pub(super) async fn upload_file( path: PathBuf, maximum: Option, cx: &mut AsyncWindowContext, -) -> Result { +) -> Result { let _ = this.update(cx, |yumush, cx| { yumush.chat.media.uploading += 1; cx.notify(); @@ -322,11 +322,11 @@ impl Yumush { &self, attachment: &Attachment, cx: &mut Context, - ) -> Task> { + ) -> Task> { let network = self.network.clone(); let attachment = attachment.clone(); cx.spawn(async move |_, cx| { - let path = cache_path(&attachment).ok_or(common::error::Error::Server)?; + let path = cache_path(&attachment).ok_or(Fail::Protocol)?; if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) { return Ok(path); } @@ -337,7 +337,7 @@ impl Yumush { async move { std::fs::write(&path, bytes) } }) .await - .map_err(|_| common::error::Error::Server)?; + .map_err(|_| Fail::Protocol)?; Ok(path) }) } diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 83df871..5f9bbbb 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -1,6 +1,7 @@ use std::future::Future; -use common::{error::Error, model::User}; +use crate::net::Fail; +use common::model::User; use gpui_kit::{ AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, @@ -255,7 +256,7 @@ impl Yumush { } } -fn apply_user(this: &WeakEntity, cx: &mut AsyncWindowContext, result: Result) { +fn apply_user(this: &WeakEntity, cx: &mut AsyncWindowContext, result: Result) { match result { Ok(user) => { let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); @@ -267,7 +268,7 @@ fn apply_user(this: &WeakEntity, cx: &mut AsyncWindowContext, result: Re pub(super) fn picked_avatar( cx: &App, maximum: u64, -) -> impl Future, Error>>> + 'static { +) -> impl Future, Fail>>> + 'static { let picked = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs index 55f951f..0bf5318 100644 --- a/crates/client/src/gui/voice_note.rs +++ b/crates/client/src/gui/voice_note.rs @@ -153,7 +153,11 @@ pub fn recording_row( .text_size(text(13.)) .text_color(palette.text) .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.))) - .child(time_text(started.elapsed().min(Duration::from_secs(MAX_SECONDS as u64)))) + .child(time_text( + started + .elapsed() + .min(Duration::from_secs(MAX_SECONDS as u64)), + )) .child(bars(levels, 1., palette, |_, _, _| {})), ) .child( diff --git a/crates/client/src/gui/wave.rs b/crates/client/src/gui/wave.rs index b7d388b..437e931 100644 --- a/crates/client/src/gui/wave.rs +++ b/crates/client/src/gui/wave.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px}; -use crate::network::Levels; +use crate::net::Levels; const DECAY: f32 = 0.82; const GONE: f32 = 0.02; diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 288a2e0..12885c3 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -9,7 +9,7 @@ pub mod embed; pub mod gui; pub mod media; pub mod mutes; -pub mod network; +pub mod net; pub mod settings; pub mod share; pub mod tray; diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 28a0748..8cf6a7f 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -3,7 +3,7 @@ use client::{ ClientConfig, NAME, gui::{self, Yumush}, - network, settings, + net, settings, tray::{self, TrayAction, TrayState}, }; use gpui_kit::{ @@ -25,7 +25,7 @@ fn main() { .init(); let settings = settings::load(); - let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); + let (network_handle, network_event_receiver) = net::start(ClientConfig::default()); let (mut tray_receiver, tray_handle) = tray::start(); application() diff --git a/crates/client/src/net/datagram.rs b/crates/client/src/net/datagram.rs new file mode 100644 index 0000000..da22553 --- /dev/null +++ b/crates/client/src/net/datagram.rs @@ -0,0 +1,34 @@ +use common::{ + datagram::{Datagram, decode_relay}, + share::Kind, +}; + +use super::*; + +pub(super) async fn datagram_receive_loop(connection: quinn::Connection, shared: Shared) { + let loss: u64 = std::env::var("YUMUSH_TEST_LOSS") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(0); + let mut received: u64 = 0; + while let Ok(datagram) = connection.read_datagram().await { + if let Some(voice) = shared.voice.lock().unwrap().as_ref() { + voice.receive(&datagram); + } + if let Some((user_id, packet)) = decode_relay(&datagram) { + if let Datagram::Video(_) = packet { + received += 1; + if received * 37 % 100 < loss { + continue; + } + } + let kind = match &packet { + Datagram::Video(fragment) => fragment.kind, + _ => Kind::Screen, + }; + if let Some(watching) = shared.share.lock().unwrap().watching.get(&(user_id, kind)) { + watching.receive(packet); + } + } + } +} diff --git a/crates/client/src/net/events.rs b/crates/client/src/net/events.rs new file mode 100644 index 0000000..0ee0875 --- /dev/null +++ b/crates/client/src/net/events.rs @@ -0,0 +1,28 @@ +use common::{ + event::Event, + frame::{self, DOWN_MAX}, +}; +use tokio::sync::mpsc; + +use super::*; + +pub(super) async fn event_receive_loop( + connection: quinn::Connection, + event_sender: mpsc::Sender, + share: SharedShare, +) { + let Ok(mut receive_stream) = connection.accept_uni().await else { + return; + }; + + while let Ok(event) = frame::read::(&mut receive_stream, DOWN_MAX).await { + share.lock().unwrap().event(&event); + if event_sender + .send(NetworkEvent::Pushed(Box::new(event))) + .await + .is_err() + { + return; + } + } +} diff --git a/crates/client/src/net/fail.rs b/crates/client/src/net/fail.rs new file mode 100644 index 0000000..6d1031b --- /dev/null +++ b/crates/client/src/net/fail.rs @@ -0,0 +1,151 @@ +use common::{error::Error, frame::FrameError, transport::Close}; + +const NO_APPLICATION_PROTOCOL: u64 = 0x100 + 120; +const CRYPTO_ERRORS: std::ops::Range = 0x100..0x200; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LinkError { + Unreachable, + Tls, + Timeout, + Outdated, + Reset, + Closed(Close), +} + +impl std::fmt::Display for LinkError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Unreachable | Self::Timeout => write!(f, "Server unreachable"), + Self::Tls => write!(f, "Certificate error"), + Self::Outdated => write!(f, "Client is outdated"), + Self::Reset => write!(f, "Connection lost"), + Self::Closed(close) => write!(f, "{}", close.reason()), + } + } +} + +impl LinkError { + fn by_code(code: u64) -> Self { + match code { + NO_APPLICATION_PROTOCOL => Self::Outdated, + code if CRYPTO_ERRORS.contains(&code) => Self::Tls, + _ => Self::Reset, + } + } +} + +impl From for LinkError { + fn from(error: quinn::ConnectionError) -> Self { + match error { + quinn::ConnectionError::TimedOut => Self::Timeout, + quinn::ConnectionError::ConnectionClosed(close) => { + Self::by_code(u64::from(close.error_code)) + } + quinn::ConnectionError::TransportError(error) => Self::by_code(u64::from(error.code)), + quinn::ConnectionError::ApplicationClosed(close) => { + Close::of(close.error_code).map_or(Self::Reset, Self::Closed) + } + quinn::ConnectionError::LocallyClosed => Self::Closed(Close::Normal), + quinn::ConnectionError::VersionMismatch => Self::Outdated, + quinn::ConnectionError::Reset | quinn::ConnectionError::CidsExhausted => Self::Reset, + } + } +} + +#[derive(Debug, Clone)] +pub enum Fail { + Server(Error), + Offline, + Link(LinkError), + Protocol, + Io(String), +} + +impl std::fmt::Display for Fail { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Server(error) => write!(f, "{error}"), + Self::Offline => write!(f, "Offline"), + Self::Link(error) => write!(f, "{error}"), + Self::Protocol => write!(f, "Protocol error"), + Self::Io(message) => write!(f, "{message}"), + } + } +} + +impl From for Fail { + fn from(error: Error) -> Self { + Self::Server(error) + } +} + +impl From for Fail { + fn from(error: LinkError) -> Self { + Self::Link(error) + } +} + +impl From for Fail { + fn from(error: quinn::ConnectionError) -> Self { + Self::Link(error.into()) + } +} + +impl From for Fail { + fn from(error: quinn::WriteError) -> Self { + match error { + quinn::WriteError::ConnectionLost(error) => error.into(), + _ => Self::Link(LinkError::Reset), + } + } +} + +impl From for Fail { + fn from(error: quinn::ReadError) -> Self { + match error { + quinn::ReadError::ConnectionLost(error) => error.into(), + _ => Self::Link(LinkError::Reset), + } + } +} + +impl From for Fail { + fn from(_: quinn::ClosedStream) -> Self { + Self::Link(LinkError::Reset) + } +} + +impl From for Fail { + fn from(_: quinn::ConnectError) -> Self { + Self::Link(LinkError::Unreachable) + } +} + +impl From for Fail { + fn from(error: FrameError) -> Self { + match error { + FrameError::Connection(error) => error.into(), + FrameError::Write(error) => error.into(), + FrameError::Read(quinn::ReadExactError::ReadError(error)) => error.into(), + FrameError::Read(quinn::ReadExactError::FinishedEarly(_)) => Self::Protocol, + FrameError::Closed(error) => error.into(), + FrameError::TooLarge { .. } | FrameError::Decode(_) => Self::Protocol, + } + } +} + +impl From for Fail { + fn from(error: std::io::Error) -> Self { + Self::Io(error.to_string()) + } +} + +impl From for Fail { + fn from(error: quinn::ReadExactError) -> Self { + match error { + quinn::ReadExactError::ReadError(error) => error.into(), + quinn::ReadExactError::FinishedEarly(_) => Self::Protocol, + } + } +} diff --git a/crates/client/src/net/fetch.rs b/crates/client/src/net/fetch.rs new file mode 100644 index 0000000..01dc4ab --- /dev/null +++ b/crates/client/src/net/fetch.rs @@ -0,0 +1,68 @@ +use std::{collections::HashMap, sync::Mutex}; + +use common::open::Blob; +use tokio::sync::{Semaphore, SemaphorePermit, oneshot}; + +use super::{Fail, link}; + +const PARALLEL_FETCHES: usize = 6; + +type Waiter = oneshot::Sender>, Fail>>; + +pub(super) struct Fetches { + permits: Semaphore, + waiting: Mutex>>, +} + +impl Default for Fetches { + fn default() -> Self { + Self { + permits: Semaphore::new(PARALLEL_FETCHES), + waiting: Mutex::default(), + } + } +} + +impl Fetches { + pub(super) async fn permit(&self) -> SemaphorePermit<'_> { + self.permits + .acquire() + .await + .expect("semaphore never closes") + } + + pub(super) async fn memory( + &self, + connection: &quinn::Connection, + blob: Blob, + ) -> Result, Fail> { + let (sender, receiver) = oneshot::channel(); + let leader = { + let mut waiting = self.waiting.lock().unwrap(); + let senders = waiting.entry(blob.clone()).or_default(); + senders.push(sender); + senders.len() == 1 + }; + + if leader { + let result = { + let _permit = self.permit().await; + link::download(connection, &blob).await + } + .map(std::sync::Arc::new); + let senders = self + .waiting + .lock() + .unwrap() + .remove(&blob) + .unwrap_or_default(); + for sender in senders { + let _ = sender.send(result.clone()); + } + } + + let bytes = receiver.await.map_err(|_| Fail::Offline)??; + + Ok((*bytes).clone()) + } +} diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs new file mode 100644 index 0000000..3c79b78 --- /dev/null +++ b/crates/client/src/net/link.rs @@ -0,0 +1,603 @@ +use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration}; + +use common::{ + constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, + error::Error, + frame::{self, DOWN_MAX, Sending, UP_MAX}, + model::Attachment, + open::{Blob, Open, Upload}, + request::Request, + response::Response, + transport::{Close, alpn, transport}, + validate::{validate_attachment_name, validate_attachment_size}, +}; +use quinn::Endpoint; +#[cfg(debug_assertions)] +use quinn::{ + crypto::rustls::QuicClientConfig, + rustls::{ + self, DigitallySignedStruct, SignatureScheme, + client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, + pki_types::{CertificateDer, ServerName, UnixTime}, + }, +}; +#[cfg(debug_assertions)] +use rustls_platform_verifier as _; +use tokio::sync::{mpsc, oneshot}; +use tracing::{info, warn}; + +use crate::{ + ClientConfig, + voice::{self}, +}; + +use super::{ + datagram::datagram_receive_loop, + events::event_receive_loop, + share::{start_share, update_share}, + *, +}; + +const CHANNEL_SIZE: usize = 32; +const BACKOFF_BASE_MILLIS: u64 = 250; +const BACKOFF_CAP_MILLIS: u64 = 8_000; + +const SHARE_TICK: Duration = Duration::from_secs(1); + +pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver) { + let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); + let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); + let shared = Shared::default(); + + std::thread::Builder::new() + .name("network".to_string()) + .spawn({ + let shared = shared.clone(); + move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("network runtime") + .block_on(actor(client_config, command_receiver, event_sender, shared)); + } + }) + .expect("network thread"); + + ( + NetworkHandle { + command_sender, + shared, + }, + event_receiver, + ) +} + +#[derive(Default)] +struct Endpoints { + v6: Option, + v4: Option, +} + +impl Endpoints { + fn get(&mut self, address: SocketAddr) -> Result { + let (slot, bind) = match address { + SocketAddr::V6(_) => (&mut self.v6, "[::]:0"), + SocketAddr::V4(_) => (&mut self.v4, "0.0.0.0:0"), + }; + if let Some(endpoint) = slot { + return Ok(endpoint.clone()); + } + + let bind: SocketAddr = bind.parse().map_err(|_| LinkError::Unreachable)?; + let mut endpoint = Endpoint::client(bind).map_err(|_| LinkError::Unreachable)?; + endpoint.set_default_client_config(config()?); + *slot = Some(endpoint.clone()); + + Ok(endpoint) + } + + fn forget(&mut self, address: SocketAddr) { + match address { + SocketAddr::V6(_) => self.v6 = None, + SocketAddr::V4(_) => self.v4 = None, + } + } +} + +fn backoff(attempt: u32) -> Duration { + let base = (BACKOFF_BASE_MILLIS << attempt.min(10)).min(BACKOFF_CAP_MILLIS); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.subsec_nanos() as u64); + let jitter = base * (80 + nanos % 41) / 100; + + Duration::from_millis(jitter) +} + +async fn connect( + client_config: &ClientConfig, + endpoints: &mut Endpoints, +) -> Result { + let mut addresses: Vec = + tokio::net::lookup_host(client_config.server_address.as_str()) + .await + .map_err(|_| LinkError::Unreachable)? + .collect(); + addresses.sort_by_key(|address| address.is_ipv4()); + + let mut last = LinkError::Unreachable; + for address in addresses { + let endpoint = match endpoints.get(address) { + Ok(endpoint) => endpoint, + Err(error) => { + last = error; + continue; + } + }; + let connecting = match endpoint.connect(address, &client_config.server_name) { + Ok(connecting) => connecting, + Err(_) => { + endpoints.forget(address); + last = LinkError::Unreachable; + continue; + } + }; + match connecting.await { + Ok(connection) => return Ok(connection), + Err(error) => { + endpoints.forget(address); + last = error.into(); + if last == LinkError::Outdated { + return Err(last); + } + } + } + } + + Err(last) +} + +fn tls_error(_: impl std::fmt::Display) -> LinkError { + LinkError::Tls +} + +#[cfg(debug_assertions)] +#[derive(Debug)] +struct AcceptAnyCertificate { + provider: Arc, +} + +#[cfg(debug_assertions)] +impl ServerCertVerifier for AcceptAnyCertificate { + fn verify_server_cert( + &self, + _end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp_response: &[u8], + _now: UnixTime, + ) -> Result { + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn supported_verify_schemes(&self) -> Vec { + self.provider + .signature_verification_algorithms + .supported_schemes() + } +} + +#[cfg(debug_assertions)] +fn accept_any_client_config() -> Result { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut tls = rustls::ClientConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(tls_error)? + .dangerous() + .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider })) + .with_no_client_auth(); + tls.alpn_protocols = vec![alpn()]; + + let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?; + + Ok(quinn::ClientConfig::new(Arc::new(crypto))) +} + +#[cfg(not(debug_assertions))] +fn platform_client_config() -> Result { + let provider = Arc::new(quinn::rustls::crypto::ring::default_provider()); + let verifier = rustls_platform_verifier::Verifier::new(provider.clone()).map_err(tls_error)?; + let mut tls = quinn::rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&quinn::rustls::version::TLS13]) + .map_err(tls_error)? + .dangerous() + .with_custom_certificate_verifier(Arc::new(verifier)) + .with_no_client_auth(); + tls.alpn_protocols = vec![alpn()]; + + let crypto = quinn::crypto::rustls::QuicClientConfig::try_from(tls).map_err(tls_error)?; + + Ok(quinn::ClientConfig::new(Arc::new(crypto))) +} + +fn config() -> Result { + #[cfg(debug_assertions)] + let mut client_config = accept_any_client_config()?; + + #[cfg(not(debug_assertions))] + let mut client_config = platform_client_config()?; + + client_config.transport_config(Arc::new(transport())); + + Ok(client_config) +} + +pub(super) async fn send( + connection: &quinn::Connection, + request: &Request, +) -> Result { + let (send_stream, mut receive_stream) = connection.open_bi().await?; + let mut send_stream = Sending::new(send_stream); + frame::write(&mut send_stream, &Open::Call(request.clone()), UP_MAX).await?; + send_stream.finish()?; + + Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) +} + +pub(super) async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Fail> { + match send(connection, &request).await? { + Response::Done => Ok(()), + _ => Err(Fail::Protocol), + } +} + +pub(super) async fn send_body( + send_stream: &mut quinn::SendStream, + file: &mut tokio::fs::File, +) -> Result<(), Fail> { + use tokio::io::AsyncReadExt; + + let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; + loop { + let read = file.read(&mut buffer).await?; + if read == 0 { + return Ok(()); + } + + send_stream.write_all(&buffer[..read]).await?; + } +} + +pub(super) async fn upload( + connection: &quinn::Connection, + community_id: &str, + path: &Path, + maximum: Option, +) -> Result { + let name = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + validate_attachment_name(&name)?; + + let mut file = tokio::fs::File::open(path).await?; + let size = file.metadata().await?.len(); + if let Some(maximum) = maximum { + validate_attachment_size(size, maximum)?; + } + + let (send_stream, mut receive_stream) = connection.open_bi().await?; + let mut send_stream = Sending::new(send_stream); + let header = Upload { + community_id: community_id.to_string(), + name, + size, + }; + frame::write(&mut send_stream, &Open::Upload(header), UP_MAX).await?; + + let write = async move { + send_body(send_stream.get(), &mut file).await?; + Ok(send_stream.finish()?) + }; + let read = frame::read::>(&mut receive_stream, DOWN_MAX); + let (sent, reply) = tokio::join!(write, read); + + match (sent, reply) { + (_, Ok(reply)) => Ok(reply?), + (Err(error), _) => Err(error), + (_, Err(error)) => Err(error.into()), + } +} + +async fn open_fetch( + connection: &quinn::Connection, + blob: &Blob, +) -> Result<(quinn::RecvStream, u64), Fail> { + let (send_stream, mut receive_stream) = connection.open_bi().await?; + let mut send_stream = Sending::new(send_stream); + frame::write(&mut send_stream, &Open::Fetch(blob.clone()), UP_MAX).await?; + send_stream.finish()?; + + let length = frame::read::>(&mut receive_stream, DOWN_MAX).await??; + + Ok((receive_stream, length)) +} + +pub(super) async fn backup_download( + connection: &quinn::Connection, + name: &str, + path: &Path, +) -> Result<(), Fail> { + let (mut receive_stream, length) = + open_fetch(connection, &Blob::Backup(name.to_string())).await?; + + let mut part = path.as_os_str().to_owned(); + part.push(".part"); + let part = std::path::PathBuf::from(part); + + let copied = async { + let mut file = tokio::fs::File::create(&part).await?; + let copied = tokio::io::copy(&mut receive_stream, &mut file).await?; + if copied != length { + return Err(Fail::Protocol); + } + file.sync_all().await?; + tokio::fs::rename(&part, path).await?; + Ok(()) + } + .await; + if copied.is_err() { + let _ = tokio::fs::remove_file(&part).await; + } + + copied +} + +pub(super) async fn download(connection: &quinn::Connection, blob: &Blob) -> Result, Fail> { + let (mut receive_stream, length) = open_fetch(connection, blob).await?; + + if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES { + return Err(Fail::Protocol); + } + + let mut bytes = vec![0u8; length as usize]; + receive_stream.read_exact(&mut bytes).await?; + + Ok(bytes) +} + +pub(super) fn answer( + reply: oneshot::Sender>, + work: impl Future> + Send + 'static, +) { + tokio::spawn(async move { + let _ = reply.send(work.await); + }); +} + +async fn actor( + client_config: ClientConfig, + mut command_receiver: mpsc::Receiver, + event_sender: mpsc::Sender, + shared: Shared, +) { + let mut token: Option = None; + let mut endpoints = Endpoints::default(); + let mut attempt = 0u32; + 'session: loop { + let connection = loop { + match connect(&client_config, &mut endpoints).await { + Ok(connection) => break connection, + Err(LinkError::Outdated) => { + warn!("server speaks another protocol version"); + let _ = event_sender + .send(NetworkEvent::Disconnected(LinkError::Outdated)) + .await; + while command_receiver.recv().await.is_some() {} + return; + } + Err(error) => { + warn!("connect failed: {error}"); + + if event_sender + .send(NetworkEvent::Disconnected(error)) + .await + .is_err() + { + return; + } + + tokio::time::sleep(backoff(attempt)).await; + attempt += 1; + } + }; + }; + + if let Some(stored) = token.clone() { + let request = Request::Resume { token: stored }; + match send(&connection, &request).await { + Ok(Response::Session { token: resumed, .. }) => { + token = Some(resumed); + } + Err(error) => { + warn!("session resume failed: {error}"); + if let Some(reason) = connection.close_reason() { + let event = LinkError::from(reason); + if event == LinkError::Closed(Close::Banned) { + let _ = event_sender.send(NetworkEvent::Disconnected(event)).await; + while command_receiver.recv().await.is_some() {} + return; + } + } + tokio::time::sleep(backoff(attempt)).await; + attempt += 1; + continue 'session; + } + Ok(_) => { + warn!("session resume rejected"); + token = None; + + if event_sender.send(NetworkEvent::SessionLost).await.is_err() { + return; + } + } + } + } + + attempt = 0; + info!("connected"); + if event_sender.send(NetworkEvent::Connected).await.is_err() { + return; + } + + tokio::spawn(event_receive_loop( + connection.clone(), + event_sender.clone(), + shared.share.clone(), + )); + tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone())); + let mut ticker = tokio::time::interval(SHARE_TICK); + + loop { + tokio::select! { + command = command_receiver.recv() => match command { + Some(Command::Request { request, reply }) => match &request { + Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { + hang_up(&shared); + + let response = send(&connection, &request).await; + if let Ok(Response::Session { token: session_token, .. }) = &response { + token = Some(session_token.clone()); + } + let _ = reply.send(response); + } + Request::Logout | Request::Detach => { + token = None; + hang_up(&shared); + + let connection = connection.clone(); + answer(reply, async move { send(&connection, &request).await }); + } + Request::JoinVoice { .. } => { + let shared = shared.clone(); + let settings = shared.voice_settings.lock().unwrap().clone(); + let connection = connection.clone(); + + answer(reply, async move { + let response = send(&connection, &request).await; + if let Ok(Response::Voice(_)) = &response { + shared.mic_test.lock().unwrap().take(); + *shared.voice.lock().unwrap() = + Some(voice::start(Some(connection), &settings)); + } + response + }); + } + Request::LeaveVoice => { + hang_up(&shared); + + let connection = connection.clone(); + answer(reply, async move { send(&connection, &request).await }); + } + _ => { + let connection = connection.clone(); + answer(reply, async move { send(&connection, &request).await }); + } + }, + Some(Command::StartShare { kind, settings, reply }) => { + let connection = connection.clone(); + let share = shared.share.clone(); + + answer(reply, async move { start_share(&connection, &share, kind, &settings).await }); + } + Some(Command::UpdateShare { settings, reply }) => { + let connection = connection.clone(); + let share = shared.share.clone(); + + answer(reply, async move { update_share(&connection, &share, &settings).await }); + } + Some(Command::Upload { community_id, path, maximum, reply }) => { + let connection = connection.clone(); + + answer(reply, async move { upload(&connection, &community_id, &path, maximum).await }); + } + Some(Command::Download { blob, reply }) => { + let connection = connection.clone(); + let fetches = shared.fetches.clone(); + + answer(reply, async move { fetches.memory(&connection, blob).await }); + } + Some(Command::BackupDownload { name, path, reply }) => { + let connection = connection.clone(); + let fetches = shared.fetches.clone(); + + answer(reply, async move { + let _permit = fetches.permit().await; + backup_download(&connection, &name, &path).await + }); + } + None => break 'session, + }, + + _ = ticker.tick() => { + let requests = shared.share.lock().unwrap().ticks(); + for request in requests { + let connection = connection.clone(); + tokio::spawn(async move { + let _ = send(&connection, &request).await; + }); + } + } + + error = connection.closed() => { + warn!("disconnected: {error}"); + hang_up(&shared); + + let event = LinkError::from(error); + let banned = event == LinkError::Closed(Close::Banned); + + if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() { + return; + } + + if banned { + while command_receiver.recv().await.is_some() {} + return; + } + + tokio::time::sleep(backoff(attempt)).await; + attempt += 1; + break; + } + } + } + } +} diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs new file mode 100644 index 0000000..dd7d8ac --- /dev/null +++ b/crates/client/src/net/mod.rs @@ -0,0 +1,1160 @@ +use std::{ + path::PathBuf, + sync::{Arc, Mutex}, +}; + +use common::{ + constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, + event::Event, + model::{ + Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community, + CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, + Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, + ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, + }, + open::Blob, + request::Request, + response::Response, + share::Kind, + validate::{ + validate_avatar_size, validate_community_name, validate_forward, validate_new_message, + validate_password, validate_poll, validate_reason, validate_server_settings, + validate_status, validate_username, + }, +}; +use tokio::sync::{mpsc, oneshot}; + +use crate::{ + settings::{ShareSettings, VoiceSettings}, + voice::Voice, +}; + +macro_rules! expect { + ($response:expr, $variant:path) => { + match $response { + $variant(value) => Ok(value), + _ => Err(Fail::Protocol), + } + }; +} + +mod datagram; +mod events; +mod fail; +mod fetch; +mod link; +mod share; +mod voice; + +pub use fail::{Fail, LinkError}; +pub use link::start; +use share::Share; + +fn device_name() -> String { + let host = gethostname::gethostname() + .to_string_lossy() + .trim() + .to_string(); + let host = if host.is_empty() { + "unknown".to_string() + } else { + host + }; + + format!("{host} {}", std::env::consts::OS) +} + +type SharedVoice = Arc>>; +type SharedSettings = Arc>; +type SharedShare = Arc>; +type SharedShareSettings = Arc>; + +#[derive(Clone, Default)] +struct Shared { + voice: SharedVoice, + mic_test: SharedVoice, + voice_settings: SharedSettings, + share: SharedShare, + share_settings: SharedShareSettings, + fetches: Arc, +} + +fn hang_up(shared: &Shared) { + shared.voice.lock().unwrap().take(); + *shared.share.lock().unwrap() = Share::default(); +} + +#[derive(Default)] +pub struct Levels { + pub voice: Vec<(String, Vec)>, + pub watching: Vec<(String, Vec)>, + pub sharing: Option>, +} + +#[derive(Debug)] +pub enum NetworkEvent { + Connected, + Disconnected(LinkError), + SessionLost, + Pushed(Box), +} + +#[derive(Debug)] +enum Command { + Request { + request: Request, + reply: oneshot::Sender>, + }, + Upload { + community_id: String, + path: PathBuf, + maximum: Option, + reply: oneshot::Sender>, + }, + Download { + blob: Blob, + reply: oneshot::Sender, Fail>>, + }, + BackupDownload { + name: String, + path: PathBuf, + reply: oneshot::Sender>, + }, + StartShare { + kind: Kind, + settings: ShareSettings, + reply: oneshot::Sender>, + }, + UpdateShare { + settings: ShareSettings, + reply: oneshot::Sender>, + }, +} + +#[derive(Clone)] +pub struct NetworkHandle { + command_sender: mpsc::Sender, + shared: Shared, +} + +impl NetworkHandle { + async fn ask( + &self, + build: impl FnOnce(oneshot::Sender>) -> Command, + ) -> Result { + let (reply, response) = oneshot::channel(); + + self.command_sender + .send(build(reply)) + .await + .map_err(|_| Fail::Offline)?; + + response.await.map_err(|_| Fail::Offline)? + } + + fn with_voice(&self, f: impl FnOnce(&Voice) -> T) -> Option { + self.shared.voice.lock().unwrap().as_ref().map(f) + } + + async fn request(&self, request: Request) -> Result { + self.ask(|reply| Command::Request { request, reply }).await + } + + async fn sign_in(&self, request: Request) -> Result<(User, String), Fail> { + let session = match self.request(request).await? { + Response::Session { user, token } => (user, token), + _ => return Err(Fail::Protocol), + }; + let _ = self + .done(Request::SetDevice { + name: device_name(), + }) + .await; + + Ok(session) + } + + pub async fn sessions(&self, user_id: &str) -> Result, Fail> { + expect!( + self.request(Request::Sessions { + user_id: user_id.to_string(), + }) + .await?, + Response::Sessions + ) + } + + pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Fail> { + self.done(Request::RevokeSession { + user_id: user_id.to_string(), + session_id: session_id.to_string(), + }) + .await + } + + pub async fn rename_user(&self, user_id: &str, username: &str) -> Result { + validate_username(username)?; + + expect!( + self.request(Request::RenameUser { + user_id: user_id.to_string(), + username: username.to_string(), + }) + .await?, + Response::User + ) + } + + pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { + self.sign_in(Request::Resume { + token: token.to_string(), + }) + .await + } + + pub async fn detach(&self) -> Result<(), Fail> { + self.done(Request::Detach).await + } + + pub async fn register( + &self, + username: &str, + password: &str, + invite: Option<&str>, + ) -> Result<(User, String), Fail> { + validate_username(username)?; + validate_password(password)?; + + self.sign_in(Request::Register { + username: username.to_string(), + password: password.to_string(), + invite: invite.map(str::to_string), + }) + .await + } + + pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> { + validate_password(password)?; + + self.sign_in(Request::Login { + username: username.to_string(), + password: password.to_string(), + }) + .await + } + + pub async fn logout(&self) -> Result<(), Fail> { + self.done(Request::Logout).await + } + + pub async fn update_user(&self, username: &str) -> Result { + validate_username(username)?; + + expect!( + self.request(Request::UpdateUser { + username: username.to_string(), + }) + .await?, + Response::User + ) + } + + pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> { + expect!( + self.request(Request::DeleteUser { + user_id: user_id.to_string(), + }) + .await?, + Response::User + ) + .map(|_| ()) + } + + pub async fn users(&self) -> Result, Fail> { + expect!(self.request(Request::Users).await?, Response::Users) + } + + pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> { + self.done(Request::SuspendUser { + user_id: user_id.to_string(), + suspended, + }) + .await + } + + pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> { + self.done(Request::TimeoutUser { + user_id: user_id.to_string(), + minutes, + }) + .await + } + + pub async fn ban_user( + &self, + user_id: &str, + reason: Option<&str>, + scope: BanScope, + ) -> Result<(), Fail> { + validate_reason(reason)?; + + self.done(Request::BanUser { + user_id: user_id.to_string(), + reason: reason.map(str::to_string), + scope, + }) + .await + } + + pub async fn server_bans(&self) -> Result, Fail> { + expect!( + self.request(Request::ServerBans).await?, + Response::ServerBans + ) + } + + pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> { + self.done(Request::RemoveServerBan { id: id.to_string() }) + .await + } + + pub async fn create_invite_code( + &self, + uses: u32, + hours: Option, + ) -> Result { + expect!( + self.request(Request::CreateInviteCode { uses, hours }) + .await?, + Response::InviteCode + ) + } + + pub async fn invite_codes(&self) -> Result, Fail> { + expect!( + self.request(Request::InviteCodes).await?, + Response::InviteCodes + ) + } + + pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> { + self.done(Request::DeleteInviteCode { + code: code.to_string(), + }) + .await + } + + pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> { + self.done(Request::RevokeSessions { + user_id: user_id.to_string(), + }) + .await + } + + pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> { + validate_password(password)?; + + self.done(Request::ResetPassword { + user_id: user_id.to_string(), + password: password.to_string(), + }) + .await + } + + pub async fn clear_profile(&self, user_id: &str) -> Result { + expect!( + self.request(Request::ClearProfile { + user_id: user_id.to_string(), + }) + .await?, + Response::User + ) + } + + pub async fn set_role(&self, user_id: &str, role: Role) -> Result { + expect!( + self.request(Request::SetRole { + user_id: user_id.to_string(), + role, + }) + .await?, + Response::User + ) + } + + pub async fn admin_logs( + &self, + actor_id: Option, + target_id: Option, + action: Option, + after_ms: Option, + before_ms: Option, + ) -> Result, Fail> { + let request = Request::AdminLogs { + actor_id, + target_id, + action, + after_ms, + before_ms, + }; + expect!(self.request(request).await?, Response::AdminLogs) + } + + pub async fn daily_stats(&self, days: u32) -> Result, Fail> { + expect!( + self.request(Request::DailyStats { days }).await?, + Response::DailyStats + ) + } + + pub async fn server_settings(&self) -> Result { + expect!( + self.request(Request::ServerSettings).await?, + Response::ServerSettings + ) + } + + pub async fn update_server_settings( + &self, + settings: ServerSettings, + ) -> Result { + validate_server_settings(&settings)?; + + expect!( + self.request(Request::UpdateServerSettings { settings }) + .await?, + Response::ServerSettings + ) + } + + pub async fn create_user(&self, username: &str, password: &str) -> Result { + validate_username(username)?; + validate_password(password)?; + + expect!( + self.request(Request::CreateUser { + username: username.to_string(), + password: password.to_string(), + }) + .await?, + Response::User + ) + } + + pub async fn overview(&self) -> Result { + expect!(self.request(Request::Overview).await?, Response::Overview) + } + + pub async fn all_communities(&self) -> Result, Fail> { + expect!( + self.request(Request::AllCommunities).await?, + Response::AllCommunities + ) + } + + pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { + self.done(Request::TransferOwnership { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + }) + .await + } + + pub async fn read_user(&self, user_id: &str) -> Result { + expect!( + self.request(Request::ReadUser { + user_id: user_id.to_string(), + }) + .await?, + Response::User + ) + } + + pub async fn create_community(&self, name: &str) -> Result { + validate_community_name(name)?; + + expect!( + self.request(Request::CreateCommunity { + name: name.to_string(), + }) + .await?, + Response::Community + ) + } + + pub async fn update_community( + &self, + community_id: &str, + name: &str, + ) -> Result { + validate_community_name(name)?; + + expect!( + self.request(Request::UpdateCommunity { + community_id: community_id.to_string(), + name: name.to_string(), + }) + .await?, + Response::Community + ) + } + + pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> { + expect!( + self.request(Request::DeleteCommunity { + community_id: community_id.to_string(), + }) + .await?, + Response::Community + ) + .map(|_| ()) + } + + pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> { + self.done(Request::LeaveCommunity { + community_id: community_id.to_string(), + }) + .await + } + + pub async fn communities(&self) -> Result, Fail> { + expect!( + self.request(Request::Communities).await?, + Response::Communities + ) + } + + pub async fn members(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(Request::Members { + community_id: community_id.to_string(), + }) + .await?, + Response::Members + ) + } + + pub async fn kick( + &self, + community_id: &str, + user_id: &str, + reason: Option<&str>, + ) -> Result<(), Fail> { + validate_reason(reason)?; + self.done(Request::Kick { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + reason: reason.map(str::to_string), + }) + .await + } + + pub async fn ban( + &self, + community_id: &str, + user_id: &str, + reason: Option<&str>, + ) -> Result<(), Fail> { + validate_reason(reason)?; + self.done(Request::Ban { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + reason: reason.map(str::to_string), + }) + .await + } + + pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { + self.done(Request::Unban { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + }) + .await + } + + pub async fn bans(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(Request::Bans { + community_id: community_id.to_string(), + }) + .await?, + Response::Bans + ) + } + + pub async fn logs(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(Request::Logs { + community_id: community_id.to_string(), + }) + .await?, + Response::Logs + ) + } + + pub async fn set_rank( + &self, + community_id: &str, + user_id: &str, + rank: Rank, + ) -> Result<(), Fail> { + self.done(Request::SetRank { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + rank, + }) + .await + } + + pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> { + expect!( + self.request(Request::DeleteMessage { + message_id: message_id.to_string(), + }) + .await?, + Response::Message + ) + .map(|_| ()) + } + + pub async fn create_message( + &self, + community_id: &str, + body: &str, + attachments: Vec, + reply_to: Option, + ) -> Result { + validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; + + expect!( + self.request(Request::CreateMessage { + community_id: community_id.to_string(), + body: body.to_string(), + attachments, + reply_to, + }) + .await?, + Response::Message + ) + } + + pub async fn update_message(&self, message_id: &str, body: &str) -> Result { + validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?; + + expect!( + self.request(Request::UpdateMessage { + message_id: message_id.to_string(), + body: body.to_string(), + }) + .await?, + Response::Message + ) + } + + pub async fn forward_messages( + &self, + message_ids: Vec, + community_id: &str, + snippet: bool, + ) -> Result, Fail> { + validate_forward(message_ids.len())?; + + expect!( + self.request(Request::ForwardMessages { + message_ids, + community_id: community_id.to_string(), + snippet, + }) + .await?, + Response::Messages + ) + } + + pub async fn find_user(&self, username: &str) -> Result { + expect!( + self.request(Request::FindUser { + username: username.to_string(), + }) + .await?, + Response::User + ) + } + + pub async fn open_notes(&self) -> Result { + expect!(self.request(Request::OpenNotes).await?, Response::Community) + } + + pub async fn open_direct(&self, user_id: &str) -> Result { + expect!( + self.request(Request::OpenDirect { + user_id: user_id.to_string(), + }) + .await?, + Response::Community + ) + } + + pub async fn friends(&self) -> Result { + expect!(self.request(Request::Friends).await?, Response::Friends) + } + + pub async fn read_presences(&self) -> Result, Fail> { + expect!( + self.request(Request::ReadPresences).await?, + Response::Presences + ) + } + + pub async fn update_presence(&self, presence: Presence) -> Result<(), Fail> { + self.done(Request::UpdatePresence { presence }).await + } + + pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> { + self.done(Request::AddFriend { + user_id: user_id.to_string(), + }) + .await + } + + pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> { + self.done(Request::AcceptFriend { + user_id: user_id.to_string(), + }) + .await + } + + pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> { + self.done(Request::RemoveFriend { + user_id: user_id.to_string(), + }) + .await + } + + pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { + self.done(Request::Invite { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + }) + .await + } + + pub async fn invitations(&self) -> Result, Fail> { + expect!( + self.request(Request::Invitations).await?, + Response::Invitations + ) + } + + pub async fn accept_invitation(&self, community_id: &str) -> Result { + expect!( + self.request(Request::AcceptInvitation { + community_id: community_id.to_string(), + }) + .await?, + Response::Community + ) + } + + pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> { + self.done(Request::DeclineInvitation { + community_id: community_id.to_string(), + }) + .await + } + + pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> { + self.done(Request::DeclineCall { + community_id: community_id.to_string(), + }) + .await + } + + pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> { + self.done(Request::React { + message_id: message_id.to_string(), + emoji: emoji.to_string(), + }) + .await + } + + pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> { + self.done(Request::Pin { + message_id: message_id.to_string(), + pinned, + }) + .await + } + + pub async fn pins(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(Request::Pins { + community_id: community_id.to_string(), + }) + .await?, + Response::Messages + ) + } + + pub async fn create_poll( + &self, + community_id: &str, + question: &str, + options: Vec, + multiple: bool, + ) -> Result { + validate_poll(question, &options)?; + + expect!( + self.request(Request::CreatePoll { + community_id: community_id.to_string(), + question: question.to_string(), + options, + multiple, + }) + .await?, + Response::Message + ) + } + + pub async fn vote(&self, message_id: &str, positions: Vec) -> Result<(), Fail> { + self.done(Request::Vote { + message_id: message_id.to_string(), + positions, + }) + .await + } + + pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> { + self.done(Request::ClosePoll { + message_id: message_id.to_string(), + }) + .await + } + + pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> { + validate_reason(Some(reason))?; + + self.done(Request::ReportMessage { + message_id: message_id.to_string(), + reason: reason.to_string(), + }) + .await + } + + pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> { + validate_reason(Some(reason))?; + + self.done(Request::ReportUser { + user_id: user_id.to_string(), + reason: reason.to_string(), + }) + .await + } + + pub async fn reports(&self, status: Option) -> Result, Fail> { + expect!( + self.request(Request::Reports { status }).await?, + Response::Reports + ) + } + + pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> { + self.done(Request::HandleReport { + report_id: report_id.to_string(), + status, + }) + .await + } + + pub async fn search_messages( + &self, + text: Option, + user_id: Option, + community_id: Option, + after_ms: Option, + before_ms: Option, + ) -> Result, Fail> { + expect!( + self.request(Request::SearchMessages { + text, + user_id, + community_id, + after_ms, + before_ms, + }) + .await?, + Response::MessageHits + ) + } + + pub async fn search_community( + &self, + community_id: String, + text: String, + ) -> Result, Fail> { + expect!( + self.request(Request::SearchCommunity { community_id, text }) + .await?, + Response::MessageHits + ) + } + + pub async fn storage_usage(&self) -> Result<(Vec, Vec), Fail> { + match self.request(Request::StorageUsage).await? { + Response::StorageUsage { users, communities } => Ok((users, communities)), + _ => Err(Fail::Protocol), + } + } + + pub async fn create_backup(&self) -> Result { + expect!(self.request(Request::CreateBackup).await?, Response::Backup) + } + + pub async fn backups(&self) -> Result, Fail> { + expect!(self.request(Request::Backups).await?, Response::Backups) + } + + pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> { + self.done(Request::DeleteBackup { + name: name.to_string(), + }) + .await + } + + pub async fn attachments( + &self, + user_id: Option, + community_id: Option, + ) -> Result, Fail> { + expect!( + self.request(Request::AllAttachments { + user_id, + community_id, + }) + .await?, + Response::AttachmentInfos + ) + } + + pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> { + self.done(Request::DeleteAttachment { + attachment_id: attachment_id.to_string(), + }) + .await + } + + pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> { + self.done(Request::PurgeUser { + user_id: user_id.to_string(), + }) + .await + } + + async fn done(&self, request: Request) -> Result<(), Fail> { + match self.request(request).await? { + Response::Done => Ok(()), + _ => Err(Fail::Protocol), + } + } + + pub async fn upload_attachment( + &self, + community_id: &str, + path: PathBuf, + maximum: Option, + ) -> Result { + self.ask(|reply| Command::Upload { + community_id: community_id.to_string(), + path, + maximum, + reply, + }) + .await + } + + pub async fn download_attachment( + &self, + attachment_id: &str, + thumbnail: bool, + ) -> Result, Fail> { + let id = attachment_id.to_string(); + let blob = if thumbnail { + Blob::Thumbnail(id) + } else { + Blob::Attachment(id) + }; + self.ask(|reply| Command::Download { blob, reply }).await + } + + pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Fail> { + self.ask(|reply| Command::BackupDownload { + name: name.to_string(), + path, + reply, + }) + .await + } + + pub async fn read_messages( + &self, + community_id: &str, + before: Option<&str>, + ) -> Result, Fail> { + expect!( + self.request(Request::ReadMessages { + community_id: community_id.to_string(), + before: before.map(str::to_string), + }) + .await?, + Response::Messages + ) + } + + pub async fn unreads(&self) -> Result, Fail> { + expect!(self.request(Request::Unreads).await?, Response::Unreads) + } + + pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> { + self.done(Request::MarkRead { + community_id: community_id.to_string(), + message_id: message_id.to_string(), + }) + .await + } + + pub async fn update_status(&self, status: &str) -> Result { + validate_status(status)?; + + expect!( + self.request(Request::UpdateStatus { + status: status.to_string(), + }) + .await?, + Response::User + ) + } + + pub async fn update_avatar(&self, bytes: Vec) -> Result { + validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?; + + expect!( + self.request(Request::UpdateAvatar { image: bytes }).await?, + Response::User + ) + } + + pub async fn update_community_avatar( + &self, + community_id: &str, + image: Option>, + ) -> Result { + if let Some(bytes) = &image { + validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; + } + + expect!( + self.request(Request::UpdateCommunityAvatar { + community_id: community_id.to_string(), + image, + }) + .await?, + Response::Community + ) + } + + pub async fn remove_avatar(&self) -> Result { + expect!(self.request(Request::RemoveAvatar).await?, Response::User) + } + + pub async fn read_avatar(&self, avatar_id: &str) -> Result, Fail> { + expect!( + self.request(Request::ReadAvatar { + avatar_id: avatar_id.to_string(), + }) + .await?, + Response::Avatar + ) + } + + pub async fn join_voice(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(Request::JoinVoice { + community_id: community_id.to_string(), + }) + .await?, + Response::Voice + ) + } + + pub async fn typing(&self, community_id: &str) -> Result<(), Fail> { + self.done(Request::Typing { + community_id: community_id.to_string(), + }) + .await + } + + pub async fn leave_voice(&self) -> Result<(), Fail> { + self.done(Request::LeaveVoice).await + } + + pub async fn read_community(&self, community_id: &str) -> Result { + expect!( + self.request(Request::ReadCommunity { + community_id: community_id.to_string(), + }) + .await?, + Response::Community + ) + } + + pub async fn voice_participants(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(Request::VoiceParticipants { + community_id: community_id.to_string(), + }) + .await?, + Response::Voice + ) + } + + pub async fn voice_rooms(&self) -> Result, Fail> { + expect!( + self.request(Request::VoiceRooms).await?, + Response::VoiceRooms + ) + } + + pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> { + self.done(Request::SetGhost { enabled }).await + } + + pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> { + self.done(Request::KickFromVoice { + user_id: user_id.to_string(), + }) + .await + } + + pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> { + self.done(Request::ServerMute { + user_id: user_id.to_string(), + muted, + }) + .await + } + + pub async fn set_community_voice( + &self, + community_id: &str, + enabled: bool, + ) -> Result { + expect!( + self.request(Request::SetCommunityVoice { + community_id: community_id.to_string(), + enabled, + }) + .await?, + Response::Community + ) + } +} diff --git a/crates/client/src/net/share.rs b/crates/client/src/net/share.rs new file mode 100644 index 0000000..8a2abcc --- /dev/null +++ b/crates/client/src/net/share.rs @@ -0,0 +1,335 @@ +use std::collections::HashMap; + +use common::{ + event::Event, + request::Request, + response::Response, + share::{Fps, Kind, Quality, Resolution, Source}, +}; + +use crate::{ + settings::ShareSettings, + share::{ + audio::AudioApp, + audio_capture, + encode::capabilities, + session::{ShareSample, Sharing, Tick, WatchQuality, Watching}, + }, +}; + +use super::{link::done, *}; + +#[derive(Default)] +pub(super) struct Share { + pub(super) sharing: HashMap, + pub(super) sources: HashMap, + pub(super) watching: HashMap<(String, Kind), Watching>, +} + +impl Share { + pub(super) fn event(&mut self, event: &Event) { + match event { + Event::ShareLayers { kind, layers } => { + if let Some(sharing) = self.sharing.get_mut(kind) { + sharing.set_layers(layers); + } + } + Event::KeyframeWanted { kind, layer } => { + if let Some(sharing) = self.sharing.get(kind) { + sharing.keyframe(*layer); + } + } + Event::ShareStopped { user_id, kind, .. } => { + self.watching.remove(&(user_id.clone(), *kind)); + } + _ => {} + } + } + + pub(super) fn ticks(&mut self) -> Vec { + self.watching + .iter_mut() + .flat_map(|((user_id, kind), watching)| { + let (user_id, kind) = (user_id.clone(), *kind); + watching + .tick() + .into_iter() + .map(|tick| match tick { + Tick::Quality(quality) => Request::WatchShare { + user_id: user_id.clone(), + kind, + quality, + decode: capabilities().decode.clone(), + }, + Tick::Keyframe => Request::RequestKeyframe { + user_id: user_id.clone(), + kind, + }, + }) + .collect::>() + }) + .collect() + } +} + +const CAMERA_TOP: Quality = Quality { + resolution: Resolution::P2160, + fps: Fps::F60, +}; + +impl NetworkHandle { + pub async fn start_share(&self) -> Result<(), Fail> { + self.start(Kind::Screen).await + } + + pub async fn start_camera(&self) -> Result<(), Fail> { + self.start(Kind::Camera).await + } + + async fn start(&self, kind: Kind) -> Result<(), Fail> { + let settings = self.shared.share_settings.lock().unwrap().clone(); + self.ask(|reply| Command::StartShare { + kind, + settings, + reply, + }) + .await + } + + pub async fn update_share(&self) -> Result<(), Fail> { + let settings = self.shared.share_settings.lock().unwrap().clone(); + self.ask(|reply| Command::UpdateShare { settings, reply }) + .await + } + + pub async fn stop_share(&self) -> Result<(), Fail> { + self.stop(Kind::Screen).await + } + + pub async fn stop_camera(&self) -> Result<(), Fail> { + self.stop(Kind::Camera).await + } + + async fn stop(&self, kind: Kind) -> Result<(), Fail> { + let result = self.done(Request::StopShare { kind }).await; + let mut share = self.shared.share.lock().unwrap(); + share.sharing.remove(&kind); + share.sources.remove(&kind); + result + } + + pub fn sharing(&self) -> bool { + self.shared + .share + .lock() + .unwrap() + .sharing + .contains_key(&Kind::Screen) + } + + pub fn camera_on(&self) -> bool { + self.shared + .share + .lock() + .unwrap() + .sharing + .contains_key(&Kind::Camera) + } + + pub fn share_source(&self) -> Option { + self.shared + .share + .lock() + .unwrap() + .sources + .get(&Kind::Screen) + .cloned() + } + + pub async fn shares(&self, community_id: &str) -> Result, Fail> { + expect!( + self.request(Request::Shares { + community_id: community_id.to_string(), + }) + .await?, + Response::Shares + ) + } + + pub async fn watch_share( + &self, + user_id: &str, + kind: Kind, + watch: WatchQuality, + ) -> Result<(), Fail> { + let volume = self.shared.share_settings.lock().unwrap().volume; + let choice = self.shared.voice_settings.lock().unwrap().choice.clone(); + let key = (user_id.to_string(), kind); + let watching = Watching::new(kind, watch, volume, choice); + let quality = watching.wanted(); + self.shared + .share + .lock() + .unwrap() + .watching + .insert(key.clone(), watching); + + let result = self + .done(Request::WatchShare { + user_id: key.0.clone(), + kind, + quality, + decode: capabilities().decode.clone(), + }) + .await; + if result.is_err() { + self.shared.share.lock().unwrap().watching.remove(&key); + } + result + } + + pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> { + self.shared + .share + .lock() + .unwrap() + .watching + .remove(&(user_id.to_string(), kind)); + self.done(Request::UnwatchShare { + user_id: user_id.to_string(), + kind, + }) + .await + } + + pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { + if let Some(watching) = self + .shared + .share + .lock() + .unwrap() + .watching + .get_mut(&(user_id.to_string(), kind)) + { + watching.set_quality(quality); + } + } + + pub fn share_sample(&self) -> ShareSample { + let mut share = self.shared.share.lock().unwrap(); + ShareSample { + sending: share + .sharing + .get(&Kind::Screen) + .map(Sharing::stats) + .unwrap_or_default(), + watching: share + .watching + .iter_mut() + .filter(|((_, kind), _)| *kind == Kind::Screen) + .map(|((user_id, _), watching)| (user_id.clone(), watching.stats())) + .collect(), + } + } + + pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option { + self.shared + .share + .lock() + .unwrap() + .watching + .get(&(user_id.to_string(), kind))? + .frame() + } + + pub fn set_share_settings(&self, settings: ShareSettings) -> bool { + let changed = self.sharing() + && self + .shared + .share_settings + .lock() + .unwrap() + .encoding_differs(&settings); + *self.shared.share_settings.lock().unwrap() = settings.clone(); + for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() { + if *kind == Kind::Screen { + watching.set_volume(settings.volume); + watching.set_quality(settings.watch); + } + } + changed + } + + pub fn audio_apps(&self) -> Vec { + audio_capture::apps() + } +} + +pub(super) async fn start_share( + connection: &quinn::Connection, + share: &SharedShare, + kind: Kind, + settings: &ShareSettings, +) -> Result<(), Fail> { + let top = match kind { + Kind::Screen => settings.top, + Kind::Camera => CAMERA_TOP, + }; + let (sharing, source) = Sharing::start( + connection.clone(), + kind, + top, + settings.encode(), + settings.audio_mode(), + ) + .await + .map_err(Fail::Io)?; + { + let mut share = share.lock().unwrap(); + share.sharing.insert(kind, sharing); + share.sources.insert(kind, source.clone()); + } + + let result = done(connection, Request::StartShare { kind, source }).await; + if result.is_err() { + let mut share = share.lock().unwrap(); + share.sharing.remove(&kind); + share.sources.remove(&kind); + } + result +} + +pub(super) async fn update_share( + connection: &quinn::Connection, + share: &SharedShare, + settings: &ShareSettings, +) -> Result<(), Fail> { + let source = { + let mut share = share.lock().unwrap(); + let Some(sharing) = share.sharing.get_mut(&Kind::Screen) else { + return Ok(()); + }; + sharing + .update( + connection, + settings.top, + settings.encode(), + settings.audio_mode(), + ) + .map_err(Fail::Io)? + }; + share + .lock() + .unwrap() + .sources + .insert(Kind::Screen, source.clone()); + + done( + connection, + Request::StartShare { + kind: Kind::Screen, + source, + }, + ) + .await +} diff --git a/crates/client/src/net/voice.rs b/crates/client/src/net/voice.rs new file mode 100644 index 0000000..f3baa08 --- /dev/null +++ b/crates/client/src/net/voice.rs @@ -0,0 +1,87 @@ +use common::share::Kind; + +use crate::{ + settings::VoiceSettings, + share::session::Sharing, + voice::{self, Voice, VoiceSample}, +}; + +use super::*; + +impl NetworkHandle { + pub fn set_voice_settings(&self, settings: VoiceSettings) { + *self.shared.voice_settings.lock().unwrap() = settings.clone(); + + if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() { + voice.apply(&settings); + } + if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() { + voice.apply(&settings); + } + } + + pub fn start_mic_test(&self) { + if self.shared.voice.lock().unwrap().is_some() { + return; + } + let settings = self.shared.voice_settings.lock().unwrap().clone(); + *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings)); + } + + pub fn play_chime(&self) { + voice::play_chime(&self.shared.voice_settings.lock().unwrap()); + } + + pub fn play_notification(&self) { + voice::play_yumush(&self.shared.voice_settings.lock().unwrap()); + } + + pub fn play_ring(&self) { + voice::play_ring(&self.shared.voice_settings.lock().unwrap()); + } + + pub fn stop_mic_test(&self) { + self.shared.mic_test.lock().unwrap().take(); + } + + pub fn voice_level_db(&self) -> Option { + self.with_voice(Voice::level_db).or_else(|| { + self.shared + .mic_test + .lock() + .unwrap() + .as_ref() + .map(Voice::level_db) + }) + } + + pub fn voice_sample(&self) -> Option { + self.with_voice(Voice::sample) + } + + pub fn set_talking(&self, talking: bool) { + self.with_voice(|voice| voice.set_talking(talking)); + } + + pub fn set_muted(&self, muted: bool) { + self.with_voice(|voice| voice.set_muted(muted)); + } + + pub fn set_deafened(&self, deafened: bool) { + self.with_voice(|voice| voice.set_deafened(deafened)); + } + + pub fn levels(&self) -> Levels { + let share = self.shared.share.lock().unwrap(); + Levels { + voice: self.with_voice(Voice::levels).unwrap_or_default(), + watching: share + .watching + .iter() + .filter(|((_, kind), _)| *kind == Kind::Screen) + .map(|((user_id, _), watching)| (user_id.clone(), watching.level())) + .collect(), + sharing: share.sharing.get(&Kind::Screen).map(Sharing::level), + } + } +} diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs deleted file mode 100644 index b9d8631..0000000 --- a/crates/client/src/network.rs +++ /dev/null @@ -1,2047 +0,0 @@ -use std::{ - collections::HashMap, - future::Future, - path::{Path, PathBuf}, - sync::{Arc, Mutex}, - time::Duration, -}; - -use common::{ - constant::{ - ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES, MAXIMUM_AVATAR_BYTES, - MAXIMUM_MESSAGE_LENGTH, - }, - datagram::{Datagram, decode_relay}, - error::Error, - event::Event, - model::{ - Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community, - CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, - Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, - ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, - }, - network::{ - RESPONSE_MAX_READ_LENGTH, StreamKind, open_download, receive_decoded, receive_event, - send_request, send_stream_kind, send_upload_header, - }, - request::{DownloadRequest, Request, UploadHeader}, - response::Response, - share::{Fps, Kind, Quality, Resolution, Source}, - validate::{ - validate_attachment_name, validate_attachment_size, validate_avatar_size, - validate_community_name, validate_forward, validate_new_message, validate_password, - validate_poll, validate_reason, validate_server_settings, validate_status, - validate_username, - }, -}; -use quinn::Endpoint; -#[cfg(debug_assertions)] -use quinn::{ - crypto::rustls::QuicClientConfig, - rustls::{ - self, DigitallySignedStruct, SignatureScheme, - client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, - pki_types::{CertificateDer, ServerName, UnixTime}, - }, -}; -use tokio::sync::{mpsc, oneshot}; -use tracing::{info, warn}; - -use crate::{ - ClientConfig, - settings::{ShareSettings, VoiceSettings}, - share::{ - audio::AudioApp, - audio_capture, - encode::capabilities, - session::{ShareSample, Sharing, Tick, WatchQuality, Watching}, - }, - voice::{self, Voice, VoiceSample}, -}; - -fn device_name() -> String { - let host = std::fs::read_to_string("/etc/hostname") - .or_else(|_| std::env::var("HOSTNAME")) - .or_else(|_| std::env::var("COMPUTERNAME")) - .map(|host| host.trim().to_string()) - .ok() - .filter(|host| !host.is_empty()) - .unwrap_or_else(|| "unknown".to_string()); - - format!("{host} {}", std::env::consts::OS) -} - -const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1); -const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3); - -const CHANNEL_SIZE: usize = 32; -const RECONNECT_DELAY: Duration = Duration::from_secs(1); - -const SHARE_TICK: Duration = Duration::from_secs(1); - -type SharedVoice = Arc>>; -type SharedSettings = Arc>; -type SharedShare = Arc>; -type SharedShareSettings = Arc>; - -#[derive(Clone, Default)] -struct Shared { - voice: SharedVoice, - mic_test: SharedVoice, - voice_settings: SharedSettings, - share: SharedShare, - share_settings: SharedShareSettings, -} - -fn hang_up(shared: &Shared) { - shared.voice.lock().unwrap().take(); - *shared.share.lock().unwrap() = Share::default(); -} - -#[derive(Default)] -pub struct Levels { - pub voice: Vec<(String, Vec)>, - pub watching: Vec<(String, Vec)>, - pub sharing: Option>, -} - -#[derive(Default)] -struct Share { - sharing: HashMap, - sources: HashMap, - watching: HashMap<(String, Kind), Watching>, -} - -impl Share { - fn event(&mut self, event: &Event) { - match event { - Event::ShareLayers { kind, layers } => { - if let Some(sharing) = self.sharing.get_mut(kind) { - sharing.set_layers(layers); - } - } - Event::KeyframeWanted { kind, layer } => { - if let Some(sharing) = self.sharing.get(kind) { - sharing.keyframe(*layer); - } - } - Event::ShareStopped { user_id, kind, .. } => { - self.watching.remove(&(user_id.clone(), *kind)); - } - _ => {} - } - } - - fn ticks(&mut self) -> Vec { - self.watching - .iter_mut() - .flat_map(|((user_id, kind), watching)| { - let (user_id, kind) = (user_id.clone(), *kind); - watching - .tick() - .into_iter() - .map(|tick| match tick { - Tick::Quality(quality) => Request::WatchShare { - user_id: user_id.clone(), - kind, - quality, - decode: capabilities().decode.clone(), - }, - Tick::Keyframe => Request::RequestKeyframe { - user_id: user_id.clone(), - kind, - }, - }) - .collect::>() - }) - .collect() - } -} - -const CAMERA_TOP: Quality = Quality { - resolution: Resolution::P2160, - fps: Fps::F60, -}; - -#[derive(Debug)] -pub enum NetworkEvent { - Connected, - Disconnected(Error), - SessionLost, - Pushed(Box), -} - -#[derive(Debug)] -enum Command { - Request { - request: Request, - reply: oneshot::Sender>, - }, - Upload { - community_id: String, - path: PathBuf, - maximum: Option, - reply: oneshot::Sender>, - }, - Download { - attachment_id: String, - thumbnail: bool, - reply: oneshot::Sender, Error>>, - }, - BackupDownload { - name: String, - path: PathBuf, - reply: oneshot::Sender>, - }, - StartShare { - kind: Kind, - settings: ShareSettings, - reply: oneshot::Sender>, - }, - UpdateShare { - settings: ShareSettings, - reply: oneshot::Sender>, - }, -} - -#[derive(Clone)] -pub struct NetworkHandle { - command_sender: mpsc::Sender, - shared: Shared, -} - -macro_rules! expect { - ($response:expr, $variant:path) => { - match $response { - $variant(value) => Ok(value), - _ => Err(Error::Server), - } - }; -} - -impl NetworkHandle { - async fn ask( - &self, - build: impl FnOnce(oneshot::Sender>) -> Command, - ) -> Result { - let (reply, response) = oneshot::channel(); - - self.command_sender - .send(build(reply)) - .await - .map_err(|_| Error::ChannelClosed)?; - - response.await.map_err(|_| Error::ChannelClosed)? - } - - fn with_voice(&self, f: impl FnOnce(&Voice) -> T) -> Option { - self.shared.voice.lock().unwrap().as_ref().map(f) - } - - async fn request(&self, request: Request) -> Result { - match self - .ask(|reply| Command::Request { request, reply }) - .await? - { - Response::Error(error) => Err(error), - response => Ok(response), - } - } - - async fn sign_in(&self, request: Request) -> Result<(User, String), Error> { - let session = match self.request(request).await? { - Response::Session { user, token } => (user, token), - _ => return Err(Error::Server), - }; - let _ = self - .done(Request::SetDevice { - name: device_name(), - }) - .await; - - Ok(session) - } - - pub async fn sessions(&self, user_id: &str) -> Result, Error> { - expect!( - self.request(Request::Sessions { - user_id: user_id.to_string(), - }) - .await?, - Response::Sessions - ) - } - - pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Error> { - self.done(Request::RevokeSession { - user_id: user_id.to_string(), - session_id: session_id.to_string(), - }) - .await - } - - pub async fn rename_user(&self, user_id: &str, username: &str) -> Result { - validate_username(username)?; - - expect!( - self.request(Request::RenameUser { - user_id: user_id.to_string(), - username: username.to_string(), - }) - .await?, - Response::User - ) - } - - pub async fn resume(&self, token: &str) -> Result<(User, String), Error> { - self.sign_in(Request::Resume { - token: token.to_string(), - }) - .await - } - - pub async fn detach(&self) -> Result<(), Error> { - self.done(Request::Detach).await - } - - pub async fn register( - &self, - username: &str, - password: &str, - invite: Option<&str>, - ) -> Result<(User, String), Error> { - validate_username(username)?; - validate_password(password)?; - - self.sign_in(Request::Register { - username: username.to_string(), - password: password.to_string(), - invite: invite.map(str::to_string), - }) - .await - } - - pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Error> { - validate_password(password)?; - - self.sign_in(Request::Login { - username: username.to_string(), - password: password.to_string(), - }) - .await - } - - pub async fn logout(&self) -> Result<(), Error> { - self.done(Request::Logout).await - } - - pub async fn update_user(&self, username: &str) -> Result { - validate_username(username)?; - - expect!( - self.request(Request::UpdateUser { - username: username.to_string(), - }) - .await?, - Response::User - ) - } - - pub async fn delete_user(&self, user_id: &str) -> Result<(), Error> { - expect!( - self.request(Request::DeleteUser { - user_id: user_id.to_string(), - }) - .await?, - Response::User - ) - .map(|_| ()) - } - - pub async fn users(&self) -> Result, Error> { - expect!(self.request(Request::Users).await?, Response::Users) - } - - pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Error> { - self.done(Request::SuspendUser { - user_id: user_id.to_string(), - suspended, - }) - .await - } - - pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Error> { - self.done(Request::TimeoutUser { - user_id: user_id.to_string(), - minutes, - }) - .await - } - - pub async fn ban_user( - &self, - user_id: &str, - reason: Option<&str>, - scope: BanScope, - ) -> Result<(), Error> { - validate_reason(reason)?; - - self.done(Request::BanUser { - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - scope, - }) - .await - } - - pub async fn server_bans(&self) -> Result, Error> { - expect!( - self.request(Request::ServerBans).await?, - Response::ServerBans - ) - } - - pub async fn remove_server_ban(&self, id: &str) -> Result<(), Error> { - self.done(Request::RemoveServerBan { id: id.to_string() }) - .await - } - - pub async fn create_invite_code( - &self, - uses: u32, - hours: Option, - ) -> Result { - expect!( - self.request(Request::CreateInviteCode { uses, hours }) - .await?, - Response::InviteCode - ) - } - - pub async fn invite_codes(&self) -> Result, Error> { - expect!( - self.request(Request::InviteCodes).await?, - Response::InviteCodes - ) - } - - pub async fn delete_invite_code(&self, code: &str) -> Result<(), Error> { - self.done(Request::DeleteInviteCode { - code: code.to_string(), - }) - .await - } - - pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Error> { - self.done(Request::RevokeSessions { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Error> { - validate_password(password)?; - - self.done(Request::ResetPassword { - user_id: user_id.to_string(), - password: password.to_string(), - }) - .await - } - - pub async fn clear_profile(&self, user_id: &str) -> Result { - expect!( - self.request(Request::ClearProfile { - user_id: user_id.to_string(), - }) - .await?, - Response::User - ) - } - - pub async fn set_role(&self, user_id: &str, role: Role) -> Result { - expect!( - self.request(Request::SetRole { - user_id: user_id.to_string(), - role, - }) - .await?, - Response::User - ) - } - - pub async fn admin_logs( - &self, - actor_id: Option, - target_id: Option, - action: Option, - after_ms: Option, - before_ms: Option, - ) -> Result, Error> { - let request = Request::AdminLogs { - actor_id, - target_id, - action, - after_ms, - before_ms, - }; - expect!(self.request(request).await?, Response::AdminLogs) - } - - pub async fn daily_stats(&self, days: u32) -> Result, Error> { - expect!( - self.request(Request::DailyStats { days }).await?, - Response::DailyStats - ) - } - - pub async fn server_settings(&self) -> Result { - expect!( - self.request(Request::ServerSettings).await?, - Response::ServerSettings - ) - } - - pub async fn update_server_settings( - &self, - settings: ServerSettings, - ) -> Result { - validate_server_settings(&settings)?; - - expect!( - self.request(Request::UpdateServerSettings { settings }) - .await?, - Response::ServerSettings - ) - } - - pub async fn create_user(&self, username: &str, password: &str) -> Result { - validate_username(username)?; - validate_password(password)?; - - expect!( - self.request(Request::CreateUser { - username: username.to_string(), - password: password.to_string(), - }) - .await?, - Response::User - ) - } - - pub async fn overview(&self) -> Result { - expect!(self.request(Request::Overview).await?, Response::Overview) - } - - pub async fn all_communities(&self) -> Result, Error> { - expect!( - self.request(Request::AllCommunities).await?, - Response::AllCommunities - ) - } - - pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Error> { - self.done(Request::TransferOwnership { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - }) - .await - } - - pub async fn read_user(&self, user_id: &str) -> Result { - expect!( - self.request(Request::ReadUser { - user_id: user_id.to_string(), - }) - .await?, - Response::User - ) - } - - pub async fn create_community(&self, name: &str) -> Result { - validate_community_name(name)?; - - expect!( - self.request(Request::CreateCommunity { - name: name.to_string(), - }) - .await?, - Response::Community - ) - } - - pub async fn update_community( - &self, - community_id: &str, - name: &str, - ) -> Result { - validate_community_name(name)?; - - expect!( - self.request(Request::UpdateCommunity { - community_id: community_id.to_string(), - name: name.to_string(), - }) - .await?, - Response::Community - ) - } - - pub async fn delete_community(&self, community_id: &str) -> Result<(), Error> { - expect!( - self.request(Request::DeleteCommunity { - community_id: community_id.to_string(), - }) - .await?, - Response::Community - ) - .map(|_| ()) - } - - pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> { - self.done(Request::LeaveCommunity { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn communities(&self) -> Result, Error> { - expect!( - self.request(Request::Communities).await?, - Response::Communities - ) - } - - pub async fn members(&self, community_id: &str) -> Result, Error> { - expect!( - self.request(Request::Members { - community_id: community_id.to_string(), - }) - .await?, - Response::Members - ) - } - - pub async fn kick( - &self, - community_id: &str, - user_id: &str, - reason: Option<&str>, - ) -> Result<(), Error> { - validate_reason(reason)?; - self.done(Request::Kick { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - }) - .await - } - - pub async fn ban( - &self, - community_id: &str, - user_id: &str, - reason: Option<&str>, - ) -> Result<(), Error> { - validate_reason(reason)?; - self.done(Request::Ban { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - }) - .await - } - - pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Error> { - self.done(Request::Unban { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - }) - .await - } - - pub async fn bans(&self, community_id: &str) -> Result, Error> { - expect!( - self.request(Request::Bans { - community_id: community_id.to_string(), - }) - .await?, - Response::Bans - ) - } - - pub async fn logs(&self, community_id: &str) -> Result, Error> { - expect!( - self.request(Request::Logs { - community_id: community_id.to_string(), - }) - .await?, - Response::Logs - ) - } - - pub async fn set_rank( - &self, - community_id: &str, - user_id: &str, - rank: Rank, - ) -> Result<(), Error> { - self.done(Request::SetRank { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - rank, - }) - .await - } - - pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> { - expect!( - self.request(Request::DeleteMessage { - message_id: message_id.to_string(), - }) - .await?, - Response::Message - ) - .map(|_| ()) - } - - pub async fn create_message( - &self, - community_id: &str, - body: &str, - attachments: Vec, - reply_to: Option, - ) -> Result { - validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; - - expect!( - self.request(Request::CreateMessage { - community_id: community_id.to_string(), - body: body.to_string(), - attachments, - reply_to, - }) - .await?, - Response::Message - ) - } - - pub async fn update_message(&self, message_id: &str, body: &str) -> Result { - validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?; - - expect!( - self.request(Request::UpdateMessage { - message_id: message_id.to_string(), - body: body.to_string(), - }) - .await?, - Response::Message - ) - } - - pub async fn forward_messages( - &self, - message_ids: Vec, - community_id: &str, - snippet: bool, - ) -> Result, Error> { - validate_forward(message_ids.len())?; - - expect!( - self.request(Request::ForwardMessages { - message_ids, - community_id: community_id.to_string(), - snippet, - }) - .await?, - Response::Messages - ) - } - - pub async fn find_user(&self, username: &str) -> Result { - expect!( - self.request(Request::FindUser { - username: username.to_string(), - }) - .await?, - Response::User - ) - } - - pub async fn open_notes(&self) -> Result { - expect!(self.request(Request::OpenNotes).await?, Response::Community) - } - - pub async fn open_direct(&self, user_id: &str) -> Result { - expect!( - self.request(Request::OpenDirect { - user_id: user_id.to_string(), - }) - .await?, - Response::Community - ) - } - - pub async fn friends(&self) -> Result { - expect!(self.request(Request::Friends).await?, Response::Friends) - } - - pub async fn read_presences(&self) -> Result, Error> { - expect!( - self.request(Request::ReadPresences).await?, - Response::Presences - ) - } - - pub async fn update_presence(&self, presence: Presence) -> Result<(), Error> { - self.done(Request::UpdatePresence { presence }).await - } - - pub async fn add_friend(&self, user_id: &str) -> Result<(), Error> { - self.done(Request::AddFriend { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn accept_friend(&self, user_id: &str) -> Result<(), Error> { - self.done(Request::AcceptFriend { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn remove_friend(&self, user_id: &str) -> Result<(), Error> { - self.done(Request::RemoveFriend { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Error> { - self.done(Request::Invite { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - }) - .await - } - - pub async fn invitations(&self) -> Result, Error> { - expect!( - self.request(Request::Invitations).await?, - Response::Invitations - ) - } - - pub async fn accept_invitation(&self, community_id: &str) -> Result { - expect!( - self.request(Request::AcceptInvitation { - community_id: community_id.to_string(), - }) - .await?, - Response::Community - ) - } - - pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Error> { - self.done(Request::DeclineInvitation { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn decline_call(&self, community_id: &str) -> Result<(), Error> { - self.done(Request::DeclineCall { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Error> { - self.done(Request::React { - message_id: message_id.to_string(), - emoji: emoji.to_string(), - }) - .await - } - - pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Error> { - self.done(Request::Pin { - message_id: message_id.to_string(), - pinned, - }) - .await - } - - pub async fn pins(&self, community_id: &str) -> Result, Error> { - expect!( - self.request(Request::Pins { - community_id: community_id.to_string(), - }) - .await?, - Response::Messages - ) - } - - pub async fn create_poll( - &self, - community_id: &str, - question: &str, - options: Vec, - multiple: bool, - ) -> Result { - validate_poll(question, &options)?; - - expect!( - self.request(Request::CreatePoll { - community_id: community_id.to_string(), - question: question.to_string(), - options, - multiple, - }) - .await?, - Response::Message - ) - } - - pub async fn vote(&self, message_id: &str, positions: Vec) -> Result<(), Error> { - self.done(Request::Vote { - message_id: message_id.to_string(), - positions, - }) - .await - } - - pub async fn close_poll(&self, message_id: &str) -> Result<(), Error> { - self.done(Request::ClosePoll { - message_id: message_id.to_string(), - }) - .await - } - - pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Error> { - validate_reason(Some(reason))?; - - self.done(Request::ReportMessage { - message_id: message_id.to_string(), - reason: reason.to_string(), - }) - .await - } - - pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Error> { - validate_reason(Some(reason))?; - - self.done(Request::ReportUser { - user_id: user_id.to_string(), - reason: reason.to_string(), - }) - .await - } - - pub async fn reports(&self, status: Option) -> Result, Error> { - expect!( - self.request(Request::Reports { status }).await?, - Response::Reports - ) - } - - pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Error> { - self.done(Request::HandleReport { - report_id: report_id.to_string(), - status, - }) - .await - } - - pub async fn search_messages( - &self, - text: Option, - user_id: Option, - community_id: Option, - after_ms: Option, - before_ms: Option, - ) -> Result, Error> { - expect!( - self.request(Request::SearchMessages { - text, - user_id, - community_id, - after_ms, - before_ms, - }) - .await?, - Response::MessageHits - ) - } - - pub async fn search_community( - &self, - community_id: String, - text: String, - ) -> Result, Error> { - expect!( - self.request(Request::SearchCommunity { community_id, text }) - .await?, - Response::MessageHits - ) - } - - pub async fn storage_usage(&self) -> Result<(Vec, Vec), Error> { - match self.request(Request::StorageUsage).await? { - Response::StorageUsage { users, communities } => Ok((users, communities)), - _ => Err(Error::Server), - } - } - - pub async fn create_backup(&self) -> Result { - expect!(self.request(Request::CreateBackup).await?, Response::Backup) - } - - pub async fn backups(&self) -> Result, Error> { - expect!(self.request(Request::Backups).await?, Response::Backups) - } - - pub async fn delete_backup(&self, name: &str) -> Result<(), Error> { - self.done(Request::DeleteBackup { - name: name.to_string(), - }) - .await - } - - pub async fn attachments( - &self, - user_id: Option, - community_id: Option, - ) -> Result, Error> { - expect!( - self.request(Request::AllAttachments { - user_id, - community_id, - }) - .await?, - Response::AttachmentInfos - ) - } - - pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Error> { - self.done(Request::DeleteAttachment { - attachment_id: attachment_id.to_string(), - }) - .await - } - - pub async fn purge_user(&self, user_id: &str) -> Result<(), Error> { - self.done(Request::PurgeUser { - user_id: user_id.to_string(), - }) - .await - } - - async fn done(&self, request: Request) -> Result<(), Error> { - match self.request(request).await? { - Response::Done => Ok(()), - _ => Err(Error::Server), - } - } - - pub async fn upload_attachment( - &self, - community_id: &str, - path: PathBuf, - maximum: Option, - ) -> Result { - self.ask(|reply| Command::Upload { - community_id: community_id.to_string(), - path, - maximum, - reply, - }) - .await - } - - pub async fn download_attachment( - &self, - attachment_id: &str, - thumbnail: bool, - ) -> Result, Error> { - self.ask(|reply| Command::Download { - attachment_id: attachment_id.to_string(), - thumbnail, - reply, - }) - .await - } - - pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Error> { - self.ask(|reply| Command::BackupDownload { - name: name.to_string(), - path, - reply, - }) - .await - } - - pub async fn read_messages( - &self, - community_id: &str, - before: Option<&str>, - ) -> Result, Error> { - expect!( - self.request(Request::ReadMessages { - community_id: community_id.to_string(), - before: before.map(str::to_string), - }) - .await?, - Response::Messages - ) - } - - pub async fn unreads(&self) -> Result, Error> { - expect!(self.request(Request::Unreads).await?, Response::Unreads) - } - - pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> { - self.done(Request::MarkRead { - community_id: community_id.to_string(), - message_id: message_id.to_string(), - }) - .await - } - - pub async fn update_status(&self, status: &str) -> Result { - validate_status(status)?; - - expect!( - self.request(Request::UpdateStatus { - status: status.to_string(), - }) - .await?, - Response::User - ) - } - - pub async fn update_avatar(&self, bytes: Vec) -> Result { - validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?; - - expect!( - self.request(Request::UpdateAvatar { image: bytes }).await?, - Response::User - ) - } - - pub async fn update_community_avatar( - &self, - community_id: &str, - image: Option>, - ) -> Result { - if let Some(bytes) = &image { - validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; - } - - expect!( - self.request(Request::UpdateCommunityAvatar { - community_id: community_id.to_string(), - image, - }) - .await?, - Response::Community - ) - } - - pub async fn remove_avatar(&self) -> Result { - expect!(self.request(Request::RemoveAvatar).await?, Response::User) - } - - pub async fn read_avatar(&self, avatar_id: &str) -> Result, Error> { - expect!( - self.request(Request::ReadAvatar { - avatar_id: avatar_id.to_string(), - }) - .await?, - Response::Avatar - ) - } - - pub async fn join_voice(&self, community_id: &str) -> Result, Error> { - expect!( - self.request(Request::JoinVoice { - community_id: community_id.to_string(), - }) - .await?, - Response::Voice - ) - } - - pub async fn typing(&self, community_id: &str) -> Result<(), Error> { - self.done(Request::Typing { - community_id: community_id.to_string(), - }) - .await - } - - pub async fn leave_voice(&self) -> Result<(), Error> { - self.done(Request::LeaveVoice).await - } - - pub async fn read_community(&self, community_id: &str) -> Result { - expect!( - self.request(Request::ReadCommunity { - community_id: community_id.to_string(), - }) - .await?, - Response::Community - ) - } - - pub async fn voice_participants(&self, community_id: &str) -> Result, Error> { - expect!( - self.request(Request::VoiceParticipants { - community_id: community_id.to_string(), - }) - .await?, - Response::Voice - ) - } - - pub async fn voice_rooms(&self) -> Result, Error> { - expect!( - self.request(Request::VoiceRooms).await?, - Response::VoiceRooms - ) - } - - pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> { - self.done(Request::SetGhost { enabled }).await - } - - pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Error> { - self.done(Request::KickFromVoice { - user_id: user_id.to_string(), - }) - .await - } - - pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Error> { - self.done(Request::ServerMute { - user_id: user_id.to_string(), - muted, - }) - .await - } - - pub async fn set_community_voice( - &self, - community_id: &str, - enabled: bool, - ) -> Result { - expect!( - self.request(Request::SetCommunityVoice { - community_id: community_id.to_string(), - enabled, - }) - .await?, - Response::Community - ) - } - - pub fn set_voice_settings(&self, settings: VoiceSettings) { - *self.shared.voice_settings.lock().unwrap() = settings.clone(); - - if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() { - voice.apply(&settings); - } - if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() { - voice.apply(&settings); - } - } - - pub fn start_mic_test(&self) { - if self.shared.voice.lock().unwrap().is_some() { - return; - } - let settings = self.shared.voice_settings.lock().unwrap().clone(); - *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings)); - } - - pub fn play_chime(&self) { - voice::play_chime(&self.shared.voice_settings.lock().unwrap()); - } - - pub fn play_notification(&self) { - voice::play_yumush(&self.shared.voice_settings.lock().unwrap()); - } - - pub fn play_ring(&self) { - voice::play_ring(&self.shared.voice_settings.lock().unwrap()); - } - - pub fn stop_mic_test(&self) { - self.shared.mic_test.lock().unwrap().take(); - } - - pub fn voice_level_db(&self) -> Option { - self.with_voice(Voice::level_db).or_else(|| { - self.shared - .mic_test - .lock() - .unwrap() - .as_ref() - .map(Voice::level_db) - }) - } - - pub fn voice_sample(&self) -> Option { - self.with_voice(Voice::sample) - } - - pub fn set_talking(&self, talking: bool) { - self.with_voice(|voice| voice.set_talking(talking)); - } - - pub fn set_muted(&self, muted: bool) { - self.with_voice(|voice| voice.set_muted(muted)); - } - - pub fn set_deafened(&self, deafened: bool) { - self.with_voice(|voice| voice.set_deafened(deafened)); - } - - pub fn levels(&self) -> Levels { - let share = self.shared.share.lock().unwrap(); - Levels { - voice: self.with_voice(Voice::levels).unwrap_or_default(), - watching: share - .watching - .iter() - .filter(|((_, kind), _)| *kind == Kind::Screen) - .map(|((user_id, _), watching)| (user_id.clone(), watching.level())) - .collect(), - sharing: share.sharing.get(&Kind::Screen).map(Sharing::level), - } - } - - pub async fn start_share(&self) -> Result<(), Error> { - self.start(Kind::Screen).await - } - - pub async fn start_camera(&self) -> Result<(), Error> { - self.start(Kind::Camera).await - } - - async fn start(&self, kind: Kind) -> Result<(), Error> { - let settings = self.shared.share_settings.lock().unwrap().clone(); - self.ask(|reply| Command::StartShare { - kind, - settings, - reply, - }) - .await - } - - pub async fn update_share(&self) -> Result<(), Error> { - let settings = self.shared.share_settings.lock().unwrap().clone(); - self.ask(|reply| Command::UpdateShare { settings, reply }) - .await - } - - pub async fn stop_share(&self) -> Result<(), Error> { - self.stop(Kind::Screen).await - } - - pub async fn stop_camera(&self) -> Result<(), Error> { - self.stop(Kind::Camera).await - } - - async fn stop(&self, kind: Kind) -> Result<(), Error> { - let result = self.done(Request::StopShare { kind }).await; - let mut share = self.shared.share.lock().unwrap(); - share.sharing.remove(&kind); - share.sources.remove(&kind); - result - } - - pub fn sharing(&self) -> bool { - self.shared - .share - .lock() - .unwrap() - .sharing - .contains_key(&Kind::Screen) - } - - pub fn camera_on(&self) -> bool { - self.shared - .share - .lock() - .unwrap() - .sharing - .contains_key(&Kind::Camera) - } - - pub fn share_source(&self) -> Option { - self.shared - .share - .lock() - .unwrap() - .sources - .get(&Kind::Screen) - .cloned() - } - - pub async fn shares(&self, community_id: &str) -> Result, Error> { - expect!( - self.request(Request::Shares { - community_id: community_id.to_string(), - }) - .await?, - Response::Shares - ) - } - - pub async fn watch_share( - &self, - user_id: &str, - kind: Kind, - watch: WatchQuality, - ) -> Result<(), Error> { - let volume = self.shared.share_settings.lock().unwrap().volume; - let choice = self.shared.voice_settings.lock().unwrap().choice.clone(); - let key = (user_id.to_string(), kind); - let watching = Watching::new(kind, watch, volume, choice); - let quality = watching.wanted(); - self.shared - .share - .lock() - .unwrap() - .watching - .insert(key.clone(), watching); - - let result = self - .done(Request::WatchShare { - user_id: key.0.clone(), - kind, - quality, - decode: capabilities().decode.clone(), - }) - .await; - if result.is_err() { - self.shared.share.lock().unwrap().watching.remove(&key); - } - result - } - - pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Error> { - self.shared - .share - .lock() - .unwrap() - .watching - .remove(&(user_id.to_string(), kind)); - self.done(Request::UnwatchShare { - user_id: user_id.to_string(), - kind, - }) - .await - } - - pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { - if let Some(watching) = self - .shared - .share - .lock() - .unwrap() - .watching - .get_mut(&(user_id.to_string(), kind)) - { - watching.set_quality(quality); - } - } - - pub fn share_sample(&self) -> ShareSample { - let mut share = self.shared.share.lock().unwrap(); - ShareSample { - sending: share - .sharing - .get(&Kind::Screen) - .map(Sharing::stats) - .unwrap_or_default(), - watching: share - .watching - .iter_mut() - .filter(|((_, kind), _)| *kind == Kind::Screen) - .map(|((user_id, _), watching)| (user_id.clone(), watching.stats())) - .collect(), - } - } - - pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option { - self.shared - .share - .lock() - .unwrap() - .watching - .get(&(user_id.to_string(), kind))? - .frame() - } - - pub fn set_share_settings(&self, settings: ShareSettings) -> bool { - let changed = self.sharing() - && self - .shared - .share_settings - .lock() - .unwrap() - .encoding_differs(&settings); - *self.shared.share_settings.lock().unwrap() = settings.clone(); - for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() { - if *kind == Kind::Screen { - watching.set_volume(settings.volume); - watching.set_quality(settings.watch); - } - } - changed - } - - pub fn audio_apps(&self) -> Vec { - audio_capture::apps() - } -} - -pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver) { - let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); - let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); - let shared = Shared::default(); - - std::thread::Builder::new() - .name("network".to_string()) - .spawn({ - let shared = shared.clone(); - move || { - tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .expect("network runtime") - .block_on(actor(client_config, command_receiver, event_sender, shared)); - } - }) - .expect("network thread"); - - ( - NetworkHandle { - command_sender, - shared, - }, - event_receiver, - ) -} - -async fn connect(client_config: &ClientConfig) -> Result { - let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; - endpoint.set_default_client_config(config()?); - - let connection = endpoint - .connect( - client_config.server_address.parse()?, - &client_config.server_name, - )? - .await?; - - Ok(connection) -} - -fn network_error(error: impl std::fmt::Display) -> Error { - Error::Network(error.to_string()) -} - -#[cfg(debug_assertions)] -#[derive(Debug)] -struct AcceptAnyCertificate { - provider: Arc, -} - -#[cfg(debug_assertions)] -impl ServerCertVerifier for AcceptAnyCertificate { - fn verify_server_cert( - &self, - _end_entity: &CertificateDer<'_>, - _intermediates: &[CertificateDer<'_>], - _server_name: &ServerName<'_>, - _ocsp_response: &[u8], - _now: UnixTime, - ) -> Result { - Ok(ServerCertVerified::assertion()) - } - - fn verify_tls12_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - rustls::crypto::verify_tls12_signature( - message, - cert, - dss, - &self.provider.signature_verification_algorithms, - ) - } - - fn verify_tls13_signature( - &self, - message: &[u8], - cert: &CertificateDer<'_>, - dss: &DigitallySignedStruct, - ) -> Result { - rustls::crypto::verify_tls13_signature( - message, - cert, - dss, - &self.provider.signature_verification_algorithms, - ) - } - - fn supported_verify_schemes(&self) -> Vec { - self.provider - .signature_verification_algorithms - .supported_schemes() - } -} - -#[cfg(debug_assertions)] -fn accept_any_client_config() -> Result { - let provider = Arc::new(rustls::crypto::ring::default_provider()); - let tls = rustls::ClientConfig::builder_with_provider(provider.clone()) - .with_protocol_versions(&[&rustls::version::TLS13]) - .map_err(network_error)? - .dangerous() - .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider })) - .with_no_client_auth(); - - let crypto = QuicClientConfig::try_from(tls).map_err(network_error)?; - - Ok(quinn::ClientConfig::new(Arc::new(crypto))) -} - -fn config() -> Result { - #[cfg(debug_assertions)] - let mut client_config = accept_any_client_config()?; - - #[cfg(not(debug_assertions))] - let mut client_config = - quinn::ClientConfig::try_with_platform_verifier().map_err(network_error)?; - - let mut transport_config = quinn::TransportConfig::default(); - transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL)); - transport_config.max_idle_timeout(Some(MAX_IDLE_TIMEOUT.try_into().unwrap())); - - client_config.transport_config(Arc::new(transport_config)); - - Ok(client_config) -} - -async fn send(connection: &quinn::Connection, request: &Request) -> Result { - let (send_stream, receive_stream) = connection.open_bi().await?; - send_request(request, send_stream, receive_stream).await -} - -async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Error> { - match send(connection, &request).await? { - Response::Done => Ok(()), - Response::Error(error) => Err(error), - _ => Err(Error::Server), - } -} - -async fn send_body( - send_stream: &mut quinn::SendStream, - file: &mut tokio::fs::File, -) -> Result<(), Error> { - use tokio::io::AsyncReadExt; - - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; - loop { - let read = file.read(&mut buffer).await?; - if read == 0 { - return Ok(()); - } - - send_stream.write_all(&buffer[..read]).await?; - } -} - -async fn upload( - connection: &quinn::Connection, - community_id: &str, - path: &Path, - maximum: Option, -) -> Result { - let name = path - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_default(); - validate_attachment_name(&name)?; - - let mut file = tokio::fs::File::open(path).await?; - let size = file.metadata().await?.len(); - if let Some(maximum) = maximum { - validate_attachment_size(size, maximum)?; - } - - let (mut send_stream, mut receive_stream) = connection.open_bi().await?; - send_stream_kind(StreamKind::Upload, &mut send_stream).await?; - let header = UploadHeader { - community_id: community_id.to_string(), - name, - size, - }; - send_upload_header(&header, &mut send_stream).await?; - - let sent = match send_body(&mut send_stream, &mut file).await { - Ok(()) => send_stream.finish().map_err(Error::from), - Err(error) => Err(error), - }; - let response = receive_decoded::(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await; - - match (sent, response) { - (_, Ok(Response::Attachment(attachment))) => Ok(attachment), - (_, Ok(Response::Error(error))) => Err(error), - (Err(error), _) | (_, Err(error)) => Err(error), - (Ok(()), Ok(_)) => Err(Error::Server), - } -} - -async fn backup_download( - connection: &quinn::Connection, - name: &str, - path: &Path, -) -> Result<(), Error> { - let request = Request::DownloadBackup { - name: name.to_string(), - }; - let (mut receive_stream, length) = - open_download(connection, StreamKind::Backup, &request).await?; - - let mut file = tokio::fs::File::create(path).await?; - let copied = tokio::io::copy(&mut receive_stream, &mut file).await?; - if copied != length { - return Err(Error::Network(format!( - "backup truncated ({copied} < {length})" - ))); - } - - Ok(()) -} - -async fn download( - connection: &quinn::Connection, - attachment_id: &str, - thumbnail: bool, -) -> Result, Error> { - let request = DownloadRequest { - attachment_id: attachment_id.to_string(), - thumbnail, - }; - let (mut receive_stream, length) = - open_download(connection, StreamKind::Download, &request).await?; - - if length > MAXIMUM_ATTACHMENT_LIMIT_BYTES { - return Err(Error::ReadBoundExceed { - actual: length as usize, - maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES as usize, - }); - } - - let mut bytes = vec![0u8; length as usize]; - receive_stream.read_exact(&mut bytes).await?; - - Ok(bytes) -} - -fn answer( - reply: oneshot::Sender>, - work: impl Future> + Send + 'static, -) { - tokio::spawn(async move { - let _ = reply.send(work.await); - }); -} - -async fn actor( - client_config: ClientConfig, - mut command_receiver: mpsc::Receiver, - event_sender: mpsc::Sender, - shared: Shared, -) { - let mut token: Option = None; - 'session: loop { - let connection = loop { - match connect(&client_config).await { - Ok(connection) => break connection, - Err(error) => { - warn!("connect failed: {error}"); - - if event_sender - .send(NetworkEvent::Disconnected(error)) - .await - .is_err() - { - return; - } - - tokio::time::sleep(RECONNECT_DELAY).await; - } - }; - }; - - if let Some(stored) = token.clone() { - let request = Request::Resume { token: stored }; - match send(&connection, &request).await { - Ok(Response::Session { token: resumed, .. }) => token = Some(resumed), - Err(error) => { - warn!("session resume failed: {error}"); - tokio::time::sleep(RECONNECT_DELAY).await; - continue 'session; - } - Ok(_) => { - warn!("session resume rejected"); - token = None; - - if event_sender.send(NetworkEvent::SessionLost).await.is_err() { - return; - } - } - } - } - - info!("connected"); - if event_sender.send(NetworkEvent::Connected).await.is_err() { - return; - } - - tokio::spawn(event_receive_loop( - connection.clone(), - event_sender.clone(), - shared.share.clone(), - )); - tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone())); - let mut ticker = tokio::time::interval(SHARE_TICK); - - loop { - tokio::select! { - command = command_receiver.recv() => match command { - Some(Command::Request { request, reply }) => match &request { - Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { - hang_up(&shared); - - let response = send(&connection, &request).await; - if let Ok(Response::Session { token: session_token, .. }) = &response { - token = Some(session_token.clone()); - } - let _ = reply.send(response); - } - Request::Logout | Request::Detach => { - token = None; - hang_up(&shared); - - let connection = connection.clone(); - answer(reply, async move { send(&connection, &request).await }); - } - Request::JoinVoice { .. } => { - let shared = shared.clone(); - let settings = shared.voice_settings.lock().unwrap().clone(); - let connection = connection.clone(); - - answer(reply, async move { - let response = send(&connection, &request).await; - if let Ok(Response::Voice(_)) = &response { - shared.mic_test.lock().unwrap().take(); - *shared.voice.lock().unwrap() = - Some(voice::start(Some(connection), &settings)); - } - response - }); - } - Request::LeaveVoice => { - hang_up(&shared); - - let connection = connection.clone(); - answer(reply, async move { send(&connection, &request).await }); - } - _ => { - let connection = connection.clone(); - answer(reply, async move { send(&connection, &request).await }); - } - }, - Some(Command::StartShare { kind, settings, reply }) => { - let connection = connection.clone(); - let share = shared.share.clone(); - - answer(reply, async move { start_share(&connection, &share, kind, &settings).await }); - } - Some(Command::UpdateShare { settings, reply }) => { - let connection = connection.clone(); - let share = shared.share.clone(); - - answer(reply, async move { update_share(&connection, &share, &settings).await }); - } - Some(Command::Upload { community_id, path, maximum, reply }) => { - let connection = connection.clone(); - - answer(reply, async move { upload(&connection, &community_id, &path, maximum).await }); - } - Some(Command::Download { attachment_id, thumbnail, reply }) => { - let connection = connection.clone(); - - answer(reply, async move { download(&connection, &attachment_id, thumbnail).await }); - } - Some(Command::BackupDownload { name, path, reply }) => { - let connection = connection.clone(); - - answer(reply, async move { backup_download(&connection, &name, &path).await }); - } - None => break 'session, - }, - - _ = ticker.tick() => { - let requests = shared.share.lock().unwrap().ticks(); - for request in requests { - let connection = connection.clone(); - tokio::spawn(async move { - let _ = send(&connection, &request).await; - }); - } - } - - error = connection.closed() => { - warn!("disconnected: {error}"); - hang_up(&shared); - - if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { - return; - } - - break; - } - } - } - } -} - -async fn start_share( - connection: &quinn::Connection, - share: &SharedShare, - kind: Kind, - settings: &ShareSettings, -) -> Result<(), Error> { - let top = match kind { - Kind::Screen => settings.top, - Kind::Camera => CAMERA_TOP, - }; - let (sharing, source) = Sharing::start( - connection.clone(), - kind, - top, - settings.encode(), - settings.audio_mode(), - ) - .await - .map_err(Error::Device)?; - { - let mut share = share.lock().unwrap(); - share.sharing.insert(kind, sharing); - share.sources.insert(kind, source.clone()); - } - - let result = done(connection, Request::StartShare { kind, source }).await; - if result.is_err() { - let mut share = share.lock().unwrap(); - share.sharing.remove(&kind); - share.sources.remove(&kind); - } - result -} - -async fn update_share( - connection: &quinn::Connection, - share: &SharedShare, - settings: &ShareSettings, -) -> Result<(), Error> { - let source = { - let mut share = share.lock().unwrap(); - let Some(sharing) = share.sharing.get_mut(&Kind::Screen) else { - return Ok(()); - }; - sharing - .update( - connection, - settings.top, - settings.encode(), - settings.audio_mode(), - ) - .map_err(Error::Device)? - }; - share - .lock() - .unwrap() - .sources - .insert(Kind::Screen, source.clone()); - - done( - connection, - Request::StartShare { - kind: Kind::Screen, - source, - }, - ) - .await -} - -async fn event_receive_loop( - connection: quinn::Connection, - event_sender: mpsc::Sender, - share: SharedShare, -) { - let Ok(mut receive_stream) = connection.accept_uni().await else { - return; - }; - - while let Ok(event) = receive_event(&mut receive_stream).await { - share.lock().unwrap().event(&event); - if event_sender - .send(NetworkEvent::Pushed(Box::new(event))) - .await - .is_err() - { - return; - } - } -} - -async fn datagram_receive_loop(connection: quinn::Connection, shared: Shared) { - let loss: u64 = std::env::var("YUMUSH_TEST_LOSS") - .ok() - .and_then(|value| value.parse().ok()) - .unwrap_or(0); - let mut received: u64 = 0; - while let Ok(datagram) = connection.read_datagram().await { - if let Some(voice) = shared.voice.lock().unwrap().as_ref() { - voice.receive(&datagram); - } - if let Some((user_id, packet)) = decode_relay(&datagram) { - if let Datagram::Video(_) = packet { - received += 1; - if received * 37 % 100 < loss { - continue; - } - } - let kind = match &packet { - Datagram::Video(fragment) => fragment.kind, - _ => Kind::Screen, - }; - if let Some(watching) = shared.share.lock().unwrap().watching.get(&(user_id, kind)) { - watching.receive(packet); - } - } - } -} diff --git a/crates/client/src/share/encode.rs b/crates/client/src/share/encode.rs index f53d0e7..e45883f 100644 --- a/crates/client/src/share/encode.rs +++ b/crates/client/src/share/encode.rs @@ -64,8 +64,8 @@ struct Settings { } enum Backend { - Hardware(hardware::Encoder), - H264(ec_h264::Encoder), + Hardware(Box), + H264(Box), } impl Backend { @@ -75,10 +75,12 @@ impl Backend { } else { None }; - hardware.map(Self::Hardware).or_else(|| { - tracing::warn!(codec = ?settings.codec, "share encode falls back to software"); - Self::software(settings) - }) + hardware + .map(|encoder| Self::Hardware(Box::new(encoder))) + .or_else(|| { + tracing::warn!(codec = ?settings.codec, "share encode falls back to software"); + Self::software(settings) + }) } fn software(settings: &Settings) -> Option { @@ -90,7 +92,7 @@ impl Backend { config.bitrate = settings.bitrate; config.gop_size = settings.gop; config.threads = 4; - report(ec_h264::Encoder::new(config)).map(Self::H264) + report(ec_h264::Encoder::new(config)).map(|encoder| Self::H264(Box::new(encoder))) } Codec::H265 | Codec::Av1 | Codec::Vp8 | Codec::Vp9 => None, } @@ -165,7 +167,10 @@ mod hardware { timestamp: i64::from(frame.timestamp_ms), force_keyframe: force, }; - let coded = if frame.width % 2 == 0 && frame.height % 2 == 0 && frame.stride % 4 == 0 { + let coded = if frame.width.is_multiple_of(2) + && frame.height.is_multiple_of(2) + && frame.stride.is_multiple_of(4) + { let rgb = ec_hw::RgbFrame { data: &frame.bgra, width: frame.width, diff --git a/crates/client/src/share/reassembly.rs b/crates/client/src/share/reassembly.rs index d116878..990c371 100644 --- a/crates/client/src/share/reassembly.rs +++ b/crates/client/src/share/reassembly.rs @@ -92,6 +92,12 @@ pub struct Reassembler { lost_frames: u32, } +impl Default for Reassembler { + fn default() -> Self { + Self::new() + } +} + impl Reassembler { pub fn new() -> Reassembler { Reassembler { diff --git a/crates/common/src/config.rs b/crates/common/src/config.rs index 03212b2..7c3c067 100644 --- a/crates/common/src/config.rs +++ b/crates/common/src/config.rs @@ -1,11 +1,17 @@ use std::collections::HashMap; -use crate::error::Error; +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + #[error("invalid line: {0}")] + InvalidLine(String), + #[error("missing key: {0}")] + MissingKey(String), +} pub struct Config(HashMap); impl Config { - pub fn parse(content: &str) -> Result { + pub fn parse(content: &str) -> Result { let mut fields = HashMap::new(); for line in content.lines().map(str::trim) { @@ -15,7 +21,7 @@ impl Config { let (key, value) = line .split_once('=') - .ok_or_else(|| Error::Config(format!("invalid line: {line}")))?; + .ok_or_else(|| ConfigError::InvalidLine(line.to_string()))?; fields.insert( key.trim().to_string(), @@ -26,10 +32,10 @@ impl Config { Ok(Self(fields)) } - pub fn get(&self, key: &str) -> Result { + pub fn get(&self, key: &str) -> Result { self.0 .get(key) .cloned() - .ok_or_else(|| Error::Config(format!("missing key: {key}"))) + .ok_or_else(|| ConfigError::MissingKey(key.to_string())) } } diff --git a/crates/common/src/error.rs b/crates/common/src/error.rs index cd4ec9f..3fa0b4c 100644 --- a/crates/common/src/error.rs +++ b/crates/common/src/error.rs @@ -2,42 +2,14 @@ use std::fmt::Display; use bitcode::{Decode, Encode}; -#[macro_export] -macro_rules! error_from { - ($target:ty { $($source:ty => $variant:path as $middle:ty),+ $(,)? }) => { - $( - impl From<$source> for $target { - fn from(value: $source) -> Self { - $variant(<$middle>::from(value)) - } - } - )+ - }; -} - -macro_rules! from_display { - ($target:ty { $($source:ty => $variant:path),+ $(,)? }) => { - $( - impl From<$source> for $target { - fn from(value: $source) -> Self { - $variant(value.to_string()) - } - } - )+ - }; -} - #[derive(Debug, Clone, Encode, Decode)] -pub enum InvalidInput { - TooShort { minimum: usize, actual: usize }, - TooLong { maximum: usize, actual: usize }, - TooLarge { maximum: u64, actual: u64 }, +pub enum Problem { + Length { min: u64, max: u64, actual: u64 }, Empty, + Characters, MultiLine, - ForbiddenCharacter, NotJpeg, Dimensions { expected: u32 }, - TooSmall { minimum: u64, actual: u64 }, } pub fn size_text(size: u64) -> String { @@ -48,38 +20,40 @@ pub fn size_text(size: u64) -> String { } } -impl Display for InvalidInput { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - InvalidInput::TooShort { minimum, actual } => { - write!(f, "too short ({actual} < {minimum})") - } - InvalidInput::TooLong { maximum, actual } => { - write!(f, "too long ({actual} > {maximum})") - } - InvalidInput::TooLarge { maximum, actual } => { - write!( - f, - "too large: {} (max {})", +impl Problem { + pub fn describe(&self, field: &Field) -> String { + match (self, field.is_size()) { + (Problem::Length { min, actual, .. }, true) if actual < min => { + format!( + "too small: {} (min {})", size_text(*actual), - size_text(*maximum) + size_text(*min) ) } - InvalidInput::Empty => write!(f, "empty"), - InvalidInput::MultiLine => write!(f, "contains line break"), - InvalidInput::ForbiddenCharacter => write!(f, "contains forbidden character"), - InvalidInput::NotJpeg => write!(f, "not JPEG"), - InvalidInput::Dimensions { expected } => { - write!(f, "must be {expected}x{expected} px") - } - InvalidInput::TooSmall { minimum, actual } => { - write!( - f, - "too small: {} (min {})", + (Problem::Length { max, actual, .. }, true) => { + format!( + "too large: {} (max {})", size_text(*actual), - size_text(*minimum) + size_text(*max) ) } + _ => self.to_string(), + } + } +} + +impl Display for Problem { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Problem::Length { min, actual, .. } if actual < min => { + write!(f, "too short ({actual} < {min})") + } + Problem::Length { max, actual, .. } => write!(f, "too long ({actual} > {max})"), + Problem::Empty => write!(f, "empty"), + Problem::Characters => write!(f, "contains forbidden character"), + Problem::MultiLine => write!(f, "contains line break"), + Problem::NotJpeg => write!(f, "not JPEG"), + Problem::Dimensions { expected } => write!(f, "must be {expected}x{expected} px"), } } } @@ -101,6 +75,17 @@ pub enum Field { BackupName, Quota, Announcement, + Poll, + Reaction, +} + +impl Field { + fn is_size(&self) -> bool { + matches!( + self, + Field::Attachment | Field::Avatar | Field::AttachmentLimit | Field::Quota + ) + } } impl Display for Field { @@ -121,6 +106,8 @@ impl Display for Field { Field::BackupName => "backup name:", Field::Quota => "quota:", Field::Announcement => "announcement:", + Field::Poll => "poll:", + Field::Reaction => "reaction:", }; write!(f, "{label}") } @@ -138,34 +125,16 @@ pub enum Error { Taken, #[error("wrong credentials")] WrongCredentials, - #[error("server error")] - Server, - #[error("channel closed")] - ChannelClosed, - #[error("config: {0}")] - Config(String), - #[error("network: {0}")] - Network(String), - #[error("decode: {0}")] - Decode(String), - #[error("read bound exceeded ({actual} > {maximum})")] - ReadBoundExceed { actual: usize, maximum: usize }, - #[error("{field} {input}")] - Invalid { field: Field, input: InvalidInput }, - #[error("upload: {0}")] - Upload(String), - #[error("certificate: {0}")] - Certificate(String), #[error("already a member")] AlreadyMember, #[error("already invited")] AlreadyInvited, #[error("suspended")] - Suspended, - #[error("registration closed")] - RegistrationClosed, + Suspended { until_ms: Option }, #[error("banned")] Banned, + #[error("registration closed")] + RegistrationClosed, #[error("maintenance")] Maintenance, #[error("storage quota exceeded")] @@ -174,19 +143,8 @@ pub enum Error { LimitReached, #[error("too many requests, retry in {retry_after_seconds}s")] RateLimited { retry_after_seconds: u64 }, - #[error("{0}")] - Device(String), + #[error("{field} {}", .problem.describe(.field))] + Invalid { field: Field, problem: Problem }, + #[error("server error")] + Server, } - -from_display! { Error { - std::net::AddrParseError => Error::Network, - std::io::Error => Error::Network, - quinn::ConnectionError => Error::Network, - quinn::ConnectError => Error::Network, - quinn::ReadError => Error::Network, - quinn::ReadToEndError => Error::Network, - quinn::ReadExactError => Error::Network, - quinn::WriteError => Error::Network, - quinn::ClosedStream => Error::Network, - bitcode::Error => Error::Decode, -} } diff --git a/crates/common/src/frame.rs b/crates/common/src/frame.rs new file mode 100644 index 0000000..fa2be81 --- /dev/null +++ b/crates/common/src/frame.rs @@ -0,0 +1,89 @@ +use bitcode::{DecodeOwned, Encode}; +use quinn::{RecvStream, SendStream}; + +use crate::constant::MAXIMUM_AVATAR_BYTES; + +#[derive(Debug, thiserror::Error)] +pub enum FrameError { + #[error(transparent)] + Connection(#[from] quinn::ConnectionError), + #[error(transparent)] + Write(#[from] quinn::WriteError), + #[error(transparent)] + Read(#[from] quinn::ReadExactError), + #[error(transparent)] + Closed(#[from] quinn::ClosedStream), + #[error("frame too large ({actual} > {maximum})")] + TooLarge { actual: u32, maximum: u32 }, + #[error("frame decode: {0}")] + Decode(#[from] bitcode::Error), +} + +pub const UP_MAX: u32 = 64 << 10; +pub const DOWN_MAX: u32 = 16 << 20; + +const _: () = assert!(MAXIMUM_AVATAR_BYTES as u32 + 4096 <= UP_MAX); + +pub struct Sending(Option); + +impl Sending { + pub fn new(stream: SendStream) -> Self { + Self(Some(stream)) + } + + pub fn get(&mut self) -> &mut SendStream { + self.0.as_mut().expect("stream is present until finish") + } + + pub fn finish(mut self) -> Result<(), FrameError> { + let mut stream = self.0.take().expect("stream is present until finish"); + stream.finish()?; + Ok(()) + } +} + +impl Drop for Sending { + fn drop(&mut self) { + if let Some(stream) = &mut self.0 { + let _ = stream.reset(quinn::VarInt::from_u32(0)); + } + } +} + +pub fn encode(value: &T) -> Vec { + let payload = bitcode::encode(value); + let mut framed = Vec::with_capacity(4 + payload.len()); + framed.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + framed.extend_from_slice(&payload); + framed +} + +pub async fn write(stream: &mut Sending, value: &T, max: u32) -> Result<(), FrameError> { + let framed = encode(value); + let length = framed.len() as u32 - 4; + if length > max { + return Err(FrameError::TooLarge { + actual: length, + maximum: max, + }); + } + stream.get().write_all(&framed).await?; + Ok(()) +} + +pub async fn read(stream: &mut RecvStream, max: u32) -> Result { + let mut length_bytes = [0u8; 4]; + stream.read_exact(&mut length_bytes).await?; + + let length = u32::from_le_bytes(length_bytes); + if length > max { + return Err(FrameError::TooLarge { + actual: length, + maximum: max, + }); + } + + let mut payload = vec![0u8; length as usize]; + stream.read_exact(&mut payload).await?; + Ok(bitcode::decode(&payload)?) +} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 01dcd2d..5e8d5b2 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -3,11 +3,13 @@ pub mod constant; pub mod datagram; pub mod error; pub mod event; +pub mod frame; pub mod model; -pub mod network; +pub mod open; pub mod permission; pub mod request; pub mod response; pub mod share; pub mod time; +pub mod transport; pub mod validate; diff --git a/crates/common/src/network.rs b/crates/common/src/network.rs deleted file mode 100644 index ca15394..0000000 --- a/crates/common/src/network.rs +++ /dev/null @@ -1,193 +0,0 @@ -use bitcode::{DecodeOwned, Encode}; -use quinn::{RecvStream, SendStream}; - -use crate::{ - error::Error, - event::Event, - request::{Request, UploadHeader}, - response::Response, -}; - -pub const UPLOAD_HEADER_MAX_LENGTH: usize = 1024; -pub const DOWNLOAD_REQUEST_MAX_READ_LENGTH: usize = 1024; -pub const REQUEST_MAX_READ_LENGTH: usize = 64 * 1024; -pub const EVENT_MAX_ENCODED_LENGTH: usize = 16 * 1024 * 1024; -pub const RESPONSE_MAX_READ_LENGTH: usize = 16 * 1024 * 1024; - -#[repr(u8)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum StreamKind { - Request = 0, - Upload = 1, - Download = 2, - Backup = 3, -} - -impl StreamKind { - pub fn parse(byte: u8) -> Option { - match byte { - 0 => Some(StreamKind::Request), - 1 => Some(StreamKind::Upload), - 2 => Some(StreamKind::Download), - 3 => Some(StreamKind::Backup), - _ => None, - } - } -} - -#[repr(u8)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum DownloadStatus { - Ok = 0, - Error = 1, -} - -impl DownloadStatus { - fn parse(byte: u8) -> Option { - match byte { - 0 => Some(DownloadStatus::Ok), - 1 => Some(DownloadStatus::Error), - _ => None, - } - } -} - -pub async fn send_stream_kind(kind: StreamKind, send_stream: &mut SendStream) -> Result<(), Error> { - send_stream.write_all(&[kind as u8]).await?; - Ok(()) -} - -pub async fn receive_stream_kind(receive_stream: &mut RecvStream) -> Result { - let mut byte = [0u8; 1]; - receive_stream.read_exact(&mut byte).await?; - - StreamKind::parse(byte[0]).ok_or_else(|| Error::Decode(format!("stream kind {}", byte[0]))) -} - -pub async fn send_download_reply( - reply: Result, - send_stream: &mut SendStream, -) -> Result<(), Error> { - match reply { - Ok(length) => { - send_stream.write_all(&[DownloadStatus::Ok as u8]).await?; - send_stream.write_all(&length.to_le_bytes()).await?; - } - Err(error) => { - send_stream - .write_all(&[DownloadStatus::Error as u8]) - .await?; - send_encoded(&error, send_stream).await?; - } - } - - Ok(()) -} - -async fn receive_download_status(receive_stream: &mut RecvStream) -> Result { - let mut byte = [0u8; 1]; - receive_stream.read_exact(&mut byte).await?; - - DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0]))) -} - -pub async fn open_download( - connection: &quinn::Connection, - kind: StreamKind, - request: &T, -) -> Result<(RecvStream, u64), Error> { - let (mut send_stream, mut receive_stream) = connection.open_bi().await?; - send_stream_kind(kind, &mut send_stream).await?; - send_encoded(request, &mut send_stream).await?; - send_stream.finish()?; - - match receive_download_status(&mut receive_stream).await? { - DownloadStatus::Error => { - Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?) - } - DownloadStatus::Ok => { - let mut length_bytes = [0u8; 8]; - receive_stream.read_exact(&mut length_bytes).await?; - Ok((receive_stream, u64::from_le_bytes(length_bytes))) - } - } -} - -async fn send_framed(value: &T, send_stream: &mut SendStream) -> Result<(), Error> { - let payload = bitcode::encode(value); - send_stream - .write_all(&(payload.len() as u32).to_le_bytes()) - .await?; - send_stream.write_all(&payload).await?; - Ok(()) -} - -async fn receive_framed( - receive_stream: &mut RecvStream, - maximum: usize, -) -> Result { - let mut length_bytes = [0u8; 4]; - receive_stream.read_exact(&mut length_bytes).await?; - - let length = u32::from_le_bytes(length_bytes) as usize; - if length > maximum { - return Err(Error::ReadBoundExceed { - actual: length, - maximum, - }); - } - - let mut payload = vec![0u8; length]; - receive_stream.read_exact(&mut payload).await?; - Ok(bitcode::decode(&payload)?) -} - -pub async fn send_upload_header( - header: &UploadHeader, - send_stream: &mut SendStream, -) -> Result<(), Error> { - send_framed(header, send_stream).await -} - -pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result { - receive_framed(receive_stream, UPLOAD_HEADER_MAX_LENGTH).await -} - -pub async fn send_encoded(value: &T, send_stream: &mut SendStream) -> Result<(), Error> { - send_stream.write_all(&bitcode::encode(value)).await?; - Ok(()) -} - -pub async fn receive_decoded( - receive_stream: &mut RecvStream, - limit: usize, -) -> Result { - let bytes = receive_stream.read_to_end(limit).await?; - Ok(bitcode::decode(&bytes)?) -} - -pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> { - send_encoded(response, &mut send_stream).await?; - send_stream.finish()?; - Ok(()) -} - -pub async fn send_request( - request: &Request, - mut send_stream: SendStream, - mut receive_stream: RecvStream, -) -> Result { - send_stream_kind(StreamKind::Request, &mut send_stream).await?; - send_encoded(request, &mut send_stream).await?; - send_stream.finish()?; - - receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await -} - -pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> { - send_framed(event, send_stream).await -} - -pub async fn receive_event(receive_stream: &mut RecvStream) -> Result { - receive_framed(receive_stream, EVENT_MAX_ENCODED_LENGTH).await -} diff --git a/crates/common/src/open.rs b/crates/common/src/open.rs new file mode 100644 index 0000000..98f3abb --- /dev/null +++ b/crates/common/src/open.rs @@ -0,0 +1,24 @@ +use bitcode::{Decode, Encode}; + +use crate::request::Request; + +#[derive(Debug, Clone, Encode, Decode)] +pub enum Open { + Call(Request), + Upload(Upload), + Fetch(Blob), +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Upload { + pub community_id: String, + pub name: String, + pub size: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)] +pub enum Blob { + Attachment(String), + Thumbnail(String), + Backup(String), +} diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs index 601729e..c328ebe 100644 --- a/crates/common/src/request.rs +++ b/crates/common/src/request.rs @@ -5,19 +5,6 @@ use crate::{ share::{Codec, Kind, Quality, Source}, }; -#[derive(Debug, Clone, Encode, Decode)] -pub struct UploadHeader { - pub community_id: String, - pub name: String, - pub size: u64, -} - -#[derive(Debug, Clone, Encode, Decode)] -pub struct DownloadRequest { - pub attachment_id: String, - pub thumbnail: bool, -} - #[derive(Debug, Clone, Encode, Decode)] pub enum Request { Register { @@ -357,7 +344,4 @@ pub enum Request { DeleteBackup { name: String, }, - DownloadBackup { - name: String, - }, } diff --git a/crates/common/src/response.rs b/crates/common/src/response.rs index 9d2a9a0..fabfc02 100644 --- a/crates/common/src/response.rs +++ b/crates/common/src/response.rs @@ -1,7 +1,6 @@ use bitcode::{Decode, Encode}; use crate::{ - error::Error, model::{ Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, @@ -32,7 +31,6 @@ pub enum Response { Friends(Friends), Invitations(Vec), Done, - Error(Error), Logs(Vec), Users(Vec), AdminLogs(Vec), diff --git a/crates/common/src/transport.rs b/crates/common/src/transport.rs new file mode 100644 index 0000000..e5f4e30 --- /dev/null +++ b/crates/common/src/transport.rs @@ -0,0 +1,69 @@ +use std::time::Duration; + +use quinn::{TransportConfig, VarInt}; + +pub const PROTOCOL: u32 = 1; + +const IDLE_TIMEOUT: Duration = Duration::from_secs(10); +const KEEP_ALIVE: Duration = Duration::from_secs(2); +const BIDI_STREAMS: u32 = 256; +const DATAGRAM_RECEIVE_BYTES: usize = 1 << 20; + +pub fn alpn() -> Vec { + format!("yumush/{PROTOCOL}").into_bytes() +} + +pub fn transport() -> TransportConfig { + let mut config = TransportConfig::default(); + config.keep_alive_interval(Some(KEEP_ALIVE)); + config.max_idle_timeout(Some(IDLE_TIMEOUT.try_into().expect("idle timeout"))); + config.max_concurrent_bidi_streams(VarInt::from_u32(BIDI_STREAMS)); + config.datagram_receive_buffer_size(Some(DATAGRAM_RECEIVE_BYTES)); + config +} + +#[repr(u32)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Close { + Normal = 0, + SignedOut = 1, + Revoked = 2, + Banned = 3, + Maintenance = 4, + Slow = 5, + Protocol = 6, +} + +impl Close { + pub const ALL: [Self; 7] = [ + Self::Normal, + Self::SignedOut, + Self::Revoked, + Self::Banned, + Self::Maintenance, + Self::Slow, + Self::Protocol, + ]; + + pub fn of(code: VarInt) -> Option { + Self::ALL + .into_iter() + .find(|close| u64::from(code) == u64::from(*close as u32)) + } + + pub fn reason(self) -> &'static str { + match self { + Self::Normal => "closed", + Self::SignedOut => "signed out", + Self::Revoked => "session revoked", + Self::Banned => "banned", + Self::Maintenance => "maintenance", + Self::Slow => "slow", + Self::Protocol => "protocol error", + } + } + + pub fn code(self) -> VarInt { + VarInt::from_u32(self as u32) + } +} diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index 22883dc..6c3b4d8 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -11,34 +11,36 @@ use crate::{ MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS, MINIMUM_USERNAME_LENGTH, REACTIONS, }, - error::{Error, Field, InvalidInput}, + error::{Error, Field, Problem}, model::{Poll, ServerSettings}, }; -fn invalid(field: Field) -> impl Fn(InvalidInput) -> Error { - move |input| Error::Invalid { field, input } +fn invalid(field: Field) -> impl Fn(Problem) -> Error { + move |problem| Error::Invalid { field, problem } } -fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { - if actual < minimum { - return Err(InvalidInput::TooShort { minimum, actual }); - } - - if actual > maximum { - return Err(InvalidInput::TooLong { maximum, actual }); +fn check_range(actual: u64, min: u64, max: u64) -> Result<(), Problem> { + if actual < min || actual > max { + return Err(Problem::Length { min, max, actual }); } Ok(()) } -fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { +fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), Problem> { + check_range(actual as u64, minimum as u64, maximum as u64) +} + +fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), Problem> { check_length(text.chars().count(), minimum, maximum) } -fn check_name(name: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { - let allowed = name.bytes().all(|byte| byte.is_ascii_graphic() || byte == b' '); +fn check_name(name: &str, minimum: usize, maximum: usize) -> Result<(), Problem> { + let allowed = name + .bytes() + .all(|byte| byte.is_ascii_graphic() || byte == b' '); if !allowed || name != name.trim() { - return Err(InvalidInput::ForbiddenCharacter); + return Err(Problem::Characters); } check_length(name.len(), minimum, maximum) @@ -50,13 +52,21 @@ pub fn validate_username(username: &str) -> Result<(), Error> { } pub fn validate_password(password: &str) -> Result<(), Error> { - check_length(password.len(), MINIMUM_PASSWORD_LENGTH, MAXIMUM_PASSWORD_LENGTH) - .map_err(invalid(Field::Password)) + check_length( + password.len(), + MINIMUM_PASSWORD_LENGTH, + MAXIMUM_PASSWORD_LENGTH, + ) + .map_err(invalid(Field::Password)) } pub fn validate_community_name(name: &str) -> Result<(), Error> { - check_name(name, MINIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_COMMUNITY_NAME_LENGTH) - .map_err(invalid(Field::Community)) + check_name( + name, + MINIMUM_COMMUNITY_NAME_LENGTH, + MAXIMUM_COMMUNITY_NAME_LENGTH, + ) + .map_err(invalid(Field::Community)) } pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> { @@ -69,11 +79,11 @@ pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> R } pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { - check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(invalid(Field::Message))?; + check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(invalid(Field::Poll))?; check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS) - .map_err(invalid(Field::Message))?; + .map_err(invalid(Field::Poll))?; for option in options { - check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(invalid(Field::Message))?; + check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(invalid(Field::Poll))?; } Ok(()) @@ -97,16 +107,14 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> { return Ok(()); } - Err(invalid(Field::Message)(InvalidInput::ForbiddenCharacter)) + Err(invalid(Field::Reaction)(Problem::Characters)) } pub fn validate_attachment_name(name: &str) -> Result<(), Error> { check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(invalid(Field::AttachmentName))?; if name.contains(['/', '\\']) || name.chars().any(char::is_control) { - return Err(invalid(Field::AttachmentName)( - InvalidInput::ForbiddenCharacter, - )); + return Err(invalid(Field::AttachmentName)(Problem::Characters)); } Ok(()) @@ -119,17 +127,16 @@ pub fn validate_backup_name(name: &str) -> Result<(), Error> { character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') }) { - return Err(invalid(Field::BackupName)(InvalidInput::ForbiddenCharacter)); + return Err(invalid(Field::BackupName)(Problem::Characters)); } Ok(()) } -fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> { +fn check_size(actual: u64, maximum: u64) -> Result<(), Problem> { match actual { - 0 => Err(InvalidInput::Empty), - actual if actual > maximum => Err(InvalidInput::TooLarge { maximum, actual }), - _ => Ok(()), + 0 => Err(Problem::Empty), + actual => check_range(actual, 0, maximum), } } @@ -138,27 +145,19 @@ pub fn validate_attachment_size(size: u64, maximum: u64) -> Result<(), Error> { } pub fn validate_attachment_limit(limit: u64) -> Result<(), Error> { - match limit { - limit if limit < MINIMUM_ATTACHMENT_LIMIT_BYTES => { - Err(invalid(Field::AttachmentLimit)(InvalidInput::TooSmall { - minimum: MINIMUM_ATTACHMENT_LIMIT_BYTES, - actual: limit, - })) - } - limit if limit > MAXIMUM_ATTACHMENT_LIMIT_BYTES => { - Err(invalid(Field::AttachmentLimit)(InvalidInput::TooLarge { - maximum: MAXIMUM_ATTACHMENT_LIMIT_BYTES, - actual: limit, - })) - } - _ => Ok(()), - } + check_range( + limit, + MINIMUM_ATTACHMENT_LIMIT_BYTES, + MAXIMUM_ATTACHMENT_LIMIT_BYTES, + ) + .map_err(invalid(Field::AttachmentLimit)) } fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { if quota != 0 && quota < minimum { - return Err(invalid(Field::Quota)(InvalidInput::TooSmall { - minimum, + return Err(invalid(Field::Quota)(Problem::Length { + min: minimum, + max: u64::MAX, actual: quota, })); } @@ -166,9 +165,9 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { Ok(()) } -fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { +fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), Problem> { if text.contains(['\n', '\r']) { - return Err(InvalidInput::MultiLine); + return Err(Problem::MultiLine); } check_text(text, minimum, maximum) diff --git a/crates/pixel/src/lib.rs b/crates/pixel/src/lib.rs index d254217..bf9d384 100644 --- a/crates/pixel/src/lib.rs +++ b/crates/pixel/src/lib.rs @@ -30,6 +30,7 @@ pub struct I420 { pub height: u32, } +#[allow(clippy::too_many_arguments)] pub fn yuv_to_bgra( y: &[u8], y_stride: usize, @@ -166,6 +167,18 @@ fn scale(source: &Bgra, width: u32, height: u32) -> Option> { Some(target.into_vec()) } +pub fn jpeg_to_bgra(data: &[u8]) -> Option<(u32, u32, Vec)> { + let options = zune_core::options::DecoderOptions::default() + .jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::BGRA); + let mut decoder = zune_jpeg::JpegDecoder::new_with_options( + zune_core::bytestream::ZCursor::new(data), + options, + ); + let bgra = decoder.decode().ok()?; + let (width, height) = decoder.dimensions()?; + Some((width as u32, height as u32, bgra)) +} + #[cfg(test)] mod tests { use super::*; @@ -185,13 +198,3 @@ mod tests { ); } } - -pub fn jpeg_to_bgra(data: &[u8]) -> Option<(u32, u32, Vec)> { - let options = zune_core::options::DecoderOptions::default() - .jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::BGRA); - let mut decoder = - zune_jpeg::JpegDecoder::new_with_options(zune_core::bytestream::ZCursor::new(data), options); - let bgra = decoder.decode().ok()?; - let (width, height) = decoder.dimensions()?; - Some((width as u32, height as u32, bgra)) -} diff --git a/crates/server/src/admin_log.rs b/crates/server/src/admin_log.rs index d6b27e3..924075a 100644 --- a/crates/server/src/admin_log.rs +++ b/crates/server/src/admin_log.rs @@ -5,7 +5,7 @@ use common::{ }; use turso::Connection; -use crate::{database::new_id, error::Error, user}; +use crate::{database::new_id, error::ServerError, user}; fn action_of(text: &str, detail: Option) -> Option { Some(match AdminActionKind::parse(text)? { @@ -63,7 +63,7 @@ pub async fn record( community: Option<&str>, action: &AdminAction, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { let id = new_id(); let detail = action_detail(action); conn.execute( @@ -89,7 +89,7 @@ pub async fn list( after_ms: Option, before_ms: Option, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let (after, before) = time::range_bounds(after_ms, before_ms); let mut rows = conn .query( diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index 40fed44..399b78f 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -10,22 +10,18 @@ use common::{ ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, MAXIMUM_ATTACHMENTS_PER_MESSAGE, THUMBNAIL_SIZE, }, - error::Error as CommonError, + error::{Error as CommonError, Field, Problem}, + frame::{self, DOWN_MAX, Sending}, model::{ Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, }, - network::{ - DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded, receive_upload_header, - send_download_reply, send_response, - }, + open::{Blob, Upload}, permission, - request::{DownloadRequest, UploadHeader}, - response::Response, time::{self, HOUR_MILLIS}, validate::{validate_attachment_name, validate_attachment_size}, }; use image::{ImageFormat, ImageReader, Limits}; -use quinn::{RecvStream, SendStream, VarInt}; +use quinn::{RecvStream, VarInt}; use tokio::{ fs::File, io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, @@ -34,9 +30,9 @@ use tracing::error; use turso::{Connection, Row}; use crate::{ - community, + backup, community, database::{self, DB, new_id}, - error::Error, + error::ServerError, request::{actor_rank, ensure}, server_settings, user, }; @@ -56,7 +52,7 @@ pub struct Stored { pub message_id: Option, } -fn from_row(row: &Row) -> Result { +fn from_row(row: &Row) -> Result { let size: i64 = row.get(2)?; let kind: String = row.get(3)?; let width: Option = row.get(4)?; @@ -76,7 +72,7 @@ pub async fn of_message( message_id: &str, snippet_position: Option, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( "SELECT id, name, size, kind, width, height FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id", @@ -98,7 +94,7 @@ pub async fn bind( community_id: &str, attachment_ids: &[String], conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { if attachment_ids.len() > MAXIMUM_ATTACHMENTS_PER_MESSAGE { return Err(CommonError::NotFound.into()); } @@ -128,7 +124,7 @@ fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> { std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop)) } -async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> { +async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { tokio::task::spawn_blocking(move || link_or_copy(&source, &target)) .await .map_err(|_| CommonError::Server)? @@ -137,7 +133,7 @@ async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> { Ok(()) } -async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), Error> { +async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { if tokio::fs::try_exists(&source) .await .map_err(|_| CommonError::Server)? @@ -156,7 +152,7 @@ pub async fn copy( snippet_position: Option, directory: &Path, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { let id = new_id(); conn.execute( "INSERT INTO attachment (id, uploader_id, community_id, message_id, name, size, kind, width, height, snippet_position) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", @@ -183,7 +179,10 @@ pub async fn copy( .await } -pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result, Error> { +pub async fn ids_of_message( + message_id: &str, + conn: &Connection, +) -> Result, ServerError> { database::ids( conn, "SELECT id FROM attachment WHERE message_id = ?1", @@ -192,7 +191,7 @@ pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result Result<(), Error> { +pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), ServerError> { conn.execute("DELETE FROM attachment WHERE id = ?1", (attachment_id,)) .await?; @@ -203,7 +202,7 @@ pub async fn all( user_id: Option<&str>, community_id: Option<&str>, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( &format!("SELECT a.id, a.name, a.size, a.kind, a.width, a.height, a.community_id, {} FROM attachment a LEFT JOIN user u ON u.id = a.uploader_id WHERE (?1 IS NULL OR a.uploader_id = ?1) AND (?2 IS NULL OR a.community_id = ?2) ORDER BY a.size DESC LIMIT ?3", user::user_columns("u")), @@ -230,7 +229,7 @@ pub async fn all( Ok(infos) } -async fn totals(column: &str, conn: &Connection) -> Result, Error> { +async fn totals(column: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!( @@ -250,7 +249,7 @@ async fn totals(column: &str, conn: &Connection) -> Result Result<(Vec, Vec), Error> { +pub async fn usage(conn: &Connection) -> Result<(Vec, Vec), ServerError> { let mut users = Vec::new(); for (user_id, bytes, count) in totals("uploader_id", conn).await? { users.push(Usage { @@ -279,7 +278,7 @@ async fn over_quota( limit: u64, size: u64, conn: &Connection, -) -> Result { +) -> Result { if limit == 0 { return Ok(false); } @@ -294,7 +293,7 @@ async fn ensure_quota( size: u64, settings: &ServerSettings, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { if over_quota( "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1", user_id, @@ -321,7 +320,7 @@ async fn ensure_quota( Ok(()) } -pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result, Error> { +pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result, ServerError> { database::ids( conn, "SELECT id FROM attachment WHERE uploader_id = ?1", @@ -330,7 +329,7 @@ pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result, .await } -pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), Error> { +pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), ServerError> { conn.execute("DELETE FROM attachment WHERE uploader_id = ?1", (user_id,)) .await?; @@ -344,7 +343,7 @@ pub fn remove_files(attachment_ids: &[String], directory: &Path) { } } -pub async fn read(attachment_id: &str, conn: &Connection) -> Result { +pub async fn read(attachment_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id FROM attachment WHERE id = ?1", @@ -423,8 +422,15 @@ async fn receive_body( reader: &mut R, part: &Path, size: u64, -) -> Result, Error> { - let mismatch = || CommonError::Upload("size mismatch".to_string()); +) -> Result, ServerError> { + let mismatch = |actual: u64| CommonError::Invalid { + field: Field::Attachment, + problem: Problem::Length { + min: size, + max: size, + actual, + }, + }; let mut file = File::create(part).await?; let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize]; @@ -441,13 +447,13 @@ async fn receive_body( received += read as u64; if received > size { - return Err(mismatch().into()); + return Err(mismatch(received).into()); } file.write_all(&buffer[..read]).await?; } if received != size { - return Err(mismatch().into()); + return Err(mismatch(received).into()); } file.flush().await?; @@ -456,11 +462,11 @@ async fn receive_body( pub async fn store( user: &User, - header: &UploadHeader, + header: &Upload, reader: &mut R, db: &DB, directory: &Path, -) -> Result { +) -> Result { let conn = database::connect(db).await?; let rank = actor_rank(user, &header.community_id, &conn).await?; ensure(permission::can_post(rank))?; @@ -525,44 +531,44 @@ pub async fn store( pub async fn upload( user: Option<&User>, + header: Upload, mut receive_stream: RecvStream, - send_stream: SendStream, + mut send_stream: Sending, db: &DB, directory: &Path, -) -> Result<(), Error> { - let header = receive_upload_header(&mut receive_stream).await?; +) -> Result<(), ServerError> { let stored = match user { Some(user) => store(user, &header, &mut receive_stream, db, directory).await, None => Err(CommonError::Unauthenticated.into()), }; + let rejected = stored.is_err(); + let reply = stored.map_err(CommonError::from); - let response = match stored { - Ok(attachment) => Response::Attachment(attachment), - Err(error) => { - let _ = receive_stream.stop(VarInt::from_u32(0)); - Response::Error(error.into()) - } - }; - send_response(&response, send_stream).await?; + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; + send_stream.finish()?; + if rejected { + let _ = receive_stream.stop(VarInt::from_u32(0)); + } Ok(()) } -async fn locate( +pub async fn locate( user: Option<&User>, - request: &DownloadRequest, + attachment_id: &str, + thumbnail: bool, db: &DB, directory: &Path, -) -> Result<(PathBuf, u64), Error> { +) -> Result<(PathBuf, u64), ServerError> { let user = user.ok_or(CommonError::Unauthenticated)?; let conn = database::connect(db).await?; - let stored = read(&request.attachment_id, &conn).await?; + let stored = read(attachment_id, &conn).await?; let rank = actor_rank(user, &stored.community_id, &conn).await?; ensure(permission::can_read(rank))?; ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; - let path = if request.thumbnail { + let path = if thumbnail { thumb_path(directory, &stored.attachment.id) } else { directory.join(&stored.attachment.id) @@ -575,46 +581,36 @@ async fn locate( Ok((path, length)) } -pub async fn stream_file(path: &Path, send_stream: &mut SendStream) -> Result<(), Error> { - let mut file = File::open(path).await?; - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; - loop { - let read = file.read(&mut buffer).await?; - if read == 0 { - return Ok(()); - } - - send_stream.write_all(&buffer[..read]).await?; - } -} - -pub async fn download( +pub async fn fetch( user: Option<&User>, - mut receive_stream: RecvStream, - mut send_stream: SendStream, + blob: Blob, + mut send_stream: Sending, db: &DB, directory: &Path, -) -> Result<(), Error> { - let request: DownloadRequest = - receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; - - let located = locate(user, &request, db, directory) - .await - .map_err(CommonError::from); - send_file(located, &mut send_stream).await -} - -pub async fn send_file( - located: Result<(PathBuf, u64), CommonError>, - send_stream: &mut SendStream, -) -> Result<(), Error> { + 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); - send_download_reply(reply, send_stream).await?; + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; + if let Ok((path, _)) = located { - stream_file(&path, send_stream).await?; + let mut file = File::open(path).await?; + let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; + loop { + let read = file.read(&mut buffer).await?; + if read == 0 { + break; + } + send_stream.get().write_all(&buffer[..read]).await?; + } } send_stream.finish()?; @@ -631,7 +627,7 @@ pub async fn collect(db: DB, directory: PathBuf) { } } -async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { +async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { let conn = database::connect(db).await?; let stale_ms = time::now_ms().saturating_sub(HOUR_MILLIS); let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); @@ -676,7 +672,8 @@ mod tests { use common::{ model::{AttachmentKind, Rank}, - request::{Request, UploadHeader}, + open::Upload, + request::Request, }; use image::{ImageFormat, RgbImage}; @@ -704,7 +701,7 @@ mod tests { .unwrap(); let png = png.into_inner(); let directory = test::directory(); - let header = UploadHeader { + let header = Upload { community_id: community.id.clone(), name: "pixel.png".to_string(), size: png.len() as u64, @@ -717,7 +714,7 @@ mod tests { user: user.clone(), token: "token".to_string(), }); - handle( + let (reply, _) = handle( Request::CreateMessage { community_id: community.id.clone(), body: String::new(), @@ -732,6 +729,7 @@ mod tests { &test::directory(), ) .await; + reply.unwrap(); let messages = message::read_page(&community.id, None, &conn) .await diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 2368fad..2217748 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -7,34 +7,35 @@ use common::{ }; use turso::Connection; -use crate::{database::new_id, error::Error, invite, server_ban, server_settings, user}; +use crate::{database::new_id, error::ServerError, invite, server_ban, server_settings, user}; const SALT_LENGTH: usize = 16; const TOKEN_LENGTH: usize = 32; -pub(crate) fn random_bytes() -> Result<[u8; N], Error> { +pub(crate) fn random_bytes() -> Result<[u8; N], ServerError> { let mut bytes = [0u8; N]; - getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; + getrandom::fill(&mut bytes) + .map_err(|error| ServerError::Internal(format!("random: {error}")))?; Ok(bytes) } -fn hash(password: &str) -> Result { +fn hash(password: &str) -> Result { let salt = random_bytes::()?; let hash = Argon2::default() .hash_password_with_salt(password.as_bytes(), &salt) - .map_err(|error| Error::Hash(error.to_string()))?; + .map_err(|error| ServerError::Internal(error.to_string()))?; Ok(hash.to_string()) } -fn verify(password: &str, password_hash: &str) -> Result<(), Error> { +fn verify(password: &str, password_hash: &str) -> Result<(), ServerError> { Argon2::default() .verify_password(password.as_bytes(), password_hash) - .map_err(|_| Error::from(CommonError::WrongCredentials)) + .map_err(|_| ServerError::from(CommonError::WrongCredentials)) } -async fn open_session(user_id: &str, conn: &Connection) -> Result { +async fn open_session(user_id: &str, conn: &Connection) -> Result { let token: String = random_bytes::()? .iter() .map(|byte| format!("{byte:02x}")) @@ -50,7 +51,7 @@ async fn open_session(user_id: &str, conn: &Connection) -> Result Ok(token) } -pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), Error> { +pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), ServerError> { if user::is_ghost(user_id, conn).await? { return Ok(()); } @@ -69,7 +70,7 @@ pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), E Ok(()) } -pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<(), Error> { +pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<(), ServerError> { validate_device(name)?; conn.execute( "UPDATE session SET device = ?2 WHERE token = ?1", @@ -80,7 +81,7 @@ pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<() Ok(()) } -pub async fn sessions(user_id: &str, conn: &Connection) -> Result, Error> { +pub async fn sessions(user_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( "SELECT id, device, last_seen FROM session WHERE user_id = ?1 ORDER BY last_seen DESC", @@ -104,7 +105,7 @@ pub async fn revoke_session( user_id: &str, session_id: &str, conn: &Connection, -) -> Result { +) -> Result { let mut rows = conn .query( "DELETE FROM session WHERE id = ?1 AND user_id = ?2 RETURNING token", @@ -120,7 +121,7 @@ pub async fn create_account( username: &str, password: &str, conn: &Connection, -) -> Result { +) -> Result { validate_username(username)?; validate_password(password)?; @@ -136,7 +137,7 @@ pub async fn register( password: &str, invite_code: Option<&str>, conn: &mut Connection, -) -> Result<(User, String), Error> { +) -> Result<(User, String), ServerError> { let tx = conn.transaction().await?; if server_ban::username_banned(username, &tx).await? { return Err(CommonError::Banned.into()); @@ -156,7 +157,7 @@ pub async fn login( username: &str, password: &str, conn: &Connection, -) -> Result<(User, String), Error> { +) -> Result<(User, String), ServerError> { let (user, password_hash) = user::credentials(username, conn) .await? .ok_or(CommonError::WrongCredentials)?; @@ -167,12 +168,12 @@ pub async fn login( Ok((user, token)) } -async fn admit(user: &User, conn: &Connection) -> Result<(), Error> { +async fn admit(user: &User, conn: &Connection) -> Result<(), ServerError> { if server_ban::username_banned(&user.username, conn).await? { return Err(CommonError::Banned.into()); } - if user::suspended(&user.id, conn).await? { - return Err(CommonError::Suspended.into()); + if let Some(until_ms) = user::suspended(&user.id, conn).await? { + return Err(CommonError::Suspended { until_ms }.into()); } if !permission::is_builder(user.role) && server_settings::read(conn).await?.maintenance { return Err(CommonError::Maintenance.into()); @@ -181,7 +182,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> { Ok(()) } -pub async fn resume(token: &str, conn: &Connection) -> Result { +pub async fn resume(token: &str, conn: &Connection) -> Result { let user = user::by_session_token(token, conn).await?; admit(&user, conn).await?; seen(&user.id, token, conn).await?; @@ -189,21 +190,25 @@ pub async fn resume(token: &str, conn: &Connection) -> Result { Ok(user) } -pub async fn logout(token: &str, conn: &Connection) -> Result<(), Error> { +pub async fn logout(token: &str, conn: &Connection) -> Result<(), ServerError> { conn.execute("DELETE FROM session WHERE token = ?1", (token,)) .await?; Ok(()) } -pub async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), Error> { +pub async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> { conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,)) .await?; Ok(()) } -pub async fn reset_password(user_id: &str, password: &str, conn: &Connection) -> Result<(), Error> { +pub async fn reset_password( + user_id: &str, + password: &str, + conn: &Connection, +) -> Result<(), ServerError> { validate_password(password)?; user::set_password_hash(user_id, &hash(password)?, conn).await?; revoke_sessions(user_id, conn).await @@ -213,7 +218,7 @@ pub async fn reset_password(user_id: &str, password: &str, conn: &Connection) -> mod tests { use common::error::Error as CommonError; - use crate::{authentication, database, error::Error, test}; + use crate::{authentication, database, error::ServerError, test}; #[tokio::test] async fn register_and_login() { @@ -232,7 +237,7 @@ mod tests { assert_eq!(registered_user, logged_in_user); assert!(matches!( wrong_password, - Err(Error::Common(CommonError::WrongCredentials)) + Err(ServerError::Wire(CommonError::WrongCredentials)) )); } } diff --git a/crates/server/src/backup.rs b/crates/server/src/backup.rs index 5e787f9..e70f546 100644 --- a/crates/server/src/backup.rs +++ b/crates/server/src/backup.rs @@ -3,19 +3,15 @@ use std::path::{Path, PathBuf}; use common::{ error::Error as CommonError, model::{AdminAction, BackupInfo, User}, - network::{DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded}, - permission, - request::Request, - time, + permission, time, validate::validate_backup_name, }; -use quinn::{RecvStream, SendStream}; use turso::Connection; use crate::{ - admin_log, attachment, + admin_log, database::{self, DB}, - error::Error, + error::ServerError, request::ensure, user, }; @@ -30,7 +26,7 @@ fn created_secs(name: &str) -> Option { .ok() } -fn info(directory: &Path, name: &str) -> Result { +fn info(directory: &Path, name: &str) -> Result { let created_secs = created_secs(name).ok_or(CommonError::NotFound)?; let size_bytes = std::fs::metadata(directory.join(name))?.len(); @@ -41,14 +37,14 @@ fn info(directory: &Path, name: &str) -> Result { }) } -fn path_of(directory: &Path, name: &str) -> Result { +fn path_of(directory: &Path, name: &str) -> Result { validate_backup_name(name)?; created_secs(name).ok_or(CommonError::NotFound)?; Ok(directory.join(name)) } -pub async fn create(conn: &Connection, directory: &Path) -> Result { +pub async fn create(conn: &Connection, directory: &Path) -> Result { let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000); let path = directory.join(&name); let statement = format!( @@ -60,7 +56,7 @@ pub async fn create(conn: &Connection, directory: &Path) -> Result Result, Error> { +pub fn list(directory: &Path) -> Result, ServerError> { let mut backups = Vec::new(); for entry in std::fs::read_dir(directory)? { let name = entry?.file_name().to_string_lossy().into_owned(); @@ -73,27 +69,24 @@ pub fn list(directory: &Path) -> Result, Error> { Ok(backups) } -pub fn delete(name: &str, directory: &Path) -> Result<(), Error> { +pub fn delete(name: &str, directory: &Path) -> Result<(), ServerError> { std::fs::remove_file(path_of(directory, name)?)?; Ok(()) } -async fn locate( +pub async fn locate( user: Option<&User>, - request: Request, + name: &str, db: &DB, directory: &Path, -) -> Result<(PathBuf, u64), Error> { +) -> Result<(PathBuf, u64), ServerError> { let user = user.ok_or(CommonError::Unauthenticated)?; - let Request::DownloadBackup { name } = request else { - return Err(CommonError::Forbidden.into()); - }; let conn = database::connect(db).await?; let me = user::read(&user.id, &conn).await?; ensure(permission::is_builder(me.role))?; - let path = path_of(directory, &name)?; + let path = path_of(directory, name)?; let length = tokio::fs::metadata(&path) .await .map_err(|_| CommonError::NotFound)? @@ -102,26 +95,12 @@ async fn locate( Some(&me.id), None, None, - &AdminAction::BackupDownloaded { name }, + &AdminAction::BackupDownloaded { + name: name.to_string(), + }, &conn, ) .await?; Ok((path, length)) } - -pub async fn download( - user: Option<&User>, - mut receive_stream: RecvStream, - mut send_stream: SendStream, - db: &DB, - directory: &Path, -) -> Result<(), Error> { - let request: Request = - receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; - - let located = locate(user, request, db, directory) - .await - .map_err(CommonError::from); - attachment::send_file(located, &mut send_stream).await -} diff --git a/crates/server/src/certificate.rs b/crates/server/src/certificate.rs index 43a795c..bdef365 100644 --- a/crates/server/src/certificate.rs +++ b/crates/server/src/certificate.rs @@ -13,7 +13,7 @@ use rustls::{ }; use tracing::{error, info, warn}; -use crate::error::Error; +use crate::error::ServerError; const RELOAD_INTERVAL: Duration = Duration::from_secs(600); const SUBJECT_ALT_NAME: &str = "localhost"; @@ -34,11 +34,11 @@ impl ResolvesServerCert for Reloader { } } -fn certificate_error(error: impl std::fmt::Display) -> Error { - Error::Common(common::error::Error::Certificate(error.to_string())) +fn certificate_error(error: impl std::fmt::Display) -> ServerError { + ServerError::Internal(format!("certificate: {error}")) } -fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> { +fn generate(certificate_path: &str, key_path: &str) -> Result<(), ServerError> { let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()]) .map_err(certificate_error)?; @@ -56,7 +56,7 @@ fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> { Ok(()) } -fn certified_key(certificate_path: &str, key_path: &str) -> Result { +fn certified_key(certificate_path: &str, key_path: &str) -> Result { let chain = CertificateDer::pem_file_iter(certificate_path) .map_err(certificate_error)? .collect::, _>>() @@ -101,7 +101,7 @@ async fn watch(reloader: Arc, certificate_path: String, key_path: Stri } } -pub fn load(certificate_path: &str, key_path: &str) -> Result { +pub fn load(certificate_path: &str, key_path: &str) -> Result { if !Path::new(certificate_path).exists() || !Path::new(key_path).exists() { generate(certificate_path, key_path)?; warn!("certificate not found, generated a self-signed one for {SUBJECT_ALT_NAME}"); @@ -115,6 +115,7 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result Result, bool); -fn raw_of(row: &Row) -> Result { +fn raw_of(row: &Row) -> Result { let text: String = row.get(2)?; let kind = Kind::parse(&text).ok_or(CommonError::Server)?; @@ -32,7 +32,7 @@ fn raw_of(row: &Row) -> Result { )) } -async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result { +async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( &format!("SELECT {} FROM direct JOIN user ON user.id = CASE WHEN direct.user_a = ?2 THEN direct.user_b ELSE direct.user_a END WHERE direct.community_id = ?1", user::user_columns("user")), @@ -48,7 +48,7 @@ async fn outsider_name( community_id: &str, viewer_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( "SELECT a.username, b.username FROM direct JOIN user a ON a.id = direct.user_a JOIN user b ON b.id = direct.user_b WHERE direct.community_id = ?1 AND direct.user_a != ?2 AND direct.user_b != ?2", @@ -64,7 +64,7 @@ async fn outsider_name( Ok(Some(format!("{first} & {second}"))) } -async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result { +async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result { let (id, mut name, kind, avatar_id, voice_enabled) = raw; let kind = match kind { Kind::Group => CommunityKind::Group, @@ -88,7 +88,7 @@ async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result Result { +pub async fn create(name: &str, conn: &Connection) -> Result { validate_community_name(name)?; let id = new_id(); @@ -107,7 +107,7 @@ pub async fn create(name: &str, conn: &Connection) -> Result { }) } -pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result { +pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result { let id = new_id(); conn.execute( "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", @@ -122,7 +122,7 @@ pub async fn read( community_id: &str, viewer_id: &str, conn: &Connection, -) -> Result { +) -> Result { let raw = { let mut rows = conn .query( @@ -138,7 +138,10 @@ pub async fn read( build(raw, viewer_id, conn).await } -pub async fn communities_of(user_id: &str, conn: &Connection) -> Result, Error> { +pub async fn communities_of( + user_id: &str, + conn: &Connection, +) -> Result, ServerError> { let raws = { let mut rows = conn .query( @@ -163,7 +166,7 @@ pub async fn communities_of(user_id: &str, conn: &Connection) -> Result Result, Error> { +pub async fn groups(conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE", @@ -191,7 +194,7 @@ pub async fn update( name: &str, viewer_id: &str, conn: &Connection, -) -> Result { +) -> Result { validate_community_name(name)?; conn.execute( @@ -208,7 +211,7 @@ pub async fn set_avatar( image: Option<&[u8]>, viewer_id: &str, conn: &mut Connection, -) -> Result { +) -> Result { if let Some(bytes) = image { user::check_avatar(bytes)?; } @@ -242,7 +245,7 @@ pub async fn delete( community_id: &str, viewer_id: &str, conn: &Connection, -) -> Result { +) -> Result { let deleted = read(community_id, viewer_id, conn).await?; conn.execute("DELETE FROM community WHERE id = ?1", (community_id,)) .await?; @@ -250,7 +253,7 @@ pub async fn delete( Ok(deleted) } -pub async fn kind(community_id: &str, conn: &Connection) -> Result { +pub async fn kind(community_id: &str, conn: &Connection) -> Result { let mut rows = conn .query("SELECT kind FROM community WHERE id = ?1", (community_id,)) .await?; @@ -260,11 +263,11 @@ pub async fn kind(community_id: &str, conn: &Connection) -> Result Ok(Kind::parse(&text).ok_or(CommonError::Server)?) } -pub async fn is_direct(community_id: &str, conn: &Connection) -> Result { +pub async fn is_direct(community_id: &str, conn: &Connection) -> Result { Ok(kind(community_id, conn).await? == Kind::Direct) } -pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result { +pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result { Ok(kind(community_id, conn).await? != Kind::Group) } @@ -272,7 +275,7 @@ pub async fn set_voice_enabled( community_id: &str, enabled: bool, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "UPDATE community SET voice_enabled = ?2 WHERE id = ?1", (community_id, i64::from(enabled)), @@ -282,7 +285,7 @@ pub async fn set_voice_enabled( Ok(()) } -pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result { +pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( "SELECT voice_enabled FROM community WHERE id = ?1", @@ -294,7 +297,7 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result Result { +pub async fn label(community_id: &str, conn: &Connection) -> Result { let prefix = match kind(community_id, conn).await? { Kind::Group => { let mut rows = conn @@ -325,7 +328,7 @@ pub async fn label(community_id: &str, conn: &Connection) -> Result Result { +pub async fn open(path: &str) -> Result { let db = turso::Builder::new_local(path).build().await?; migrate(&db).await?; Ok(db) } -pub async fn connect(db: &DB) -> Result { +pub async fn connect(db: &DB) -> Result { let conn = db.connect()?; conn.busy_timeout(BUSY_TIMEOUT)?; conn.execute_batch("PRAGMA foreign_keys = ON;").await?; @@ -311,7 +311,7 @@ pub async fn scalar_i64( conn: &Connection, sql: &str, params: impl turso::IntoParams, -) -> Result { +) -> Result { let mut rows = conn.query(sql, params).await?; let row = rows .next() @@ -325,7 +325,7 @@ pub async fn exists( conn: &Connection, sql: &str, params: impl turso::IntoParams, -) -> Result { +) -> Result { Ok(scalar_i64(conn, sql, params).await? != 0) } @@ -333,7 +333,7 @@ pub async fn ids( conn: &Connection, sql: &str, params: impl turso::IntoParams, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn.query(sql, params).await?; let mut ids = Vec::new(); @@ -344,7 +344,7 @@ pub async fn ids( Ok(ids) } -pub fn expect_one(affected: u64) -> Result<(), Error> { +pub fn expect_one(affected: u64) -> Result<(), ServerError> { if affected != 1 { return Err(CommonError::NotFound.into()); } @@ -352,7 +352,7 @@ pub fn expect_one(affected: u64) -> Result<(), Error> { Ok(()) } -async fn migrate(db: &DB) -> Result<(), Error> { +async fn migrate(db: &DB) -> Result<(), ServerError> { let mut conn = connect(db).await?; let applied = user_version(&conn).await?; @@ -366,7 +366,7 @@ async fn migrate(db: &DB) -> Result<(), Error> { Ok(()) } -async fn user_version(conn: &Connection) -> Result { +async fn user_version(conn: &Connection) -> Result { Ok(scalar_i64(conn, "PRAGMA user_version", ()).await? as usize) } diff --git a/crates/server/src/datagram.rs b/crates/server/src/datagram.rs new file mode 100644 index 0000000..360f8f9 --- /dev/null +++ b/crates/server/src/datagram.rs @@ -0,0 +1,19 @@ +use std::sync::{Arc, Mutex}; + +use quinn::Connection; + +use crate::network::{Shared, State, publish}; + +pub(crate) async fn relay_datagrams( + connection: Connection, + state: Arc>, + shared: Shared, +) { + while let Ok(bytes) = connection.read_datagram().await { + if matches!(*state.lock().unwrap(), State::Authenticated { .. }) { + shared.services.voice.relay(connection.stable_id(), &bytes); + let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); + publish(&shared, broadcasts).await; + } + } +} diff --git a/crates/server/src/direct.rs b/crates/server/src/direct.rs index d031ef9..08106c9 100644 --- a/crates/server/src/direct.rs +++ b/crates/server/src/direct.rs @@ -1,9 +1,13 @@ use common::model::{Community, Rank}; use turso::Connection; -use crate::{community, error::Error, request::ensure, user, user_community}; +use crate::{community, error::ServerError, request::ensure, user, user_community}; -async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result, Error> { +async fn find( + user_a: &str, + user_b: &str, + conn: &Connection, +) -> Result, ServerError> { let mut rows = conn .query( "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", @@ -19,7 +23,7 @@ pub enum Opening { Existing(Community), } -pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result { +pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result { ensure(me != other)?; user::read(other, conn).await?; diff --git a/crates/server/src/error.rs b/crates/server/src/error.rs index c3786f4..4590661 100644 --- a/crates/server/src/error.rs +++ b/crates/server/src/error.rs @@ -1,22 +1,19 @@ -use common::error_from; use tracing::error; #[derive(Debug, thiserror::Error)] -pub enum Error { +pub enum ServerError { #[error(transparent)] - Common(#[from] common::error::Error), - #[error(transparent)] - Database(#[from] turso::Error), - #[error("password hash: {0}")] - Hash(String), + Wire(#[from] common::error::Error), + #[error("{0}")] + Internal(String), } -impl From for common::error::Error { - fn from(value: Error) -> Self { +impl From for common::error::Error { + fn from(value: ServerError) -> Self { match value { - Error::Common(error) => error, - error => { - error!("{error}"); + ServerError::Wire(error) => error, + ServerError::Internal(message) => { + error!("{message}"); common::error::Error::Server } @@ -24,13 +21,28 @@ impl From for common::error::Error { } } -error_from! { Error { - std::net::AddrParseError => Error::Common as common::error::Error, - std::io::Error => Error::Common as common::error::Error, - quinn::ConnectionError => Error::Common as common::error::Error, - quinn::ReadError => Error::Common as common::error::Error, - quinn::ReadExactError => Error::Common as common::error::Error, - quinn::WriteError => Error::Common as common::error::Error, - quinn::ClosedStream => Error::Common as common::error::Error, - bitcode::Error => Error::Common as common::error::Error, -} } +macro_rules! internal_from { + ($($source:ty),+ $(,)?) => { + $( + impl From<$source> for ServerError { + fn from(value: $source) -> Self { + ServerError::Internal(value.to_string()) + } + } + )+ + }; +} + +internal_from! { + std::net::AddrParseError, + std::io::Error, + turso::Error, + quinn::ConnectionError, + quinn::ReadError, + quinn::ReadExactError, + quinn::WriteError, + quinn::ClosedStream, + bitcode::Error, + common::config::ConfigError, + common::frame::FrameError, +} diff --git a/crates/server/src/friend.rs b/crates/server/src/friend.rs index dfc4e95..6dd3876 100644 --- a/crates/server/src/friend.rs +++ b/crates/server/src/friend.rs @@ -4,9 +4,9 @@ use common::{ }; use turso::Connection; -use crate::{database, error::Error, request::ensure_with, user}; +use crate::{database, error::ServerError, request::ensure_with, user}; -async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result, Error> { +async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn.query(sql, (user_id,)).await?; let mut users = Vec::new(); @@ -22,11 +22,11 @@ async fn pair_exists( first: &str, second: &str, conn: &Connection, -) -> Result { +) -> Result { database::exists(conn, sql, (first, second)).await } -async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result { +async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result { pair_exists( "SELECT COUNT(*) FROM friend WHERE user_id = ?1 AND friend_id = ?2", me, @@ -36,7 +36,7 @@ async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result Result { +async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result { pair_exists( "SELECT COUNT(*) FROM friend_request WHERE from_id = ?1 AND to_id = ?2", from, @@ -46,7 +46,7 @@ async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result Result<(), Error> { +async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), ServerError> { conn.execute( "DELETE FROM friend_request WHERE from_id = ?1 AND to_id = ?2", (other, me), @@ -66,7 +66,7 @@ async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), Error> Ok(()) } -pub async fn state(user_id: &str, conn: &Connection) -> Result { +pub async fn state(user_id: &str, conn: &Connection) -> Result { Ok(Friends { friends: users( &format!("SELECT {} FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 ORDER BY user.id", user::user_columns("user")), @@ -89,7 +89,7 @@ pub async fn state(user_id: &str, conn: &Connection) -> Result { }) } -pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> { +pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { ensure_with(me != other, CommonError::Forbidden)?; user::read(other, conn).await?; @@ -112,7 +112,7 @@ pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Err Ok(()) } -pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> { +pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { let tx = conn.transaction().await?; if !is_requested(other, me, &tx).await? { return Err(CommonError::NotFound.into()); @@ -123,7 +123,7 @@ pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), Ok(()) } -pub async fn remove(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> { +pub async fn remove(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { let tx = conn.transaction().await?; tx.execute( "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)", diff --git a/crates/server/src/invitation.rs b/crates/server/src/invitation.rs index 378b975..271fdd0 100644 --- a/crates/server/src/invitation.rs +++ b/crates/server/src/invitation.rs @@ -1,9 +1,9 @@ use common::{error::Error as CommonError, model::Invitation}; use turso::Connection; -use crate::{community, database, error::Error, user}; +use crate::{community, database, error::ServerError, user}; -pub async fn of(user_id: &str, conn: &Connection) -> Result, Error> { +pub async fn of(user_id: &str, conn: &Connection) -> Result, ServerError> { let pairs = { let mut rows = conn .query( @@ -31,7 +31,11 @@ pub async fn of(user_id: &str, conn: &Connection) -> Result, Err Ok(invitations) } -pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result { +pub async fn exists( + community_id: &str, + user_id: &str, + conn: &Connection, +) -> Result { database::exists( conn, "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", @@ -45,7 +49,7 @@ pub async fn insert( user_id: &str, inviter_id: &str, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)", (community_id, user_id, inviter_id), @@ -55,7 +59,7 @@ pub async fn insert( Ok(()) } -pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), Error> { +pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), ServerError> { let mut rows = conn .query( "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2 RETURNING community_id", diff --git a/crates/server/src/invite.rs b/crates/server/src/invite.rs index 6a56bb1..6adc211 100644 --- a/crates/server/src/invite.rs +++ b/crates/server/src/invite.rs @@ -5,12 +5,12 @@ use common::{ }; use turso::Connection; -use crate::{authentication, error::Error}; +use crate::{authentication, error::ServerError}; const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; const CODE_LENGTH: usize = 8; -fn generate() -> Result { +fn generate() -> Result { let bytes = authentication::random_bytes::()?; Ok(bytes @@ -24,7 +24,7 @@ pub async fn create( hours: Option, created_by: &User, conn: &Connection, -) -> Result { +) -> Result { let code = generate()?; let expires_at = hours.map(|hours| time::now_ms() + u64::from(hours) * HOUR_MILLIS); conn.execute( @@ -45,7 +45,7 @@ pub async fn create( }) } -pub async fn list(conn: &Connection) -> Result, Error> { +pub async fn list(conn: &Connection) -> Result, ServerError> { let mut rows = conn .query("SELECT code, uses_left, expires_at FROM invite_code", ()) .await?; @@ -64,7 +64,7 @@ pub async fn list(conn: &Connection) -> Result, Error> { Ok(codes) } -pub async fn delete(code: &str, conn: &Connection) -> Result<(), Error> { +pub async fn delete(code: &str, conn: &Connection) -> Result<(), ServerError> { let mut rows = conn .query( "DELETE FROM invite_code WHERE code = ?1 RETURNING code", @@ -76,7 +76,7 @@ pub async fn delete(code: &str, conn: &Connection) -> Result<(), Error> { Ok(()) } -pub async fn consume(code: &str, conn: &Connection) -> Result<(), Error> { +pub async fn consume(code: &str, conn: &Connection) -> Result<(), ServerError> { let mut rows = conn .query( "UPDATE invite_code SET uses_left = uses_left - 1 WHERE code = ?1 AND uses_left > 0 AND (expires_at IS NULL OR expires_at > ?2) RETURNING code", diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 4129a30..3df6446 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -5,6 +5,7 @@ pub mod backup; pub mod certificate; pub mod community; pub mod database; +pub mod datagram; pub mod direct; pub mod error; pub mod friend; @@ -34,7 +35,7 @@ use std::path::{Path, PathBuf}; use common::{config::Config, error::Error as CommonError, model::Role}; -use crate::error::Error; +use crate::error::ServerError; const SERVER_CONFIG_FILE_PATH: &str = concat!( env!("CARGO_MANIFEST_DIR"), @@ -54,7 +55,7 @@ pub struct ServerConfig { pub key_path: String, } -fn load_config() -> Result { +fn load_config() -> Result { let content = std::fs::read_to_string(config_path())?; let config = Config::parse(&content)?; @@ -66,7 +67,7 @@ fn load_config() -> Result { }) } -fn sibling_directory(database_path: &str, name: &str) -> Result { +fn sibling_directory(database_path: &str, name: &str) -> Result { let directory = Path::new(database_path) .parent() .unwrap_or_else(|| Path::new("")) @@ -76,7 +77,7 @@ fn sibling_directory(database_path: &str, name: &str) -> Result Ok(directory) } -pub async fn showtime() -> Result<(), Error> { +pub async fn showtime() -> Result<(), ServerError> { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); let config = load_config()?; @@ -98,7 +99,7 @@ pub async fn showtime() -> Result<(), Error> { .await } -pub async fn set_role(username: &str, role: Role) -> Result<(), Error> { +pub async fn set_role(username: &str, role: Role) -> Result<(), ServerError> { let config = load_config()?; let database = database::open(&config.database_path).await?; let conn = database::connect(&database).await?; diff --git a/crates/server/src/log.rs b/crates/server/src/log.rs index a738bca..5881225 100644 --- a/crates/server/src/log.rs +++ b/crates/server/src/log.rs @@ -4,7 +4,7 @@ use common::{ }; use turso::Connection; -use crate::{database::new_id, error::Error, user}; +use crate::{database::new_id, error::ServerError, user}; common::string_enum! { #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -67,7 +67,7 @@ pub async fn record( target_id: Option<&str>, action: &LogAction, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { let id = new_id(); let (action, detail) = parts(action); conn.execute( @@ -79,7 +79,7 @@ pub async fn record( Ok(()) } -pub async fn list(community_id: &str, conn: &Connection) -> Result, Error> { +pub async fn list(community_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!("SELECT l.id, l.action, l.detail, {}, {} FROM community_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE l.community_id = ?1 ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")), diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index 6e7485a..f2bb16a 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -2,7 +2,7 @@ use common::model::Role; use server::{set_role, showtime}; #[tokio::main] -async fn main() -> Result<(), server::error::Error> { +async fn main() -> Result<(), server::error::ServerError> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .init(); diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs index 463cb2c..23fcf81 100644 --- a/crates/server/src/message.rs +++ b/crates/server/src/message.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, path::Path}; use common::{ constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, - error::{Error as CommonError, Field, InvalidInput}, + error::{Error as CommonError, Field, Problem}, model::{ CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage, User, @@ -11,13 +11,13 @@ use common::{ }; use turso::{Connection, Row}; -use crate::{attachment, community, database, database::new_id, error::Error, user}; +use crate::{attachment, community, database, database::new_id, error::ServerError, user}; const SEARCH_LIMIT: usize = 200; const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned FROM message m LEFT JOIN message r ON r.id = m.reply_to"; -fn from_row(row: &Row) -> Result { +fn from_row(row: &Row) -> Result { let edited: i64 = row.get(4)?; let call_seconds: i64 = row.get(10)?; let pinned: i64 = row.get(11)?; @@ -64,7 +64,7 @@ fn placeholders(count: usize) -> String { async fn reactions_of( message_ids: &[String], conn: &Connection, -) -> Result>, Error> { +) -> Result>, ServerError> { let mut reactions: HashMap> = HashMap::new(); if message_ids.is_empty() { return Ok(reactions); @@ -103,7 +103,7 @@ async fn reactions_of( async fn polls_of( message_ids: &[String], conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut polls: HashMap = HashMap::new(); if message_ids.is_empty() { return Ok(polls); @@ -174,7 +174,7 @@ async fn polls_of( Ok(polls) } -async fn snippet_of(message_id: &str, conn: &Connection) -> Result, Error> { +async fn snippet_of(message_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( "SELECT origin FROM snippet WHERE message_id = ?1", @@ -222,7 +222,7 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result, conn: &Connection) -> Result, Error> { +async fn hydrate(messages: Vec, conn: &Connection) -> Result, ServerError> { let ids: Vec = messages.iter().map(|message| message.id.clone()).collect(); let mut reactions = reactions_of(&ids, conn).await?; let mut polls = polls_of(&ids, conn).await?; @@ -245,7 +245,7 @@ async fn insert( body: &str, reply_to: Option<&str>, conn: &Connection, -) -> Result { +) -> Result { let message_id = new_id(); conn.execute( "INSERT INTO message (id, user_id, community_id, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5)", @@ -260,7 +260,7 @@ pub async fn ensure_in_community( message_id: &str, community_id: &str, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { let mut rows = conn .query( "SELECT id FROM message WHERE id = ?1 AND community_id = ?2", @@ -279,7 +279,7 @@ pub async fn create_call_log( user_id: &str, call: CallLog, conn: &Connection, -) -> Result { +) -> Result { let message_id = new_id(); conn.execute( "INSERT INTO message (id, user_id, community_id, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5)", @@ -303,7 +303,7 @@ pub async fn create( attachments: &[String], reply_to: Option<&str>, conn: &Connection, -) -> Result { +) -> Result { if let Some(reply_to) = reply_to { ensure_in_community(reply_to, community_id, conn).await?; } @@ -314,7 +314,7 @@ pub async fn create( read(&message_id, conn).await } -pub async fn read(message_id: &str, conn: &Connection) -> Result { +pub async fn read(message_id: &str, conn: &Connection) -> Result { let mut rows = conn .query(&format!("{SELECT} WHERE m.id = ?1"), (message_id,)) .await?; @@ -332,7 +332,7 @@ pub async fn read_page( community_id: &str, before: Option<&str>, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( &format!( @@ -359,7 +359,7 @@ pub async fn create_poll( options: &[String], multiple: bool, conn: &Connection, -) -> Result { +) -> Result { let message_id = insert(user_id, community_id, "", None, conn).await?; conn.execute( "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)", @@ -382,7 +382,7 @@ pub async fn vote( user_id: &str, positions: &[u32], conn: &Connection, -) -> Result { +) -> Result { conn.execute( "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", (message_id, user_id), @@ -399,7 +399,7 @@ pub async fn vote( read(message_id, conn).await } -pub async fn close_poll(message_id: &str, conn: &Connection) -> Result { +pub async fn close_poll(message_id: &str, conn: &Connection) -> Result { let updated = conn .execute( "UPDATE poll SET closed = 1 WHERE message_id = ?1", @@ -416,7 +416,7 @@ pub async fn react( user_id: &str, emoji: &str, conn: &Connection, -) -> Result { +) -> Result { let removed = conn .execute( "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", @@ -434,7 +434,11 @@ pub async fn react( read(message_id, conn).await } -pub async fn pin(message_id: &str, pinned: bool, conn: &Connection) -> Result { +pub async fn pin( + message_id: &str, + pinned: bool, + conn: &Connection, +) -> Result { conn.execute( "UPDATE message SET pinned = ?2 WHERE id = ?1", (message_id, pinned as i64), @@ -444,7 +448,7 @@ pub async fn pin(message_id: &str, pinned: bool, conn: &Connection) -> Result Result, Error> { +pub async fn pinned(community_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!("{SELECT} WHERE m.community_id = ?1 AND m.pinned = 1 ORDER BY m.id DESC"), @@ -461,7 +465,11 @@ pub async fn pinned(community_id: &str, conn: &Connection) -> Result Result { +pub async fn update( + message_id: &str, + body: &str, + conn: &Connection, +) -> Result { let updated = conn .execute( "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1", @@ -473,7 +481,7 @@ pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result Result { +pub async fn delete(message_id: &str, conn: &Connection) -> Result { let message = read(message_id, conn).await?; conn.execute("DELETE FROM message WHERE id = ?1", (message_id,)) .await?; @@ -481,7 +489,7 @@ pub async fn delete(message_id: &str, conn: &Connection) -> Result Result, Error> { +pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result, ServerError> { database::ids( conn, "SELECT id FROM message WHERE user_id = ?1", @@ -497,7 +505,7 @@ pub async fn search( after_ms: Option, before_ms: Option, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let (after, before) = time::range_bounds(after_ms, before_ms); let mut rows = conn .query( @@ -534,7 +542,7 @@ pub async fn search( Ok(hits) } -async fn origin(sources: &[Message], conn: &Connection) -> Result, Error> { +async fn origin(sources: &[Message], conn: &Connection) -> Result, ServerError> { let Some(first) = sources.first() else { return Ok(None); }; @@ -558,7 +566,7 @@ async fn origin(sources: &[Message], conn: &Connection) -> Result }) } -async fn entry(source: &Message, conn: &Connection) -> Result { +async fn entry(source: &Message, conn: &Connection) -> Result { let author: User = user::read(&source.user_id, conn).await?; Ok(SnippetMessage { @@ -580,7 +588,7 @@ async fn write_snippet( entries: &[SnippetMessage], directory: &Path, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)", (message_id, origin), @@ -634,7 +642,7 @@ pub async fn forward( mode: ForwardMode, directory: &Path, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { if mode == ForwardMode::Copy { let mut created = Vec::new(); for source in sources { @@ -679,9 +687,10 @@ pub async fn forward( if entries.len() > MAXIMUM_FORWARD_MESSAGES { return Err(CommonError::Invalid { field: Field::Forward, - input: InvalidInput::TooLong { - maximum: MAXIMUM_FORWARD_MESSAGES, - actual: entries.len(), + problem: Problem::Length { + min: 1, + max: MAXIMUM_FORWARD_MESSAGES as u64, + actual: entries.len() as u64, }, } .into()); @@ -707,7 +716,7 @@ pub async fn forward( mod tests { use common::error::Error as CommonError; - use crate::{community, database, error::Error, message, test, user}; + use crate::{community, database, error::ServerError, message, test, user}; #[tokio::test] async fn create() { @@ -802,7 +811,7 @@ mod tests { assert!(matches!( updated_message, - Err(Error::Common(CommonError::NotFound)) + Err(ServerError::Wire(CommonError::NotFound)) )); } diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index a6b92c5..4bc8e9a 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -6,21 +6,21 @@ use std::{ use common::{ event::Event as Push, + frame::{self, DOWN_MAX, Sending, UP_MAX}, model::User, - network::{ - REQUEST_MAX_READ_LENGTH, StreamKind, receive_decoded, receive_stream_kind, send_event, - send_response, - }, + open::Open, request::Request, + transport::Close, }; use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; use tokio::{sync::mpsc, task::JoinHandle}; use tracing::{info, warn}; use crate::{ - attachment, authentication, backup, + attachment, authentication, database::{self, DB}, - error::Error, + datagram, + error::ServerError, rate_limit::RateLimit, request::{self, Broadcast}, server_ban, @@ -139,7 +139,7 @@ impl Presence { self.user_ids().len() } - fn close_where(&self, matches: impl Fn(&Signed) -> bool, reason: &[u8]) { + fn close_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) { let connections: Vec = self .0 .lock() @@ -149,20 +149,20 @@ impl Presence { .map(|signed| signed.connection.clone()) .collect(); for connection in connections { - connection.close(0u32.into(), reason); + connection.close(close.code(), close.reason().as_bytes()); } } - pub fn disconnect(&self, user_id: &str) { - self.close_where(|signed| signed.user_id == user_id, b"signed out"); + pub fn disconnect(&self, user_id: &str, close: Close) { + self.close_where(|signed| signed.user_id == user_id, close); } - pub fn disconnect_except(&self, keep: &[String], reason: &[u8]) { - self.close_where(|signed| !keep.contains(&signed.user_id), reason); + pub fn disconnect_except(&self, keep: &[String], close: Close) { + self.close_where(|signed| !keep.contains(&signed.user_id), close); } pub fn disconnect_token(&self, token: &str) { - self.close_where(|signed| signed.token == token, b"session revoked"); + self.close_where(|signed| signed.token == token, Close::Revoked); } } @@ -194,10 +194,10 @@ struct Session { } #[derive(Clone)] -struct Shared { +pub(crate) struct Shared { event_sender: mpsc::Sender, db: DB, - services: Services, + pub(crate) services: Services, directory: PathBuf, backups: PathBuf, } @@ -208,7 +208,7 @@ pub async fn serve( db: DB, directory: PathBuf, backups: PathBuf, -) -> Result<(), Error> { +) -> Result<(), ServerError> { let endpoint = Endpoint::server(server_config, server_address.parse()?)?; info!("listening on {server_address}"); @@ -236,11 +236,14 @@ async fn handle_connection(incoming: Incoming, shared: Shared) { } } -async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Error> { +async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), ServerError> { let ip = incoming.remote_address().ip().to_string(); let conn = database::connect(&shared.db).await?; if server_ban::ip_banned(&ip, &conn).await? { - incoming.refuse(); + incoming + .accept()? + .await? + .close(Close::Banned.code(), Close::Banned.reason().as_bytes()); return Ok(()); } let connection = incoming.await?; @@ -256,7 +259,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro let state = Arc::new(Mutex::new(State::Anonymous)); - tokio::spawn(relay_datagrams( + tokio::spawn(datagram::relay_datagrams( connection.clone(), Arc::clone(&state), shared.clone(), @@ -297,31 +300,21 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro Ok(()) } -async fn relay_datagrams(connection: Connection, state: Arc>, shared: Shared) { - while let Ok(bytes) = connection.read_datagram().await { - if matches!(*state.lock().unwrap(), State::Authenticated { .. }) { - shared.services.voice.relay(connection.stable_id(), &bytes); - let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); - publish(&shared, broadcasts).await; - } - } -} - async fn route( connection: Connection, state: Arc>, (send_stream, mut receive_stream): (SendStream, RecvStream), shared: Shared, -) -> Result<(), Error> { - let kind = receive_stream_kind(&mut receive_stream).await?; +) -> Result<(), ServerError> { + let send_stream = Sending::new(send_stream); + let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; let user = signed_user(&state); - match kind { - StreamKind::Request => { - answer(connection, state, (send_stream, receive_stream), shared).await - } - StreamKind::Upload => { + match open { + Open::Call(request) => answer(connection, state, request, send_stream, shared).await, + Open::Upload(upload) => { attachment::upload( user.as_ref(), + upload, receive_stream, send_stream, &shared.db, @@ -329,22 +322,13 @@ async fn route( ) .await } - StreamKind::Download => { - attachment::download( + Open::Fetch(blob) => { + attachment::fetch( user.as_ref(), - receive_stream, + blob, send_stream, &shared.db, &shared.directory, - ) - .await - } - StreamKind::Backup => { - backup::download( - user.as_ref(), - receive_stream, - send_stream, - &shared.db, &shared.backups, ) .await @@ -355,11 +339,10 @@ async fn route( async fn answer( connection: Connection, state: Arc>, - (send_stream, mut receive_stream): (SendStream, RecvStream), + request: Request, + mut send_stream: Sending, shared: Shared, -) -> Result<(), Error> { - let request: Request = receive_decoded(&mut receive_stream, REQUEST_MAX_READ_LENGTH).await?; - +) -> Result<(), ServerError> { let before = signed_in(&state); let (response, broadcasts) = request::handle( request, @@ -377,7 +360,10 @@ async fn answer( let connection_id = connection.stable_id(); shared.services.visits.forget(connection_id); match &after { - Some((user_id, token)) => shared.services.presence.sign_in(&connection, user_id, token), + Some((user_id, token)) => shared + .services + .presence + .sign_in(&connection, user_id, token), None => shared.services.presence.sign_out(connection_id), } let before_id = before.map(|(user_id, _)| user_id); @@ -392,21 +378,22 @@ async fn answer( if let Some(user_id) = &before_id { broadcast_presence(&shared, user_id).await; } - if after_id != before_id { - if let Some(user_id) = &after_id { - broadcast_presence(&shared, user_id).await; - } + if after_id != before_id + && let Some(user_id) = &after_id + { + broadcast_presence(&shared, user_id).await; } } publish(&shared, broadcasts).await; - send_response(&response, send_stream).await?; + frame::write(&mut send_stream, &response, DOWN_MAX).await?; + send_stream.finish()?; Ok(()) } -async fn publish(shared: &Shared, broadcasts: Vec) { +pub(crate) async fn publish(shared: &Shared, broadcasts: Vec) { for broadcast in broadcasts { let _ = shared .event_sender @@ -440,9 +427,10 @@ fn signed_in(state: &Mutex) -> Option<(String, String)> { } } -async fn write_session(mut event_receiver: mpsc::Receiver>, mut send_stream: SendStream) { +async fn write_session(mut event_receiver: mpsc::Receiver>, send_stream: SendStream) { + let mut send_stream = Sending::new(send_stream); while let Some(event) = event_receiver.recv().await { - if let Err(error) = send_event(&event, &mut send_stream).await { + if let Err(error) = frame::write(&mut send_stream, &*event, DOWN_MAX).await { warn!("session write: {error}"); break; } @@ -505,7 +493,9 @@ async fn the_actor(mut event_receiver: mpsc::Receiver, visits: Visits) { Err(error) => { warn!("session dropped {user_id}: {error}"); session.writer.abort(); - session.connection.close(0u32.into(), b"slow"); + session + .connection + .close(Close::Slow.code(), Close::Slow.reason().as_bytes()); false } } diff --git a/crates/server/src/notes.rs b/crates/server/src/notes.rs index 3e96aa0..3b8641e 100644 --- a/crates/server/src/notes.rs +++ b/crates/server/src/notes.rs @@ -1,9 +1,9 @@ use common::model::{Community, Rank}; use turso::Connection; -use crate::{community, error::Error, user_community}; +use crate::{community, error::ServerError, user_community}; -async fn find(user_id: &str, conn: &Connection) -> Result, Error> { +async fn find(user_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( "SELECT community_id FROM notes WHERE user_id = ?1", @@ -14,7 +14,7 @@ async fn find(user_id: &str, conn: &Connection) -> Result, Error> Ok(rows.next().await?.map(|row| row.get(0)).transpose()?) } -pub async fn open(me: &str, conn: &mut Connection) -> Result { +pub async fn open(me: &str, conn: &mut Connection) -> Result { let tx = conn.transaction().await?; let community_id = match find(me, &tx).await? { Some(community_id) => community_id, diff --git a/crates/server/src/overview.rs b/crates/server/src/overview.rs index 39cc7e1..d8df43f 100644 --- a/crates/server/src/overview.rs +++ b/crates/server/src/overview.rs @@ -1,13 +1,13 @@ use common::model::{Overview, Role}; use turso::Connection; -use crate::{community::Kind, error::Error, network::Presence, voice::Voice}; +use crate::{community::Kind, error::ServerError, network::Presence, voice::Voice}; pub async fn read( presence: &Presence, voice: &Voice, conn: &Connection, -) -> Result { +) -> Result { let mut rows = conn .query( "SELECT @@ -24,7 +24,7 @@ pub async fn read( .next() .await? .ok_or(turso::Error::QueryReturnedNoRows)?; - let count = |index: usize| -> Result { + let count = |index: usize| -> Result { let value: i64 = row.get(index)?; Ok(value as u64) }; diff --git a/crates/server/src/report.rs b/crates/server/src/report.rs index 5c152b4..f2449f0 100644 --- a/crates/server/src/report.rs +++ b/crates/server/src/report.rs @@ -7,7 +7,7 @@ use turso::Connection; use crate::{ database::{self, new_id}, - error::Error, + error::ServerError, user, }; @@ -16,7 +16,7 @@ pub async fn is_open( target_id: &str, message_id: Option<&str>, conn: &Connection, -) -> Result { +) -> Result { database::exists( conn, "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", @@ -33,7 +33,7 @@ pub async fn insert( body: Option<&str>, reason: &str, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "INSERT INTO report (id, reporter_id, target_id, message_id, community_id, body, reason) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", (new_id(), reporter_id, target_id, message_id, community_id, body, reason), @@ -43,7 +43,10 @@ pub async fn insert( Ok(()) } -pub async fn list(status: Option, conn: &Connection) -> Result, Error> { +pub async fn list( + status: Option, + conn: &Connection, +) -> Result, ServerError> { let mut rows = conn .query( &format!("SELECT r.id, {}, {}, c.name, r.message_id, r.community_id, r.body, r.reason, r.status, {} FROM report r LEFT JOIN user rp ON rp.id = r.reporter_id LEFT JOIN user t ON t.id = r.target_id LEFT JOIN community c ON c.id = r.community_id LEFT JOIN user h ON h.id = r.handled_by WHERE ?1 IS NULL OR r.status = ?1 ORDER BY r.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("rp"), user::user_columns("t"), user::user_columns("h")), @@ -76,7 +79,7 @@ pub async fn handle( status: ReportStatus, handled_by: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id", diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index cf7ed73..c5c2438 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -16,6 +16,7 @@ use common::{ response::Response, share::{Kind, Share}, time::{self, MINUTE_MILLIS}, + transport::Close, validate::{ validate_avatar_size, validate_forward, validate_new_message, validate_poll, validate_reaction, validate_reason, validate_server_settings, validate_vote, @@ -27,7 +28,7 @@ use crate::{ admin_log, attachment, authentication, backup, community, database::{self, DB}, direct, - error::Error, + error::ServerError, friend, invitation, invite, log, message, network::{self, Services, State}, notes, overview, @@ -53,10 +54,10 @@ pub async fn handle( connection: Option<&quinn::Connection>, directory: &Path, backups: &Path, -) -> Outcome { +) -> (Result, Vec) { match dispatch(request, state, db, services, connection, directory, backups).await { - Ok(outcome) => outcome, - Err(error) => (Response::Error(error.into()), Vec::new()), + Ok((response, broadcasts)) => (Ok(response), broadcasts), + Err(error) => (Err(error.into()), Vec::new()), } } @@ -68,7 +69,7 @@ async fn dispatch( connection: Option<&quinn::Connection>, directory: &Path, backups: &Path, -) -> Result { +) -> Result { let Services { voice, share, @@ -146,7 +147,7 @@ async fn dispatch( .await?; if settings.maintenance { let builders = user::builder_ids(&conn).await?; - presence.disconnect_except(&builders, b"maintenance"); + presence.disconnect_except(&builders, Close::Maintenance); } let broadcasts = if settings.announcement == previous.announcement { Vec::new() @@ -275,7 +276,7 @@ async fn dispatch( admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?; if suspended { authentication::revoke_sessions(&user_id, &conn).await?; - presence.disconnect(&user_id); + presence.disconnect(&user_id, Close::Revoked); } (Response::Done, Vec::new()) } @@ -283,7 +284,7 @@ async fn dispatch( let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; authentication::revoke_sessions(&user_id, &conn).await?; - presence.disconnect(&user_id); + presence.disconnect(&user_id, Close::Revoked); admin_log::record( Some(&me.id), Some(&user_id), @@ -298,7 +299,7 @@ async fn dispatch( let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; authentication::reset_password(&user_id, &password, &conn).await?; - presence.disconnect(&user_id); + presence.disconnect(&user_id, Close::Revoked); admin_log::record( Some(&me.id), Some(&user_id), @@ -342,7 +343,7 @@ async fn dispatch( broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); } else { user::set_ghost(&user_id, false, &conn).await?; - presence.disconnect(&user_id); + presence.disconnect(&user_id, Close::Revoked); } (Response::User(user), broadcasts) } @@ -435,7 +436,7 @@ async fn dispatch( if me.id == user_id { set_state(state, State::Anonymous); } else { - presence.disconnect(&user_id); + presence.disconnect(&user_id, Close::Revoked); } (Response::User(deleted), broadcasts) } @@ -1291,7 +1292,7 @@ async fn dispatch( user::set_timeout(&user_id, until, &conn).await?; if until.is_some() { authentication::revoke_sessions(&user_id, &conn).await?; - presence.disconnect(&user_id); + presence.disconnect(&user_id, Close::Revoked); } admin_log::record( Some(&me.id), @@ -1337,7 +1338,7 @@ async fn dispatch( ) .await?; tx.commit().await?; - presence.disconnect(&user_id); + presence.disconnect(&user_id, Close::Banned); (Response::Done, Vec::new()) } Request::ServerBans => { @@ -1549,9 +1550,6 @@ async fn dispatch( admin_log::record(Some(&me.id), None, None, &action, &conn).await?; (Response::Done, Vec::new()) } - Request::DownloadBackup { .. } => { - return Err(CommonError::Server.into()); - } Request::VoiceRooms => { builder(state, &conn).await?; ( @@ -1687,7 +1685,7 @@ async fn dispatch( Ok(outcome) } -async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result, Error> { +async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result, ServerError> { let mut rooms = Vec::new(); for (community_id, user_ids, ghosts) in voice.rooms() { let community = community::label(&community_id, conn).await?; @@ -1713,7 +1711,7 @@ async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result, Ok(rooms) } -async fn report_created(conn: &Connection) -> Result { +async fn report_created(conn: &Connection) -> Result { Ok(Broadcast { event: Event::ReportCreated, user_ids: user::builder_ids(conn).await?, @@ -1728,7 +1726,7 @@ async fn limit_logins( rate_limit: &RateLimit, connection: Option<&quinn::Connection>, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { let limit = server_settings::read(conn).await?.logins_per_minute; Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?) @@ -1738,7 +1736,7 @@ fn limit_messages( me: &User, rate_limit: &RateLimit, settings: &ServerSettings, -) -> Result<(), Error> { +) -> Result<(), ServerError> { if permission::is_builder(me.role) { return Ok(()); } @@ -1750,7 +1748,7 @@ async fn record_address( user: &User, connection: Option<&quinn::Connection>, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { if let Some(ip) = ip_of(connection) { user::set_last_ip(&user.id, &ip, conn).await?; } @@ -1771,7 +1769,7 @@ async fn remove_member( voice: &Voice, share: &Shares, conn: &mut Connection, -) -> Result { +) -> Result { let Removal { community_id, user_id, @@ -1821,7 +1819,7 @@ async fn remove_member( Ok((Response::Done, broadcasts)) } -async fn related_user_ids(user_id: &str, conn: &Connection) -> Result, Error> { +async fn related_user_ids(user_id: &str, conn: &Connection) -> Result, ServerError> { let mut user_ids = BTreeSet::from([user_id.to_string()]); for community in community::communities_of(user_id, conn).await? { for member in user_community::members(&community.id, conn).await? { @@ -1835,7 +1833,7 @@ async fn related_user_ids(user_id: &str, conn: &Connection) -> Result Result, Error> { +async fn user_updated(user: &User, conn: &Connection) -> Result, ServerError> { Ok(vec![Broadcast { event: Event::UserUpdated(user.clone()), user_ids: related_user_ids(&user.id, conn).await?, @@ -1846,7 +1844,7 @@ async fn effective_presence( presence: &network::Presence, user_id: &str, conn: &Connection, -) -> Result { +) -> Result { if !presence.is_online(user_id) { return Ok(Presence::Offline); } @@ -1858,7 +1856,7 @@ pub async fn presence_changed( presence: &network::Presence, user_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let presence = effective_presence(presence, user_id, conn).await?; Ok(vec![Broadcast { @@ -1870,7 +1868,10 @@ pub async fn presence_changed( }]) } -async fn friends_updated(user_ids: &[&str], conn: &Connection) -> Result, Error> { +async fn friends_updated( + user_ids: &[&str], + conn: &Connection, +) -> Result, ServerError> { let mut broadcasts = Vec::new(); for user_id in user_ids { broadcasts.push(Broadcast { @@ -1882,7 +1883,7 @@ async fn friends_updated(user_ids: &[&str], conn: &Connection) -> Result Result { +async fn invitations_updated(user_id: &str, conn: &Connection) -> Result { Ok(Broadcast { event: Event::InvitationsUpdated(invitation::of(user_id, conn).await?), user_ids: vec![user_id.to_string()], @@ -1894,7 +1895,7 @@ async fn leave_user_voice( share: &Shares, user_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { match voice.leave(user_id) { Some(left) => voice_left(share, left, conn).await, None => Ok(Vec::new()), @@ -1906,7 +1907,7 @@ pub async fn leave_connection_voice( share: &Shares, connection: Option<&quinn::Connection>, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { match connection.and_then(|connection| voice.leave_connection(connection.stable_id())) { Some(left) => voice_left(share, left, conn).await, None => Ok(Vec::new()), @@ -1919,7 +1920,7 @@ async fn leave_room_voice( community_id: &str, user_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { match voice.leave_room(community_id, user_id) { Some(left) => voice_left(share, left, conn).await, None => Ok(Vec::new()), @@ -1930,7 +1931,7 @@ async fn voice_unmuted( voice: &Voice, user_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let Some(community_id) = voice.set_muted(user_id, false) else { return Ok(Vec::new()); }; @@ -1958,7 +1959,7 @@ async fn voice_silenced( share: &Shares, community_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut broadcasts = Vec::new(); for user_id in voice.room_users(community_id) { if permission::is_builder(user::read(&user_id, conn).await?.role) { @@ -1977,7 +1978,7 @@ async fn voice_closed( share: &Shares, community_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut broadcasts = Vec::new(); for left in voice.remove_room(community_id) { broadcasts.extend(voice_left(share, left, conn).await?); @@ -2000,7 +2001,7 @@ async fn call_ended( call: Option, members: &[Member], conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let Some(call) = call else { return Ok(Vec::new()); }; @@ -2019,7 +2020,7 @@ async fn voice_left( share: &Shares, left: Left, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut broadcasts = share_left(share, &left.user_id, conn).await?; let Some(seconds) = left.ghost_seconds else { let members = user_community::members(&left.community_id, conn).await?; @@ -2044,7 +2045,7 @@ async fn share_ended( user_id: &str, kind: Kind, conn: &Connection, -) -> Result { +) -> Result { let members = user_community::members(community_id, conn).await?; let event = Event::ShareStopped { community_id: community_id.to_string(), @@ -2060,7 +2061,7 @@ async fn share_stopped( user_id: &str, kind: Kind, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let Some(community_id) = share.stop(user_id, kind) else { return Ok(Vec::new()); }; @@ -2072,7 +2073,7 @@ async fn share_left( share: &Shares, user_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut broadcasts = Vec::new(); for (community_id, kind) in share.stop_all(user_id) { broadcasts.push(share_ended(&community_id, user_id, kind, conn).await?); @@ -2090,7 +2091,7 @@ async fn enter( share: &Shares, connection: Option<&quinn::Connection>, conn: &Connection, -) -> Result { +) -> Result { stats::mark_active(&user.id, conn).await?; record_address(&user, connection, conn).await?; let broadcasts = leave_connection_voice(voice, share, connection, conn).await?; @@ -2114,14 +2115,14 @@ fn set_state(state: &Mutex, new_state: State) { *state.lock().unwrap() = new_state; } -fn session(state: &Mutex) -> Result<(User, String), Error> { +fn session(state: &Mutex) -> Result<(User, String), ServerError> { match state.lock().unwrap().clone() { State::Anonymous => Err(CommonError::Unauthenticated.into()), State::Authenticated { user, token } => Ok((user, token)), } } -fn session_token(state: &Mutex) -> Result { +fn session_token(state: &Mutex) -> Result { Ok(session(state)?.1) } @@ -2131,7 +2132,7 @@ fn cache_user(state: &Mutex, user: User) { } } -async fn authenticated(state: &Mutex, conn: &Connection) -> Result { +async fn authenticated(state: &Mutex, conn: &Connection) -> Result { let (cached, _) = session(state)?; let user = user::read(&cached.id, conn).await?; cache_user(state, user.clone()); @@ -2139,7 +2140,7 @@ async fn authenticated(state: &Mutex, conn: &Connection) -> Result, conn: &Connection) -> Result { +async fn builder(state: &Mutex, conn: &Connection) -> Result { let user = authenticated(state, conn).await?; ensure(permission::is_builder(user.role))?; @@ -2150,13 +2151,13 @@ pub async fn actor_rank( me: &User, community_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let rank = user_community::rank(&me.id, community_id, conn).await?; Ok(permission::effective_rank(me.role, rank)) } -async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result { +async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result { let target = user::read(user_id, conn).await?; ensure(permission::can_manage_user( me.role, @@ -2167,11 +2168,11 @@ async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result Result<(), Error> { +pub fn ensure(allowed: bool) -> Result<(), ServerError> { ensure_with(allowed, CommonError::Forbidden) } -pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), Error> { +pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError> { if !allowed { return Err(error.into()); } @@ -2184,17 +2185,21 @@ async fn allowed( community_id: &str, conn: &Connection, check: fn(Option) -> bool, -) -> Result<(), Error> { +) -> Result<(), ServerError> { ensure(check(actor_rank(me, community_id, conn).await?)) } -async fn is_outsider(user_id: &str, community_id: &str, conn: &Connection) -> Result { +async fn is_outsider( + user_id: &str, + community_id: &str, + conn: &Connection, +) -> Result { Ok(user_community::rank(user_id, community_id, conn) .await? .is_none()) } -async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), Error> { +async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), ServerError> { ensure(!community::is_fixed(community_id, conn).await?) } @@ -2212,7 +2217,7 @@ async fn message_broadcast( event: fn(Message) -> Event, actor_id: &str, conn: &Connection, -) -> Result { +) -> Result { let members = user_community::members(&message.community_id, conn).await?; Ok(broadcast_with(event(message.clone()), &members, actor_id)) @@ -2249,7 +2254,7 @@ async fn record_ghost_voice( community_id: &str, seconds: u64, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { let community = community::label(community_id, conn).await?; admin_log::record( Some(user_id), @@ -2293,6 +2298,17 @@ mod tests { db: &DB, services: &Services, ) -> Response { + send_result(request, state, db, services) + .await + .expect("request failed") + } + + async fn send_result( + request: Request, + state: &Mutex, + db: &DB, + services: &Services, + ) -> Result { handle( request, state, @@ -2384,7 +2400,7 @@ mod tests { }; invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; - let response = send( + let response = send_result( Request::UpdateCommunity { community_id: community.id, name: "Renamed".to_string(), @@ -2395,7 +2411,7 @@ mod tests { ) .await; - assert!(matches!(response, Response::Error(CommonError::Forbidden))); + assert!(matches!(response, Err(CommonError::Forbidden))); } #[tokio::test] diff --git a/crates/server/src/retention.rs b/crates/server/src/retention.rs index 2ad9177..a4db7c2 100644 --- a/crates/server/src/retention.rs +++ b/crates/server/src/retention.rs @@ -10,7 +10,7 @@ use turso::Connection; use crate::{ attachment, database::{self, DB}, - error::Error, + error::ServerError, message, server_settings, }; @@ -31,7 +31,7 @@ fn cutoff(now: u64, days: u32) -> String { time::id_bound(now.saturating_sub(u64::from(days) * time::DAY_MILLIS)) } -async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result, Error> { +async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!("SELECT id FROM {table} WHERE id < ?1 ORDER BY id LIMIT ?2"), @@ -51,7 +51,7 @@ async fn purge_messages( cutoff: &str, conn: &mut Connection, directory: &Path, -) -> Result { +) -> Result { let mut purged = 0; loop { let ids = expired("message", cutoff, conn).await?; @@ -75,7 +75,7 @@ async fn purge_attachments( cutoff: &str, conn: &mut Connection, directory: &Path, -) -> Result { +) -> Result { let mut purged = 0; loop { let ids = expired("attachment", cutoff, conn).await?; @@ -91,7 +91,7 @@ async fn purge_attachments( } } -async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { +async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { let mut conn = database::connect(db).await?; let settings = server_settings::read(&conn).await?; let now = time::now_ms(); diff --git a/crates/server/src/server_ban.rs b/crates/server/src/server_ban.rs index 729e15f..f88ba95 100644 --- a/crates/server/src/server_ban.rs +++ b/crates/server/src/server_ban.rs @@ -6,7 +6,7 @@ use turso::Connection; use crate::{ database::{self, new_id}, - error::Error, + error::ServerError, }; pub async fn insert( @@ -15,7 +15,7 @@ pub async fn insert( reason: Option<&str>, created_by: &str, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "INSERT INTO server_ban (id, kind, value, reason, created_by) SELECT ?1, ?2, ?3, ?4, ?5 WHERE NOT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?2 AND value = ?3)", @@ -26,7 +26,7 @@ pub async fn insert( Ok(()) } -pub async fn list(conn: &Connection) -> Result, Error> { +pub async fn list(conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value", @@ -48,7 +48,7 @@ pub async fn list(conn: &Connection) -> Result, Error> { Ok(bans) } -async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result { +async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result { database::exists( conn, "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", @@ -57,7 +57,7 @@ async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result Result { +pub async fn username_banned(username: &str, conn: &Connection) -> Result { exists( ServerBanKind::Username, &username.to_ascii_lowercase(), @@ -66,11 +66,11 @@ pub async fn username_banned(username: &str, conn: &Connection) -> Result Result { +pub async fn ip_banned(ip: &str, conn: &Connection) -> Result { exists(ServerBanKind::Ip, ip, conn).await } -pub async fn remove(id: &str, conn: &Connection) -> Result<(), Error> { +pub async fn remove(id: &str, conn: &Connection) -> Result<(), ServerError> { let mut rows = conn .query("DELETE FROM server_ban WHERE id = ?1 RETURNING id", (id,)) .await?; diff --git a/crates/server/src/server_settings.rs b/crates/server/src/server_settings.rs index 1925517..4e55eb9 100644 --- a/crates/server/src/server_settings.rs +++ b/crates/server/src/server_settings.rs @@ -1,7 +1,7 @@ use common::model::ServerSettings; use turso::Connection; -use crate::{error::Error, user}; +use crate::{error::ServerError, user}; const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute"; @@ -14,7 +14,7 @@ fn assignments() -> String { .join(", ") } -pub async fn read(conn: &Connection) -> Result { +pub async fn read(conn: &Connection) -> Result { let mut rows = conn .query( &format!("SELECT {COLUMNS} FROM server_settings WHERE id = 1"), @@ -25,7 +25,7 @@ pub async fn read(conn: &Connection) -> Result { .next() .await? .ok_or(turso::Error::QueryReturnedNoRows)?; - let int = |index: usize| -> Result { Ok(row.get(index)?) }; + let int = |index: usize| -> Result { Ok(row.get(index)?) }; Ok(ServerSettings { name: row.get(0)?, @@ -45,7 +45,7 @@ pub async fn read(conn: &Connection) -> Result { }) } -pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), Error> { +pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), ServerError> { conn.execute( &format!("UPDATE server_settings SET {} WHERE id = 1", assignments()), ( diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs index 08bfdf4..867713c 100644 --- a/crates/server/src/stats.rs +++ b/crates/server/src/stats.rs @@ -4,11 +4,11 @@ use common::{ }; use turso::Connection; -use crate::{database, error::Error, user}; +use crate::{database, error::ServerError, user}; const MAXIMUM_DAYS: u32 = 90; -pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), Error> { +pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), ServerError> { if user::is_ghost(user_id, conn).await? { return Ok(()); } @@ -22,7 +22,7 @@ pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), Error> Ok(()) } -pub async fn daily(days: u32, conn: &Connection) -> Result, Error> { +pub async fn daily(days: u32, conn: &Connection) -> Result, ServerError> { let days = u64::from(days.clamp(1, MAXIMUM_DAYS)); let today = time::now_ms() / DAY_MILLIS; let mut stats = Vec::new(); @@ -52,6 +52,10 @@ pub async fn daily(days: u32, conn: &Connection) -> Result, Error> Ok(stats) } -async fn count(conn: &Connection, sql: &str, params: impl turso::IntoParams) -> Result { +async fn count( + conn: &Connection, + sql: &str, + params: impl turso::IntoParams, +) -> Result { Ok(database::scalar_i64(conn, sql, params).await? as u64) } diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index 6806969..50a7820 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -1,6 +1,6 @@ use common::{ constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, - error::{Error as CommonError, Field, InvalidInput}, + error::{Error as CommonError, Field, Problem}, model::{Account, Presence, Role, User}, permission, time, validate::{validate_avatar_size, validate_status, validate_username}, @@ -10,14 +10,14 @@ use turso::{Connection, Row}; use crate::{ database::{self, new_id}, - error::Error, + error::ServerError, }; pub fn user_columns(alias: &str) -> String { format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id") } -pub fn from_row_at(row: &Row, start: usize) -> Result, Error> { +pub fn from_row_at(row: &Row, start: usize) -> Result, ServerError> { let Some(id) = row.get::>(start)? else { return Ok(None); }; @@ -32,24 +32,32 @@ pub fn from_row_at(row: &Row, start: usize) -> Result, Error> { })) } -pub fn from_row(row: &Row) -> Result { +pub fn from_row(row: &Row) -> Result { Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?) } -pub fn bool_at(row: &Row, index: usize) -> Result { +pub fn bool_at(row: &Row, index: usize) -> Result { let flag: i64 = row.get(index)?; Ok(flag != 0) } -async fn one(sql: &str, params: impl turso::IntoParams, conn: &Connection) -> Result { +async fn one( + sql: &str, + params: impl turso::IntoParams, + conn: &Connection, +) -> Result { let mut rows = conn.query(sql, params).await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } -async fn set(column: &str, params: impl turso::IntoParams, conn: &Connection) -> Result<(), Error> { +async fn set( + column: &str, + params: impl turso::IntoParams, + conn: &Connection, +) -> Result<(), ServerError> { conn.execute( &format!("UPDATE user SET {column} = ?2 WHERE id = ?1"), params, @@ -63,7 +71,7 @@ async fn set_returning( column: &str, params: impl turso::IntoParams, conn: &Connection, -) -> Result { +) -> Result { one( &format!( "UPDATE user SET {column} = ?2 WHERE id = ?1 RETURNING {}", @@ -75,7 +83,11 @@ async fn set_returning( .await } -pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result { +pub async fn create( + username: &str, + password_hash: &str, + conn: &Connection, +) -> Result { one( &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")), ( @@ -90,7 +102,7 @@ pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> R .await } -pub async fn read(user_id: &str, conn: &Connection) -> Result { +pub async fn read(user_id: &str, conn: &Connection) -> Result { one( &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")), (user_id,), @@ -99,11 +111,11 @@ pub async fn read(user_id: &str, conn: &Connection) -> Result { .await } -pub async fn any(conn: &Connection) -> Result { +pub async fn any(conn: &Connection) -> Result { database::exists(conn, "SELECT EXISTS (SELECT 1 FROM user)", ()).await } -pub async fn by_username(username: &str, conn: &Connection) -> Result, Error> { +pub async fn by_username(username: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!( @@ -121,13 +133,13 @@ pub async fn is_taken( username: &str, except_id: Option<&str>, conn: &Connection, -) -> Result { +) -> Result { Ok(by_username(username, conn) .await? .is_some_and(|existing| Some(existing.id.as_str()) != except_id)) } -pub async fn by_session_token(token: &str, conn: &Connection) -> Result { +pub async fn by_session_token(token: &str, conn: &Connection) -> Result { let mut rows = conn .query( &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user_columns("user")), @@ -142,7 +154,7 @@ pub async fn by_session_token(token: &str, conn: &Connection) -> Result Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( &format!( @@ -159,7 +171,7 @@ pub async fn credentials( Ok(Some((from_row(&row)?, row.get(5)?))) } -pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result { +pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result { validate_username(username)?; if is_taken(username, Some(user_id), conn).await? { @@ -169,24 +181,28 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result< set_returning("username", (user_id, username), conn).await } -pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result { +pub async fn update_status( + user_id: &str, + status: &str, + conn: &Connection, +) -> Result { validate_status(status)?; set_returning("status", (user_id, status), conn).await } -pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { +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, - input: InvalidInput::NotJpeg, + problem: Problem::NotJpeg, } })?; if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE { return Err(CommonError::Invalid { field: Field::Avatar, - input: InvalidInput::Dimensions { + problem: Problem::Dimensions { expected: AVATAR_SIZE, }, } @@ -200,7 +216,7 @@ pub async fn set_avatar( user_id: &str, avatar: Option<&[u8]>, conn: &mut Connection, -) -> Result { +) -> Result { if let Some(bytes) = avatar { check_avatar(bytes)?; } @@ -226,11 +242,11 @@ async fn set_avatar_id( user_id: &str, avatar_id: Option<&str>, conn: &Connection, -) -> Result { +) -> Result { set_returning("avatar_id", (user_id, avatar_id), conn).await } -pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error> { +pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( "SELECT data FROM avatar WHERE id = ?1 UNION ALL SELECT data FROM community_avatar WHERE id = ?1", @@ -242,11 +258,18 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error Ok(row.get(0)?) } -pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result { +pub async fn set_role_by_id( + user_id: &str, + role: Role, + conn: &Connection, +) -> Result { set_returning("role", (user_id, role.as_str()), conn).await } -pub async fn suspended(user_id: &str, conn: &Connection) -> Result { +pub async fn suspended( + user_id: &str, + conn: &Connection, +) -> Result>, ServerError> { let mut rows = conn .query( "SELECT suspended, suspended_until FROM user WHERE id = ?1", @@ -254,16 +277,20 @@ pub async fn suspended(user_id: &str, conn: &Connection) -> Result ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let until: Option = row.get(1)?; + let until: Option = row.get::>(1)?.map(|until| until as u64); + + if bool_at(&row, 0)? { + return Ok(Some(None)); + } - Ok(bool_at(&row, 0)? || until.is_some_and(|until| until as u64 > time::now_ms())) + Ok(until.filter(|until| *until > time::now_ms()).map(Some)) } pub async fn set_timeout( user_id: &str, until: Option, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { set( "suspended_until", (user_id, until.map(|until| until as i64)), @@ -272,11 +299,11 @@ pub async fn set_timeout( .await } -pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), Error> { +pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), ServerError> { set("last_ip", (user_id, ip), conn).await } -pub async fn last_ip(user_id: &str, conn: &Connection) -> Result, Error> { +pub async fn last_ip(user_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query("SELECT last_ip FROM user WHERE id = ?1", (user_id,)) .await?; @@ -285,7 +312,7 @@ pub async fn last_ip(user_id: &str, conn: &Connection) -> Result, Ok(row.get(0)?) } -pub async fn builder_ids(conn: &Connection) -> Result, Error> { +pub async fn builder_ids(conn: &Connection) -> Result, ServerError> { database::ids( conn, "SELECT id FROM user WHERE role = ?1", @@ -294,19 +321,27 @@ pub async fn builder_ids(conn: &Connection) -> Result, Error> { .await } -pub async fn set_suspended(user_id: &str, suspended: bool, conn: &Connection) -> Result<(), Error> { +pub async fn set_suspended( + user_id: &str, + suspended: bool, + conn: &Connection, +) -> Result<(), ServerError> { set("suspended", (user_id, i64::from(suspended)), conn).await } -pub async fn set_voice_muted(user_id: &str, muted: bool, conn: &Connection) -> Result<(), Error> { +pub async fn set_voice_muted( + user_id: &str, + muted: bool, + conn: &Connection, +) -> Result<(), ServerError> { set("voice_muted", (user_id, i64::from(muted)), conn).await } -pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), Error> { +pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), ServerError> { set("ghost", (user_id, i64::from(ghost)), conn).await } -pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result { +pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query("SELECT ghost FROM user WHERE id = ?1", (user_id,)) .await?; @@ -317,7 +352,7 @@ pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result { bool_at(&row, 0) } -pub async fn presence(user_id: &str, conn: &Connection) -> Result { +pub async fn presence(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query("SELECT presence FROM user WHERE id = ?1", (user_id,)) .await?; @@ -331,11 +366,11 @@ pub async fn update_presence( user_id: &str, presence: Presence, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { set("presence", (user_id, presence.as_str()), conn).await } -pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result { +pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( "SELECT voice_muted, role FROM user WHERE id = ?1", @@ -353,11 +388,11 @@ pub async fn set_password_hash( user_id: &str, password_hash: &str, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { set("password_hash", (user_id, password_hash), conn).await } -pub async fn all(conn: &Connection) -> Result, Error> { +pub async fn all(conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!("SELECT {}, suspended, last_seen, suspended_until, ghost FROM user ORDER BY username COLLATE NOCASE", user_columns("user")), @@ -380,7 +415,7 @@ pub async fn all(conn: &Connection) -> Result, Error> { Ok(accounts) } -pub async fn delete(user_id: &str, conn: &Connection) -> Result { +pub async fn delete(user_id: &str, conn: &Connection) -> Result { one( &format!( "DELETE FROM user WHERE id = ?1 RETURNING {}", @@ -402,7 +437,7 @@ mod tests { }; use image::{ImageFormat, RgbImage}; - use crate::{database, error::Error, test, user}; + use crate::{database, error::ServerError, test, user}; fn jpeg(size: u32) -> Vec { let mut bytes = Cursor::new(Vec::new()); @@ -428,14 +463,14 @@ mod tests { assert!(matches!( small, - Err(Error::Common(CommonError::Invalid { + Err(ServerError::Wire(CommonError::Invalid { field: Field::Avatar, .. })) )); assert!(matches!( not_jpeg, - Err(Error::Common(CommonError::Invalid { + Err(ServerError::Wire(CommonError::Invalid { field: Field::Avatar, .. })) @@ -503,7 +538,7 @@ mod tests { assert!(matches!( updated_user, - Err(Error::Common(CommonError::NotFound)) + Err(ServerError::Wire(CommonError::NotFound)) )); } diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs index 9c45cba..b164d7e 100644 --- a/crates/server/src/user_community.rs +++ b/crates/server/src/user_community.rs @@ -6,9 +6,9 @@ use common::{ }; use turso::{Connection, Row}; -use crate::{community, database, error::Error, user}; +use crate::{community, database, error::ServerError, user}; -fn rank_of(row: &Row, index: usize) -> Result { +fn rank_of(row: &Row, index: usize) -> Result { let text: String = row.get(index)?; Ok(Rank::parse(&text).ok_or(CommonError::Server)?) @@ -19,7 +19,7 @@ pub async fn join( community_id: &str, rank: Rank, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "INSERT INTO user_community (user_id, community_id, rank) VALUES (?1, ?2, ?3)", (user_id, community_id, rank.as_str()), @@ -29,7 +29,11 @@ pub async fn join( Ok(()) } -pub async fn leave(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> { +pub async fn leave( + user_id: &str, + community_id: &str, + conn: &Connection, +) -> Result<(), ServerError> { conn.execute( "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", (user_id, community_id), @@ -43,7 +47,7 @@ pub async fn rank( user_id: &str, community_id: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( "SELECT rank FROM user_community WHERE user_id = ?1 AND community_id = ?2", @@ -63,7 +67,7 @@ pub async fn set_rank( community_id: &str, rank: Rank, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "UPDATE user_community SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2", (user_id, community_id, rank.as_str()), @@ -78,7 +82,7 @@ pub async fn mark_read( community_id: &str, message_id: &str, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "UPDATE user_community SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", (user_id, community_id, message_id), @@ -92,7 +96,7 @@ pub async fn unreads( user_id: &str, username: &str, conn: &Connection, -) -> Result, Error> { +) -> Result, ServerError> { let mut rows = conn .query( "SELECT uc.community_id, (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read)), uc.last_read FROM user_community uc WHERE uc.user_id = ?1", @@ -137,7 +141,7 @@ pub async fn unreads( Ok(unreads) } -pub async fn members(community_id: &str, conn: &Connection) -> Result, Error> { +pub async fn members(community_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!("SELECT {}, user_community.rank FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id", user::user_columns("user")), @@ -156,7 +160,7 @@ pub async fn members(community_id: &str, conn: &Connection) -> Result Result { +pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result { let count = database::scalar_i64( conn, "SELECT COUNT(*) FROM user_community JOIN community ON community.id = user_community.community_id WHERE user_community.user_id = ?1 AND user_community.rank = ?2 AND community.kind = ?3", @@ -167,7 +171,7 @@ pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result Result, Error> { +pub async fn owned(user_id: &str, conn: &Connection) -> Result, ServerError> { database::ids( conn, "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", @@ -181,7 +185,7 @@ pub async fn ban( community_id: &str, reason: Option<&str>, conn: &Connection, -) -> Result<(), Error> { +) -> Result<(), ServerError> { conn.execute( "INSERT OR REPLACE INTO ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)", (user_id, community_id, reason), @@ -191,7 +195,11 @@ pub async fn ban( Ok(()) } -pub async fn unban(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> { +pub async fn unban( + user_id: &str, + community_id: &str, + conn: &Connection, +) -> Result<(), ServerError> { conn.execute( "DELETE FROM ban WHERE user_id = ?1 AND community_id = ?2", (user_id, community_id), @@ -205,7 +213,7 @@ pub async fn is_banned( user_id: &str, community_id: &str, conn: &Connection, -) -> Result { +) -> Result { database::exists( conn, "SELECT EXISTS (SELECT 1 FROM ban WHERE user_id = ?1 AND community_id = ?2)", @@ -214,7 +222,7 @@ pub async fn is_banned( .await } -pub async fn bans(community_id: &str, conn: &Connection) -> Result, Error> { +pub async fn bans(community_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( &format!("SELECT {}, ban.reason FROM user JOIN ban ON ban.user_id = user.id WHERE ban.community_id = ?1 ORDER BY ban.rowid DESC", user::user_columns("user")),