use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration}; use bytes::Bytes; use common::{ call::{Login, Register, Request}, event::Event, frame::{self, DOWN_MAX, Sending, UP_MAX}, model::{Id, ServerBanKind, User}, open::Open, session::{Hello, Welcome}, transport::{self, Close}, validate::validate_device, }; use quinn::{Connection, Incoming, RecvStream, SendStream}; use tokio::sync::mpsc; use tracing::{info, warn}; use crate::{ authentication, call::{self, Cx}, db::{self, Db}, error::ServerError, files, hub::{Client, Hub, Signed}, publish::{self, Broadcast, To}, rate_limit::RateLimit, retention, rooms::Rooms, stats::{Follows, Machine}, }; const HELLO_DEADLINE: Duration = Duration::from_secs(5); const RESTART_DRAIN: Duration = Duration::from_secs(2); const RESTART_DELAY: Duration = Duration::from_millis(300); pub enum Exit { Stopped, Restart, } #[derive(Clone)] pub(crate) struct Shared { pub(crate) db: Db, pub(crate) services: Services, pub(crate) attachments: PathBuf, pub(crate) backups: PathBuf, pub(crate) releases: crate::update::Releases, } #[derive(Clone)] pub struct Services { pub rooms: Rooms, pub hub: Hub, pub rate_limit: RateLimit, pub stats: Follows, pub machine: Machine, pub restart: Arc, } impl Services { pub fn new(attachments: PathBuf) -> Self { Self { rooms: Rooms::default(), hub: Hub::default(), rate_limit: RateLimit::default(), stats: Follows::default(), machine: Machine::new(attachments), restart: Arc::default(), } } pub fn restart_soon(&self) { let restart = self.restart.clone(); tokio::spawn(async move { tokio::time::sleep(RESTART_DELAY).await; restart.notify_one(); }); } } struct Pending { client: Arc, events: mpsc::Receiver, reply_stream: Sending, } pub async fn serve( server_address: &str, server_config: quinn::ServerConfig, db: Db, attachments: PathBuf, backups: PathBuf, releases: crate::update::Releases, ) -> Result { let endpoint = transport::endpoint( server_address.parse()?, quinn::EndpointConfig::default(), Some(server_config), )?; info!("listening on {server_address}"); let shared = Shared { db, services: Services::new(attachments.clone()), attachments, backups, releases, }; let runtime = tokio::runtime::Handle::current(); let sweeper = shared.clone(); std::thread::spawn(move || runtime.block_on(retention::collect(sweeper))); tokio::spawn(files::collect( shared.db.clone(), shared.attachments.clone(), )); let restart = shared.services.restart.clone(); loop { tokio::select! { incoming = endpoint.accept() => match incoming { Some(incoming) => { tokio::spawn(handle_connection(incoming, shared.clone())); } None => return Ok(Exit::Stopped), }, _ = restart.notified() => break, } } info!("restarting"); endpoint.close(Close::Restart.code(), Close::Restart.reason().as_bytes()); let _ = tokio::time::timeout(RESTART_DRAIN, endpoint.wait_idle()).await; Ok(Exit::Restart) } async fn handle_connection(incoming: Incoming, shared: Shared) { if let Err(error) = serve_connection(incoming, shared).await { warn!("connection: {error}"); } } async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), ServerError> { let ip = incoming.remote_address().ip().to_string(); let banned = shared .db .run(async |db| db::server_ban::banned(ServerBanKind::Ip, &ip, db).await) .await?; if banned { Close::Banned.on(&incoming.accept()?.await?); return Ok(()); } let connection = incoming.await?; let alpn = connection .handshake_data() .and_then(|data| data.downcast::().ok()) .and_then(|data| data.protocol); if alpn.as_deref() == Some(common::update::ALPN) { shared.releases.serve(connection, &shared.db).await; return Ok(()); } let pending = match tokio::time::timeout(HELLO_DEADLINE, greet(&connection, &shared)).await { Ok(Ok(Some(pending))) => pending, Ok(Ok(None)) => return Ok(()), Ok(Err(error)) => { Close::Protocol.on(&connection); return Err(error); } Err(_) => { Close::Protocol.on(&connection); return Ok(()); } }; let Pending { client, events, reply_stream, } = pending; let hub = &shared.services.hub; let joined = hub.add(Arc::clone(&client)); match establish(&client, &connection, reply_stream, events, &shared).await { Ok(true) => publish_presence(&shared, joined).await, Ok(false) => { publish_presence(&shared, joined.or(hub.remove(client.id))).await; let _ = tokio::time::timeout(HELLO_DEADLINE, connection.closed()).await; return Ok(()); } Err(error) => { publish_presence(&shared, joined.or(hub.remove(client.id))).await; Close::Protocol.on(&connection); return Err(error); } } if client .user_id() .is_some_and(|user_id| shared.services.stats.is_followed(user_id)) { let to = To::Conn(client.id); publish::direct(hub, vec![Broadcast::new(to, Event::StatsWanted(true))]); } tokio::spawn(relay_datagrams( connection.clone(), Arc::clone(&client), shared.clone(), )); while let Ok(streams) = connection.accept_bi().await { let route = route(Arc::clone(&client), streams, shared.clone()); tokio::spawn(async move { if let Err(error) = route.await { warn!("stream: {error}"); } }); } client.closed.store(true, Ordering::Release); let left = hub.remove(client.id); let departure = shared.services.rooms.leave(client.id); if let Some(user_id) = shared.services.stats.leave(client.id) { let to = To::User(user_id); publish::direct(hub, vec![Broadcast::new(to, Event::StatsWanted(false))]); } let session_id = client.me.as_ref().map(|me| me.session_id); let cleanup = publish::job(&shared, async |db| { let mut broadcasts = match departure { Some(departure) => call::shared::departed(departure, db).await?, None => Vec::new(), }; if let Some(user_id) = left { broadcasts.extend(call::shared::presence_changed(hub, user_id, db).await?); } if let Some(session_id) = session_id { db::session::seen(session_id, db).await?; } Ok(broadcasts) }) .await; if let Err(error) = cleanup { warn!("disconnect: {error}"); } Ok(()) } async fn greet(connection: &Connection, shared: &Shared) -> Result, ServerError> { let (send_stream, mut receive_stream) = connection.accept_bi().await?; let mut reply_stream = Sending::new(send_stream); let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?; let install = hello.install; match admit(hello, connection, shared).await { Ok(me) => { let (client, events) = Client::new(Some(connection.clone()), me, install); Ok(Some(Pending { client, events, reply_stream, })) } Err(error) => { let reply: Result = Err(error.into()); frame::write(&mut reply_stream, &reply, DOWN_MAX).await?; reply_stream.finish()?; let _ = tokio::time::timeout(HELLO_DEADLINE, connection.closed()).await; Ok(None) } } } async fn admit( hello: Hello, connection: &Connection, shared: &Shared, ) -> Result, ServerError> { let Some(token) = hello.token else { return Ok(None); }; let ip = connection.remote_address().ip().to_string(); let me = shared .db .run(async |db| { let (session_id, user) = authentication::resume(&token, db).await?; db::stats::mark_active(user.id, db).await?; db::user::set_last_ip(user.id, &ip, db).await?; let device = async { validate_device(&hello.device)?; db::session::set_device(session_id, &hello.device, db).await } .await; if let Err(error) = device { warn!("device: {error}"); } Ok(Signed { user_id: user.id, session_id, }) }) .await?; Ok(Some(me)) } async fn establish( client: &Client, connection: &Connection, reply_stream: Sending, events: mpsc::Receiver, shared: &Shared, ) -> Result { if !welcome(client, reply_stream, shared).await? { return Ok(false); } let send_stream = connection.open_uni().await?; tokio::spawn(write_events(events, send_stream, connection.clone())); Ok(true) } async fn welcome( client: &Client, mut reply_stream: Sending, shared: &Shared, ) -> Result { let checked = match &client.me { Some(me) => shared .db .run(async |db| authentication::recheck(me.session_id, db).await) .await .map(Some), None => Ok(None), }; let accepted = checked.is_ok(); let reply: Result = checked.map(|user| Welcome { user }).map_err(Into::into); frame::write(&mut reply_stream, &reply, DOWN_MAX).await?; reply_stream.finish()?; Ok(accepted) } async fn route( client: Arc, (send_stream, mut receive_stream): (SendStream, RecvStream), shared: Shared, ) -> Result<(), ServerError> { let send_stream = Sending::new(send_stream); let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; match open { Open::Call(request) => answer(client, *request, send_stream, shared).await, Open::Upload(upload) => { let user = signed_user(&client, &shared).await?; files::upload( user.as_ref(), upload, receive_stream, send_stream, &shared.db, &shared.attachments, ) .await } Open::Stage(stage) => { let user = signed_user(&client, &shared).await?; shared .releases .stage( user.as_ref(), stage, receive_stream, send_stream, &shared.db, ) .await } Open::Fetch(blob) => { let user = signed_user(&client, &shared).await?; files::fetch( user.as_ref(), blob, send_stream, &shared.db, &shared.attachments, &shared.backups, ) .await } } } async fn signed_user(client: &Client, shared: &Shared) -> Result, ServerError> { if client.me.is_none() { return Ok(None); } let user = shared .db .run(async |db| call::shared::authenticated(client, db).await) .await?; Ok(Some(user)) } async fn answer( client: Arc, request: Request, mut send_stream: Sending, shared: Shared, ) -> Result<(), ServerError> { let reply = match request { Request::Register(call) => { call::encode::(authentication::register(call, &client, &shared).await) } Request::Login(call) => { call::encode::(authentication::login(call, &client, &shared).await) } request => { let db = shared.db.lock().await?; let mut cx = Cx::new(&client, &shared, &db); let reply = call::dispatch(request, &mut cx).await; publish::publish(&shared, &db, std::mem::take(&mut cx.out)).await; reply } }; send_stream.get().write_all(&reply).await?; send_stream.finish()?; Ok(()) } async fn publish_presence(shared: &Shared, flipped: Option) { let Some(user_id) = flipped else { return; }; let hub = &shared.services.hub; if let Err(error) = publish::job(shared, async |db| { call::shared::presence_changed(hub, user_id, db).await }) .await { warn!("presence: {error}"); } } async fn relay_datagrams(connection: Connection, client: Arc, shared: Shared) { while let Ok(bytes) = connection.read_datagram().await { let broadcasts = shared.services.rooms.relay(&client, &bytes); publish::direct(&shared.services.hub, broadcasts); } } async fn write_events( mut events: mpsc::Receiver, send_stream: SendStream, connection: Connection, ) { let mut send_stream = Sending::new(send_stream); while let Some(bytes) = events.recv().await { if let Err(error) = send_stream.get().write_all(&bytes).await { warn!("event write: {error}"); Close::Protocol.on(&connection); return; } } }