Auto update. Server relays an Ed25519-signed manifest and binaries over a stable yumush-update/1 ALPN
Browse files at this commit769f1ab7cd7c6a4761f1e4051e9d019db6a69939Parent: ba41270- feat
- auto update. Server relays an Ed25519-signed manifest and binaries over a stable yumush-update/1 ALPN
- client verifies against compiled-in keys, checks size+sha256, self-tests the new exe, swaps on disk, applies on restart, rolls back if the new version never reaches its window. Release builds only (YUMUSH_RELEASE_SEQ), x86-64-v3 baseline, macOS off for now. Settings › Updates: Off / Automatic
26 changed files +1008 -13
- .gitignore +1 -0
- crates/client/Cargo.toml +1 -0
- crates/client/lang/en/settings_page.txt +3 -0
- crates/client/lang/tr/settings_page.txt +3 -0
- crates/client/src/autostart.rs +10 -5
- crates/client/src/gui/settings_page.rs +18 -2
- crates/client/src/lib.rs +8 -0
- crates/client/src/logo.rs +1 -1
- crates/client/src/main.rs +6 -0
- crates/client/src/net/link.rs +12 -4
- crates/client/src/net/mod.rs +1 -0
- crates/client/src/settings.rs +27 -0
- crates/client/src/update.rs +594 -0
- crates/client/src/update/keys.rs +1 -0
- crates/common/src/lib.rs +1 -0
- crates/common/src/update.rs +83 -0
- crates/server/src/authentication.rs +1 -0
- crates/server/src/certificate.rs +4 -1
- crates/server/src/error.rs +2 -0
- crates/server/src/lib.rs +3 -0
- crates/server/src/network.rs +11 -0
- crates/server/src/request.rs +1 -0
- crates/server/src/update.rs +108 -0
- packaging/keygen.sh +29 -0
- packaging/release-windows.ps1 +14 -0
- packaging/release.sh +65 -0
.gitignoremodified+1 -0
| @@ -6,3 +6,4 @@ yumush.db* | ||
| 6 | 6 | attachments/ |
| 7 | 7 | backups/ |
| 8 | 8 | crates/client/design/tokens.css |
| 9 | +/dist |
crates/client/Cargo.tomlmodified+1 -0
| @@ -33,6 +33,7 @@ dirs = "7.0.0" | ||
| 33 | 33 | sys-locale = "0.3.2" |
| 34 | 34 | image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } |
| 35 | 35 | rtrb = "0.4.1" |
| 36 | +ring = "0.17.14" | |
| 36 | 37 | gethostname = "1.1.0" |
| 37 | 38 | rustls-platform-verifier = "0.7.1" |
| 38 | 39 | sysinfo = { version = "0.40.4", default-features = false, features = ["system"] } |
crates/client/lang/en/settings_page.txtmodified+3 -0
| @@ -20,6 +20,9 @@ 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 | |
| 23 | 26 | your_hue = Your hue |
| 24 | 27 | camera = Camera |
| 25 | 28 | screen_share = Screen share |
crates/client/lang/tr/settings_page.txtmodified+3 -0
| @@ -20,6 +20,9 @@ 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 | |
| 23 | 26 | your_hue = Rengin |
| 24 | 27 | camera = Kamera |
| 25 | 28 | screen_share = Ekran paylaşımı |
crates/client/src/autostart.rsmodified+10 -5
| @@ -8,7 +8,7 @@ pub fn hidden() -> bool { | ||
| 8 | 8 | |
| 9 | 9 | #[cfg(any(target_os = "linux", target_os = "windows"))] |
| 10 | 10 | fn command(args: &[&str]) -> std::io::Result<String> { |
| 11 | - let exe = std::env::current_exe()?; | |
| 11 | + let exe = crate::exe().ok_or(std::io::ErrorKind::NotFound)?; | |
| 12 | 12 | Ok(std::iter::once(format!("\"{}\"", exe.display())) |
| 13 | 13 | .chain(args.iter().map(|arg| arg.to_string())) |
| 14 | 14 | .collect::<Vec<_>>() |
| @@ -58,10 +58,15 @@ fn apply(args: Option<&[&str]>) -> std::io::Result<()> { | ||
| 58 | 58 | }; |
| 59 | 59 | let content = format!( |
| 60 | 60 | "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict><key>Label</key><string>{LABEL}</string><key>ProgramArguments</key><array>{}</array><key>RunAtLoad</key><true/></dict></plist>\n", |
| 61 | - std::iter::once(std::env::current_exe()?.display().to_string()) | |
| 62 | - .chain(args.iter().map(|arg| arg.to_string())) | |
| 63 | - .map(|arg| format!("<string>{arg}</string>")) | |
| 64 | - .collect::<String>() | |
| 61 | + std::iter::once( | |
| 62 | + crate::exe() | |
| 63 | + .ok_or(std::io::ErrorKind::NotFound)? | |
| 64 | + .display() | |
| 65 | + .to_string() | |
| 66 | + ) | |
| 67 | + .chain(args.iter().map(|arg| arg.to_string())) | |
| 68 | + .map(|arg| format!("<string>{arg}</string>")) | |
| 69 | + .collect::<String>() | |
| 65 | 70 | ); |
| 66 | 71 | crate::logo::put(&path, &content) |
| 67 | 72 | } |
crates/client/src/gui/settings_page.rsmodified+18 -2
| @@ -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}, | |
| 28 | + settings::{self, FontSize, Launch, ShareAudio, ShareCodec, Updates}, | |
| 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); 25] { | |
| 45 | +pub(super) fn setting_rows() -> [(usize, &'static str); 26] { | |
| 46 | 46 | let s = &w().settings_page; |
| 47 | 47 | let v = &w().voice_settings; |
| 48 | 48 | [ |
| @@ -69,6 +69,7 @@ pub(super) fn setting_rows() -> [(usize, &'static str); 25] { | ||
| 69 | 69 | (3, s.language), |
| 70 | 70 | (3, s.close_to_tray), |
| 71 | 71 | (3, s.launch), |
| 72 | + (3, s.updates), | |
| 72 | 73 | (3, s.clock_seconds), |
| 73 | 74 | (3, s.your_hue), |
| 74 | 75 | ] |
| @@ -221,6 +222,16 @@ impl Yumush { | ||
| 221 | 222 | Yumush::set_launch, |
| 222 | 223 | ), |
| 223 | 224 | ), |
| 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 | + ), | |
| 224 | 235 | row( |
| 225 | 236 | w().settings_page.clock_seconds, |
| 226 | 237 | super::parts::toggle( |
| @@ -388,6 +399,11 @@ impl Yumush { | ||
| 388 | 399 | self.commit_settings(cx); |
| 389 | 400 | } |
| 390 | 401 | |
| 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 | + | |
| 391 | 407 | pub(super) fn toggle_clock_seconds(&mut self, cx: &mut Context<Self>) { |
| 392 | 408 | self.settings.clock_seconds = !self.settings.clock_seconds; |
| 393 | 409 | self.commit_settings(cx); |
crates/client/src/lib.rsmodified+8 -0
| @@ -18,11 +18,19 @@ pub mod net; | ||
| 18 | 18 | pub mod settings; |
| 19 | 19 | pub mod share; |
| 20 | 20 | pub mod tray; |
| 21 | +pub mod update; | |
| 21 | 22 | pub use usage; |
| 22 | 23 | pub mod voice; |
| 23 | 24 | |
| 24 | 25 | pub const NAME: &str = "Yumush"; |
| 25 | 26 | |
| 27 | +static EXE: std::sync::LazyLock<Option<PathBuf>> = | |
| 28 | + std::sync::LazyLock::new(|| std::env::current_exe().ok()); | |
| 29 | + | |
| 30 | +pub fn exe() -> Option<&'static std::path::Path> { | |
| 31 | + EXE.as_deref() | |
| 32 | +} | |
| 33 | + | |
| 26 | 34 | pub fn config_dir() -> Option<PathBuf> { |
| 27 | 35 | std::env::var_os("YUMUSH_CONFIG_DIR") |
| 28 | 36 | .map(PathBuf::from) |
crates/client/src/logo.rsmodified+1 -1
| @@ -20,7 +20,7 @@ pub fn window_icon() -> std::sync::Arc<image::RgbaImage> { | ||
| 20 | 20 | #[cfg(target_os = "linux")] |
| 21 | 21 | pub fn install() -> std::io::Result<()> { |
| 22 | 22 | let data = dirs::data_dir().ok_or(std::io::ErrorKind::NotFound)?; |
| 23 | - let exe = std::env::current_exe()?; | |
| 23 | + let exe = crate::exe().ok_or(std::io::ErrorKind::NotFound)?; | |
| 24 | 24 | put( |
| 25 | 25 | &data |
| 26 | 26 | .join("icons/hicolor/scalable/apps") |
crates/client/src/main.rsmodified+6 -0
| @@ -18,6 +18,9 @@ use tracing::Level; | ||
| 18 | 18 | use tracing_subscriber::{filter::Targets, layer::SubscriberExt, util::SubscriberInitExt}; |
| 19 | 19 | |
| 20 | 20 | fn main() { |
| 21 | + if client::update::selftest() || client::update::boot() { | |
| 22 | + return; | |
| 23 | + } | |
| 21 | 24 | tracing_subscriber::registry() |
| 22 | 25 | .with(tracing_subscriber::fmt::layer()) |
| 23 | 26 | .with( |
| @@ -42,8 +45,10 @@ fn main() { | ||
| 42 | 45 | } |
| 43 | 46 | |
| 44 | 47 | let client::instance::Instance::First(mut wake) = client::instance::claim() else { |
| 48 | + client::update::claimed(false); | |
| 45 | 49 | return; |
| 46 | 50 | }; |
| 51 | + client::update::claimed(true); | |
| 47 | 52 | |
| 48 | 53 | #[cfg(target_os = "linux")] |
| 49 | 54 | if let Err(error) = client::logo::install() { |
| @@ -75,6 +80,7 @@ fn main() { | ||
| 75 | 80 | if hidden { |
| 76 | 81 | hide(&view, cx); |
| 77 | 82 | } |
| 83 | + client::update::ready(); | |
| 78 | 84 | |
| 79 | 85 | let (mut tray_receiver, tray_handle) = tray::start(); |
| 80 | 86 | let mut tray_state = TrayState::default(); |
crates/client/src/net/link.rsmodified+12 -4
| @@ -110,9 +110,17 @@ async fn backoff(attempt: &mut u32) { | ||
| 110 | 110 | *attempt += 1; |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | +pub(crate) async fn dial( | |
| 114 | + server: &crate::Server, | |
| 115 | + alpn: &[u8], | |
| 116 | +) -> Result<quinn::Connection, LinkError> { | |
| 117 | + connect(server, &mut Endpoints::default(), alpn).await | |
| 118 | +} | |
| 119 | + | |
| 113 | 120 | async fn connect( |
| 114 | 121 | server: &crate::Server, |
| 115 | 122 | endpoints: &mut Endpoints, |
| 123 | + alpn: &[u8], | |
| 116 | 124 | ) -> Result<quinn::Connection, LinkError> { |
| 117 | 125 | let mut addresses: Vec<SocketAddr> = tokio::net::lookup_host(server.address.as_str()) |
| 118 | 126 | .await |
| @@ -130,7 +138,7 @@ async fn connect( | ||
| 130 | 138 | } |
| 131 | 139 | }; |
| 132 | 140 | let connecting = |
| 133 | - match endpoint.connect_with(config(server.any_cert)?, address, server.host()) { | |
| 141 | + match endpoint.connect_with(config(server.any_cert, alpn)?, address, server.host()) { | |
| 134 | 142 | Ok(connecting) => connecting, |
| 135 | 143 | Err(_) => { |
| 136 | 144 | endpoints.forget(address); |
| @@ -209,7 +217,7 @@ impl ServerCertVerifier for AcceptAnyCertificate { | ||
| 209 | 217 | } |
| 210 | 218 | } |
| 211 | 219 | |
| 212 | -fn config(any_cert: bool) -> Result<quinn::ClientConfig, LinkError> { | |
| 220 | +fn config(any_cert: bool, alpn: &[u8]) -> Result<quinn::ClientConfig, LinkError> { | |
| 213 | 221 | let provider = Arc::new(rustls::crypto::ring::default_provider()); |
| 214 | 222 | let verifier: Arc<dyn ServerCertVerifier> = if any_cert { |
| 215 | 223 | Arc::new(AcceptAnyCertificate { |
| @@ -225,7 +233,7 @@ fn config(any_cert: bool) -> Result<quinn::ClientConfig, LinkError> { | ||
| 225 | 233 | .dangerous() |
| 226 | 234 | .with_custom_certificate_verifier(verifier) |
| 227 | 235 | .with_no_client_auth(); |
| 228 | - tls.alpn_protocols = vec![ALPN.to_vec()]; | |
| 236 | + tls.alpn_protocols = vec![alpn.to_vec()]; | |
| 229 | 237 | |
| 230 | 238 | let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?; |
| 231 | 239 | let mut client_config = quinn::ClientConfig::new(Arc::new(crypto)); |
| @@ -383,7 +391,7 @@ async fn actor( | ||
| 383 | 391 | let connection = loop { |
| 384 | 392 | let address = server.borrow_and_update().clone(); |
| 385 | 393 | let result = tokio::select! { |
| 386 | - result = connect(&address, &mut endpoints) => result, | |
| 394 | + result = connect(&address, &mut endpoints, ALPN) => result, | |
| 387 | 395 | _ = server.changed() => { |
| 388 | 396 | attempt = 0; |
| 389 | 397 | token = None; |
crates/client/src/net/mod.rsmodified+1 -0
| @@ -16,6 +16,7 @@ mod link; | ||
| 16 | 16 | mod media; |
| 17 | 17 | |
| 18 | 18 | pub use fail::{Fail, LinkError}; |
| 19 | +pub(crate) use link::dial; | |
| 19 | 20 | pub use link::start; |
| 20 | 21 | use media::Media; |
| 21 | 22 |
crates/client/src/settings.rsmodified+27 -0
| @@ -90,6 +90,27 @@ 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 | + | |
| 93 | 114 | string_enum! { |
| 94 | 115 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 95 | 116 | Activation { |
| @@ -221,6 +242,7 @@ pub struct Settings { | ||
| 221 | 242 | pub share: ShareSettings, |
| 222 | 243 | pub close_to_tray: bool, |
| 223 | 244 | pub launch: Launch, |
| 245 | + pub updates: Updates, | |
| 224 | 246 | pub clock_seconds: bool, |
| 225 | 247 | pub jump_usage: BTreeMap<String, u32>, |
| 226 | 248 | pub last_chats: BTreeMap<Id, Id>, |
| @@ -250,6 +272,7 @@ impl Default for Settings { | ||
| 250 | 272 | } else { |
| 251 | 273 | Launch::Window |
| 252 | 274 | }, |
| 275 | + updates: Updates::Auto, | |
| 253 | 276 | clock_seconds: false, |
| 254 | 277 | jump_usage: BTreeMap::new(), |
| 255 | 278 | last_chats: BTreeMap::new(), |
| @@ -368,6 +391,9 @@ pub fn load() -> Settings { | ||
| 368 | 391 | .and_then(|value| Launch::parse(&value)) |
| 369 | 392 | .filter(|launch| Launch::options().any(|option| option == *launch)) |
| 370 | 393 | .unwrap_or(defaults.launch), |
| 394 | + updates: text("updates") | |
| 395 | + .and_then(|value| Updates::parse(&value)) | |
| 396 | + .unwrap_or(defaults.updates), | |
| 371 | 397 | clock_seconds: text("clock_seconds") |
| 372 | 398 | .map_or(defaults.clock_seconds, |value| value == "true"), |
| 373 | 399 | jump_usage: text("jump.usage") |
| @@ -410,6 +436,7 @@ pub fn save(settings: &Settings) { | ||
| 410 | 436 | line("language", settings.language.as_str()), |
| 411 | 437 | line("close_to_tray", settings.close_to_tray), |
| 412 | 438 | line("launch", settings.launch.as_str()), |
| 439 | + line("updates", settings.updates.as_str()), | |
| 413 | 440 | line("clock_seconds", settings.clock_seconds), |
| 414 | 441 | line("voice.sensitivity", voice.sensitivity_db), |
| 415 | 442 | line("voice.input_volume", voice.input_volume), |
crates/client/src/update.rsadded+594 -0
| @@ -0,0 +1,594 @@ | ||
| 1 | +use std::{ | |
| 2 | + fs, | |
| 3 | + io::{Read, Write}, | |
| 4 | + path::{Path, PathBuf}, | |
| 5 | + process::{Command, Stdio}, | |
| 6 | + time::{Duration, Instant}, | |
| 7 | +}; | |
| 8 | + | |
| 9 | +use common::update::{self as wire, FILE_MAX, MANIFEST, MANIFEST_MAX}; | |
| 10 | +use ring::{digest, signature}; | |
| 11 | +use tracing::{info, warn}; | |
| 12 | + | |
| 13 | +mod keys; | |
| 14 | + | |
| 15 | +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); | |
| 20 | +const SELFTEST_LIMIT: Duration = Duration::from_secs(20); | |
| 21 | +const PACKAGED_ENV: [&str; 3] = ["FLATPAK_ID", "SNAP", "APPIMAGE"]; | |
| 22 | +const PACKAGED_ROOTS: [&str; 2] = ["/usr/", "/nix/"]; | |
| 23 | + | |
| 24 | +pub const SEQ: Option<u64> = match option_env!("YUMUSH_RELEASE_SEQ") { | |
| 25 | + Some(text) => Some(parse_seq(text)), | |
| 26 | + None => None, | |
| 27 | +}; | |
| 28 | + | |
| 29 | +const _: () = assert!( | |
| 30 | + SEQ.is_none() || !keys::KEYS.is_empty(), | |
| 31 | + "release build needs update keys" | |
| 32 | +); | |
| 33 | + | |
| 34 | +const fn parse_seq(text: &str) -> u64 { | |
| 35 | + let bytes = text.as_bytes(); | |
| 36 | + assert!(!bytes.is_empty() && bytes.len() <= 18, "YUMUSH_RELEASE_SEQ"); | |
| 37 | + let mut value = 0u64; | |
| 38 | + let mut index = 0; | |
| 39 | + while index < bytes.len() { | |
| 40 | + assert!(bytes[index].is_ascii_digit(), "YUMUSH_RELEASE_SEQ"); | |
| 41 | + value = value * 10 + (bytes[index] - b'0') as u64; | |
| 42 | + index += 1; | |
| 43 | + } | |
| 44 | + assert!(value > 0, "YUMUSH_RELEASE_SEQ"); | |
| 45 | + value | |
| 46 | +} | |
| 47 | + | |
| 48 | +#[derive(Debug)] | |
| 49 | +enum Off { | |
| 50 | + Unofficial, | |
| 51 | + Platform, | |
| 52 | + Multi, | |
| 53 | + Packaged, | |
| 54 | + NoExe, | |
| 55 | +} | |
| 56 | + | |
| 57 | +#[allow(dead_code)] | |
| 58 | +#[derive(Debug)] | |
| 59 | +enum Fail { | |
| 60 | + Link(crate::net::LinkError), | |
| 61 | + Connection(quinn::ConnectionError), | |
| 62 | + Wire(wire::UpdateError), | |
| 63 | + Reject(Reject), | |
| 64 | + Hash, | |
| 65 | + Selftest, | |
| 66 | + Io(std::io::Error), | |
| 67 | +} | |
| 68 | + | |
| 69 | +#[derive(Debug)] | |
| 70 | +enum Reject { | |
| 71 | + Short, | |
| 72 | + Signature, | |
| 73 | + Format, | |
| 74 | + Target, | |
| 75 | +} | |
| 76 | + | |
| 77 | +enum Check { | |
| 78 | + Current, | |
| 79 | + Staged(u64), | |
| 80 | +} | |
| 81 | + | |
| 82 | +#[derive(Debug, PartialEq)] | |
| 83 | +struct Release { | |
| 84 | + seq: u64, | |
| 85 | + version: String, | |
| 86 | + size: u64, | |
| 87 | + sha256: [u8; 32], | |
| 88 | +} | |
| 89 | + | |
| 90 | +impl From<std::io::Error> for Fail { | |
| 91 | + fn from(error: std::io::Error) -> Self { | |
| 92 | + Self::Io(error) | |
| 93 | + } | |
| 94 | +} | |
| 95 | + | |
| 96 | +impl From<wire::UpdateError> for Fail { | |
| 97 | + fn from(error: wire::UpdateError) -> Self { | |
| 98 | + Self::Wire(error) | |
| 99 | + } | |
| 100 | +} | |
| 101 | + | |
| 102 | +impl From<quinn::ConnectionError> for Fail { | |
| 103 | + fn from(error: quinn::ConnectionError) -> Self { | |
| 104 | + Self::Connection(error) | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 108 | +fn mode() -> Result<(u64, &'static Path), Off> { | |
| 109 | + 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) { | |
| 114 | + return Err(Off::Multi); | |
| 115 | + } | |
| 116 | + if PACKAGED_ENV | |
| 117 | + .iter() | |
| 118 | + .any(|name| std::env::var_os(name).is_some()) | |
| 119 | + { | |
| 120 | + return Err(Off::Packaged); | |
| 121 | + } | |
| 122 | + let exe = crate::exe().ok_or(Off::NoExe)?; | |
| 123 | + let shown = exe.to_string_lossy(); | |
| 124 | + if PACKAGED_ROOTS.iter().any(|root| shown.starts_with(root)) { | |
| 125 | + return Err(Off::Packaged); | |
| 126 | + } | |
| 127 | + Ok((seq, exe)) | |
| 128 | +} | |
| 129 | + | |
| 130 | +fn target() -> String { | |
| 131 | + format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS) | |
| 132 | +} | |
| 133 | + | |
| 134 | +fn sibling(exe: &Path, tag: &str) -> PathBuf { | |
| 135 | + let stem = exe.file_stem().unwrap_or_default().to_string_lossy(); | |
| 136 | + let name = match exe.extension() { | |
| 137 | + Some(extension) => format!("{stem}.{tag}.{}", extension.to_string_lossy()), | |
| 138 | + None => format!("{stem}.{tag}"), | |
| 139 | + }; | |
| 140 | + exe.with_file_name(name) | |
| 141 | +} | |
| 142 | + | |
| 143 | +fn state(exe: &Path, tag: &str) -> PathBuf { | |
| 144 | + let name = exe.file_name().unwrap_or_default().to_string_lossy(); | |
| 145 | + exe.with_file_name(format!("{name}.{tag}")) | |
| 146 | +} | |
| 147 | + | |
| 148 | +fn read(path: &Path) -> Option<String> { | |
| 149 | + fs::read_to_string(path) | |
| 150 | + .ok() | |
| 151 | + .map(|text| text.trim().to_string()) | |
| 152 | +} | |
| 153 | + | |
| 154 | +fn number(path: &Path) -> Option<u64> { | |
| 155 | + read(path)?.parse().ok() | |
| 156 | +} | |
| 157 | + | |
| 158 | +fn sync_dir(path: &Path) { | |
| 159 | + #[cfg(unix)] | |
| 160 | + if let Some(dir) = path.parent() { | |
| 161 | + let _ = fs::File::open(dir).and_then(|dir| dir.sync_all()); | |
| 162 | + } | |
| 163 | + #[cfg(not(unix))] | |
| 164 | + let _ = path; | |
| 165 | +} | |
| 166 | + | |
| 167 | +fn put(path: &Path, text: &str) -> std::io::Result<()> { | |
| 168 | + let part = path.with_added_extension("part"); | |
| 169 | + let mut file = fs::File::create(&part)?; | |
| 170 | + file.write_all(text.as_bytes())?; | |
| 171 | + file.sync_all()?; | |
| 172 | + drop(file); | |
| 173 | + fs::rename(&part, path)?; | |
| 174 | + sync_dir(path); | |
| 175 | + Ok(()) | |
| 176 | +} | |
| 177 | + | |
| 178 | +fn trial(exe: &Path) -> Option<(u64, u32)> { | |
| 179 | + let text = read(&state(exe, "trial"))?; | |
| 180 | + let (seq, pid) = text.split_once(' ')?; | |
| 181 | + Some((seq.parse().ok()?, pid.parse().ok()?)) | |
| 182 | +} | |
| 183 | + | |
| 184 | +fn claim_trial(exe: &Path, seq: u64) -> std::io::Result<()> { | |
| 185 | + put( | |
| 186 | + &state(exe, "trial"), | |
| 187 | + &format!("{seq} {}", std::process::id()), | |
| 188 | + ) | |
| 189 | +} | |
| 190 | + | |
| 191 | +fn alive(pid: u32) -> bool { | |
| 192 | + let pid = sysinfo::Pid::from_u32(pid); | |
| 193 | + let Ok(mut system) = sysinfo::System::new() else { | |
| 194 | + return false; | |
| 195 | + }; | |
| 196 | + system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true); | |
| 197 | + system.process(pid).is_some() | |
| 198 | +} | |
| 199 | + | |
| 200 | +pub fn selftest() -> bool { | |
| 201 | + if !std::env::args().any(|arg| arg == SELFTEST) { | |
| 202 | + return false; | |
| 203 | + } | |
| 204 | + println!("{}", SEQ.unwrap_or(0)); | |
| 205 | + true | |
| 206 | +} | |
| 207 | + | |
| 208 | +pub fn boot() -> bool { | |
| 209 | + let Ok((seq, exe)) = mode() else { | |
| 210 | + return false; | |
| 211 | + }; | |
| 212 | + if let Some((trying, pid)) = trial(exe) | |
| 213 | + && trying == seq | |
| 214 | + && !alive(pid) | |
| 215 | + { | |
| 216 | + return rollback(seq, exe); | |
| 217 | + } | |
| 218 | + let pending = state(exe, "pending"); | |
| 219 | + if number(&pending) == Some(seq) && claim_trial(exe, seq).is_ok() { | |
| 220 | + let _ = fs::remove_file(&pending); | |
| 221 | + sync_dir(exe); | |
| 222 | + } | |
| 223 | + false | |
| 224 | +} | |
| 225 | + | |
| 226 | +pub fn claimed(first: bool) { | |
| 227 | + let Ok((seq, exe)) = mode() else { | |
| 228 | + return; | |
| 229 | + }; | |
| 230 | + let me = std::process::id(); | |
| 231 | + match trial(exe) { | |
| 232 | + Some((trying, pid)) if trying == seq => { | |
| 233 | + if !first { | |
| 234 | + if pid == me && put(&state(exe, "pending"), &seq.to_string()).is_ok() { | |
| 235 | + let _ = fs::remove_file(state(exe, "trial")); | |
| 236 | + } | |
| 237 | + } else if pid != me { | |
| 238 | + let _ = claim_trial(exe, seq); | |
| 239 | + } | |
| 240 | + if first { | |
| 241 | + info!("update: trying {seq}"); | |
| 242 | + } | |
| 243 | + } | |
| 244 | + _ if first => { | |
| 245 | + for tag in ["trial", "pending"] { | |
| 246 | + let _ = fs::remove_file(state(exe, tag)); | |
| 247 | + } | |
| 248 | + for tag in ["new", "bad", "old"] { | |
| 249 | + let _ = fs::remove_file(sibling(exe, tag)); | |
| 250 | + } | |
| 251 | + } | |
| 252 | + _ => {} | |
| 253 | + } | |
| 254 | +} | |
| 255 | + | |
| 256 | +fn rollback(seq: u64, exe: &Path) -> bool { | |
| 257 | + let old = sibling(exe, "old"); | |
| 258 | + if !old.exists() { | |
| 259 | + let _ = fs::remove_file(state(exe, "trial")); | |
| 260 | + return false; | |
| 261 | + } | |
| 262 | + let _ = put(&state(exe, "skip"), &seq.to_string()); | |
| 263 | + if let Err(error) = restore(exe, &old) { | |
| 264 | + warn!("update: rollback {error}"); | |
| 265 | + return false; | |
| 266 | + } | |
| 267 | + sync_dir(exe); | |
| 268 | + let _ = fs::remove_file(state(exe, "trial")); | |
| 269 | + Command::new(exe) | |
| 270 | + .args(std::env::args_os().skip(1)) | |
| 271 | + .spawn() | |
| 272 | + .is_ok() | |
| 273 | +} | |
| 274 | + | |
| 275 | +#[cfg(unix)] | |
| 276 | +fn restore(exe: &Path, old: &Path) -> std::io::Result<()> { | |
| 277 | + fs::rename(old, exe) | |
| 278 | +} | |
| 279 | + | |
| 280 | +#[cfg(not(unix))] | |
| 281 | +fn restore(exe: &Path, old: &Path) -> std::io::Result<()> { | |
| 282 | + let bad = sibling(exe, "bad"); | |
| 283 | + let _ = fs::remove_file(&bad); | |
| 284 | + fs::rename(exe, &bad)?; | |
| 285 | + fs::rename(old, exe).inspect_err(|_| { | |
| 286 | + let _ = fs::rename(&bad, exe); | |
| 287 | + }) | |
| 288 | +} | |
| 289 | + | |
| 290 | +pub fn ready() { | |
| 291 | + let Ok((seq, exe)) = mode() else { | |
| 292 | + return; | |
| 293 | + }; | |
| 294 | + if trial(exe) == Some((seq, std::process::id())) { | |
| 295 | + let _ = fs::remove_file(sibling(exe, "old")); | |
| 296 | + let _ = fs::remove_file(state(exe, "trial")); | |
| 297 | + info!("update: {seq} is healthy"); | |
| 298 | + } | |
| 299 | + let _ = std::thread::Builder::new() | |
| 300 | + .name("update".to_string()) | |
| 301 | + .spawn(move || watch(seq, exe)); | |
| 302 | +} | |
| 303 | + | |
| 304 | +fn watch(seq: u64, exe: &'static Path) { | |
| 305 | + let Ok(runtime) = tokio::runtime::Builder::new_current_thread() | |
| 306 | + .enable_all() | |
| 307 | + .build() | |
| 308 | + else { | |
| 309 | + return; | |
| 310 | + }; | |
| 311 | + std::thread::sleep(FIRST_CHECK); | |
| 312 | + 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:?}"), | |
| 321 | + } | |
| 322 | + } | |
| 323 | + std::thread::sleep(CHECK_EVERY); | |
| 324 | + } | |
| 325 | +} | |
| 326 | + | |
| 327 | +async fn fetch(connection: &quinn::Connection, name: &str, maximum: u64) -> Result<Vec<u8>, Fail> { | |
| 328 | + let (mut send, mut receive) = connection.open_bi().await?; | |
| 329 | + wire::ask(&mut send, name).await?; | |
| 330 | + Ok(wire::receive(&mut receive, maximum).await?) | |
| 331 | +} | |
| 332 | + | |
| 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)) | |
| 344 | +} | |
| 345 | + | |
| 346 | +async fn fetch_release( | |
| 347 | + connection: &quinn::Connection, | |
| 348 | + seq: u64, | |
| 349 | + exe: &Path, | |
| 350 | +) -> Result<Option<(Release, fs::File, Vec<u8>)>, Fail> { | |
| 351 | + let manifest = fetch(connection, MANIFEST, MANIFEST_MAX).await?; | |
| 352 | + 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); | |
| 355 | + } | |
| 356 | + let file = open_new(exe)?; | |
| 357 | + info!("update: downloading {} ({})", release.version, release.seq); | |
| 358 | + let bytes = fetch(connection, &target(), release.size).await; | |
| 359 | + let bytes = bytes.inspect_err(|_| { | |
| 360 | + let _ = fs::remove_file(sibling(exe, "new")); | |
| 361 | + })?; | |
| 362 | + if bytes.len() as u64 != release.size | |
| 363 | + || digest::digest(&digest::SHA256, &bytes).as_ref() != release.sha256 | |
| 364 | + { | |
| 365 | + let _ = fs::remove_file(sibling(exe, "new")); | |
| 366 | + return Err(Fail::Hash); | |
| 367 | + } | |
| 368 | + Ok(Some((release, file, bytes))) | |
| 369 | +} | |
| 370 | + | |
| 371 | +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)?; | |
| 375 | + let signed_by_us = keys.iter().any(|key| { | |
| 376 | + signature::UnparsedPublicKey::new(&signature::ED25519, key) | |
| 377 | + .verify(body, sig) | |
| 378 | + .is_ok() | |
| 379 | + }); | |
| 380 | + if !signed_by_us { | |
| 381 | + return Err(Reject::Signature); | |
| 382 | + } | |
| 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)?; | |
| 422 | + Ok(Release { | |
| 423 | + seq, | |
| 424 | + version, | |
| 425 | + size, | |
| 426 | + sha256, | |
| 427 | + }) | |
| 428 | +} | |
| 429 | + | |
| 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> { | |
| 452 | + let new = sibling(exe, "new"); | |
| 453 | + let _ = fs::remove_file(&new); | |
| 454 | + let mut options = fs::OpenOptions::new(); | |
| 455 | + options.write(true).create_new(true); | |
| 456 | + #[cfg(unix)] | |
| 457 | + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o755); | |
| 458 | + options.open(&new) | |
| 459 | +} | |
| 460 | + | |
| 461 | +fn stage(exe: &Path, mut file: fs::File, bytes: &[u8], seq: u64) -> Result<(), Fail> { | |
| 462 | + let new = sibling(exe, "new"); | |
| 463 | + let written = file.write_all(bytes).and_then(|()| file.sync_all()); | |
| 464 | + drop(file); | |
| 465 | + let staged = written.map_err(Fail::Io).and_then(|()| { | |
| 466 | + run_selftest(&new, seq).inspect_err(|_| { | |
| 467 | + let _ = put(&state(exe, "skip"), &seq.to_string()); | |
| 468 | + }) | |
| 469 | + }); | |
| 470 | + let staged = staged.and_then(|()| swap(exe, &new, seq)); | |
| 471 | + if staged.is_err() { | |
| 472 | + let _ = fs::remove_file(&new); | |
| 473 | + } | |
| 474 | + staged | |
| 475 | +} | |
| 476 | + | |
| 477 | +fn run_selftest(new: &Path, seq: u64) -> Result<(), Fail> { | |
| 478 | + let mut child = Command::new(new) | |
| 479 | + .arg(SELFTEST) | |
| 480 | + .stdin(Stdio::null()) | |
| 481 | + .stdout(Stdio::piped()) | |
| 482 | + .stderr(Stdio::null()) | |
| 483 | + .spawn()?; | |
| 484 | + let started = Instant::now(); | |
| 485 | + let status = loop { | |
| 486 | + if let Some(status) = child.try_wait()? { | |
| 487 | + break status; | |
| 488 | + } | |
| 489 | + if started.elapsed() > SELFTEST_LIMIT { | |
| 490 | + let _ = child.kill(); | |
| 491 | + let _ = child.wait(); | |
| 492 | + return Err(Fail::Selftest); | |
| 493 | + } | |
| 494 | + std::thread::sleep(Duration::from_millis(100)); | |
| 495 | + }; | |
| 496 | + let mut out = String::new(); | |
| 497 | + if let Some(mut stdout) = child.stdout.take() { | |
| 498 | + let _ = stdout.read_to_string(&mut out); | |
| 499 | + } | |
| 500 | + if !status.success() || out.trim() != seq.to_string() { | |
| 501 | + return Err(Fail::Selftest); | |
| 502 | + } | |
| 503 | + Ok(()) | |
| 504 | +} | |
| 505 | + | |
| 506 | +fn swap(exe: &Path, new: &Path, seq: u64) -> Result<(), Fail> { | |
| 507 | + let old = sibling(exe, "old"); | |
| 508 | + let pending = state(exe, "pending"); | |
| 509 | + let _ = fs::remove_file(&old); | |
| 510 | + put(&pending, &seq.to_string())?; | |
| 511 | + let swapped = replace(exe, new, &old); | |
| 512 | + if swapped.is_err() { | |
| 513 | + let _ = fs::remove_file(&pending); | |
| 514 | + } | |
| 515 | + sync_dir(exe); | |
| 516 | + Ok(swapped?) | |
| 517 | +} | |
| 518 | + | |
| 519 | +#[cfg(unix)] | |
| 520 | +fn replace(exe: &Path, new: &Path, old: &Path) -> std::io::Result<()> { | |
| 521 | + fs::hard_link(exe, old).or_else(|_| fs::copy(exe, old).map(drop))?; | |
| 522 | + fs::rename(new, exe).inspect_err(|_| { | |
| 523 | + let _ = fs::remove_file(old); | |
| 524 | + }) | |
| 525 | +} | |
| 526 | + | |
| 527 | +#[cfg(not(unix))] | |
| 528 | +fn replace(exe: &Path, new: &Path, old: &Path) -> std::io::Result<()> { | |
| 529 | + fs::rename(exe, old)?; | |
| 530 | + fs::rename(new, exe).inspect_err(|_| { | |
| 531 | + let _ = fs::rename(old, exe); | |
| 532 | + }) | |
| 533 | +} | |
| 534 | + | |
| 535 | +#[cfg(test)] | |
| 536 | +mod tests { | |
| 537 | + use ring::{ | |
| 538 | + rand::SystemRandom, | |
| 539 | + signature::{Ed25519KeyPair, KeyPair}, | |
| 540 | + }; | |
| 541 | + | |
| 542 | + use super::*; | |
| 543 | + | |
| 544 | + fn signed(key: &Ed25519KeyPair, body: &str) -> Vec<u8> { | |
| 545 | + let mut out = key.sign(body.as_bytes()).as_ref().to_vec(); | |
| 546 | + out.extend_from_slice(body.as_bytes()); | |
| 547 | + out | |
| 548 | + } | |
| 549 | + | |
| 550 | + fn pair() -> (Ed25519KeyPair, [u8; 32]) { | |
| 551 | + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap(); | |
| 552 | + let key = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(); | |
| 553 | + let public = key.public_key().as_ref().try_into().unwrap(); | |
| 554 | + (key, public) | |
| 555 | + } | |
| 556 | + | |
| 557 | + const HASH: &str = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; | |
| 558 | + | |
| 559 | + #[test] | |
| 560 | + fn verifies() { | |
| 561 | + let (key, public) = pair(); | |
| 562 | + let body = format!( | |
| 563 | + "{MAGIC}\nseq 7\nversion 0.2.0\nx86_64-linux 10 {HASH}\nx86_64-windows 20 {HASH}\n" | |
| 564 | + ); | |
| 565 | + let release = verify(&signed(&key, &body), "x86_64-windows", &[public]).unwrap(); | |
| 566 | + assert_eq!( | |
| 567 | + (release.seq, release.size, release.sha256[1]), | |
| 568 | + (7, 20, 0x11) | |
| 569 | + ); | |
| 570 | + } | |
| 571 | + | |
| 572 | + #[test] | |
| 573 | + fn rejects() { | |
| 574 | + let (key, public) = pair(); | |
| 575 | + let (other, _) = pair(); | |
| 576 | + let good = format!("{MAGIC}\nseq 7\nversion 1\nx86_64-linux 10 {HASH}\n"); | |
| 577 | + let mut tampered = signed(&key, &good); | |
| 578 | + *tampered.last_mut().unwrap() ^= 1; | |
| 579 | + let cases = [ | |
| 580 | + signed(&other, &good), | |
| 581 | + tampered, | |
| 582 | + signed(&key, &good)[..63].to_vec(), | |
| 583 | + signed(&key, &good.replace("x86_64-linux", "aarch64-linux")), | |
| 584 | + signed(&key, &format!("{good}x86_64-linux 10 {HASH}\n")), | |
| 585 | + signed(&key, &good.replace(" 10 ", " 0 ")), | |
| 586 | + signed(&key, &good.replace("seq 7", "seq x")), | |
| 587 | + signed(&key, &good.replace(MAGIC, "yumush-update 2")), | |
| 588 | + signed(&key, &format!("{good}manifest 10 {HASH}\n")), | |
| 589 | + ]; | |
| 590 | + for case in cases { | |
| 591 | + assert!(verify(&case, "x86_64-linux", &[public]).is_err()); | |
| 592 | + } | |
| 593 | + } | |
| 594 | +} |
crates/client/src/update/keys.rsadded+1 -0
| @@ -0,0 +1 @@ | ||
| 1 | +pub const KEYS: &[[u8; 32]] = &[]; |
crates/common/src/lib.rsmodified+1 -0
| @@ -13,4 +13,5 @@ pub mod share; | ||
| 13 | 13 | pub mod stats; |
| 14 | 14 | pub mod time; |
| 15 | 15 | pub mod transport; |
| 16 | +pub mod update; | |
| 16 | 17 | pub mod validate; |
crates/common/src/update.rsadded+83 -0
| @@ -0,0 +1,83 @@ | ||
| 1 | +use quinn::{RecvStream, SendStream}; | |
| 2 | + | |
| 3 | +pub const ALPN: &[u8] = b"yumush-update/1"; | |
| 4 | +pub const MANIFEST: &str = "manifest"; | |
| 5 | +pub const MANIFEST_MAX: u64 = 64 << 10; | |
| 6 | +pub const FILE_MAX: u64 = 512 << 20; | |
| 7 | +const NAME_MAX: usize = 32; | |
| 8 | +const MISSING: u64 = u64::MAX; | |
| 9 | + | |
| 10 | +#[derive(Debug, thiserror::Error)] | |
| 11 | +pub enum UpdateError { | |
| 12 | + #[error(transparent)] | |
| 13 | + Write(#[from] quinn::WriteError), | |
| 14 | + #[error(transparent)] | |
| 15 | + Read(#[from] quinn::ReadExactError), | |
| 16 | + #[error(transparent)] | |
| 17 | + ReadToEnd(#[from] quinn::ReadToEndError), | |
| 18 | + #[error(transparent)] | |
| 19 | + Closed(#[from] quinn::ClosedStream), | |
| 20 | + #[error("invalid name")] | |
| 21 | + Name, | |
| 22 | + #[error("missing")] | |
| 23 | + Missing, | |
| 24 | + #[error("size {0}")] | |
| 25 | + Size(u64), | |
| 26 | +} | |
| 27 | + | |
| 28 | +pub fn valid_name(name: &str) -> bool { | |
| 29 | + !name.is_empty() | |
| 30 | + && name.len() <= NAME_MAX | |
| 31 | + && name.bytes().all(|byte| { | |
| 32 | + byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-' | |
| 33 | + }) | |
| 34 | +} | |
| 35 | + | |
| 36 | +pub async fn ask(send: &mut SendStream, name: &str) -> Result<(), UpdateError> { | |
| 37 | + if !valid_name(name) { | |
| 38 | + return Err(UpdateError::Name); | |
| 39 | + } | |
| 40 | + send.write_all(&[name.len() as u8]).await?; | |
| 41 | + send.write_all(name.as_bytes()).await?; | |
| 42 | + send.finish()?; | |
| 43 | + Ok(()) | |
| 44 | +} | |
| 45 | + | |
| 46 | +pub async fn asked(receive: &mut RecvStream) -> Result<String, UpdateError> { | |
| 47 | + let mut length = [0u8; 1]; | |
| 48 | + receive.read_exact(&mut length).await?; | |
| 49 | + let length = length[0] as usize; | |
| 50 | + if length > NAME_MAX { | |
| 51 | + return Err(UpdateError::Name); | |
| 52 | + } | |
| 53 | + let mut name = vec![0u8; length]; | |
| 54 | + receive.read_exact(&mut name).await?; | |
| 55 | + let name = String::from_utf8(name).map_err(|_| UpdateError::Name)?; | |
| 56 | + if !valid_name(&name) { | |
| 57 | + return Err(UpdateError::Name); | |
| 58 | + } | |
| 59 | + Ok(name) | |
| 60 | +} | |
| 61 | + | |
| 62 | +pub async fn answer_size(send: &mut SendStream, size: Option<u64>) -> Result<(), UpdateError> { | |
| 63 | + send.write_all(&size.unwrap_or(MISSING).to_le_bytes()) | |
| 64 | + .await?; | |
| 65 | + Ok(()) | |
| 66 | +} | |
| 67 | + | |
| 68 | +pub async fn receive(receive: &mut RecvStream, maximum: u64) -> Result<Vec<u8>, UpdateError> { | |
| 69 | + let mut size = [0u8; 8]; | |
| 70 | + receive.read_exact(&mut size).await?; | |
| 71 | + let size = u64::from_le_bytes(size); | |
| 72 | + if size == MISSING { | |
| 73 | + return Err(UpdateError::Missing); | |
| 74 | + } | |
| 75 | + if size > maximum { | |
| 76 | + return Err(UpdateError::Size(size)); | |
| 77 | + } | |
| 78 | + let bytes = receive.read_to_end(maximum as usize).await?; | |
| 79 | + if bytes.len() as u64 != size { | |
| 80 | + return Err(UpdateError::Size(bytes.len() as u64)); | |
| 81 | + } | |
| 82 | + Ok(bytes) | |
| 83 | +} |
crates/server/src/authentication.rsmodified+1 -0
| @@ -234,6 +234,7 @@ mod tests { | ||
| 234 | 234 | services: Services::default(), |
| 235 | 235 | directory: test::directory(), |
| 236 | 236 | backups: test::directory(), |
| 237 | + updates: test::directory(), | |
| 237 | 238 | }; |
| 238 | 239 | let client = Client::detached(None); |
| 239 | 240 |
crates/server/src/certificate.rsmodified+4 -1
| @@ -115,7 +115,10 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfi | ||
| 115 | 115 | .with_no_client_auth() |
| 116 | 116 | .with_cert_resolver(reloader.clone()); |
| 117 | 117 | tls.max_early_data_size = u32::MAX; |
| 118 | - tls.alpn_protocols = vec![common::transport::ALPN.to_vec()]; | |
| 118 | + tls.alpn_protocols = vec![ | |
| 119 | + common::transport::ALPN.to_vec(), | |
| 120 | + common::update::ALPN.to_vec(), | |
| 121 | + ]; | |
| 119 | 122 | |
| 120 | 123 | let crypto = |
| 121 | 124 | quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?; |
crates/server/src/error.rsmodified+2 -0
| @@ -75,4 +75,6 @@ internal_from! { | ||
| 75 | 75 | bitcode::Error, |
| 76 | 76 | common::config::ConfigError, |
| 77 | 77 | common::frame::FrameError, |
| 78 | + common::update::UpdateError, | |
| 79 | + tokio::time::error::Elapsed, | |
| 78 | 80 | } |
crates/server/src/lib.rsmodified+3 -0
| @@ -14,6 +14,7 @@ pub mod request; | ||
| 14 | 14 | pub mod retention; |
| 15 | 15 | pub mod rooms; |
| 16 | 16 | pub mod stats; |
| 17 | +pub mod update; | |
| 17 | 18 | |
| 18 | 19 | #[cfg(test)] |
| 19 | 20 | mod test; |
| @@ -73,6 +74,7 @@ pub async fn showtime() -> Result<(), ServerError> { | ||
| 73 | 74 | let certificate = certificate::load(&config.certificate_path, &config.key_path)?; |
| 74 | 75 | let attachments = sibling_directory(&config.database_path, "attachments")?; |
| 75 | 76 | let backups = sibling_directory(&config.database_path, "backups")?; |
| 77 | + let updates = sibling_directory(&config.database_path, "updates")?; | |
| 76 | 78 | tokio::spawn(files::collect(database.clone(), attachments.clone())); |
| 77 | 79 | |
| 78 | 80 | network::serve( |
| @@ -81,6 +83,7 @@ pub async fn showtime() -> Result<(), ServerError> { | ||
| 81 | 83 | database, |
| 82 | 84 | attachments, |
| 83 | 85 | backups, |
| 86 | + updates, | |
| 84 | 87 | ) |
| 85 | 88 | .await |
| 86 | 89 | } |
crates/server/src/network.rsmodified+11 -0
| @@ -48,6 +48,7 @@ pub(crate) struct Shared { | ||
| 48 | 48 | pub(crate) services: Services, |
| 49 | 49 | pub(crate) directory: PathBuf, |
| 50 | 50 | pub(crate) backups: PathBuf, |
| 51 | + pub(crate) updates: PathBuf, | |
| 51 | 52 | } |
| 52 | 53 | |
| 53 | 54 | struct Pending { |
| @@ -63,6 +64,7 @@ pub async fn serve( | ||
| 63 | 64 | db: Db, |
| 64 | 65 | directory: PathBuf, |
| 65 | 66 | backups: PathBuf, |
| 67 | + updates: PathBuf, | |
| 66 | 68 | ) -> Result<(), ServerError> { |
| 67 | 69 | let endpoint = transport::endpoint( |
| 68 | 70 | server_address.parse()?, |
| @@ -76,6 +78,7 @@ pub async fn serve( | ||
| 76 | 78 | services: Services::default(), |
| 77 | 79 | directory, |
| 78 | 80 | backups, |
| 81 | + updates, | |
| 79 | 82 | }; |
| 80 | 83 | shared.services.machine.watch(shared.directory.clone()); |
| 81 | 84 | |
| @@ -108,6 +111,14 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv | ||
| 108 | 111 | return Ok(()); |
| 109 | 112 | } |
| 110 | 113 | let connection = incoming.await?; |
| 114 | + let alpn = connection | |
| 115 | + .handshake_data() | |
| 116 | + .and_then(|data| data.downcast::<quinn::crypto::rustls::HandshakeData>().ok()) | |
| 117 | + .and_then(|data| data.protocol); | |
| 118 | + if alpn.as_deref() == Some(common::update::ALPN) { | |
| 119 | + crate::update::serve(connection, shared.updates.clone()).await; | |
| 120 | + return Ok(()); | |
| 121 | + } | |
| 111 | 122 | let pending = match tokio::time::timeout(HELLO_DEADLINE, greet(&connection, &shared)).await { |
| 112 | 123 | Ok(Ok(Some(pending))) => pending, |
| 113 | 124 | Ok(Ok(None)) => return Ok(()), |
crates/server/src/request.rsmodified+1 -0
| @@ -373,6 +373,7 @@ mod tests { | ||
| 373 | 373 | services: services.clone(), |
| 374 | 374 | directory: test::directory(), |
| 375 | 375 | backups: test::directory(), |
| 376 | + updates: test::directory(), | |
| 376 | 377 | } |
| 377 | 378 | } |
| 378 | 379 |
crates/server/src/update.rsadded+108 -0
| @@ -0,0 +1,108 @@ | ||
| 1 | +use std::{ | |
| 2 | + collections::HashSet, | |
| 3 | + net::IpAddr, | |
| 4 | + path::{Path, PathBuf}, | |
| 5 | + sync::Mutex, | |
| 6 | + time::Duration, | |
| 7 | +}; | |
| 8 | + | |
| 9 | +use common::update::{self, FILE_MAX, MANIFEST, MANIFEST_MAX}; | |
| 10 | +use quinn::{Connection, RecvStream, SendStream}; | |
| 11 | +use tokio::{io::AsyncReadExt, sync::Semaphore, time::timeout}; | |
| 12 | +use tracing::warn; | |
| 13 | + | |
| 14 | +use crate::error::ServerError; | |
| 15 | + | |
| 16 | +const STREAMS: usize = 4; | |
| 17 | +const ACCEPT_DEADLINE: Duration = Duration::from_secs(30); | |
| 18 | +const ASK_DEADLINE: Duration = Duration::from_secs(5); | |
| 19 | +const TRANSFER_DEADLINE: Duration = Duration::from_secs(15 * 60); | |
| 20 | +const STALL_DEADLINE: Duration = Duration::from_secs(30); | |
| 21 | +const CHUNK: usize = 64 << 10; | |
| 22 | +static PERMITS: Semaphore = Semaphore::const_new(16); | |
| 23 | +static PEERS: Mutex<Option<HashSet<IpAddr>>> = Mutex::new(None); | |
| 24 | + | |
| 25 | +struct Peer(IpAddr); | |
| 26 | + | |
| 27 | +impl Peer { | |
| 28 | + fn claim(ip: IpAddr) -> Option<Self> { | |
| 29 | + let mut peers = PEERS.lock().unwrap(); | |
| 30 | + peers.get_or_insert_default().insert(ip).then_some(Self(ip)) | |
| 31 | + } | |
| 32 | +} | |
| 33 | + | |
| 34 | +impl Drop for Peer { | |
| 35 | + fn drop(&mut self) { | |
| 36 | + if let Some(peers) = PEERS.lock().unwrap().as_mut() { | |
| 37 | + peers.remove(&self.0); | |
| 38 | + } | |
| 39 | + } | |
| 40 | +} | |
| 41 | + | |
| 42 | +pub async fn serve(connection: Connection, directory: PathBuf) { | |
| 43 | + let (Some(_peer), Ok(_permit)) = ( | |
| 44 | + Peer::claim(connection.remote_address().ip()), | |
| 45 | + PERMITS.try_acquire(), | |
| 46 | + ) else { | |
| 47 | + connection.close(0u32.into(), b"busy"); | |
| 48 | + return; | |
| 49 | + }; | |
| 50 | + for _ in 0..STREAMS { | |
| 51 | + let Ok(Ok((mut send, mut receive))) = | |
| 52 | + timeout(ACCEPT_DEADLINE, connection.accept_bi()).await | |
| 53 | + else { | |
| 54 | + break; | |
| 55 | + }; | |
| 56 | + let sent = timeout( | |
| 57 | + TRANSFER_DEADLINE, | |
| 58 | + transfer(&mut send, &mut receive, &directory), | |
| 59 | + ) | |
| 60 | + .await; | |
| 61 | + if let Err(error) = sent.map_err(ServerError::from).and_then(|sent| sent) { | |
| 62 | + warn!("update: {error}"); | |
| 63 | + break; | |
| 64 | + } | |
| 65 | + } | |
| 66 | + let _ = timeout(ACCEPT_DEADLINE, connection.closed()).await; | |
| 67 | + connection.close(0u32.into(), b""); | |
| 68 | +} | |
| 69 | + | |
| 70 | +async fn transfer( | |
| 71 | + send: &mut SendStream, | |
| 72 | + receive: &mut RecvStream, | |
| 73 | + directory: &Path, | |
| 74 | +) -> Result<(), ServerError> { | |
| 75 | + let name = timeout(ASK_DEADLINE, update::asked(receive)).await??; | |
| 76 | + let maximum = if name == MANIFEST { | |
| 77 | + MANIFEST_MAX | |
| 78 | + } else { | |
| 79 | + FILE_MAX | |
| 80 | + }; | |
| 81 | + let path = directory.join(&name); | |
| 82 | + let metadata = tokio::fs::metadata(&path) | |
| 83 | + .await | |
| 84 | + .ok() | |
| 85 | + .filter(|metadata| metadata.is_file() && metadata.len() <= maximum); | |
| 86 | + let Some(metadata) = metadata else { | |
| 87 | + update::answer_size(send, None).await?; | |
| 88 | + send.finish()?; | |
| 89 | + return Ok(()); | |
| 90 | + }; | |
| 91 | + | |
| 92 | + update::answer_size(send, Some(metadata.len())).await?; | |
| 93 | + let mut file = tokio::fs::File::open(&path).await?; | |
| 94 | + let mut remaining = metadata.len(); | |
| 95 | + let mut chunk = vec![0u8; CHUNK]; | |
| 96 | + while remaining > 0 { | |
| 97 | + let want = remaining.min(CHUNK as u64) as usize; | |
| 98 | + let read = file.read(&mut chunk[..want]).await?; | |
| 99 | + if read == 0 { | |
| 100 | + break; | |
| 101 | + } | |
| 102 | + timeout(STALL_DEADLINE, send.write_all(&chunk[..read])).await??; | |
| 103 | + remaining -= read as u64; | |
| 104 | + } | |
| 105 | + send.finish()?; | |
| 106 | + | |
| 107 | + Ok(()) | |
| 108 | +} |
packaging/keygen.shadded+29 -0
| @@ -0,0 +1,29 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +set -euo pipefail | |
| 3 | +ROOT="$(cd "$(dirname "$0")/.." && pwd)" | |
| 4 | +KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}" | |
| 5 | +OUT="$ROOT/crates/client/src/update/keys.rs" | |
| 6 | +umask 077 | |
| 7 | +mkdir -p "$KEYS" | |
| 8 | +if grep -q 0x "$OUT"; then | |
| 9 | + echo "$OUT already holds keys; rotating them is a release of its own" >&2 | |
| 10 | + exit 1 | |
| 11 | +fi | |
| 12 | +for name in primary backup; do | |
| 13 | + [[ -e "$KEYS/$name.pem" ]] && continue | |
| 14 | + echo "passphrase for $name key:" | |
| 15 | + openssl genpkey -algorithm ed25519 | openssl pkcs8 -topk8 -v2 aes-256-cbc -iter 2000000 -out "$KEYS/$name.pem.part" | |
| 16 | + mv "$KEYS/$name.pem.part" "$KEYS/$name.pem" | |
| 17 | +done | |
| 18 | +{ | |
| 19 | + echo "pub const KEYS: &[[u8; 32]] = &[" | |
| 20 | + for name in primary backup; do | |
| 21 | + echo "unlock $name key to export its public half:" >&2 | |
| 22 | + bytes=$(openssl pkey -in "$KEYS/$name.pem" -pubout -outform DER | tail -c 32 | od -An -v -tx1 | tr -s ' \n' ' ' | sed 's/^ //; s/ $//; s/\([0-9a-f][0-9a-f]\)/0x\1,/g; s/,$//') | |
| 23 | + echo " [$bytes]," | |
| 24 | + done | |
| 25 | + echo "];" | |
| 26 | +} > "$OUT.tmp" | |
| 27 | +mv "$OUT.tmp" "$OUT" | |
| 28 | +echo "keys in $KEYS, public keys in $OUT" | |
| 29 | +echo "copy $KEYS/backup.pem to offline storage, then delete it from this machine" |
packaging/release-windows.ps1added+14 -0
| @@ -0,0 +1,14 @@ | ||
| 1 | +param([Parameter(Mandatory)][ValidatePattern('^[1-9][0-9]{0,17}$')][string]$Seq) | |
| 2 | +$ErrorActionPreference = 'Stop' | |
| 3 | +Set-Location (Split-Path $PSScriptRoot) | |
| 4 | +if (git status --porcelain) { throw 'working tree is dirty' } | |
| 5 | +$env:RUSTFLAGS = '-C target-feature=+crt-static -C target-cpu=x86-64-v3 -C link-arg=/OPT:REF -C link-arg=/OPT:ICF' | |
| 6 | +$env:YUMUSH_RELEASE_SEQ = $Seq | |
| 7 | +cargo build --release --locked -p client | |
| 8 | +if ($LASTEXITCODE -ne 0) { throw 'build failed' } | |
| 9 | +$out = (& .\target\release\client.exe --selftest | Out-String).Trim() | |
| 10 | +if ($out -ne $Seq) { throw "selftest printed '$out'" } | |
| 11 | +New-Item -ItemType Directory -Force "dist\$Seq" | Out-Null | |
| 12 | +Copy-Item .\target\release\client.exe "dist\$Seq\x86_64-windows" | |
| 13 | +Set-Content -NoNewline "dist\$Seq\x86_64-windows.seq" $out | |
| 14 | +Write-Output "copy dist\$Seq\x86_64-windows and x86_64-windows.seq into dist/$Seq on the signing machine" |
packaging/release.shadded+65 -0
| @@ -0,0 +1,65 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +set -euo pipefail | |
| 3 | +ROOT="$(cd "$(dirname "$0")/.." && pwd)" | |
| 4 | +KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}" | |
| 5 | +cd "$ROOT" | |
| 6 | +usage() { | |
| 7 | + echo "usage: $0 build <seq> | sign <seq> [primary|backup]" >&2 | |
| 8 | + exit 1 | |
| 9 | +} | |
| 10 | +[[ $# -ge 2 && "$2" =~ ^[1-9][0-9]{0,17}$ ]] || usage | |
| 11 | +SEQ="$2" | |
| 12 | +DIST="$ROOT/dist/$SEQ" | |
| 13 | + | |
| 14 | +case "$1" in | |
| 15 | +build) | |
| 16 | + [[ -z "$(git status --porcelain)" ]] || { echo "working tree is dirty" >&2; exit 1; } | |
| 17 | + for done in "$ROOT"/dist/*/; do | |
| 18 | + [[ -d "$done" ]] || continue | |
| 19 | + (( $(basename "$done") < SEQ )) || { echo "seq $SEQ is not above $(basename "$done")" >&2; exit 1; } | |
| 20 | + done | |
| 21 | + TARGET="$(uname -m)-linux" | |
| 22 | + RUSTFLAGS="-C target-cpu=x86-64-v3 -C link-arg=-Wl,--gc-sections -C link-arg=-Wl,-O2" \ | |
| 23 | + YUMUSH_RELEASE_SEQ="$SEQ" cargo build --release --locked -p client | |
| 24 | + mkdir -p "$DIST" | |
| 25 | + cp target/release/client "$DIST/$TARGET" | |
| 26 | + [[ "$("$DIST/$TARGET" --selftest)" == "$SEQ" ]] || { echo "selftest failed" >&2; exit 1; } | |
| 27 | + echo "$DIST/$TARGET" | |
| 28 | + ;; | |
| 29 | +sign) | |
| 30 | + KEY="$KEYS/${3:-primary}.pem" | |
| 31 | + VERSION=$(cargo pkgid -p client | sed 's/.*[#@]//') | |
| 32 | + BODY="$DIST/manifest.body" | |
| 33 | + { | |
| 34 | + printf 'yumush-update 1\nseq %s\nversion %s\n' "$SEQ" "$VERSION" | |
| 35 | + for file in "$DIST"/*; do | |
| 36 | + name=$(basename "$file") | |
| 37 | + [[ "$name" =~ ^[a-z0-9_]+-[a-z0-9_]+$ ]] || continue | |
| 38 | + if [[ "$name" == "$(uname -m)-linux" ]]; then | |
| 39 | + built=$("$file" --selftest) | |
| 40 | + else | |
| 41 | + built=$(cat "$file.seq") | |
| 42 | + fi | |
| 43 | + [[ "$built" == "$SEQ" ]] || { echo "$name was built as seq '$built', not $SEQ" >&2; exit 1; } | |
| 44 | + printf '%s %s %s\n' "$name" "$(stat -c %s "$file")" "$(sha256sum "$file" | cut -d' ' -f1)" | |
| 45 | + done | |
| 46 | + } > "$BODY" | |
| 47 | + grep -q ' ' <(tail -n +4 "$BODY") || { echo "no binaries in $DIST" >&2; exit 1; } | |
| 48 | + cat "$BODY" | |
| 49 | + SIG=$(mktemp) | |
| 50 | + PUBLIC=$(mktemp) | |
| 51 | + trap 'rm -f "$SIG" "$PUBLIC"' EXIT | |
| 52 | + openssl pkeyutl -sign -rawin -inkey "$KEY" -in "$BODY" -out "$SIG" | |
| 53 | + [[ $(stat -c %s "$SIG") == 64 ]] || { echo "bad signature size" >&2; exit 1; } | |
| 54 | + TRUSTED=0 | |
| 55 | + while read -r hex; do | |
| 56 | + { printf '302a300506032b6570032100'; printf '%s' "$hex"; } | xxd -r -p > "$PUBLIC" | |
| 57 | + openssl pkeyutl -verify -rawin -pubin -keyform DER -inkey "$PUBLIC" -in "$BODY" -sigfile "$SIG" >/dev/null 2>&1 && TRUSTED=1 | |
| 58 | + done < <(grep -o '\[0x[^]]*\]' crates/client/src/update/keys.rs | tr -d '[], ' | sed 's/0x//g') | |
| 59 | + [[ $TRUSTED == 1 ]] || { echo "signature does not match any key in keys.rs" >&2; exit 1; } | |
| 60 | + cat "$SIG" "$BODY" > "$DIST/manifest" | |
| 61 | + rm "$BODY" | |
| 62 | + echo "upload the binaries in $DIST to the server's updates/ directory first, then manifest last" | |
| 63 | + ;; | |
| 64 | +*) usage ;; | |
| 65 | +esac |