Push-driven, enforceable updates. Server watches updates/manifest and pushes Event::Release
Browse files at this commitdebc8fb584664b58ad95ca040aeacbfcd98e3af3Parent: 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
17 changed files +398 -187
- crates/client/lang/en/settings_page.txt +0 -3
- crates/client/lang/tr/settings_page.txt +0 -3
- crates/client/src/gui/chat.rs +1 -1
- crates/client/src/gui/settings_page.rs +2 -18
- crates/client/src/net/events.rs +3 -0
- crates/client/src/net/fail.rs +9 -3
- crates/client/src/net/link.rs +27 -10
- crates/client/src/settings.rs +0 -27
- crates/client/src/update.rs +162 -110
- crates/common/src/event.rs +1 -0
- crates/common/src/session.rs +1 -0
- crates/common/src/transport.rs +5 -2
- crates/common/src/update.rs +92 -0
- crates/server/src/hub.rs +16 -0
- crates/server/src/network.rs +8 -0
- crates/server/src/update.rs +65 -6
- packaging/release.sh +6 -4
crates/client/lang/en/settings_page.txtmodified+0 -3
| @@ -20,9 +20,6 @@ launch = Launch at login | ||
| 20 | 20 | launch_off = Off |
| 21 | 21 | launch_window = Window |
| 22 | 22 | launch_tray = Tray |
| 23 | -updates = Updates | |
| 24 | -updates_off = Off | |
| 25 | -updates_auto = Automatic | |
| 26 | 23 | your_hue = Your hue |
| 27 | 24 | camera = Camera |
| 28 | 25 | screen_share = Screen share |
crates/client/lang/tr/settings_page.txtmodified+0 -3
| @@ -20,9 +20,6 @@ launch = Oturum açılınca | ||
| 20 | 20 | launch_off = Kapalı |
| 21 | 21 | launch_window = Pencere |
| 22 | 22 | launch_tray = Tepsi |
| 23 | -updates = Güncellemeler | |
| 24 | -updates_off = Kapalı | |
| 25 | -updates_auto = Otomatik | |
| 26 | 23 | your_hue = Rengin |
| 27 | 24 | camera = Kamera |
| 28 | 25 | screen_share = Ekran paylaşımı |
crates/client/src/gui/chat.rsmodified+1 -1
| @@ -799,7 +799,7 @@ impl Chat { | ||
| 799 | 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 | 26 | use crate::{ |
| 27 | 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 | 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 | 46 | let s = &w().settings_page; |
| 47 | 47 | let v = &w().voice_settings; |
| 48 | 48 | [ |
| @@ -69,7 +69,6 @@ pub(super) fn setting_rows() -> [(usize, &'static str); 26] { | ||
| 69 | 69 | (3, s.language), |
| 70 | 70 | (3, s.close_to_tray), |
| 71 | 71 | (3, s.launch), |
| 72 | - (3, s.updates), | |
| 73 | 72 | (3, s.clock_seconds), |
| 74 | 73 | (3, s.your_hue), |
| 75 | 74 | ] |
| @@ -222,16 +221,6 @@ impl Yumush { | ||
| 222 | 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 | 224 | row( |
| 236 | 225 | w().settings_page.clock_seconds, |
| 237 | 226 | super::parts::toggle( |
| @@ -399,11 +388,6 @@ impl Yumush { | ||
| 399 | 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 | 391 | pub(super) fn toggle_clock_seconds(&mut self, cx: &mut Context<Self>) { |
| 408 | 392 | self.settings.clock_seconds = !self.settings.clock_seconds; |
| 409 | 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 | 18 | while let Ok(down) = frame::read::<Down>(&mut receive_stream, DOWN_MAX).await { |
| 19 | 19 | match down { |
| 20 | + Down::Event(event) if matches!(*event, common::event::Event::Release) => { | |
| 21 | + crate::update::poke(); | |
| 22 | + } | |
| 20 | 23 | Down::Event(event) => { |
| 21 | 24 | media.pushed(&event); |
| 22 | 25 | 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 | 29 | impl LinkError { |
| 30 | + pub(super) fn terminal(self) -> bool { | |
| 31 | + matches!(self, Self::Outdated | Self::Closed(Close::Banned)) | |
| 32 | + } | |
| 33 | + | |
| 30 | 34 | fn by_code(code: u64) -> Self { |
| 31 | 35 | match code { |
| 32 | 36 | NO_APPLICATION_PROTOCOL => Self::Outdated, |
| @@ -44,9 +48,11 @@ impl From<quinn::ConnectionError> for LinkError { | ||
| 44 | 48 | Self::by_code(u64::from(close.error_code)) |
| 45 | 49 | } |
| 46 | 50 | 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 | + }, | |
| 50 | 56 | quinn::ConnectionError::LocallyClosed => Self::Closed(Close::Normal), |
| 51 | 57 | quinn::ConnectionError::VersionMismatch => Self::Outdated, |
| 52 | 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 | 110 | *attempt += 1; |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | -pub(crate) async fn dial( | |
| 113 | +pub(crate) async fn dial<T>( | |
| 114 | 114 | server: &crate::Server, |
| 115 | 115 | 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) | |
| 118 | 126 | } |
| 119 | 127 | |
| 120 | 128 | async fn connect( |
| @@ -271,6 +279,7 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result< | ||
| 271 | 279 | let hello = Hello { |
| 272 | 280 | token, |
| 273 | 281 | device: device_name(), |
| 282 | + release: crate::update::SEQ, | |
| 274 | 283 | }; |
| 275 | 284 | |
| 276 | 285 | Ok(exchange(connection, &hello).await?.0) |
| @@ -402,6 +411,7 @@ async fn actor( | ||
| 402 | 411 | Ok(connection) => break connection, |
| 403 | 412 | Err(LinkError::Outdated) => { |
| 404 | 413 | warn!("server speaks another protocol version"); |
| 414 | + crate::update::outdated(); | |
| 405 | 415 | let _ = event_sender |
| 406 | 416 | .send(NetworkEvent::Disconnected(LinkError::Outdated)) |
| 407 | 417 | .await; |
| @@ -455,12 +465,15 @@ async fn actor( | ||
| 455 | 465 | } |
| 456 | 466 | Err(error) => { |
| 457 | 467 | 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()) | |
| 460 | 472 | { |
| 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; | |
| 464 | 477 | while command_receiver.recv().await.is_some() {} |
| 465 | 478 | return; |
| 466 | 479 | } |
| @@ -471,6 +484,7 @@ async fn actor( | ||
| 471 | 484 | |
| 472 | 485 | attempt = 0; |
| 473 | 486 | info!("connected"); |
| 487 | + crate::update::poke(); | |
| 474 | 488 | shared.media.ready(connection.clone(), event_sender.clone()); |
| 475 | 489 | if event_sender.send(NetworkEvent::Connected).await.is_err() { |
| 476 | 490 | return; |
| @@ -536,13 +550,16 @@ async fn actor( | ||
| 536 | 550 | shared.media.lost(); |
| 537 | 551 | |
| 538 | 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 | 558 | if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() { |
| 542 | 559 | return; |
| 543 | 560 | } |
| 544 | 561 | |
| 545 | - if banned { | |
| 562 | + if terminal { | |
| 546 | 563 | while command_receiver.recv().await.is_some() {} |
| 547 | 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 | 93 | string_enum! { |
| 115 | 94 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 116 | 95 | Activation { |
| @@ -242,7 +221,6 @@ pub struct Settings { | ||
| 242 | 221 | pub share: ShareSettings, |
| 243 | 222 | pub close_to_tray: bool, |
| 244 | 223 | pub launch: Launch, |
| 245 | - pub updates: Updates, | |
| 246 | 224 | pub clock_seconds: bool, |
| 247 | 225 | pub jump_usage: BTreeMap<String, u32>, |
| 248 | 226 | pub last_chats: BTreeMap<Id, Id>, |
| @@ -272,7 +250,6 @@ impl Default for Settings { | ||
| 272 | 250 | } else { |
| 273 | 251 | Launch::Window |
| 274 | 252 | }, |
| 275 | - updates: Updates::Auto, | |
| 276 | 253 | clock_seconds: false, |
| 277 | 254 | jump_usage: BTreeMap::new(), |
| 278 | 255 | last_chats: BTreeMap::new(), |
| @@ -391,9 +368,6 @@ pub fn load() -> Settings { | ||
| 391 | 368 | .and_then(|value| Launch::parse(&value)) |
| 392 | 369 | .filter(|launch| Launch::options().any(|option| option == *launch)) |
| 393 | 370 | .unwrap_or(defaults.launch), |
| 394 | - updates: text("updates") | |
| 395 | - .and_then(|value| Updates::parse(&value)) | |
| 396 | - .unwrap_or(defaults.updates), | |
| 397 | 371 | clock_seconds: text("clock_seconds") |
| 398 | 372 | .map_or(defaults.clock_seconds, |value| value == "true"), |
| 399 | 373 | jump_usage: text("jump.usage") |
| @@ -436,7 +410,6 @@ pub fn save(settings: &Settings) { | ||
| 436 | 410 | line("language", settings.language.as_str()), |
| 437 | 411 | line("close_to_tray", settings.close_to_tray), |
| 438 | 412 | line("launch", settings.launch.as_str()), |
| 439 | - line("updates", settings.updates.as_str()), | |
| 440 | 413 | line("clock_seconds", settings.clock_seconds), |
| 441 | 414 | line("voice.sensitivity", voice.sensitivity_db), |
| 442 | 415 | line("voice.input_volume", voice.input_volume), |
crates/client/src/update.rsmodified+162 -110
| @@ -3,20 +3,31 @@ use std::{ | ||
| 3 | 3 | io::{Read, Write}, |
| 4 | 4 | path::{Path, PathBuf}, |
| 5 | 5 | process::{Command, Stdio}, |
| 6 | + sync::{ | |
| 7 | + OnceLock, | |
| 8 | + atomic::{AtomicBool, Ordering}, | |
| 9 | + mpsc, | |
| 10 | + }, | |
| 6 | 11 | time::{Duration, Instant}, |
| 7 | 12 | }; |
| 8 | 13 | |
| 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 | +}; | |
| 11 | 20 | use tracing::{info, warn}; |
| 12 | 21 | |
| 13 | 22 | mod keys; |
| 14 | 23 | |
| 15 | 24 | 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); | |
| 20 | 31 | const SELFTEST_LIMIT: Duration = Duration::from_secs(20); |
| 21 | 32 | const PACKAGED_ENV: [&str; 3] = ["FLATPAK_ID", "SNAP", "APPIMAGE"]; |
| 22 | 33 | const PACKAGED_ROOTS: [&str; 2] = ["/usr/", "/nix/"]; |
| @@ -48,7 +59,6 @@ const fn parse_seq(text: &str) -> u64 { | ||
| 48 | 59 | #[derive(Debug)] |
| 49 | 60 | enum Off { |
| 50 | 61 | Unofficial, |
| 51 | - Platform, | |
| 52 | 62 | Multi, |
| 53 | 63 | Packaged, |
| 54 | 64 | NoExe, |
| @@ -74,19 +84,35 @@ enum Reject { | ||
| 74 | 84 | Target, |
| 75 | 85 | } |
| 76 | 86 | |
| 77 | -enum Check { | |
| 87 | +enum Outcome { | |
| 78 | 88 | Current, |
| 79 | 89 | Staged(u64), |
| 90 | + Restart, | |
| 80 | 91 | } |
| 81 | 92 | |
| 82 | 93 | #[derive(Debug, PartialEq)] |
| 83 | 94 | struct Release { |
| 84 | 95 | seq: u64, |
| 96 | + minimum: u64, | |
| 85 | 97 | version: String, |
| 86 | 98 | size: u64, |
| 87 | 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 | 116 | impl From<std::io::Error> for Fail { |
| 91 | 117 | fn from(error: std::io::Error) -> Self { |
| 92 | 118 | Self::Io(error) |
| @@ -107,9 +133,6 @@ impl From<quinn::ConnectionError> for Fail { | ||
| 107 | 133 | |
| 108 | 134 | fn mode() -> Result<(u64, &'static Path), Off> { |
| 109 | 135 | let seq = SEQ.ok_or(Off::Unofficial)?; |
| 110 | - if cfg!(target_os = "macos") { | |
| 111 | - return Err(Off::Platform); | |
| 112 | - } | |
| 113 | 136 | if std::env::args().any(|arg| arg == crate::instance::MULTI) { |
| 114 | 137 | return Err(Off::Multi); |
| 115 | 138 | } |
| @@ -205,7 +228,19 @@ pub fn selftest() -> bool { | ||
| 205 | 228 | 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 | 242 | pub fn boot() -> bool { |
| 243 | + wait_parent(); | |
| 209 | 244 | let Ok((seq, exe)) = mode() else { |
| 210 | 245 | return false; |
| 211 | 246 | }; |
| @@ -296,31 +331,88 @@ pub fn ready() { | ||
| 296 | 331 | let _ = fs::remove_file(state(exe, "trial")); |
| 297 | 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 | 338 | let _ = std::thread::Builder::new() |
| 300 | 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 | 350 | let Ok(runtime) = tokio::runtime::Builder::new_current_thread() |
| 306 | 351 | .enable_all() |
| 307 | 352 | .build() |
| 308 | 353 | else { |
| 309 | 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 | 359 | 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; | |
| 321 | 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 | + } | |
| 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; | |
| 322 | 401 | } |
| 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}"), | |
| 324 | 416 | } |
| 325 | 417 | } |
| 326 | 418 | |
| @@ -330,28 +422,32 @@ async fn fetch(connection: &quinn::Connection, name: &str, maximum: u64) -> Resu | ||
| 330 | 422 | Ok(wire::receive(&mut receive, maximum).await?) |
| 331 | 423 | } |
| 332 | 424 | |
| 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)? | |
| 344 | 431 | } |
| 345 | 432 | |
| 346 | 433 | async fn fetch_release( |
| 347 | 434 | connection: &quinn::Connection, |
| 348 | - seq: u64, | |
| 435 | + running: u64, | |
| 436 | + installed: u64, | |
| 349 | 437 | exe: &Path, |
| 350 | -) -> Result<Option<(Release, fs::File, Vec<u8>)>, Fail> { | |
| 438 | +) -> Result<Outcome, Fail> { | |
| 351 | 439 | let manifest = fetch(connection, MANIFEST, MANIFEST_MAX).await?; |
| 352 | 440 | 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); | |
| 355 | 451 | } |
| 356 | 452 | let file = open_new(exe)?; |
| 357 | 453 | info!("update: downloading {} ({})", release.version, release.seq); |
| @@ -365,13 +461,16 @@ async fn fetch_release( | ||
| 365 | 461 | let _ = fs::remove_file(sibling(exe, "new")); |
| 366 | 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 | 472 | 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)?; | |
| 375 | 474 | let signed_by_us = keys.iter().any(|key| { |
| 376 | 475 | signature::UnparsedPublicKey::new(&signature::ED25519, key) |
| 377 | 476 | .verify(body, sig) |
| @@ -380,74 +479,17 @@ fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result<Release, Rej | ||
| 380 | 479 | if !signed_by_us { |
| 381 | 480 | return Err(Reject::Signature); |
| 382 | 481 | } |
| 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)?; | |
| 422 | 484 | 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, | |
| 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 | 493 | fn open_new(exe: &Path) -> std::io::Result<fs::File> { |
| 452 | 494 | let new = sibling(exe, "new"); |
| 453 | 495 | let _ = fs::remove_file(&new); |
| @@ -539,6 +581,8 @@ mod tests { | ||
| 539 | 581 | signature::{Ed25519KeyPair, KeyPair}, |
| 540 | 582 | }; |
| 541 | 583 | |
| 584 | + use common::update::MAGIC; | |
| 585 | + | |
| 542 | 586 | use super::*; |
| 543 | 587 | |
| 544 | 588 | fn signed(key: &Ed25519KeyPair, body: &str) -> Vec<u8> { |
| @@ -560,12 +604,17 @@ mod tests { | ||
| 560 | 604 | fn verifies() { |
| 561 | 605 | let (key, public) = pair(); |
| 562 | 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 | 609 | let release = verify(&signed(&key, &body), "x86_64-windows", &[public]).unwrap(); |
| 566 | 610 | 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) | |
| 569 | 618 | ); |
| 570 | 619 | } |
| 571 | 620 | |
| @@ -573,7 +622,7 @@ mod tests { | ||
| 573 | 622 | fn rejects() { |
| 574 | 623 | let (key, public) = pair(); |
| 575 | 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 | 626 | let mut tampered = signed(&key, &good); |
| 578 | 627 | *tampered.last_mut().unwrap() ^= 1; |
| 579 | 628 | let cases = [ |
| @@ -586,6 +635,9 @@ mod tests { | ||
| 586 | 635 | signed(&key, &good.replace("seq 7", "seq x")), |
| 587 | 636 | signed(&key, &good.replace(MAGIC, "yumush-update 2")), |
| 588 | 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 | 642 | for case in cases { |
| 591 | 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 | 86 | user_id: Id, |
| 87 | 87 | stats: Stats, |
| 88 | 88 | }, |
| 89 | + Release, | |
| 89 | 90 | } |
| 90 | 91 | |
| 91 | 92 | #[derive(Debug, Clone, Encode, Decode)] |
crates/common/src/session.rsmodified+1 -0
| @@ -6,6 +6,7 @@ use crate::model::User; | ||
| 6 | 6 | pub struct Hello { |
| 7 | 7 | pub token: Option<String>, |
| 8 | 8 | pub device: String, |
| 9 | + pub release: Option<u64>, | |
| 9 | 10 | } |
| 10 | 11 | |
| 11 | 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 | 3 | use quinn::{Endpoint, EndpointConfig, ServerConfig, TokioRuntime, TransportConfig, VarInt}; |
| 4 | 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 | 8 | const IDLE_TIMEOUT: Duration = Duration::from_secs(10); |
| 9 | 9 | pub const KEEP_ALIVE: Duration = Duration::from_secs(1); |
| @@ -43,10 +43,11 @@ pub enum Close { | ||
| 43 | 43 | Maintenance = 4, |
| 44 | 44 | Slow = 5, |
| 45 | 45 | Protocol = 6, |
| 46 | + Outdated = 7, | |
| 46 | 47 | } |
| 47 | 48 | |
| 48 | 49 | impl Close { |
| 49 | - pub const ALL: [Self; 7] = [ | |
| 50 | + pub const ALL: [Self; 8] = [ | |
| 50 | 51 | Self::Normal, |
| 51 | 52 | Self::SignedOut, |
| 52 | 53 | Self::Revoked, |
| @@ -54,6 +55,7 @@ impl Close { | ||
| 54 | 55 | Self::Maintenance, |
| 55 | 56 | Self::Slow, |
| 56 | 57 | Self::Protocol, |
| 58 | + Self::Outdated, | |
| 57 | 59 | ]; |
| 58 | 60 | |
| 59 | 61 | pub fn of(code: VarInt) -> Option<Self> { |
| @@ -69,6 +71,7 @@ impl Close { | ||
| 69 | 71 | Self::Maintenance => "maintenance", |
| 70 | 72 | Self::Slow => "slow", |
| 71 | 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 | 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 | 29 | pub me: Option<Signed>, |
| 30 | 30 | tx: mpsc::Sender<Bytes>, |
| 31 | 31 | pub closed: AtomicBool, |
| 32 | + pub release: AtomicU64, | |
| 32 | 33 | watching: Mutex<Option<Id>>, |
| 33 | 34 | ghost_logged: Mutex<HashSet<Id>>, |
| 34 | 35 | } |
| @@ -42,6 +43,7 @@ impl Client { | ||
| 42 | 43 | me, |
| 43 | 44 | tx, |
| 44 | 45 | closed: AtomicBool::new(false), |
| 46 | + release: AtomicU64::new(u64::MAX), | |
| 45 | 47 | watching: Mutex::new(None), |
| 46 | 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 | 211 | pub fn kick_user(&self, user_id: Id, close: Close) { |
| 196 | 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 | 40 | pub rate_limit: RateLimit, |
| 41 | 41 | pub stats: Follows, |
| 42 | 42 | pub machine: Machine, |
| 43 | + pub minimum: std::sync::Arc<std::sync::atomic::AtomicU64>, | |
| 43 | 44 | } |
| 44 | 45 | |
| 45 | 46 | #[derive(Clone)] |
| @@ -83,6 +84,7 @@ pub async fn serve( | ||
| 83 | 84 | shared.services.machine.watch(shared.directory.clone()); |
| 84 | 85 | |
| 85 | 86 | tokio::spawn(retention::collect(shared.clone())); |
| 87 | + tokio::spawn(crate::update::watch(shared.clone())); | |
| 86 | 88 | |
| 87 | 89 | while let Some(incoming) = endpoint.accept().await { |
| 88 | 90 | tokio::spawn(handle_connection(incoming, shared.clone())); |
| @@ -230,10 +232,16 @@ async fn greet(connection: &Connection, shared: &Shared) -> Result<Option<Pendin | ||
| 230 | 232 | let (send_stream, mut receive_stream) = connection.accept_bi().await?; |
| 231 | 233 | let mut reply_stream = Sending::new(send_stream); |
| 232 | 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 | 241 | match admit(hello, connection, shared).await { |
| 235 | 242 | Ok((me, user)) => { |
| 236 | 243 | let (client, events) = Client::new(Some(connection.clone()), me); |
| 244 | + client.release.store(release, Ordering::Relaxed); | |
| 237 | 245 | |
| 238 | 246 | Ok(Some(Pending { |
| 239 | 247 | client, |
crates/server/src/update.rsmodified+65 -6
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | use std::{ |
| 2 | - collections::HashSet, | |
| 2 | + collections::HashMap, | |
| 3 | 3 | net::IpAddr, |
| 4 | 4 | path::{Path, PathBuf}, |
| 5 | 5 | sync::Mutex, |
| @@ -11,30 +11,42 @@ use quinn::{Connection, RecvStream, SendStream}; | ||
| 11 | 11 | use tokio::{io::AsyncReadExt, sync::Semaphore, time::timeout}; |
| 12 | 12 | use tracing::warn; |
| 13 | 13 | |
| 14 | -use crate::error::ServerError; | |
| 14 | +use crate::{error::ServerError, network::Shared}; | |
| 15 | 15 | |
| 16 | 16 | const STREAMS: usize = 4; |
| 17 | 17 | const ACCEPT_DEADLINE: Duration = Duration::from_secs(30); |
| 18 | 18 | const ASK_DEADLINE: Duration = Duration::from_secs(5); |
| 19 | 19 | const TRANSFER_DEADLINE: Duration = Duration::from_secs(15 * 60); |
| 20 | 20 | const STALL_DEADLINE: Duration = Duration::from_secs(30); |
| 21 | +const WATCH_EVERY: Duration = Duration::from_secs(5); | |
| 21 | 22 | const CHUNK: usize = 64 << 10; |
| 22 | 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 | 27 | struct Peer(IpAddr); |
| 26 | 28 | |
| 27 | 29 | impl Peer { |
| 28 | 30 | fn claim(ip: IpAddr) -> Option<Self> { |
| 29 | 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 | 41 | impl Drop for Peer { |
| 35 | 42 | 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 | + } | |
| 38 | 50 | } |
| 39 | 51 | } |
| 40 | 52 | } |
| @@ -106,3 +118,50 @@ async fn transfer( | ||
| 106 | 118 | |
| 107 | 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 | 4 | KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}" |
| 5 | 5 | cd "$ROOT" |
| 6 | 6 | 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 | |
| 8 | 8 | exit 1 |
| 9 | 9 | } |
| 10 | 10 | [[ $# -ge 2 && "$2" =~ ^[1-9][0-9]{0,17}$ ]] || usage |
| @@ -27,11 +27,13 @@ build) | ||
| 27 | 27 | echo "$DIST/$TARGET" |
| 28 | 28 | ;; |
| 29 | 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 | 33 | VERSION=$(cargo pkgid -p client | sed 's/.*[#@]//') |
| 32 | 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 | 37 | for file in "$DIST"/*; do |
| 36 | 38 | name=$(basename "$file") |
| 37 | 39 | [[ "$name" =~ ^[a-z0-9_]+-[a-z0-9_]+$ ]] || continue |
| @@ -44,7 +46,7 @@ sign) | ||
| 44 | 46 | printf '%s %s %s\n' "$name" "$(stat -c %s "$file")" "$(sha256sum "$file" | cut -d' ' -f1)" |
| 45 | 47 | done |
| 46 | 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 | 50 | cat "$BODY" |
| 49 | 51 | SIG=$(mktemp) |
| 50 | 52 | PUBLIC=$(mktemp) |