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
20 launch_off = Off20 launch_off = Off
21 launch_window = Window21 launch_window = Window
22 launch_tray = Tray22 launch_tray = Tray
23-updates = Updates
24-updates_off = Off
25-updates_auto = Automatic
26 your_hue = Your hue23 your_hue = Your hue
27 camera = Camera24 camera = Camera
28 screen_share = Screen share25 screen_share = Screen share
crates/client/lang/tr/settings_page.txtmodified+0 -3
@@ -20,9 +20,6 @@ launch = Oturum açılınca
20 launch_off = Kapalı20 launch_off = Kapalı
21 launch_window = Pencere21 launch_window = Pencere
22 launch_tray = Tepsi22 launch_tray = Tepsi
23-updates = Güncellemeler
24-updates_off = Kapalı
25-updates_auto = Otomatik
26 your_hue = Rengin23 your_hue = Rengin
27 camera = Kamera24 camera = Kamera
28 screen_share = Ekran paylaşımı25 screen_share = Ekran paylaşımı
crates/client/src/gui/chat.rsmodified+1 -1
@@ -799,7 +799,7 @@ impl Chat {
799 followed.1 = stats;799 followed.1 = stats;
800 }800 }
801 }801 }
802- Event::ReportCreated | Event::SettingsUpdated(_) => {}802+ Event::ReportCreated | Event::SettingsUpdated(_) | Event::Release => {}
803 }803 }
804 }804 }
805 805
crates/client/src/gui/settings_page.rsmodified+2 -18
@@ -25,7 +25,7 @@ use super::{
25 };25 };
26 use crate::{26 use crate::{
27 gui::style::{self, Theme, radius, size, space, stroke, text},27 gui::style::{self, Theme, radius, size, space, stroke, text},
28- settings::{self, FontSize, Launch, ShareAudio, ShareCodec, Updates},28+ settings::{self, FontSize, Launch, ShareAudio, ShareCodec},
29 share::encode::capabilities,29 share::encode::capabilities,
30 };30 };
31 31
@@ -42,7 +42,7 @@ pub(super) fn settings_titles() -> [&'static str; 5] {
42 ]42 ]
43 }43 }
44 44
45-pub(super) fn setting_rows() -> [(usize, &'static str); 26] {45+pub(super) fn setting_rows() -> [(usize, &'static str); 25] {
46 let s = &w().settings_page;46 let s = &w().settings_page;
47 let v = &w().voice_settings;47 let v = &w().voice_settings;
48 [48 [
@@ -69,7 +69,6 @@ pub(super) fn setting_rows() -> [(usize, &'static str); 26] {
69 (3, s.language),69 (3, s.language),
70 (3, s.close_to_tray),70 (3, s.close_to_tray),
71 (3, s.launch),71 (3, s.launch),
72- (3, s.updates),
73 (3, s.clock_seconds),72 (3, s.clock_seconds),
74 (3, s.your_hue),73 (3, s.your_hue),
75 ]74 ]
@@ -222,16 +221,6 @@ impl Yumush {
222 Yumush::set_launch,221 Yumush::set_launch,
223 ),222 ),
224 ),223 ),
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- ),
235 row(224 row(
236 w().settings_page.clock_seconds,225 w().settings_page.clock_seconds,
237 super::parts::toggle(226 super::parts::toggle(
@@ -399,11 +388,6 @@ impl Yumush {
399 self.commit_settings(cx);388 self.commit_settings(cx);
400 }389 }
401 390
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-
407 pub(super) fn toggle_clock_seconds(&mut self, cx: &mut Context<Self>) {391 pub(super) fn toggle_clock_seconds(&mut self, cx: &mut Context<Self>) {
408 self.settings.clock_seconds = !self.settings.clock_seconds;392 self.settings.clock_seconds = !self.settings.clock_seconds;
409 self.commit_settings(cx);393 self.commit_settings(cx);
crates/client/src/net/events.rsmodified+3 -0
@@ -17,6 +17,9 @@ pub(super) async fn event_receive_loop(
17 17
18 while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await {18 while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await {
19 match down {19 match down {
20+ Down::Event(event) if matches!(*event, common::event::Event::Release) => {
21+ crate::update::poke();
22+ }
20 Down::Event(event) => {23 Down::Event(event) => {
21 media.pushed(&event);24 media.pushed(&event);
22 if event_sender25 if event_sender
crates/client/src/net/fail.rsmodified+9 -3
@@ -27,6 +27,10 @@ impl std::fmt::Display for LinkError {
27 }27 }
28 28
29 impl LinkError {29 impl LinkError {
30+ pub(super) fn terminal(self) -> bool {
31+ matches!(self, Self::Outdated | Self::Closed(Close::Banned))
32+ }
33+
30 fn by_code(code: u64) -> Self {34 fn by_code(code: u64) -> Self {
31 match code {35 match code {
32 NO_APPLICATION_PROTOCOL => Self::Outdated,36 NO_APPLICATION_PROTOCOL => Self::Outdated,
@@ -44,9 +48,11 @@ impl From<quinn::ConnectionError> for LinkError {
44 Self::by_code(u64::from(close.error_code))48 Self::by_code(u64::from(close.error_code))
45 }49 }
46 quinn::ConnectionError::TransportError(error) => Self::by_code(u64::from(error.code)),50 quinn::ConnectionError::TransportError(error) => Self::by_code(u64::from(error.code)),
47- quinn::ConnectionError::ApplicationClosed(close) => {51+ quinn::ConnectionError::ApplicationClosed(close) => match Close::of(close.error_code) {
48- Close::of(close.error_code).map_or(Self::Reset, Self::Closed)52+ Some(Close::Outdated) => Self::Outdated,
49- }53+ Some(close) => Self::Closed(close),
54+ None => Self::Reset,
55+ },
50 quinn::ConnectionError::LocallyClosed => Self::Closed(Close::Normal),56 quinn::ConnectionError::LocallyClosed => Self::Closed(Close::Normal),
51 quinn::ConnectionError::VersionMismatch => Self::Outdated,57 quinn::ConnectionError::VersionMismatch => Self::Outdated,
52 quinn::ConnectionError::Reset | quinn::ConnectionError::CidsExhausted => Self::Reset,58 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) {
110 *attempt += 1;110 *attempt += 1;
111 }111 }
112 112
113-pub(crate) async fn dial(113+pub(crate) async fn dial<T>(
114 server: &crate::Server,114 server: &crate::Server,
115 alpn: &[u8],115 alpn: &[u8],
116-) -> Result<quinn::Connection, LinkError> {116+ work: impl AsyncFnOnce(&quinn::Connection) -> T,
117- connect(server, &mut Endpoints::default(), alpn).await117+) -> 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)
118 }126 }
119 127
120 async fn connect(128 async fn connect(
@@ -271,6 +279,7 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<
271 let hello = Hello {279 let hello = Hello {
272 token,280 token,
273 device: device_name(),281 device: device_name(),
282+ release: crate::update::SEQ,
274 };283 };
275 284
276 Ok(exchange(connection, &hello).await?.0)285 Ok(exchange(connection, &hello).await?.0)
@@ -402,6 +411,7 @@ async fn actor(
402 Ok(connection) => break connection,411 Ok(connection) => break connection,
403 Err(LinkError::Outdated) => {412 Err(LinkError::Outdated) => {
404 warn!("server speaks another protocol version");413 warn!("server speaks another protocol version");
414+ crate::update::outdated();
405 let _ = event_sender415 let _ = event_sender
406 .send(NetworkEvent::Disconnected(LinkError::Outdated))416 .send(NetworkEvent::Disconnected(LinkError::Outdated))
407 .await;417 .await;
@@ -455,12 +465,15 @@ async fn actor(
455 }465 }
456 Err(error) => {466 Err(error) => {
457 warn!("hello failed: {error}");467 warn!("hello failed: {error}");
458- if connection.close_reason().map(LinkError::from)468+ if let Some(reason) = connection
459- == Some(LinkError::Closed(Close::Banned))469+ .close_reason()
470+ .map(LinkError::from)
471+ .filter(|reason| reason.terminal())
460 {472 {
461- let _ = event_sender473+ if reason == LinkError::Outdated {
462- .send(NetworkEvent::Disconnected(LinkError::Closed(Close::Banned)))474+ crate::update::outdated();
463- .await;475+ }
476+ let _ = event_sender.send(NetworkEvent::Disconnected(reason)).await;
464 while command_receiver.recv().await.is_some() {}477 while command_receiver.recv().await.is_some() {}
465 return;478 return;
466 }479 }
@@ -471,6 +484,7 @@ async fn actor(
471 484
472 attempt = 0;485 attempt = 0;
473 info!("connected");486 info!("connected");
487+ crate::update::poke();
474 shared.media.ready(connection.clone(), event_sender.clone());488 shared.media.ready(connection.clone(), event_sender.clone());
475 if event_sender.send(NetworkEvent::Connected).await.is_err() {489 if event_sender.send(NetworkEvent::Connected).await.is_err() {
476 return;490 return;
@@ -536,13 +550,16 @@ async fn actor(
536 shared.media.lost();550 shared.media.lost();
537 551
538 let event = LinkError::from(error);552 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+ }
540 557
541 if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() {558 if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() {
542 return;559 return;
543 }560 }
544 561
545- if banned {562+ if terminal {
546 while command_receiver.recv().await.is_some() {}563 while command_receiver.recv().await.is_some() {}
547 return;564 return;
548 }565 }
crates/client/src/settings.rsmodified+0 -27
@@ -90,27 +90,6 @@ impl Launch {
90 }90 }
91 }91 }
92 92
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-
114 string_enum! {93 string_enum! {
115 #[derive(Debug, Clone, Copy, PartialEq, Eq)]94 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
116 Activation {95 Activation {
@@ -242,7 +221,6 @@ pub struct Settings {
242 pub share: ShareSettings,221 pub share: ShareSettings,
243 pub close_to_tray: bool,222 pub close_to_tray: bool,
244 pub launch: Launch,223 pub launch: Launch,
245- pub updates: Updates,
246 pub clock_seconds: bool,224 pub clock_seconds: bool,
247 pub jump_usage: BTreeMap<String, u32>,225 pub jump_usage: BTreeMap<String, u32>,
248 pub last_chats: BTreeMap<Id, Id>,226 pub last_chats: BTreeMap<Id, Id>,
@@ -272,7 +250,6 @@ impl Default for Settings {
272 } else {250 } else {
273 Launch::Window251 Launch::Window
274 },252 },
275- updates: Updates::Auto,
276 clock_seconds: false,253 clock_seconds: false,
277 jump_usage: BTreeMap::new(),254 jump_usage: BTreeMap::new(),
278 last_chats: BTreeMap::new(),255 last_chats: BTreeMap::new(),
@@ -391,9 +368,6 @@ pub fn load() -> Settings {
391 .and_then(|value| Launch::parse(&value))368 .and_then(|value| Launch::parse(&value))
392 .filter(|launch| Launch::options().any(|option| option == *launch))369 .filter(|launch| Launch::options().any(|option| option == *launch))
393 .unwrap_or(defaults.launch),370 .unwrap_or(defaults.launch),
394- updates: text("updates")
395- .and_then(|value| Updates::parse(&value))
396- .unwrap_or(defaults.updates),
397 clock_seconds: text("clock_seconds")371 clock_seconds: text("clock_seconds")
398 .map_or(defaults.clock_seconds, |value| value == "true"),372 .map_or(defaults.clock_seconds, |value| value == "true"),
399 jump_usage: text("jump.usage")373 jump_usage: text("jump.usage")
@@ -436,7 +410,6 @@ pub fn save(settings: &Settings) {
436 line("language", settings.language.as_str()),410 line("language", settings.language.as_str()),
437 line("close_to_tray", settings.close_to_tray),411 line("close_to_tray", settings.close_to_tray),
438 line("launch", settings.launch.as_str()),412 line("launch", settings.launch.as_str()),
439- line("updates", settings.updates.as_str()),
440 line("clock_seconds", settings.clock_seconds),413 line("clock_seconds", settings.clock_seconds),
441 line("voice.sensitivity", voice.sensitivity_db),414 line("voice.sensitivity", voice.sensitivity_db),
442 line("voice.input_volume", voice.input_volume),415 line("voice.input_volume", voice.input_volume),
crates/client/src/update.rsmodified+159 -107
@@ -3,20 +3,31 @@ use std::{
3 io::{Read, Write},3 io::{Read, Write},
4 path::{Path, PathBuf},4 path::{Path, PathBuf},
5 process::{Command, Stdio},5 process::{Command, Stdio},
6+ sync::{
7+ OnceLock,
8+ atomic::{AtomicBool, Ordering},
9+ mpsc,
10+ },
6 time::{Duration, Instant},11 time::{Duration, Instant},
7 };12 };
8 13
9-use common::update::{self as wire, FILE_MAX, MANIFEST, MANIFEST_MAX};14+use common::update::{self as wire, MANIFEST, MANIFEST_MAX};
10-use ring::{digest, signature};15+use ring::{
16+ digest,
17+ rand::{SecureRandom, SystemRandom},
18+ signature,
19+};
11 use tracing::{info, warn};20 use tracing::{info, warn};
12 21
13 mod keys;22 mod keys;
14 23
15 pub const SELFTEST: &str = "--selftest";24 pub const SELFTEST: &str = "--selftest";
16-const MAGIC: &str = "yumush-update 1";25+const AFTER: &str = "--after";
17-const SIGNATURE_BYTES: usize = 64;26+const FIRST_CHECK: Duration = Duration::from_secs(5);
18-const FIRST_CHECK: Duration = Duration::from_secs(60);27+const POKE_SPREAD: Duration = Duration::from_secs(20);
19-const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);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);
20 const SELFTEST_LIMIT: Duration = Duration::from_secs(20);31 const SELFTEST_LIMIT: Duration = Duration::from_secs(20);
21 const PACKAGED_ENV: [&str; 3] = ["FLATPAK_ID", "SNAP", "APPIMAGE"];32 const PACKAGED_ENV: [&str; 3] = ["FLATPAK_ID", "SNAP", "APPIMAGE"];
22 const PACKAGED_ROOTS: [&str; 2] = ["/usr/", "/nix/"];33 const PACKAGED_ROOTS: [&str; 2] = ["/usr/", "/nix/"];
@@ -48,7 +59,6 @@ const fn parse_seq(text: &str) -> u64 {
48 #[derive(Debug)]59 #[derive(Debug)]
49 enum Off {60 enum Off {
50 Unofficial,61 Unofficial,
51- Platform,
52 Multi,62 Multi,
53 Packaged,63 Packaged,
54 NoExe,64 NoExe,
@@ -74,19 +84,35 @@ enum Reject {
74 Target,84 Target,
75 }85 }
76 86
77-enum Check {87+enum Outcome {
78 Current,88 Current,
79 Staged(u64),89 Staged(u64),
90+ Restart,
80 }91 }
81 92
82 #[derive(Debug, PartialEq)]93 #[derive(Debug, PartialEq)]
83 struct Release {94 struct Release {
84 seq: u64,95 seq: u64,
96+ minimum: u64,
85 version: String,97 version: String,
86 size: u64,98 size: u64,
87 sha256: [u8; 32],99 sha256: [u8; 32],
88 }100 }
89 101
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+
90 impl From<std::io::Error> for Fail {116 impl From<std::io::Error> for Fail {
91 fn from(error: std::io::Error) -> Self {117 fn from(error: std::io::Error) -> Self {
92 Self::Io(error)118 Self::Io(error)
@@ -107,9 +133,6 @@ impl From<quinn::ConnectionError> for Fail {
107 133
108 fn mode() -> Result<(u64, &'static Path), Off> {134 fn mode() -> Result<(u64, &'static Path), Off> {
109 let seq = SEQ.ok_or(Off::Unofficial)?;135 let seq = SEQ.ok_or(Off::Unofficial)?;
110- if cfg!(target_os = "macos") {
111- return Err(Off::Platform);
112- }
113 if std::env::args().any(|arg| arg == crate::instance::MULTI) {136 if std::env::args().any(|arg| arg == crate::instance::MULTI) {
114 return Err(Off::Multi);137 return Err(Off::Multi);
115 }138 }
@@ -205,7 +228,19 @@ pub fn selftest() -> bool {
205 true228 true
206 }229 }
207 230
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+
208 pub fn boot() -> bool {242 pub fn boot() -> bool {
243+ wait_parent();
209 let Ok((seq, exe)) = mode() else {244 let Ok((seq, exe)) = mode() else {
210 return false;245 return false;
211 };246 };
@@ -296,31 +331,88 @@ pub fn ready() {
296 let _ = fs::remove_file(state(exe, "trial"));331 let _ = fs::remove_file(state(exe, "trial"));
297 info!("update: {seq} is healthy");332 info!("update: {seq} is healthy");
298 }333 }
334+ let (sender, receiver) = mpsc::channel();
335+ if POKE.set(sender).is_err() {
336+ return;
337+ }
299 let _ = std::thread::Builder::new()338 let _ = std::thread::Builder::new()
300 .name("update".to_string())339 .name("update".to_string())
301- .spawn(move || watch(seq, exe));340+ .spawn(move || watch(seq, exe, receiver));
302 }341 }
303 342
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<()>) {
305 let Ok(runtime) = tokio::runtime::Builder::new_current_thread()350 let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
306 .enable_all()351 .enable_all()
307 .build()352 .build()
308 else {353 else {
309 return;354 return;
310 };355 };
311- std::thread::sleep(FIRST_CHECK);356+ let mut installed = running;
357+ let mut retry = RETRY_FIRST;
358+ let mut wait = Some(FIRST_CHECK);
312 loop {359 loop {
313- if crate::settings::load().updates != crate::settings::Updates::Off {360+ let woke = match wait {
314- match runtime.block_on(check(seq, exe)) {361+ Some(wait) => pokes
315- Ok(Check::Staged(next)) => {362+ .recv_timeout(wait)
316- info!("update: {next} staged, applies on restart");363+ .map_err(|error| error == mpsc::RecvTimeoutError::Disconnected),
364+ None => pokes.recv().map_err(|_| true),
365+ };
366+ if woke == Err(true) {
317 return;367 return;
318 }368 }
319- Ok(Check::Current) => {}369+ if woke.is_ok() && !OUTDATED.load(Ordering::Relaxed) {
320- Err(fail) => warn!("update: {fail:?}"),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;
383+ }
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+ }
321 }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;
401+ }
402+ if arg == AFTER {
403+ skip = true;
404+ continue;
322 }405 }
323- std::thread::sleep(CHECK_EVERY);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}"),
324 }416 }
325 }417 }
326 418
@@ -330,28 +422,32 @@ async fn fetch(connection: &quinn::Connection, name: &str, maximum: u64) -> Resu
330 Ok(wire::receive(&mut receive, maximum).await?)422 Ok(wire::receive(&mut receive, maximum).await?)
331 }423 }
332 424
333-async fn check(seq: u64, exe: &Path) -> Result<Check, Fail> {425+async fn check(running: u64, installed: u64, exe: &Path) -> Result<Outcome, Fail> {
334- let connection = crate::net::dial(&crate::Server::load(), wire::ALPN)426+ crate::net::dial(&crate::Server::load(), wire::ALPN, async |connection| {
427+ fetch_release(connection, running, installed, exe).await
428+ })
335 .await429 .await
336- .map_err(Fail::Link)?;430+ .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))
344 }431 }
345 432
346 async fn fetch_release(433 async fn fetch_release(
347 connection: &quinn::Connection,434 connection: &quinn::Connection,
348- seq: u64,435+ running: u64,
436+ installed: u64,
349 exe: &Path,437 exe: &Path,
350-) -> Result<Option<(Release, fs::File, Vec<u8>)>, Fail> {438+) -> Result<Outcome, Fail> {
351 let manifest = fetch(connection, MANIFEST, MANIFEST_MAX).await?;439 let manifest = fetch(connection, MANIFEST, MANIFEST_MAX).await?;
352 let release = verify(&manifest, &target(), keys::KEYS).map_err(Fail::Reject)?;440 let release = verify(&manifest, &target(), keys::KEYS).map_err(Fail::Reject)?;
353- if release.seq <= seq || number(&state(exe, "skip")) == Some(release.seq) {441+ let required = running < release.minimum || OUTDATED.load(Ordering::Relaxed);
354- return Ok(None);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);
355 }451 }
356 let file = open_new(exe)?;452 let file = open_new(exe)?;
357 info!("update: downloading {} ({})", release.version, release.seq);453 info!("update: downloading {} ({})", release.version, release.seq);
@@ -365,13 +461,16 @@ async fn fetch_release(
365 let _ = fs::remove_file(sibling(exe, "new"));461 let _ = fs::remove_file(sibling(exe, "new"));
366 return Err(Fail::Hash);462 return Err(Fail::Hash);
367 }463 }
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+ })
369 }470 }
370 471
371 fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result<Release, Reject> {472 fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result<Release, Reject> {
372- let (sig, body) = signed473+ let (sig, body) = wire::split(signed).ok_or(Reject::Short)?;
373- .split_at_checked(SIGNATURE_BYTES)
374- .ok_or(Reject::Short)?;
375 let signed_by_us = keys.iter().any(|key| {474 let signed_by_us = keys.iter().any(|key| {
376 signature::UnparsedPublicKey::new(&signature::ED25519, key)475 signature::UnparsedPublicKey::new(&signature::ED25519, key)
377 .verify(body, sig)476 .verify(body, sig)
@@ -380,74 +479,17 @@ fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result<Release, Rej
380 if !signed_by_us {479 if !signed_by_us {
381 return Err(Reject::Signature);480 return Err(Reject::Signature);
382 }481 }
383- let text = std::str::from_utf8(body).map_err(|_| Reject::Format)?;482+ let manifest = wire::parse(body).ok_or(Reject::Format)?;
384- let mut lines = text.split('\n');483+ let file = manifest.file(target).ok_or(Reject::Target)?;
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)?;
422 Ok(Release {484 Ok(Release {
423- seq,485+ seq: manifest.seq,
424- version,486+ minimum: manifest.minimum,
425- size,487+ version: manifest.version.clone(),
426- sha256,488+ size: file.size,
489+ sha256: file.sha256,
427 })490 })
428 }491 }
429 492
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-
451 fn open_new(exe: &Path) -> std::io::Result<fs::File> {493 fn open_new(exe: &Path) -> std::io::Result<fs::File> {
452 let new = sibling(exe, "new");494 let new = sibling(exe, "new");
453 let _ = fs::remove_file(&new);495 let _ = fs::remove_file(&new);
@@ -539,6 +581,8 @@ mod tests {
539 signature::{Ed25519KeyPair, KeyPair},581 signature::{Ed25519KeyPair, KeyPair},
540 };582 };
541 583
584+ use common::update::MAGIC;
585+
542 use super::*;586 use super::*;
543 587
544 fn signed(key: &Ed25519KeyPair, body: &str) -> Vec<u8> {588 fn signed(key: &Ed25519KeyPair, body: &str) -> Vec<u8> {
@@ -560,12 +604,17 @@ mod tests {
560 fn verifies() {604 fn verifies() {
561 let (key, public) = pair();605 let (key, public) = pair();
562 let body = format!(606 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"
564 );608 );
565 let release = verify(&signed(&key, &body), "x86_64-windows", &[public]).unwrap();609 let release = verify(&signed(&key, &body), "x86_64-windows", &[public]).unwrap();
566 assert_eq!(610 assert_eq!(
567- (release.seq, release.size, release.sha256[1]),611+ (
568- (7, 20, 0x11)612+ release.seq,
613+ release.minimum,
614+ release.size,
615+ release.sha256[1]
616+ ),
617+ (7, 3, 20, 0x11)
569 );618 );
570 }619 }
571 620
@@ -573,7 +622,7 @@ mod tests {
573 fn rejects() {622 fn rejects() {
574 let (key, public) = pair();623 let (key, public) = pair();
575 let (other, _) = pair();624 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");
577 let mut tampered = signed(&key, &good);626 let mut tampered = signed(&key, &good);
578 *tampered.last_mut().unwrap() ^= 1;627 *tampered.last_mut().unwrap() ^= 1;
579 let cases = [628 let cases = [
@@ -586,6 +635,9 @@ mod tests {
586 signed(&key, &good.replace("seq 7", "seq x")),635 signed(&key, &good.replace("seq 7", "seq x")),
587 signed(&key, &good.replace(MAGIC, "yumush-update 2")),636 signed(&key, &good.replace(MAGIC, "yumush-update 2")),
588 signed(&key, &format!("{good}manifest 10 {HASH}\n")),637 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", "")),
589 ];641 ];
590 for case in cases {642 for case in cases {
591 assert!(verify(&case, "x86_64-linux", &[public]).is_err());643 assert!(verify(&case, "x86_64-linux", &[public]).is_err());
crates/common/src/event.rsmodified+1 -0
@@ -86,6 +86,7 @@ pub enum Event {
86 user_id: Id,86 user_id: Id,
87 stats: Stats,87 stats: Stats,
88 },88 },
89+ Release,
89 }90 }
90 91
91 #[derive(Debug, Clone, Encode, Decode)]92 #[derive(Debug, Clone, Encode, Decode)]
crates/common/src/session.rsmodified+1 -0
@@ -6,6 +6,7 @@ use crate::model::User;
6 pub struct Hello {6 pub struct Hello {
7 pub token: Option<String>,7 pub token: Option<String>,
8 pub device: String,8 pub device: String,
9+ pub release: Option<u64>,
9 }10 }
10 11
11 #[derive(Debug, Clone, Encode, Decode)]12 #[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};
3 use quinn::{Endpoint, EndpointConfig, ServerConfig, TokioRuntime, TransportConfig, VarInt};3 use quinn::{Endpoint, EndpointConfig, ServerConfig, TokioRuntime, TransportConfig, VarInt};
4 use socket2::{Domain, Protocol, Socket, Type};4 use socket2::{Domain, Protocol, Socket, Type};
5 5
6-pub const ALPN: &[u8] = b"yumush/2";6+pub const ALPN: &[u8] = b"yumush/3";
7 7
8 const IDLE_TIMEOUT: Duration = Duration::from_secs(10);8 const IDLE_TIMEOUT: Duration = Duration::from_secs(10);
9 pub const KEEP_ALIVE: Duration = Duration::from_secs(1);9 pub const KEEP_ALIVE: Duration = Duration::from_secs(1);
@@ -43,10 +43,11 @@ pub enum Close {
43 Maintenance = 4,43 Maintenance = 4,
44 Slow = 5,44 Slow = 5,
45 Protocol = 6,45 Protocol = 6,
46+ Outdated = 7,
46 }47 }
47 48
48 impl Close {49 impl Close {
49- pub const ALL: [Self; 7] = [50+ pub const ALL: [Self; 8] = [
50 Self::Normal,51 Self::Normal,
51 Self::SignedOut,52 Self::SignedOut,
52 Self::Revoked,53 Self::Revoked,
@@ -54,6 +55,7 @@ impl Close {
54 Self::Maintenance,55 Self::Maintenance,
55 Self::Slow,56 Self::Slow,
56 Self::Protocol,57 Self::Protocol,
58+ Self::Outdated,
57 ];59 ];
58 60
59 pub fn of(code: VarInt) -> Option<Self> {61 pub fn of(code: VarInt) -> Option<Self> {
@@ -69,6 +71,7 @@ impl Close {
69 Self::Maintenance => "maintenance",71 Self::Maintenance => "maintenance",
70 Self::Slow => "slow",72 Self::Slow => "slow",
71 Self::Protocol => "protocol error",73 Self::Protocol => "protocol error",
74+ Self::Outdated => "outdated",
72 }75 }
73 }76 }
74 77
crates/common/src/update.rsmodified+92 -0
@@ -81,3 +81,95 @@ pub async fn receive(receive: &mut RecvStream, maximum: u64) -> Result<Vec<u8>,
81 }81 }
82 Ok(bytes)82 Ok(bytes)
83 }83 }
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 {
29 pub me: Option<Signed>,29 pub me: Option<Signed>,
30 tx: mpsc::Sender<Bytes>,30 tx: mpsc::Sender<Bytes>,
31 pub closed: AtomicBool,31 pub closed: AtomicBool,
32+ pub release: AtomicU64,
32 watching: Mutex<Option<Id>>,33 watching: Mutex<Option<Id>>,
33 ghost_logged: Mutex<HashSet<Id>>,34 ghost_logged: Mutex<HashSet<Id>>,
34 }35 }
@@ -42,6 +43,7 @@ impl Client {
42 me,43 me,
43 tx,44 tx,
44 closed: AtomicBool::new(false),45 closed: AtomicBool::new(false),
46+ release: AtomicU64::new(u64::MAX),
45 watching: Mutex::new(None),47 watching: Mutex::new(None),
46 ghost_logged: Mutex::new(HashSet::new()),48 ghost_logged: Mutex::new(HashSet::new()),
47 });49 });
@@ -192,6 +194,20 @@ impl Hub {
192 }194 }
193 }195 }
194 196
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+
195 pub fn kick_user(&self, user_id: Id, close: Close) {211 pub fn kick_user(&self, user_id: Id, close: Close) {
196 self.kick_where(|me| me.user_id == user_id, close);212 self.kick_where(|me| me.user_id == user_id, close);
197 }213 }
crates/server/src/network.rsmodified+8 -0
@@ -40,6 +40,7 @@ pub struct Services {
40 pub rate_limit: RateLimit,40 pub rate_limit: RateLimit,
41 pub stats: Follows,41 pub stats: Follows,
42 pub machine: Machine,42 pub machine: Machine,
43+ pub minimum: std::sync::Arc<std::sync::atomic::AtomicU64>,
43 }44 }
44 45
45 #[derive(Clone)]46 #[derive(Clone)]
@@ -83,6 +84,7 @@ pub async fn serve(
83 shared.services.machine.watch(shared.directory.clone());84 shared.services.machine.watch(shared.directory.clone());
84 85
85 tokio::spawn(retention::collect(shared.clone()));86 tokio::spawn(retention::collect(shared.clone()));
87+ tokio::spawn(crate::update::watch(shared.clone()));
86 88
87 while let Some(incoming) = endpoint.accept().await {89 while let Some(incoming) = endpoint.accept().await {
88 tokio::spawn(handle_connection(incoming, shared.clone()));90 tokio::spawn(handle_connection(incoming, shared.clone()));
@@ -230,10 +232,16 @@ async fn greet(connection: &Connection, shared: &Shared) -> Result<Option<Pendin
230 let (send_stream, mut receive_stream) = connection.accept_bi().await?;232 let (send_stream, mut receive_stream) = connection.accept_bi().await?;
231 let mut reply_stream = Sending::new(send_stream);233 let mut reply_stream = Sending::new(send_stream);
232 let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?;234 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+ }
233 240
234 match admit(hello, connection, shared).await {241 match admit(hello, connection, shared).await {
235 Ok((me, user)) => {242 Ok((me, user)) => {
236 let (client, events) = Client::new(Some(connection.clone()), me);243 let (client, events) = Client::new(Some(connection.clone()), me);
244+ client.release.store(release, Ordering::Relaxed);
237 245
238 Ok(Some(Pending {246 Ok(Some(Pending {
239 client,247 client,
crates/server/src/update.rsmodified+64 -5
@@ -1,5 +1,5 @@
1 use std::{1 use std::{
2- collections::HashSet,2+ collections::HashMap,
3 net::IpAddr,3 net::IpAddr,
4 path::{Path, PathBuf},4 path::{Path, PathBuf},
5 sync::Mutex,5 sync::Mutex,
@@ -11,33 +11,45 @@ use quinn::{Connection, RecvStream, SendStream};
11 use tokio::{io::AsyncReadExt, sync::Semaphore, time::timeout};11 use tokio::{io::AsyncReadExt, sync::Semaphore, time::timeout};
12 use tracing::warn;12 use tracing::warn;
13 13
14-use crate::error::ServerError;14+use crate::{error::ServerError, network::Shared};
15 15
16 const STREAMS: usize = 4;16 const STREAMS: usize = 4;
17 const ACCEPT_DEADLINE: Duration = Duration::from_secs(30);17 const ACCEPT_DEADLINE: Duration = Duration::from_secs(30);
18 const ASK_DEADLINE: Duration = Duration::from_secs(5);18 const ASK_DEADLINE: Duration = Duration::from_secs(5);
19 const TRANSFER_DEADLINE: Duration = Duration::from_secs(15 * 60);19 const TRANSFER_DEADLINE: Duration = Duration::from_secs(15 * 60);
20 const STALL_DEADLINE: Duration = Duration::from_secs(30);20 const STALL_DEADLINE: Duration = Duration::from_secs(30);
21+const WATCH_EVERY: Duration = Duration::from_secs(5);
21 const CHUNK: usize = 64 << 10;22 const CHUNK: usize = 64 << 10;
22 static PERMITS: Semaphore = Semaphore::const_new(16);23 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);
24 26
25 struct Peer(IpAddr);27 struct Peer(IpAddr);
26 28
27 impl Peer {29 impl Peer {
28 fn claim(ip: IpAddr) -> Option<Self> {30 fn claim(ip: IpAddr) -> Option<Self> {
29 let mut peers = PEERS.lock().unwrap();31 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))
31 }38 }
32 }39 }
33 40
34 impl Drop for Peer {41 impl Drop for Peer {
35 fn drop(&mut self) {42 fn drop(&mut self) {
36- if let Some(peers) = PEERS.lock().unwrap().as_mut() {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 {
37 peers.remove(&self.0);48 peers.remove(&self.0);
38 }49 }
39 }50 }
40 }51 }
52+}
41 53
42 pub async fn serve(connection: Connection, directory: PathBuf) {54 pub async fn serve(connection: Connection, directory: PathBuf) {
43 let (Some(_peer), Ok(_permit)) = (55 let (Some(_peer), Ok(_permit)) = (
@@ -106,3 +118,50 @@ async fn transfer(
106 118
107 Ok(())119 Ok(())
108 }120 }
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)"
4 KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}"4 KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}"
5 cd "$ROOT"5 cd "$ROOT"
6 usage() {6 usage() {
7- echo "usage: $0 build <seq> | sign <seq> [primary|backup]" >&27+ echo "usage: $0 build <seq> | sign <seq> <minimum> (minimum = oldest seq still allowed; = seq forces everyone up)" >&2
8 exit 18 exit 1
9 }9 }
10 [[ $# -ge 2 && "$2" =~ ^[1-9][0-9]{0,17}$ ]] || usage10 [[ $# -ge 2 && "$2" =~ ^[1-9][0-9]{0,17}$ ]] || usage
@@ -27,11 +27,13 @@ build)
27 echo "$DIST/$TARGET"27 echo "$DIST/$TARGET"
28 ;;28 ;;
29 sign)29 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"
31 VERSION=$(cargo pkgid -p client | sed 's/.*[#@]//')33 VERSION=$(cargo pkgid -p client | sed 's/.*[#@]//')
32 BODY="$DIST/manifest.body"34 BODY="$DIST/manifest.body"
33 {35 {
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"
35 for file in "$DIST"/*; do37 for file in "$DIST"/*; do
36 name=$(basename "$file")38 name=$(basename "$file")
37 [[ "$name" =~ ^[a-z0-9_]+-[a-z0-9_]+$ ]] || continue39 [[ "$name" =~ ^[a-z0-9_]+-[a-z0-9_]+$ ]] || continue
@@ -44,7 +46,7 @@ sign)
44 printf '%s %s %s\n' "$name" "$(stat -c %s "$file")" "$(sha256sum "$file" | cut -d' ' -f1)"46 printf '%s %s %s\n' "$name" "$(stat -c %s "$file")" "$(sha256sum "$file" | cut -d' ' -f1)"
45 done47 done
46 } > "$BODY"48 } > "$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; }
48 cat "$BODY"50 cat "$BODY"
49 SIG=$(mktemp)51 SIG=$(mktemp)
50 PUBLIC=$(mktemp)52 PUBLIC=$(mktemp)