forge
Explore
Log in

Don't you dare go Hollow

Push-driven, enforceable updates. Server watches updates/manifest and pushes Event::Release

Browse files at this commit

debc8fb584664b58ad95ca040aeacbfcd98e3af3Ahmet Kaan GümüşParent: 5e74ca5
  • feat
    • push-driven, enforceable updates. Server watches updates/manifest and pushes Event::Release
    • clients check at start, on connect and on Outdated (no polling, backoff only on failure). Signed manifest carries a minimum seq: server turns away and kicks clients below it (Close::Outdated, release seq in Hello), and such clients download and restart themselves at once. macOS updates too
    • no Updates setting. Fix: server per-IP guard self-deadlocked on a second connection from one IP
    • client now flushes its close before dropping the endpoint
Show full message
✨ feat: push-driven, enforceable updates. Server watches updates/manifest and pushes Event::Release; clients check at start, on connect and on Outdated (no polling, backoff only on failure). Signed manifest carries a minimum seq: server turns away and kicks clients below it (Close::Outdated, release seq in Hello), and such clients download and restart themselves at once. macOS updates too; no Updates setting. Fix: server per-IP guard self-deadlocked on a second connection from one IP; client now flushes its close before dropping the endpoint
crates/client/lang/en/settings_page.txtmodified+0 -3
@@ -20,9 +20,6 @@ launch = Launch at login
2020 launch_off = Off
2121 launch_window = Window
2222 launch_tray = Tray
23-updates = Updates
24-updates_off = Off
25-updates_auto = Automatic
2623 your_hue = Your hue
2724 camera = Camera
2825 screen_share = Screen share
crates/client/lang/tr/settings_page.txtmodified+0 -3
@@ -20,9 +20,6 @@ launch = Oturum açılınca
2020 launch_off = Kapalı
2121 launch_window = Pencere
2222 launch_tray = Tepsi
23-updates = Güncellemeler
24-updates_off = Kapalı
25-updates_auto = Otomatik
2623 your_hue = Rengin
2724 camera = Kamera
2825 screen_share = Ekran paylaşımı
crates/client/src/gui/chat.rsmodified+1 -1
@@ -799,7 +799,7 @@ impl Chat {
799799 followed.1 = stats;
800800 }
801801 }
802- Event::ReportCreated | Event::SettingsUpdated(_) => {}
802+ Event::ReportCreated | Event::SettingsUpdated(_) | Event::Release => {}
803803 }
804804 }
805805
crates/client/src/gui/settings_page.rsmodified+2 -18
@@ -25,7 +25,7 @@ use super::{
2525 };
2626 use crate::{
2727 gui::style::{self, Theme, radius, size, space, stroke, text},
28- settings::{self, FontSize, Launch, ShareAudio, ShareCodec, Updates},
28+ settings::{self, FontSize, Launch, ShareAudio, ShareCodec},
2929 share::encode::capabilities,
3030 };
3131
@@ -42,7 +42,7 @@ pub(super) fn settings_titles() -> [&'static str; 5] {
4242 ]
4343 }
4444
45-pub(super) fn setting_rows() -> [(usize, &'static str); 26] {
45+pub(super) fn setting_rows() -> [(usize, &'static str); 25] {
4646 let s = &w().settings_page;
4747 let v = &w().voice_settings;
4848 [
@@ -69,7 +69,6 @@ pub(super) fn setting_rows() -> [(usize, &'static str); 26] {
6969 (3, s.language),
7070 (3, s.close_to_tray),
7171 (3, s.launch),
72- (3, s.updates),
7372 (3, s.clock_seconds),
7473 (3, s.your_hue),
7574 ]
@@ -222,16 +221,6 @@ impl Yumush {
222221 Yumush::set_launch,
223222 ),
224223 ),
225- row(
226- w().settings_page.updates,
227- segmented(
228- Updates::options().map(|updates| (updates, updates.label())),
229- self.settings.updates,
230- entity,
231- palette,
232- Yumush::set_updates,
233- ),
234- ),
235224 row(
236225 w().settings_page.clock_seconds,
237226 super::parts::toggle(
@@ -399,11 +388,6 @@ impl Yumush {
399388 self.commit_settings(cx);
400389 }
401390
402- pub(super) fn set_updates(&mut self, updates: Updates, cx: &mut Context<Self>) {
403- self.settings.updates = updates;
404- self.commit_settings(cx);
405- }
406-
407391 pub(super) fn toggle_clock_seconds(&mut self, cx: &mut Context<Self>) {
408392 self.settings.clock_seconds = !self.settings.clock_seconds;
409393 self.commit_settings(cx);
crates/client/src/net/events.rsmodified+3 -0
@@ -17,6 +17,9 @@ pub(super) async fn event_receive_loop(
1717
1818 while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await {
1919 match down {
20+ Down::Event(event) if matches!(*event, common::event::Event::Release) => {
21+ crate::update::poke();
22+ }
2023 Down::Event(event) => {
2124 media.pushed(&event);
2225 if event_sender
crates/client/src/net/fail.rsmodified+9 -3
@@ -27,6 +27,10 @@ impl std::fmt::Display for LinkError {
2727 }
2828
2929 impl LinkError {
30+ pub(super) fn terminal(self) -> bool {
31+ matches!(self, Self::Outdated | Self::Closed(Close::Banned))
32+ }
33+
3034 fn by_code(code: u64) -> Self {
3135 match code {
3236 NO_APPLICATION_PROTOCOL => Self::Outdated,
@@ -44,9 +48,11 @@ impl From<quinn::ConnectionError> for LinkError {
4448 Self::by_code(u64::from(close.error_code))
4549 }
4650 quinn::ConnectionError::TransportError(error) => Self::by_code(u64::from(error.code)),
47- quinn::ConnectionError::ApplicationClosed(close) => {
48- Close::of(close.error_code).map_or(Self::Reset, Self::Closed)
49- }
51+ quinn::ConnectionError::ApplicationClosed(close) => match Close::of(close.error_code) {
52+ Some(Close::Outdated) => Self::Outdated,
53+ Some(close) => Self::Closed(close),
54+ None => Self::Reset,
55+ },
5056 quinn::ConnectionError::LocallyClosed => Self::Closed(Close::Normal),
5157 quinn::ConnectionError::VersionMismatch => Self::Outdated,
5258 quinn::ConnectionError::Reset | quinn::ConnectionError::CidsExhausted => Self::Reset,
crates/client/src/net/link.rsmodified+27 -10
@@ -110,11 +110,19 @@ async fn backoff(attempt: &mut u32) {
110110 *attempt += 1;
111111 }
112112
113-pub(crate) async fn dial(
113+pub(crate) async fn dial<T>(
114114 server: &crate::Server,
115115 alpn: &[u8],
116-) -> Result<quinn::Connection, LinkError> {
117- connect(server, &mut Endpoints::default(), alpn).await
116+ work: impl AsyncFnOnce(&quinn::Connection) -> T,
117+) -> Result<T, LinkError> {
118+ let mut endpoints = Endpoints::default();
119+ let connection = connect(server, &mut endpoints, alpn).await?;
120+ let done = work(&connection).await;
121+ connection.close(0u32.into(), b"");
122+ for endpoint in [endpoints.v4, endpoints.v6].into_iter().flatten() {
123+ endpoint.wait_idle().await;
124+ }
125+ Ok(done)
118126 }
119127
120128 async fn connect(
@@ -271,6 +279,7 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<
271279 let hello = Hello {
272280 token,
273281 device: device_name(),
282+ release: crate::update::SEQ,
274283 };
275284
276285 Ok(exchange(connection, &hello).await?.0)
@@ -402,6 +411,7 @@ async fn actor(
402411 Ok(connection) => break connection,
403412 Err(LinkError::Outdated) => {
404413 warn!("server speaks another protocol version");
414+ crate::update::outdated();
405415 let _ = event_sender
406416 .send(NetworkEvent::Disconnected(LinkError::Outdated))
407417 .await;
@@ -455,12 +465,15 @@ async fn actor(
455465 }
456466 Err(error) => {
457467 warn!("hello failed: {error}");
458- if connection.close_reason().map(LinkError::from)
459- == Some(LinkError::Closed(Close::Banned))
468+ if let Some(reason) = connection
469+ .close_reason()
470+ .map(LinkError::from)
471+ .filter(|reason| reason.terminal())
460472 {
461- let _ = event_sender
462- .send(NetworkEvent::Disconnected(LinkError::Closed(Close::Banned)))
463- .await;
473+ if reason == LinkError::Outdated {
474+ crate::update::outdated();
475+ }
476+ let _ = event_sender.send(NetworkEvent::Disconnected(reason)).await;
464477 while command_receiver.recv().await.is_some() {}
465478 return;
466479 }
@@ -471,6 +484,7 @@ async fn actor(
471484
472485 attempt = 0;
473486 info!("connected");
487+ crate::update::poke();
474488 shared.media.ready(connection.clone(), event_sender.clone());
475489 if event_sender.send(NetworkEvent::Connected).await.is_err() {
476490 return;
@@ -536,13 +550,16 @@ async fn actor(
536550 shared.media.lost();
537551
538552 let event = LinkError::from(error);
539- let banned = event == LinkError::Closed(Close::Banned);
553+ let terminal = event.terminal();
554+ if event == LinkError::Outdated {
555+ crate::update::outdated();
556+ }
540557
541558 if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() {
542559 return;
543560 }
544561
545- if banned {
562+ if terminal {
546563 while command_receiver.recv().await.is_some() {}
547564 return;
548565 }
crates/client/src/settings.rsmodified+0 -27
@@ -90,27 +90,6 @@ impl Launch {
9090 }
9191 }
9292
93-string_enum! {
94- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
95- Updates {
96- Off => "off",
97- Auto => "auto",
98- }
99-}
100-
101-impl Updates {
102- pub fn options() -> impl Iterator<Item = Self> {
103- Self::ALL.into_iter()
104- }
105-
106- pub fn label(self) -> &'static str {
107- match self {
108- Updates::Off => w().settings_page.updates_off,
109- Updates::Auto => w().settings_page.updates_auto,
110- }
111- }
112-}
113-
11493 string_enum! {
11594 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11695 Activation {
@@ -242,7 +221,6 @@ pub struct Settings {
242221 pub share: ShareSettings,
243222 pub close_to_tray: bool,
244223 pub launch: Launch,
245- pub updates: Updates,
246224 pub clock_seconds: bool,
247225 pub jump_usage: BTreeMap<String, u32>,
248226 pub last_chats: BTreeMap<Id, Id>,
@@ -272,7 +250,6 @@ impl Default for Settings {
272250 } else {
273251 Launch::Window
274252 },
275- updates: Updates::Auto,
276253 clock_seconds: false,
277254 jump_usage: BTreeMap::new(),
278255 last_chats: BTreeMap::new(),
@@ -391,9 +368,6 @@ pub fn load() -> Settings {
391368 .and_then(|value| Launch::parse(&value))
392369 .filter(|launch| Launch::options().any(|option| option == *launch))
393370 .unwrap_or(defaults.launch),
394- updates: text("updates")
395- .and_then(|value| Updates::parse(&value))
396- .unwrap_or(defaults.updates),
397371 clock_seconds: text("clock_seconds")
398372 .map_or(defaults.clock_seconds, |value| value == "true"),
399373 jump_usage: text("jump.usage")
@@ -436,7 +410,6 @@ pub fn save(settings: &Settings) {
436410 line("language", settings.language.as_str()),
437411 line("close_to_tray", settings.close_to_tray),
438412 line("launch", settings.launch.as_str()),
439- line("updates", settings.updates.as_str()),
440413 line("clock_seconds", settings.clock_seconds),
441414 line("voice.sensitivity", voice.sensitivity_db),
442415 line("voice.input_volume", voice.input_volume),
crates/client/src/update.rsmodified+162 -110
@@ -3,20 +3,31 @@ use std::{
33 io::{Read, Write},
44 path::{Path, PathBuf},
55 process::{Command, Stdio},
6+ sync::{
7+ OnceLock,
8+ atomic::{AtomicBool, Ordering},
9+ mpsc,
10+ },
611 time::{Duration, Instant},
712 };
813
9-use common::update::{self as wire, FILE_MAX, MANIFEST, MANIFEST_MAX};
10-use ring::{digest, signature};
14+use common::update::{self as wire, MANIFEST, MANIFEST_MAX};
15+use ring::{
16+ digest,
17+ rand::{SecureRandom, SystemRandom},
18+ signature,
19+};
1120 use tracing::{info, warn};
1221
1322 mod keys;
1423
1524 pub const SELFTEST: &str = "--selftest";
16-const MAGIC: &str = "yumush-update 1";
17-const SIGNATURE_BYTES: usize = 64;
18-const FIRST_CHECK: Duration = Duration::from_secs(60);
19-const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);
25+const AFTER: &str = "--after";
26+const FIRST_CHECK: Duration = Duration::from_secs(5);
27+const POKE_SPREAD: Duration = Duration::from_secs(20);
28+const RETRY_FIRST: Duration = Duration::from_secs(30);
29+const RETRY_LAST: Duration = Duration::from_secs(30 * 60);
30+const PARENT_LIMIT: Duration = Duration::from_secs(30);
2031 const SELFTEST_LIMIT: Duration = Duration::from_secs(20);
2132 const PACKAGED_ENV: [&str; 3] = ["FLATPAK_ID", "SNAP", "APPIMAGE"];
2233 const PACKAGED_ROOTS: [&str; 2] = ["/usr/", "/nix/"];
@@ -48,7 +59,6 @@ const fn parse_seq(text: &str) -> u64 {
4859 #[derive(Debug)]
4960 enum Off {
5061 Unofficial,
51- Platform,
5262 Multi,
5363 Packaged,
5464 NoExe,
@@ -74,19 +84,35 @@ enum Reject {
7484 Target,
7585 }
7686
77-enum Check {
87+enum Outcome {
7888 Current,
7989 Staged(u64),
90+ Restart,
8091 }
8192
8293 #[derive(Debug, PartialEq)]
8394 struct Release {
8495 seq: u64,
96+ minimum: u64,
8597 version: String,
8698 size: u64,
8799 sha256: [u8; 32],
88100 }
89101
102+static POKE: OnceLock<mpsc::Sender<()>> = OnceLock::new();
103+static OUTDATED: AtomicBool = AtomicBool::new(false);
104+
105+pub fn poke() {
106+ if let Some(sender) = POKE.get() {
107+ let _ = sender.send(());
108+ }
109+}
110+
111+pub fn outdated() {
112+ OUTDATED.store(true, Ordering::Relaxed);
113+ poke();
114+}
115+
90116 impl From<std::io::Error> for Fail {
91117 fn from(error: std::io::Error) -> Self {
92118 Self::Io(error)
@@ -107,9 +133,6 @@ impl From<quinn::ConnectionError> for Fail {
107133
108134 fn mode() -> Result<(u64, &'static Path), Off> {
109135 let seq = SEQ.ok_or(Off::Unofficial)?;
110- if cfg!(target_os = "macos") {
111- return Err(Off::Platform);
112- }
113136 if std::env::args().any(|arg| arg == crate::instance::MULTI) {
114137 return Err(Off::Multi);
115138 }
@@ -205,7 +228,19 @@ pub fn selftest() -> bool {
205228 true
206229 }
207230
231+fn wait_parent() {
232+ let mut args = std::env::args().skip_while(|arg| arg != AFTER).skip(1);
233+ let Some(pid) = args.next().and_then(|pid| pid.parse::<u32>().ok()) else {
234+ return;
235+ };
236+ let started = Instant::now();
237+ while alive(pid) && started.elapsed() < PARENT_LIMIT {
238+ std::thread::sleep(Duration::from_millis(100));
239+ }
240+}
241+
208242 pub fn boot() -> bool {
243+ wait_parent();
209244 let Ok((seq, exe)) = mode() else {
210245 return false;
211246 };
@@ -296,31 +331,88 @@ pub fn ready() {
296331 let _ = fs::remove_file(state(exe, "trial"));
297332 info!("update: {seq} is healthy");
298333 }
334+ let (sender, receiver) = mpsc::channel();
335+ if POKE.set(sender).is_err() {
336+ return;
337+ }
299338 let _ = std::thread::Builder::new()
300339 .name("update".to_string())
301- .spawn(move || watch(seq, exe));
340+ .spawn(move || watch(seq, exe, receiver));
302341 }
303342
304-fn watch(seq: u64, exe: &'static Path) {
343+fn spread(limit: Duration) -> Duration {
344+ let mut bytes = [0u8; 4];
345+ let _ = SystemRandom::new().fill(&mut bytes);
346+ limit.mul_f64(f64::from(u32::from_le_bytes(bytes)) / f64::from(u32::MAX))
347+}
348+
349+fn watch(running: u64, exe: &'static Path, pokes: mpsc::Receiver<()>) {
305350 let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
306351 .enable_all()
307352 .build()
308353 else {
309354 return;
310355 };
311- std::thread::sleep(FIRST_CHECK);
356+ let mut installed = running;
357+ let mut retry = RETRY_FIRST;
358+ let mut wait = Some(FIRST_CHECK);
312359 loop {
313- if crate::settings::load().updates != crate::settings::Updates::Off {
314- match runtime.block_on(check(seq, exe)) {
315- Ok(Check::Staged(next)) => {
316- info!("update: {next} staged, applies on restart");
317- return;
318- }
319- Ok(Check::Current) => {}
320- Err(fail) => warn!("update: {fail:?}"),
360+ let woke = match wait {
361+ Some(wait) => pokes
362+ .recv_timeout(wait)
363+ .map_err(|error| error == mpsc::RecvTimeoutError::Disconnected),
364+ None => pokes.recv().map_err(|_| true),
365+ };
366+ if woke == Err(true) {
367+ return;
368+ }
369+ if woke.is_ok() && !OUTDATED.load(Ordering::Relaxed) {
370+ std::thread::sleep(spread(POKE_SPREAD));
371+ }
372+ while pokes.try_recv().is_ok() {}
373+ match runtime.block_on(check(running, installed, exe)) {
374+ Ok(Outcome::Current) => {
375+ retry = RETRY_FIRST;
376+ wait = None;
377+ }
378+ Ok(Outcome::Staged(next)) => {
379+ info!("update: {next} staged, applies on restart");
380+ installed = next;
381+ retry = RETRY_FIRST;
382+ wait = None;
321383 }
384+ Ok(Outcome::Restart) => restart(exe),
385+ Err(fail) => {
386+ warn!("update: {fail:?}");
387+ wait = Some(retry / 2 + spread(retry / 2));
388+ retry = (retry * 2).min(RETRY_LAST);
389+ }
390+ }
391+ }
392+}
393+
394+fn restart(exe: &Path) {
395+ info!("update: required, restarting");
396+ let mut args: Vec<std::ffi::OsString> = Vec::new();
397+ let mut skip = false;
398+ for arg in std::env::args_os().skip(1) {
399+ if std::mem::take(&mut skip) {
400+ continue;
322401 }
323- std::thread::sleep(CHECK_EVERY);
402+ if arg == AFTER {
403+ skip = true;
404+ continue;
405+ }
406+ args.push(arg);
407+ }
408+ let spawned = Command::new(exe)
409+ .args(args)
410+ .arg(AFTER)
411+ .arg(std::process::id().to_string())
412+ .spawn();
413+ match spawned {
414+ Ok(_) => std::process::exit(0),
415+ Err(error) => warn!("update: restart {error}"),
324416 }
325417 }
326418
@@ -330,28 +422,32 @@ async fn fetch(connection: &quinn::Connection, name: &str, maximum: u64) -> Resu
330422 Ok(wire::receive(&mut receive, maximum).await?)
331423 }
332424
333-async fn check(seq: u64, exe: &Path) -> Result<Check, Fail> {
334- let connection = crate::net::dial(&crate::Server::load(), wire::ALPN)
335- .await
336- .map_err(Fail::Link)?;
337- let checked = fetch_release(&connection, seq, exe).await;
338- connection.close(0u32.into(), b"");
339- let Some((release, file, bytes)) = checked? else {
340- return Ok(Check::Current);
341- };
342- stage(exe, file, &bytes, release.seq)?;
343- Ok(Check::Staged(release.seq))
425+async fn check(running: u64, installed: u64, exe: &Path) -> Result<Outcome, Fail> {
426+ crate::net::dial(&crate::Server::load(), wire::ALPN, async |connection| {
427+ fetch_release(connection, running, installed, exe).await
428+ })
429+ .await
430+ .map_err(Fail::Link)?
344431 }
345432
346433 async fn fetch_release(
347434 connection: &quinn::Connection,
348- seq: u64,
435+ running: u64,
436+ installed: u64,
349437 exe: &Path,
350-) -> Result<Option<(Release, fs::File, Vec<u8>)>, Fail> {
438+) -> Result<Outcome, Fail> {
351439 let manifest = fetch(connection, MANIFEST, MANIFEST_MAX).await?;
352440 let release = verify(&manifest, &target(), keys::KEYS).map_err(Fail::Reject)?;
353- if release.seq <= seq || number(&state(exe, "skip")) == Some(release.seq) {
354- return Ok(None);
441+ let required = running < release.minimum || OUTDATED.load(Ordering::Relaxed);
442+ if release.seq <= installed {
443+ return Ok(if required && installed > running {
444+ Outcome::Restart
445+ } else {
446+ Outcome::Current
447+ });
448+ }
449+ if number(&state(exe, "skip")) == Some(release.seq) {
450+ return Ok(Outcome::Current);
355451 }
356452 let file = open_new(exe)?;
357453 info!("update: downloading {} ({})", release.version, release.seq);
@@ -365,13 +461,16 @@ async fn fetch_release(
365461 let _ = fs::remove_file(sibling(exe, "new"));
366462 return Err(Fail::Hash);
367463 }
368- Ok(Some((release, file, bytes)))
464+ stage(exe, file, &bytes, release.seq)?;
465+ Ok(if required {
466+ Outcome::Restart
467+ } else {
468+ Outcome::Staged(release.seq)
469+ })
369470 }
370471
371472 fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result<Release, Reject> {
372- let (sig, body) = signed
373- .split_at_checked(SIGNATURE_BYTES)
374- .ok_or(Reject::Short)?;
473+ let (sig, body) = wire::split(signed).ok_or(Reject::Short)?;
375474 let signed_by_us = keys.iter().any(|key| {
376475 signature::UnparsedPublicKey::new(&signature::ED25519, key)
377476 .verify(body, sig)
@@ -380,74 +479,17 @@ fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result<Release, Rej
380479 if !signed_by_us {
381480 return Err(Reject::Signature);
382481 }
383- let text = std::str::from_utf8(body).map_err(|_| Reject::Format)?;
384- let mut lines = text.split('\n');
385- if lines.next() != Some(MAGIC) {
386- return Err(Reject::Format);
387- }
388- let seq = field(lines.next(), "seq")
389- .and_then(|value| value.parse::<u64>().ok())
390- .ok_or(Reject::Format)?;
391- let version = field(lines.next(), "version")
392- .filter(|value| !value.is_empty())
393- .ok_or(Reject::Format)?
394- .to_string();
395- let mut found = None;
396- let mut seen = Vec::new();
397- for line in lines {
398- if line.is_empty() {
399- continue;
400- }
401- let mut parts = line.split(' ');
402- let (Some(name), Some(size), Some(hash), None) =
403- (parts.next(), parts.next(), parts.next(), parts.next())
404- else {
405- return Err(Reject::Format);
406- };
407- if !wire::valid_name(name) || name == MANIFEST || seen.contains(&name) {
408- return Err(Reject::Format);
409- }
410- seen.push(name);
411- let size = size
412- .parse::<u64>()
413- .ok()
414- .filter(|size| (1..=FILE_MAX).contains(size))
415- .ok_or(Reject::Format)?;
416- let sha256 = hex32(hash).ok_or(Reject::Format)?;
417- if name == target {
418- found = Some((size, sha256));
419- }
420- }
421- let (size, sha256) = found.ok_or(Reject::Target)?;
482+ let manifest = wire::parse(body).ok_or(Reject::Format)?;
483+ let file = manifest.file(target).ok_or(Reject::Target)?;
422484 Ok(Release {
423- seq,
424- version,
425- size,
426- sha256,
485+ seq: manifest.seq,
486+ minimum: manifest.minimum,
487+ version: manifest.version.clone(),
488+ size: file.size,
489+ sha256: file.sha256,
427490 })
428491 }
429492
430-fn field<'a>(line: Option<&'a str>, key: &str) -> Option<&'a str> {
431- line?.strip_prefix(key)?.strip_prefix(' ')
432-}
433-
434-fn hex32(text: &str) -> Option<[u8; 32]> {
435- let bytes = text.as_bytes();
436- if bytes.len() != 64 {
437- return None;
438- }
439- let mut out = [0u8; 32];
440- for (index, pair) in bytes.chunks(2).enumerate() {
441- let digit = |byte: u8| match byte {
442- b'0'..=b'9' => Some(byte - b'0'),
443- b'a'..=b'f' => Some(byte - b'a' + 10),
444- _ => None,
445- };
446- out[index] = digit(pair[0])? << 4 | digit(pair[1])?;
447- }
448- Some(out)
449-}
450-
451493 fn open_new(exe: &Path) -> std::io::Result<fs::File> {
452494 let new = sibling(exe, "new");
453495 let _ = fs::remove_file(&new);
@@ -539,6 +581,8 @@ mod tests {
539581 signature::{Ed25519KeyPair, KeyPair},
540582 };
541583
584+ use common::update::MAGIC;
585+
542586 use super::*;
543587
544588 fn signed(key: &Ed25519KeyPair, body: &str) -> Vec<u8> {
@@ -560,12 +604,17 @@ mod tests {
560604 fn verifies() {
561605 let (key, public) = pair();
562606 let body = format!(
563- "{MAGIC}\nseq 7\nversion 0.2.0\nx86_64-linux 10 {HASH}\nx86_64-windows 20 {HASH}\n"
607+ "{MAGIC}\nseq 7\nminimum 3\nversion 0.2.0\nx86_64-linux 10 {HASH}\nx86_64-windows 20 {HASH}\n"
564608 );
565609 let release = verify(&signed(&key, &body), "x86_64-windows", &[public]).unwrap();
566610 assert_eq!(
567- (release.seq, release.size, release.sha256[1]),
568- (7, 20, 0x11)
611+ (
612+ release.seq,
613+ release.minimum,
614+ release.size,
615+ release.sha256[1]
616+ ),
617+ (7, 3, 20, 0x11)
569618 );
570619 }
571620
@@ -573,7 +622,7 @@ mod tests {
573622 fn rejects() {
574623 let (key, public) = pair();
575624 let (other, _) = pair();
576- let good = format!("{MAGIC}\nseq 7\nversion 1\nx86_64-linux 10 {HASH}\n");
625+ let good = format!("{MAGIC}\nseq 7\nminimum 7\nversion 1\nx86_64-linux 10 {HASH}\n");
577626 let mut tampered = signed(&key, &good);
578627 *tampered.last_mut().unwrap() ^= 1;
579628 let cases = [
@@ -586,6 +635,9 @@ mod tests {
586635 signed(&key, &good.replace("seq 7", "seq x")),
587636 signed(&key, &good.replace(MAGIC, "yumush-update 2")),
588637 signed(&key, &format!("{good}manifest 10 {HASH}\n")),
638+ signed(&key, &good.replace("minimum 7", "minimum 8")),
639+ signed(&key, &good.replace("minimum 7", "minimum 0")),
640+ signed(&key, &good.replace("minimum 7\n", "")),
589641 ];
590642 for case in cases {
591643 assert!(verify(&case, "x86_64-linux", &[public]).is_err());
crates/common/src/event.rsmodified+1 -0
@@ -86,6 +86,7 @@ pub enum Event {
8686 user_id: Id,
8787 stats: Stats,
8888 },
89+ Release,
8990 }
9091
9192 #[derive(Debug, Clone, Encode, Decode)]
crates/common/src/session.rsmodified+1 -0
@@ -6,6 +6,7 @@ use crate::model::User;
66 pub struct Hello {
77 pub token: Option<String>,
88 pub device: String,
9+ pub release: Option<u64>,
910 }
1011
1112 #[derive(Debug, Clone, Encode, Decode)]
crates/common/src/transport.rsmodified+5 -2
@@ -3,7 +3,7 @@ use std::{io, net::SocketAddr, sync::Arc, time::Duration};
33 use quinn::{Endpoint, EndpointConfig, ServerConfig, TokioRuntime, TransportConfig, VarInt};
44 use socket2::{Domain, Protocol, Socket, Type};
55
6-pub const ALPN: &[u8] = b"yumush/2";
6+pub const ALPN: &[u8] = b"yumush/3";
77
88 const IDLE_TIMEOUT: Duration = Duration::from_secs(10);
99 pub const KEEP_ALIVE: Duration = Duration::from_secs(1);
@@ -43,10 +43,11 @@ pub enum Close {
4343 Maintenance = 4,
4444 Slow = 5,
4545 Protocol = 6,
46+ Outdated = 7,
4647 }
4748
4849 impl Close {
49- pub const ALL: [Self; 7] = [
50+ pub const ALL: [Self; 8] = [
5051 Self::Normal,
5152 Self::SignedOut,
5253 Self::Revoked,
@@ -54,6 +55,7 @@ impl Close {
5455 Self::Maintenance,
5556 Self::Slow,
5657 Self::Protocol,
58+ Self::Outdated,
5759 ];
5860
5961 pub fn of(code: VarInt) -> Option<Self> {
@@ -69,6 +71,7 @@ impl Close {
6971 Self::Maintenance => "maintenance",
7072 Self::Slow => "slow",
7173 Self::Protocol => "protocol error",
74+ Self::Outdated => "outdated",
7275 }
7376 }
7477
crates/common/src/update.rsmodified+92 -0
@@ -81,3 +81,95 @@ pub async fn receive(receive: &mut RecvStream, maximum: u64) -> Result<Vec<u8>,
8181 }
8282 Ok(bytes)
8383 }
84+
85+pub const MAGIC: &str = "yumush-update 1";
86+pub const SIGNATURE_BYTES: usize = 64;
87+
88+#[derive(Debug, PartialEq, Eq)]
89+pub struct Manifest {
90+ pub seq: u64,
91+ pub minimum: u64,
92+ pub version: String,
93+ pub files: Vec<File>,
94+}
95+
96+#[derive(Debug, PartialEq, Eq)]
97+pub struct File {
98+ pub name: String,
99+ pub size: u64,
100+ pub sha256: [u8; 32],
101+}
102+
103+impl Manifest {
104+ pub fn file(&self, name: &str) -> Option<&File> {
105+ self.files.iter().find(|file| file.name == name)
106+ }
107+}
108+
109+pub fn split(signed: &[u8]) -> Option<(&[u8], &[u8])> {
110+ signed.split_at_checked(SIGNATURE_BYTES)
111+}
112+
113+pub fn parse(body: &[u8]) -> Option<Manifest> {
114+ let text = std::str::from_utf8(body).ok()?;
115+ let mut lines = text.split('\n');
116+ if lines.next() != Some(MAGIC) {
117+ return None;
118+ }
119+ let seq = number(lines.next(), "seq")?;
120+ let minimum = number(lines.next(), "minimum").filter(|minimum| *minimum <= seq)?;
121+ let version = field(lines.next(), "version")
122+ .filter(|value| !value.is_empty())?
123+ .to_string();
124+ let mut files: Vec<File> = Vec::new();
125+ for line in lines.filter(|line| !line.is_empty()) {
126+ let mut parts = line.split(' ');
127+ let (Some(name), Some(size), Some(hash), None) =
128+ (parts.next(), parts.next(), parts.next(), parts.next())
129+ else {
130+ return None;
131+ };
132+ if !valid_name(name) || name == MANIFEST || files.iter().any(|file| file.name == name) {
133+ return None;
134+ }
135+ files.push(File {
136+ name: name.to_string(),
137+ size: size
138+ .parse()
139+ .ok()
140+ .filter(|size| (1..=FILE_MAX).contains(size))?,
141+ sha256: hex32(hash)?,
142+ });
143+ }
144+ Some(Manifest {
145+ seq,
146+ minimum,
147+ version,
148+ files,
149+ })
150+}
151+
152+fn field<'a>(line: Option<&'a str>, key: &str) -> Option<&'a str> {
153+ line?.strip_prefix(key)?.strip_prefix(' ')
154+}
155+
156+fn number(line: Option<&str>, key: &str) -> Option<u64> {
157+ field(line, key)?.parse().ok().filter(|value| *value > 0)
158+}
159+
160+fn hex32(text: &str) -> Option<[u8; 32]> {
161+ let bytes = text.as_bytes();
162+ if bytes.len() != 64 {
163+ return None;
164+ }
165+ let digit = |byte: u8| match byte {
166+ b'0'..=b'9' => Some(byte - b'0'),
167+ b'a'..=b'f' => Some(byte - b'a' + 10),
168+ _ => None,
169+ };
170+ let mut out = [0u8; 32];
171+ for (index, pair) in bytes.chunks(2).enumerate() {
172+ out[index] = digit(pair[0])? << 4 | digit(pair[1])?;
173+ }
174+ Some(out)
175+}
crates/server/src/hub.rsmodified+16 -0
@@ -29,6 +29,7 @@ pub struct Client {
2929 pub me: Option<Signed>,
3030 tx: mpsc::Sender<Bytes>,
3131 pub closed: AtomicBool,
32+ pub release: AtomicU64,
3233 watching: Mutex<Option<Id>>,
3334 ghost_logged: Mutex<HashSet<Id>>,
3435 }
@@ -42,6 +43,7 @@ impl Client {
4243 me,
4344 tx,
4445 closed: AtomicBool::new(false),
46+ release: AtomicU64::new(u64::MAX),
4547 watching: Mutex::new(None),
4648 ghost_logged: Mutex::new(HashSet::new()),
4749 });
@@ -192,6 +194,20 @@ impl Hub {
192194 }
193195 }
194196
197+ pub fn kick_outdated(&self, minimum: u64) {
198+ let targets: Vec<Arc<Client>> = self
199+ .0
200+ .lock()
201+ .unwrap()
202+ .values()
203+ .filter(|client| client.release.load(Ordering::Relaxed) < minimum)
204+ .cloned()
205+ .collect();
206+ for client in targets {
207+ client.close(Close::Outdated);
208+ }
209+ }
210+
195211 pub fn kick_user(&self, user_id: Id, close: Close) {
196212 self.kick_where(|me| me.user_id == user_id, close);
197213 }
crates/server/src/network.rsmodified+8 -0
@@ -40,6 +40,7 @@ pub struct Services {
4040 pub rate_limit: RateLimit,
4141 pub stats: Follows,
4242 pub machine: Machine,
43+ pub minimum: std::sync::Arc<std::sync::atomic::AtomicU64>,
4344 }
4445
4546 #[derive(Clone)]
@@ -83,6 +84,7 @@ pub async fn serve(
8384 shared.services.machine.watch(shared.directory.clone());
8485
8586 tokio::spawn(retention::collect(shared.clone()));
87+ tokio::spawn(crate::update::watch(shared.clone()));
8688
8789 while let Some(incoming) = endpoint.accept().await {
8890 tokio::spawn(handle_connection(incoming, shared.clone()));
@@ -230,10 +232,16 @@ async fn greet(connection: &Connection, shared: &Shared) -> Result<Option<Pendin
230232 let (send_stream, mut receive_stream) = connection.accept_bi().await?;
231233 let mut reply_stream = Sending::new(send_stream);
232234 let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?;
235+ let release = hello.release.unwrap_or(u64::MAX);
236+ if release < shared.services.minimum.load(Ordering::Relaxed) {
237+ close(connection, Close::Outdated);
238+ return Ok(None);
239+ }
233240
234241 match admit(hello, connection, shared).await {
235242 Ok((me, user)) => {
236243 let (client, events) = Client::new(Some(connection.clone()), me);
244+ client.release.store(release, Ordering::Relaxed);
237245
238246 Ok(Some(Pending {
239247 client,
crates/server/src/update.rsmodified+65 -6
@@ -1,5 +1,5 @@
11 use std::{
2- collections::HashSet,
2+ collections::HashMap,
33 net::IpAddr,
44 path::{Path, PathBuf},
55 sync::Mutex,
@@ -11,30 +11,42 @@ use quinn::{Connection, RecvStream, SendStream};
1111 use tokio::{io::AsyncReadExt, sync::Semaphore, time::timeout};
1212 use tracing::warn;
1313
14-use crate::error::ServerError;
14+use crate::{error::ServerError, network::Shared};
1515
1616 const STREAMS: usize = 4;
1717 const ACCEPT_DEADLINE: Duration = Duration::from_secs(30);
1818 const ASK_DEADLINE: Duration = Duration::from_secs(5);
1919 const TRANSFER_DEADLINE: Duration = Duration::from_secs(15 * 60);
2020 const STALL_DEADLINE: Duration = Duration::from_secs(30);
21+const WATCH_EVERY: Duration = Duration::from_secs(5);
2122 const CHUNK: usize = 64 << 10;
2223 static PERMITS: Semaphore = Semaphore::const_new(16);
23-static PEERS: Mutex<Option<HashSet<IpAddr>>> = Mutex::new(None);
24+const PER_PEER: u8 = 4;
25+static PEERS: Mutex<Option<HashMap<IpAddr, u8>>> = Mutex::new(None);
2426
2527 struct Peer(IpAddr);
2628
2729 impl Peer {
2830 fn claim(ip: IpAddr) -> Option<Self> {
2931 let mut peers = PEERS.lock().unwrap();
30- peers.get_or_insert_default().insert(ip).then_some(Self(ip))
32+ let count = peers.get_or_insert_default().entry(ip).or_default();
33+ if *count >= PER_PEER {
34+ return None;
35+ }
36+ *count += 1;
37+ Some(Self(ip))
3138 }
3239 }
3340
3441 impl Drop for Peer {
3542 fn drop(&mut self) {
36- if let Some(peers) = PEERS.lock().unwrap().as_mut() {
37- peers.remove(&self.0);
43+ if let Some(peers) = PEERS.lock().unwrap().as_mut()
44+ && let Some(count) = peers.get_mut(&self.0)
45+ {
46+ *count -= 1;
47+ if *count == 0 {
48+ peers.remove(&self.0);
49+ }
3850 }
3951 }
4052 }
@@ -106,3 +118,50 @@ async fn transfer(
106118
107119 Ok(())
108120 }
121+
122+pub(crate) async fn watch(shared: Shared) {
123+ let path = shared.updates.join(MANIFEST);
124+ let mut seen = None;
125+ let mut seq = None;
126+ let mut interval = tokio::time::interval(WATCH_EVERY);
127+ loop {
128+ interval.tick().await;
129+ let stamp = tokio::fs::metadata(&path)
130+ .await
131+ .ok()
132+ .map(|metadata| (metadata.modified().ok(), metadata.len()));
133+ if stamp == seen {
134+ continue;
135+ }
136+ seen = stamp;
137+ let manifest = tokio::fs::read(&path).await.ok().and_then(|signed| {
138+ let (_, body) = update::split(&signed)?;
139+ update::parse(body)
140+ });
141+ let Some(manifest) = manifest else {
142+ continue;
143+ };
144+ shared
145+ .services
146+ .minimum
147+ .store(manifest.minimum, std::sync::atomic::Ordering::Relaxed);
148+ shared.services.hub.kick_outdated(manifest.minimum);
149+ if seq
150+ .replace(manifest.seq)
151+ .is_some_and(|old| old != manifest.seq)
152+ {
153+ announce(&shared);
154+ }
155+ }
156+}
157+
158+fn announce(shared: &Shared) {
159+ let down = common::event::Down::Event(Box::new(common::event::Event::Release));
160+ match common::frame::encode(&down, common::frame::DOWN_MAX) {
161+ Ok(bytes) => {
162+ let hub = &shared.services.hub;
163+ hub.send(&hub.all(), &bytes.into(), true);
164+ }
165+ Err(error) => warn!("update: announce {error}"),
166+ }
167+}
packaging/release.shmodified+6 -4
@@ -4,7 +4,7 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
44 KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}"
55 cd "$ROOT"
66 usage() {
7- echo "usage: $0 build <seq> | sign <seq> [primary|backup]" >&2
7+ echo "usage: $0 build <seq> | sign <seq> <minimum> (minimum = oldest seq still allowed; = seq forces everyone up)" >&2
88 exit 1
99 }
1010 [[ $# -ge 2 && "$2" =~ ^[1-9][0-9]{0,17}$ ]] || usage
@@ -27,11 +27,13 @@ build)
2727 echo "$DIST/$TARGET"
2828 ;;
2929 sign)
30- KEY="$KEYS/${3:-primary}.pem"
30+ [[ $# -ge 3 && "$3" =~ ^[1-9][0-9]{0,17}$ ]] && (( $3 <= SEQ )) || usage
31+ MINIMUM="$3"
32+ KEY="$KEYS/${YUMUSH_SIGNING_KEY:-primary}.pem"
3133 VERSION=$(cargo pkgid -p client | sed 's/.*[#@]//')
3234 BODY="$DIST/manifest.body"
3335 {
34- printf 'yumush-update 1\nseq %s\nversion %s\n' "$SEQ" "$VERSION"
36+ printf 'yumush-update 1\nseq %s\nminimum %s\nversion %s\n' "$SEQ" "$MINIMUM" "$VERSION"
3537 for file in "$DIST"/*; do
3638 name=$(basename "$file")
3739 [[ "$name" =~ ^[a-z0-9_]+-[a-z0-9_]+$ ]] || continue
@@ -44,7 +46,7 @@ sign)
4446 printf '%s %s %s\n' "$name" "$(stat -c %s "$file")" "$(sha256sum "$file" | cut -d' ' -f1)"
4547 done
4648 } > "$BODY"
47- grep -q ' ' <(tail -n +4 "$BODY") || { echo "no binaries in $DIST" >&2; exit 1; }
49+ grep -q ' ' <(tail -n +5 "$BODY") || { echo "no binaries in $DIST" >&2; exit 1; }
4850 cat "$BODY"
4951 SIG=$(mktemp)
5052 PUBLIC=$(mktemp)