diff --git a/crates/client/lang/en/settings_page.txt b/crates/client/lang/en/settings_page.txt index 259a949..01fb7ee 100644 --- a/crates/client/lang/en/settings_page.txt +++ b/crates/client/lang/en/settings_page.txt @@ -20,9 +20,6 @@ launch = Launch at login launch_off = Off launch_window = Window launch_tray = Tray -updates = Updates -updates_off = Off -updates_auto = Automatic your_hue = Your hue camera = Camera screen_share = Screen share diff --git a/crates/client/lang/tr/settings_page.txt b/crates/client/lang/tr/settings_page.txt index f255985..2ce7538 100644 --- a/crates/client/lang/tr/settings_page.txt +++ b/crates/client/lang/tr/settings_page.txt @@ -20,9 +20,6 @@ launch = Oturum açılınca launch_off = Kapalı launch_window = Pencere launch_tray = Tepsi -updates = Güncellemeler -updates_off = Kapalı -updates_auto = Otomatik your_hue = Rengin camera = Kamera screen_share = Ekran paylaşımı diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 3d8c939..d616da8 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -799,7 +799,7 @@ impl Chat { followed.1 = stats; } } - Event::ReportCreated | Event::SettingsUpdated(_) => {} + Event::ReportCreated | Event::SettingsUpdated(_) | Event::Release => {} } } diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 0757883..37ce990 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -25,7 +25,7 @@ use super::{ }; use crate::{ gui::style::{self, Theme, radius, size, space, stroke, text}, - settings::{self, FontSize, Launch, ShareAudio, ShareCodec, Updates}, + settings::{self, FontSize, Launch, ShareAudio, ShareCodec}, share::encode::capabilities, }; @@ -42,7 +42,7 @@ pub(super) fn settings_titles() -> [&'static str; 5] { ] } -pub(super) fn setting_rows() -> [(usize, &'static str); 26] { +pub(super) fn setting_rows() -> [(usize, &'static str); 25] { let s = &w().settings_page; let v = &w().voice_settings; [ @@ -69,7 +69,6 @@ pub(super) fn setting_rows() -> [(usize, &'static str); 26] { (3, s.language), (3, s.close_to_tray), (3, s.launch), - (3, s.updates), (3, s.clock_seconds), (3, s.your_hue), ] @@ -222,16 +221,6 @@ impl Yumush { Yumush::set_launch, ), ), - row( - w().settings_page.updates, - segmented( - Updates::options().map(|updates| (updates, updates.label())), - self.settings.updates, - entity, - palette, - Yumush::set_updates, - ), - ), row( w().settings_page.clock_seconds, super::parts::toggle( @@ -399,11 +388,6 @@ impl Yumush { self.commit_settings(cx); } - pub(super) fn set_updates(&mut self, updates: Updates, cx: &mut Context) { - self.settings.updates = updates; - self.commit_settings(cx); - } - pub(super) fn toggle_clock_seconds(&mut self, cx: &mut Context) { self.settings.clock_seconds = !self.settings.clock_seconds; self.commit_settings(cx); diff --git a/crates/client/src/net/events.rs b/crates/client/src/net/events.rs index ef2c6ec..6cbe68f 100644 --- a/crates/client/src/net/events.rs +++ b/crates/client/src/net/events.rs @@ -17,6 +17,9 @@ pub(super) async fn event_receive_loop( while let Ok(down) = frame::read::(&mut receive_stream, DOWN_MAX).await { match down { + Down::Event(event) if matches!(*event, common::event::Event::Release) => { + crate::update::poke(); + } Down::Event(event) => { media.pushed(&event); if event_sender diff --git a/crates/client/src/net/fail.rs b/crates/client/src/net/fail.rs index b89d142..40267e8 100644 --- a/crates/client/src/net/fail.rs +++ b/crates/client/src/net/fail.rs @@ -27,6 +27,10 @@ impl std::fmt::Display for LinkError { } impl LinkError { + pub(super) fn terminal(self) -> bool { + matches!(self, Self::Outdated | Self::Closed(Close::Banned)) + } + fn by_code(code: u64) -> Self { match code { NO_APPLICATION_PROTOCOL => Self::Outdated, @@ -44,9 +48,11 @@ impl From for LinkError { 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::ApplicationClosed(close) => match Close::of(close.error_code) { + Some(Close::Outdated) => Self::Outdated, + Some(close) => Self::Closed(close), + None => Self::Reset, + }, quinn::ConnectionError::LocallyClosed => Self::Closed(Close::Normal), quinn::ConnectionError::VersionMismatch => Self::Outdated, quinn::ConnectionError::Reset | quinn::ConnectionError::CidsExhausted => Self::Reset, diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index e03d406..00e956c 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -110,11 +110,19 @@ async fn backoff(attempt: &mut u32) { *attempt += 1; } -pub(crate) async fn dial( +pub(crate) async fn dial( server: &crate::Server, alpn: &[u8], -) -> Result { - connect(server, &mut Endpoints::default(), alpn).await + work: impl AsyncFnOnce(&quinn::Connection) -> T, +) -> Result { + let mut endpoints = Endpoints::default(); + let connection = connect(server, &mut endpoints, alpn).await?; + let done = work(&connection).await; + connection.close(0u32.into(), b""); + for endpoint in [endpoints.v4, endpoints.v6].into_iter().flatten() { + endpoint.wait_idle().await; + } + Ok(done) } async fn connect( @@ -271,6 +279,7 @@ async fn hello(connection: &quinn::Connection, token: Option) -> Result< let hello = Hello { token, device: device_name(), + release: crate::update::SEQ, }; Ok(exchange(connection, &hello).await?.0) @@ -402,6 +411,7 @@ async fn actor( Ok(connection) => break connection, Err(LinkError::Outdated) => { warn!("server speaks another protocol version"); + crate::update::outdated(); let _ = event_sender .send(NetworkEvent::Disconnected(LinkError::Outdated)) .await; @@ -455,12 +465,15 @@ async fn actor( } Err(error) => { warn!("hello failed: {error}"); - if connection.close_reason().map(LinkError::from) - == Some(LinkError::Closed(Close::Banned)) + if let Some(reason) = connection + .close_reason() + .map(LinkError::from) + .filter(|reason| reason.terminal()) { - let _ = event_sender - .send(NetworkEvent::Disconnected(LinkError::Closed(Close::Banned))) - .await; + if reason == LinkError::Outdated { + crate::update::outdated(); + } + let _ = event_sender.send(NetworkEvent::Disconnected(reason)).await; while command_receiver.recv().await.is_some() {} return; } @@ -471,6 +484,7 @@ async fn actor( attempt = 0; info!("connected"); + crate::update::poke(); shared.media.ready(connection.clone(), event_sender.clone()); if event_sender.send(NetworkEvent::Connected).await.is_err() { return; @@ -536,13 +550,16 @@ async fn actor( shared.media.lost(); let event = LinkError::from(error); - let banned = event == LinkError::Closed(Close::Banned); + let terminal = event.terminal(); + if event == LinkError::Outdated { + crate::update::outdated(); + } if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() { return; } - if banned { + if terminal { while command_receiver.recv().await.is_some() {} return; } diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index c2d63db..0c81538 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -90,27 +90,6 @@ impl Launch { } } -string_enum! { - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - Updates { - Off => "off", - Auto => "auto", - } -} - -impl Updates { - pub fn options() -> impl Iterator { - Self::ALL.into_iter() - } - - pub fn label(self) -> &'static str { - match self { - Updates::Off => w().settings_page.updates_off, - Updates::Auto => w().settings_page.updates_auto, - } - } -} - string_enum! { #[derive(Debug, Clone, Copy, PartialEq, Eq)] Activation { @@ -242,7 +221,6 @@ pub struct Settings { pub share: ShareSettings, pub close_to_tray: bool, pub launch: Launch, - pub updates: Updates, pub clock_seconds: bool, pub jump_usage: BTreeMap, pub last_chats: BTreeMap, @@ -272,7 +250,6 @@ impl Default for Settings { } else { Launch::Window }, - updates: Updates::Auto, clock_seconds: false, jump_usage: BTreeMap::new(), last_chats: BTreeMap::new(), @@ -391,9 +368,6 @@ pub fn load() -> Settings { .and_then(|value| Launch::parse(&value)) .filter(|launch| Launch::options().any(|option| option == *launch)) .unwrap_or(defaults.launch), - updates: text("updates") - .and_then(|value| Updates::parse(&value)) - .unwrap_or(defaults.updates), clock_seconds: text("clock_seconds") .map_or(defaults.clock_seconds, |value| value == "true"), jump_usage: text("jump.usage") @@ -436,7 +410,6 @@ pub fn save(settings: &Settings) { line("language", settings.language.as_str()), line("close_to_tray", settings.close_to_tray), line("launch", settings.launch.as_str()), - line("updates", settings.updates.as_str()), line("clock_seconds", settings.clock_seconds), line("voice.sensitivity", voice.sensitivity_db), line("voice.input_volume", voice.input_volume), diff --git a/crates/client/src/update.rs b/crates/client/src/update.rs index 05492d3..235a30f 100644 --- a/crates/client/src/update.rs +++ b/crates/client/src/update.rs @@ -3,20 +3,31 @@ use std::{ io::{Read, Write}, path::{Path, PathBuf}, process::{Command, Stdio}, + sync::{ + OnceLock, + atomic::{AtomicBool, Ordering}, + mpsc, + }, time::{Duration, Instant}, }; -use common::update::{self as wire, FILE_MAX, MANIFEST, MANIFEST_MAX}; -use ring::{digest, signature}; +use common::update::{self as wire, MANIFEST, MANIFEST_MAX}; +use ring::{ + digest, + rand::{SecureRandom, SystemRandom}, + signature, +}; use tracing::{info, warn}; mod keys; pub const SELFTEST: &str = "--selftest"; -const MAGIC: &str = "yumush-update 1"; -const SIGNATURE_BYTES: usize = 64; -const FIRST_CHECK: Duration = Duration::from_secs(60); -const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60); +const AFTER: &str = "--after"; +const FIRST_CHECK: Duration = Duration::from_secs(5); +const POKE_SPREAD: Duration = Duration::from_secs(20); +const RETRY_FIRST: Duration = Duration::from_secs(30); +const RETRY_LAST: Duration = Duration::from_secs(30 * 60); +const PARENT_LIMIT: Duration = Duration::from_secs(30); const SELFTEST_LIMIT: Duration = Duration::from_secs(20); const PACKAGED_ENV: [&str; 3] = ["FLATPAK_ID", "SNAP", "APPIMAGE"]; const PACKAGED_ROOTS: [&str; 2] = ["/usr/", "/nix/"]; @@ -48,7 +59,6 @@ const fn parse_seq(text: &str) -> u64 { #[derive(Debug)] enum Off { Unofficial, - Platform, Multi, Packaged, NoExe, @@ -74,19 +84,35 @@ enum Reject { Target, } -enum Check { +enum Outcome { Current, Staged(u64), + Restart, } #[derive(Debug, PartialEq)] struct Release { seq: u64, + minimum: u64, version: String, size: u64, sha256: [u8; 32], } +static POKE: OnceLock> = OnceLock::new(); +static OUTDATED: AtomicBool = AtomicBool::new(false); + +pub fn poke() { + if let Some(sender) = POKE.get() { + let _ = sender.send(()); + } +} + +pub fn outdated() { + OUTDATED.store(true, Ordering::Relaxed); + poke(); +} + impl From for Fail { fn from(error: std::io::Error) -> Self { Self::Io(error) @@ -107,9 +133,6 @@ impl From for Fail { fn mode() -> Result<(u64, &'static Path), Off> { let seq = SEQ.ok_or(Off::Unofficial)?; - if cfg!(target_os = "macos") { - return Err(Off::Platform); - } if std::env::args().any(|arg| arg == crate::instance::MULTI) { return Err(Off::Multi); } @@ -205,7 +228,19 @@ pub fn selftest() -> bool { true } +fn wait_parent() { + let mut args = std::env::args().skip_while(|arg| arg != AFTER).skip(1); + let Some(pid) = args.next().and_then(|pid| pid.parse::().ok()) else { + return; + }; + let started = Instant::now(); + while alive(pid) && started.elapsed() < PARENT_LIMIT { + std::thread::sleep(Duration::from_millis(100)); + } +} + pub fn boot() -> bool { + wait_parent(); let Ok((seq, exe)) = mode() else { return false; }; @@ -296,31 +331,88 @@ pub fn ready() { let _ = fs::remove_file(state(exe, "trial")); info!("update: {seq} is healthy"); } + let (sender, receiver) = mpsc::channel(); + if POKE.set(sender).is_err() { + return; + } let _ = std::thread::Builder::new() .name("update".to_string()) - .spawn(move || watch(seq, exe)); + .spawn(move || watch(seq, exe, receiver)); } -fn watch(seq: u64, exe: &'static Path) { +fn spread(limit: Duration) -> Duration { + let mut bytes = [0u8; 4]; + let _ = SystemRandom::new().fill(&mut bytes); + limit.mul_f64(f64::from(u32::from_le_bytes(bytes)) / f64::from(u32::MAX)) +} + +fn watch(running: u64, exe: &'static Path, pokes: mpsc::Receiver<()>) { let Ok(runtime) = tokio::runtime::Builder::new_current_thread() .enable_all() .build() else { return; }; - std::thread::sleep(FIRST_CHECK); + let mut installed = running; + let mut retry = RETRY_FIRST; + let mut wait = Some(FIRST_CHECK); loop { - if crate::settings::load().updates != crate::settings::Updates::Off { - match runtime.block_on(check(seq, exe)) { - Ok(Check::Staged(next)) => { - info!("update: {next} staged, applies on restart"); - return; - } - Ok(Check::Current) => {} - Err(fail) => warn!("update: {fail:?}"), + let woke = match wait { + Some(wait) => pokes + .recv_timeout(wait) + .map_err(|error| error == mpsc::RecvTimeoutError::Disconnected), + None => pokes.recv().map_err(|_| true), + }; + if woke == Err(true) { + return; + } + if woke.is_ok() && !OUTDATED.load(Ordering::Relaxed) { + std::thread::sleep(spread(POKE_SPREAD)); + } + while pokes.try_recv().is_ok() {} + match runtime.block_on(check(running, installed, exe)) { + Ok(Outcome::Current) => { + retry = RETRY_FIRST; + wait = None; + } + Ok(Outcome::Staged(next)) => { + info!("update: {next} staged, applies on restart"); + installed = next; + retry = RETRY_FIRST; + wait = None; } + Ok(Outcome::Restart) => restart(exe), + Err(fail) => { + warn!("update: {fail:?}"); + wait = Some(retry / 2 + spread(retry / 2)); + retry = (retry * 2).min(RETRY_LAST); + } + } + } +} + +fn restart(exe: &Path) { + info!("update: required, restarting"); + let mut args: Vec = Vec::new(); + let mut skip = false; + for arg in std::env::args_os().skip(1) { + if std::mem::take(&mut skip) { + continue; } - std::thread::sleep(CHECK_EVERY); + if arg == AFTER { + skip = true; + continue; + } + args.push(arg); + } + let spawned = Command::new(exe) + .args(args) + .arg(AFTER) + .arg(std::process::id().to_string()) + .spawn(); + match spawned { + Ok(_) => std::process::exit(0), + Err(error) => warn!("update: restart {error}"), } } @@ -330,28 +422,32 @@ async fn fetch(connection: &quinn::Connection, name: &str, maximum: u64) -> Resu Ok(wire::receive(&mut receive, maximum).await?) } -async fn check(seq: u64, exe: &Path) -> Result { - let connection = crate::net::dial(&crate::Server::load(), wire::ALPN) - .await - .map_err(Fail::Link)?; - let checked = fetch_release(&connection, seq, exe).await; - connection.close(0u32.into(), b""); - let Some((release, file, bytes)) = checked? else { - return Ok(Check::Current); - }; - stage(exe, file, &bytes, release.seq)?; - Ok(Check::Staged(release.seq)) +async fn check(running: u64, installed: u64, exe: &Path) -> Result { + crate::net::dial(&crate::Server::load(), wire::ALPN, async |connection| { + fetch_release(connection, running, installed, exe).await + }) + .await + .map_err(Fail::Link)? } async fn fetch_release( connection: &quinn::Connection, - seq: u64, + running: u64, + installed: u64, exe: &Path, -) -> Result)>, Fail> { +) -> Result { let manifest = fetch(connection, MANIFEST, MANIFEST_MAX).await?; let release = verify(&manifest, &target(), keys::KEYS).map_err(Fail::Reject)?; - if release.seq <= seq || number(&state(exe, "skip")) == Some(release.seq) { - return Ok(None); + let required = running < release.minimum || OUTDATED.load(Ordering::Relaxed); + if release.seq <= installed { + return Ok(if required && installed > running { + Outcome::Restart + } else { + Outcome::Current + }); + } + if number(&state(exe, "skip")) == Some(release.seq) { + return Ok(Outcome::Current); } let file = open_new(exe)?; info!("update: downloading {} ({})", release.version, release.seq); @@ -365,13 +461,16 @@ async fn fetch_release( let _ = fs::remove_file(sibling(exe, "new")); return Err(Fail::Hash); } - Ok(Some((release, file, bytes))) + stage(exe, file, &bytes, release.seq)?; + Ok(if required { + Outcome::Restart + } else { + Outcome::Staged(release.seq) + }) } fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result { - let (sig, body) = signed - .split_at_checked(SIGNATURE_BYTES) - .ok_or(Reject::Short)?; + let (sig, body) = wire::split(signed).ok_or(Reject::Short)?; let signed_by_us = keys.iter().any(|key| { signature::UnparsedPublicKey::new(&signature::ED25519, key) .verify(body, sig) @@ -380,74 +479,17 @@ fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result().ok()) - .ok_or(Reject::Format)?; - let version = field(lines.next(), "version") - .filter(|value| !value.is_empty()) - .ok_or(Reject::Format)? - .to_string(); - let mut found = None; - let mut seen = Vec::new(); - for line in lines { - if line.is_empty() { - continue; - } - let mut parts = line.split(' '); - let (Some(name), Some(size), Some(hash), None) = - (parts.next(), parts.next(), parts.next(), parts.next()) - else { - return Err(Reject::Format); - }; - if !wire::valid_name(name) || name == MANIFEST || seen.contains(&name) { - return Err(Reject::Format); - } - seen.push(name); - let size = size - .parse::() - .ok() - .filter(|size| (1..=FILE_MAX).contains(size)) - .ok_or(Reject::Format)?; - let sha256 = hex32(hash).ok_or(Reject::Format)?; - if name == target { - found = Some((size, sha256)); - } - } - let (size, sha256) = found.ok_or(Reject::Target)?; + let manifest = wire::parse(body).ok_or(Reject::Format)?; + let file = manifest.file(target).ok_or(Reject::Target)?; Ok(Release { - seq, - version, - size, - sha256, + seq: manifest.seq, + minimum: manifest.minimum, + version: manifest.version.clone(), + size: file.size, + sha256: file.sha256, }) } -fn field<'a>(line: Option<&'a str>, key: &str) -> Option<&'a str> { - line?.strip_prefix(key)?.strip_prefix(' ') -} - -fn hex32(text: &str) -> Option<[u8; 32]> { - let bytes = text.as_bytes(); - if bytes.len() != 64 { - return None; - } - let mut out = [0u8; 32]; - for (index, pair) in bytes.chunks(2).enumerate() { - let digit = |byte: u8| match byte { - b'0'..=b'9' => Some(byte - b'0'), - b'a'..=b'f' => Some(byte - b'a' + 10), - _ => None, - }; - out[index] = digit(pair[0])? << 4 | digit(pair[1])?; - } - Some(out) -} - fn open_new(exe: &Path) -> std::io::Result { let new = sibling(exe, "new"); let _ = fs::remove_file(&new); @@ -539,6 +581,8 @@ mod tests { signature::{Ed25519KeyPair, KeyPair}, }; + use common::update::MAGIC; + use super::*; fn signed(key: &Ed25519KeyPair, body: &str) -> Vec { @@ -560,12 +604,17 @@ mod tests { fn verifies() { let (key, public) = pair(); let body = format!( - "{MAGIC}\nseq 7\nversion 0.2.0\nx86_64-linux 10 {HASH}\nx86_64-windows 20 {HASH}\n" + "{MAGIC}\nseq 7\nminimum 3\nversion 0.2.0\nx86_64-linux 10 {HASH}\nx86_64-windows 20 {HASH}\n" ); let release = verify(&signed(&key, &body), "x86_64-windows", &[public]).unwrap(); assert_eq!( - (release.seq, release.size, release.sha256[1]), - (7, 20, 0x11) + ( + release.seq, + release.minimum, + release.size, + release.sha256[1] + ), + (7, 3, 20, 0x11) ); } @@ -573,7 +622,7 @@ mod tests { fn rejects() { let (key, public) = pair(); let (other, _) = pair(); - let good = format!("{MAGIC}\nseq 7\nversion 1\nx86_64-linux 10 {HASH}\n"); + let good = format!("{MAGIC}\nseq 7\nminimum 7\nversion 1\nx86_64-linux 10 {HASH}\n"); let mut tampered = signed(&key, &good); *tampered.last_mut().unwrap() ^= 1; let cases = [ @@ -586,6 +635,9 @@ mod tests { signed(&key, &good.replace("seq 7", "seq x")), signed(&key, &good.replace(MAGIC, "yumush-update 2")), signed(&key, &format!("{good}manifest 10 {HASH}\n")), + signed(&key, &good.replace("minimum 7", "minimum 8")), + signed(&key, &good.replace("minimum 7", "minimum 0")), + signed(&key, &good.replace("minimum 7\n", "")), ]; for case in cases { assert!(verify(&case, "x86_64-linux", &[public]).is_err()); diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs index 18a4e67..6ef8591 100644 --- a/crates/common/src/event.rs +++ b/crates/common/src/event.rs @@ -86,6 +86,7 @@ pub enum Event { user_id: Id, stats: Stats, }, + Release, } #[derive(Debug, Clone, Encode, Decode)] diff --git a/crates/common/src/session.rs b/crates/common/src/session.rs index 427cf32..9552f53 100644 --- a/crates/common/src/session.rs +++ b/crates/common/src/session.rs @@ -6,6 +6,7 @@ use crate::model::User; pub struct Hello { pub token: Option, pub device: String, + pub release: Option, } #[derive(Debug, Clone, Encode, Decode)] diff --git a/crates/common/src/transport.rs b/crates/common/src/transport.rs index 2df3166..66bdac6 100644 --- a/crates/common/src/transport.rs +++ b/crates/common/src/transport.rs @@ -3,7 +3,7 @@ use std::{io, net::SocketAddr, sync::Arc, time::Duration}; use quinn::{Endpoint, EndpointConfig, ServerConfig, TokioRuntime, TransportConfig, VarInt}; use socket2::{Domain, Protocol, Socket, Type}; -pub const ALPN: &[u8] = b"yumush/2"; +pub const ALPN: &[u8] = b"yumush/3"; const IDLE_TIMEOUT: Duration = Duration::from_secs(10); pub const KEEP_ALIVE: Duration = Duration::from_secs(1); @@ -43,10 +43,11 @@ pub enum Close { Maintenance = 4, Slow = 5, Protocol = 6, + Outdated = 7, } impl Close { - pub const ALL: [Self; 7] = [ + pub const ALL: [Self; 8] = [ Self::Normal, Self::SignedOut, Self::Revoked, @@ -54,6 +55,7 @@ impl Close { Self::Maintenance, Self::Slow, Self::Protocol, + Self::Outdated, ]; pub fn of(code: VarInt) -> Option { @@ -69,6 +71,7 @@ impl Close { Self::Maintenance => "maintenance", Self::Slow => "slow", Self::Protocol => "protocol error", + Self::Outdated => "outdated", } } diff --git a/crates/common/src/update.rs b/crates/common/src/update.rs index 4a8a948..38120af 100644 --- a/crates/common/src/update.rs +++ b/crates/common/src/update.rs @@ -81,3 +81,95 @@ pub async fn receive(receive: &mut RecvStream, maximum: u64) -> Result, } Ok(bytes) } + +pub const MAGIC: &str = "yumush-update 1"; +pub const SIGNATURE_BYTES: usize = 64; + +#[derive(Debug, PartialEq, Eq)] +pub struct Manifest { + pub seq: u64, + pub minimum: u64, + pub version: String, + pub files: Vec, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct File { + pub name: String, + pub size: u64, + pub sha256: [u8; 32], +} + +impl Manifest { + pub fn file(&self, name: &str) -> Option<&File> { + self.files.iter().find(|file| file.name == name) + } +} + +pub fn split(signed: &[u8]) -> Option<(&[u8], &[u8])> { + signed.split_at_checked(SIGNATURE_BYTES) +} + +pub fn parse(body: &[u8]) -> Option { + let text = std::str::from_utf8(body).ok()?; + let mut lines = text.split('\n'); + if lines.next() != Some(MAGIC) { + return None; + } + let seq = number(lines.next(), "seq")?; + let minimum = number(lines.next(), "minimum").filter(|minimum| *minimum <= seq)?; + let version = field(lines.next(), "version") + .filter(|value| !value.is_empty())? + .to_string(); + let mut files: Vec = Vec::new(); + for line in lines.filter(|line| !line.is_empty()) { + let mut parts = line.split(' '); + let (Some(name), Some(size), Some(hash), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return None; + }; + if !valid_name(name) || name == MANIFEST || files.iter().any(|file| file.name == name) { + return None; + } + files.push(File { + name: name.to_string(), + size: size + .parse() + .ok() + .filter(|size| (1..=FILE_MAX).contains(size))?, + sha256: hex32(hash)?, + }); + } + Some(Manifest { + seq, + minimum, + version, + files, + }) +} + +fn field<'a>(line: Option<&'a str>, key: &str) -> Option<&'a str> { + line?.strip_prefix(key)?.strip_prefix(' ') +} + +fn number(line: Option<&str>, key: &str) -> Option { + field(line, key)?.parse().ok().filter(|value| *value > 0) +} + +fn hex32(text: &str) -> Option<[u8; 32]> { + let bytes = text.as_bytes(); + if bytes.len() != 64 { + return None; + } + let digit = |byte: u8| match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + _ => None, + }; + let mut out = [0u8; 32]; + for (index, pair) in bytes.chunks(2).enumerate() { + out[index] = digit(pair[0])? << 4 | digit(pair[1])?; + } + Some(out) +} diff --git a/crates/server/src/hub.rs b/crates/server/src/hub.rs index 4af1483..8fb995a 100644 --- a/crates/server/src/hub.rs +++ b/crates/server/src/hub.rs @@ -29,6 +29,7 @@ pub struct Client { pub me: Option, tx: mpsc::Sender, pub closed: AtomicBool, + pub release: AtomicU64, watching: Mutex>, ghost_logged: Mutex>, } @@ -42,6 +43,7 @@ impl Client { me, tx, closed: AtomicBool::new(false), + release: AtomicU64::new(u64::MAX), watching: Mutex::new(None), ghost_logged: Mutex::new(HashSet::new()), }); @@ -192,6 +194,20 @@ impl Hub { } } + pub fn kick_outdated(&self, minimum: u64) { + let targets: Vec> = self + .0 + .lock() + .unwrap() + .values() + .filter(|client| client.release.load(Ordering::Relaxed) < minimum) + .cloned() + .collect(); + for client in targets { + client.close(Close::Outdated); + } + } + pub fn kick_user(&self, user_id: Id, close: Close) { self.kick_where(|me| me.user_id == user_id, close); } diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index 0c1465f..3ffaf86 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -40,6 +40,7 @@ pub struct Services { pub rate_limit: RateLimit, pub stats: Follows, pub machine: Machine, + pub minimum: std::sync::Arc, } #[derive(Clone)] @@ -83,6 +84,7 @@ pub async fn serve( shared.services.machine.watch(shared.directory.clone()); tokio::spawn(retention::collect(shared.clone())); + tokio::spawn(crate::update::watch(shared.clone())); while let Some(incoming) = endpoint.accept().await { tokio::spawn(handle_connection(incoming, shared.clone())); @@ -230,10 +232,16 @@ async fn greet(connection: &Connection, shared: &Shared) -> Result { let (client, events) = Client::new(Some(connection.clone()), me); + client.release.store(release, Ordering::Relaxed); Ok(Some(Pending { client, diff --git a/crates/server/src/update.rs b/crates/server/src/update.rs index 81ae46d..8f90cc6 100644 --- a/crates/server/src/update.rs +++ b/crates/server/src/update.rs @@ -1,5 +1,5 @@ use std::{ - collections::HashSet, + collections::HashMap, net::IpAddr, path::{Path, PathBuf}, sync::Mutex, @@ -11,30 +11,42 @@ use quinn::{Connection, RecvStream, SendStream}; use tokio::{io::AsyncReadExt, sync::Semaphore, time::timeout}; use tracing::warn; -use crate::error::ServerError; +use crate::{error::ServerError, network::Shared}; const STREAMS: usize = 4; const ACCEPT_DEADLINE: Duration = Duration::from_secs(30); const ASK_DEADLINE: Duration = Duration::from_secs(5); const TRANSFER_DEADLINE: Duration = Duration::from_secs(15 * 60); const STALL_DEADLINE: Duration = Duration::from_secs(30); +const WATCH_EVERY: Duration = Duration::from_secs(5); const CHUNK: usize = 64 << 10; static PERMITS: Semaphore = Semaphore::const_new(16); -static PEERS: Mutex>> = Mutex::new(None); +const PER_PEER: u8 = 4; +static PEERS: Mutex>> = Mutex::new(None); struct Peer(IpAddr); impl Peer { fn claim(ip: IpAddr) -> Option { let mut peers = PEERS.lock().unwrap(); - peers.get_or_insert_default().insert(ip).then_some(Self(ip)) + let count = peers.get_or_insert_default().entry(ip).or_default(); + if *count >= PER_PEER { + return None; + } + *count += 1; + Some(Self(ip)) } } impl Drop for Peer { fn drop(&mut self) { - if let Some(peers) = PEERS.lock().unwrap().as_mut() { - peers.remove(&self.0); + if let Some(peers) = PEERS.lock().unwrap().as_mut() + && let Some(count) = peers.get_mut(&self.0) + { + *count -= 1; + if *count == 0 { + peers.remove(&self.0); + } } } } @@ -106,3 +118,50 @@ async fn transfer( Ok(()) } + +pub(crate) async fn watch(shared: Shared) { + let path = shared.updates.join(MANIFEST); + let mut seen = None; + let mut seq = None; + let mut interval = tokio::time::interval(WATCH_EVERY); + loop { + interval.tick().await; + let stamp = tokio::fs::metadata(&path) + .await + .ok() + .map(|metadata| (metadata.modified().ok(), metadata.len())); + if stamp == seen { + continue; + } + seen = stamp; + let manifest = tokio::fs::read(&path).await.ok().and_then(|signed| { + let (_, body) = update::split(&signed)?; + update::parse(body) + }); + let Some(manifest) = manifest else { + continue; + }; + shared + .services + .minimum + .store(manifest.minimum, std::sync::atomic::Ordering::Relaxed); + shared.services.hub.kick_outdated(manifest.minimum); + if seq + .replace(manifest.seq) + .is_some_and(|old| old != manifest.seq) + { + announce(&shared); + } + } +} + +fn announce(shared: &Shared) { + let down = common::event::Down::Event(Box::new(common::event::Event::Release)); + match common::frame::encode(&down, common::frame::DOWN_MAX) { + Ok(bytes) => { + let hub = &shared.services.hub; + hub.send(&hub.all(), &bytes.into(), true); + } + Err(error) => warn!("update: announce {error}"), + } +} diff --git a/packaging/release.sh b/packaging/release.sh index 1d382bf..fde3cc0 100755 --- a/packaging/release.sh +++ b/packaging/release.sh @@ -4,7 +4,7 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)" KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}" cd "$ROOT" usage() { - echo "usage: $0 build | sign [primary|backup]" >&2 + echo "usage: $0 build | sign (minimum = oldest seq still allowed; = seq forces everyone up)" >&2 exit 1 } [[ $# -ge 2 && "$2" =~ ^[1-9][0-9]{0,17}$ ]] || usage @@ -27,11 +27,13 @@ build) echo "$DIST/$TARGET" ;; sign) - KEY="$KEYS/${3:-primary}.pem" + [[ $# -ge 3 && "$3" =~ ^[1-9][0-9]{0,17}$ ]] && (( $3 <= SEQ )) || usage + MINIMUM="$3" + KEY="$KEYS/${YUMUSH_SIGNING_KEY:-primary}.pem" VERSION=$(cargo pkgid -p client | sed 's/.*[#@]//') BODY="$DIST/manifest.body" { - printf 'yumush-update 1\nseq %s\nversion %s\n' "$SEQ" "$VERSION" + printf 'yumush-update 1\nseq %s\nminimum %s\nversion %s\n' "$SEQ" "$MINIMUM" "$VERSION" for file in "$DIST"/*; do name=$(basename "$file") [[ "$name" =~ ^[a-z0-9_]+-[a-z0-9_]+$ ]] || continue @@ -44,7 +46,7 @@ sign) printf '%s %s %s\n' "$name" "$(stat -c %s "$file")" "$(sha256sum "$file" | cut -d' ' -f1)" done } > "$BODY" - grep -q ' ' <(tail -n +4 "$BODY") || { echo "no binaries in $DIST" >&2; exit 1; } + grep -q ' ' <(tail -n +5 "$BODY") || { echo "no binaries in $DIST" >&2; exit 1; } cat "$BODY" SIG=$(mktemp) PUBLIC=$(mktemp)