From 769f1ab7cd7c6a4761f1e4051e9d019db6a69939 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 29 Nov 2026 16:12:57 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20auto=20update.=20Server=20r?= =?UTF-8?q?elays=20an=20Ed25519-signed=20manifest=20and=20binaries=20over?= =?UTF-8?q?=20a=20stable=20yumush-update/1=20ALPN;=20client=20verifies=20a?= =?UTF-8?q?gainst=20compiled-in=20keys,=20checks=20size+sha256,=20self-tes?= =?UTF-8?q?ts=20the=20new=20exe,=20swaps=20on=20disk,=20applies=20on=20res?= =?UTF-8?q?tart,=20rolls=20back=20if=20the=20new=20version=20never=20reach?= =?UTF-8?q?es=20its=20window.=20Release=20builds=20only=20(YUMUSH=5FRELEAS?= =?UTF-8?q?E=5FSEQ),=20x86-64-v3=20baseline,=20macOS=20off=20for=20now.=20?= =?UTF-8?q?Settings=20=E2=80=BA=20Updates:=20Off=20/=20Automatic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + crates/client/Cargo.toml | 1 + crates/client/lang/en/settings_page.txt | 3 + crates/client/lang/tr/settings_page.txt | 3 + crates/client/src/autostart.rs | 15 +- crates/client/src/gui/settings_page.rs | 20 +- crates/client/src/lib.rs | 8 + crates/client/src/logo.rs | 2 +- crates/client/src/main.rs | 6 + crates/client/src/net/link.rs | 16 +- crates/client/src/net/mod.rs | 1 + crates/client/src/settings.rs | 27 ++ crates/client/src/update.rs | 594 ++++++++++++++++++++++++ crates/client/src/update/keys.rs | 1 + crates/common/src/lib.rs | 1 + crates/common/src/update.rs | 83 ++++ crates/server/src/authentication.rs | 1 + crates/server/src/certificate.rs | 5 +- crates/server/src/error.rs | 2 + crates/server/src/lib.rs | 3 + crates/server/src/network.rs | 11 + crates/server/src/request.rs | 1 + crates/server/src/update.rs | 108 +++++ packaging/keygen.sh | 29 ++ packaging/release-windows.ps1 | 14 + packaging/release.sh | 65 +++ 26 files changed, 1008 insertions(+), 13 deletions(-) create mode 100644 crates/client/src/update.rs create mode 100644 crates/client/src/update/keys.rs create mode 100644 crates/common/src/update.rs create mode 100644 crates/server/src/update.rs create mode 100755 packaging/keygen.sh create mode 100644 packaging/release-windows.ps1 create mode 100755 packaging/release.sh diff --git a/.gitignore b/.gitignore index cac5648..8b2e46e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ yumush.db* attachments/ backups/ crates/client/design/tokens.css +/dist diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 6460637..45a0024 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -33,6 +33,7 @@ dirs = "7.0.0" sys-locale = "0.3.2" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } rtrb = "0.4.1" +ring = "0.17.14" gethostname = "1.1.0" rustls-platform-verifier = "0.7.1" sysinfo = { version = "0.40.4", default-features = false, features = ["system"] } diff --git a/crates/client/lang/en/settings_page.txt b/crates/client/lang/en/settings_page.txt index 01fb7ee..259a949 100644 --- a/crates/client/lang/en/settings_page.txt +++ b/crates/client/lang/en/settings_page.txt @@ -20,6 +20,9 @@ launch = Launch at login launch_off = Off launch_window = Window launch_tray = Tray +updates = Updates +updates_off = Off +updates_auto = Automatic your_hue = Your hue camera = Camera screen_share = Screen share diff --git a/crates/client/lang/tr/settings_page.txt b/crates/client/lang/tr/settings_page.txt index 2ce7538..f255985 100644 --- a/crates/client/lang/tr/settings_page.txt +++ b/crates/client/lang/tr/settings_page.txt @@ -20,6 +20,9 @@ launch = Oturum açılınca launch_off = Kapalı launch_window = Pencere launch_tray = Tepsi +updates = Güncellemeler +updates_off = Kapalı +updates_auto = Otomatik your_hue = Rengin camera = Kamera screen_share = Ekran paylaşımı diff --git a/crates/client/src/autostart.rs b/crates/client/src/autostart.rs index f372337..8f27c85 100644 --- a/crates/client/src/autostart.rs +++ b/crates/client/src/autostart.rs @@ -8,7 +8,7 @@ pub fn hidden() -> bool { #[cfg(any(target_os = "linux", target_os = "windows"))] fn command(args: &[&str]) -> std::io::Result { - let exe = std::env::current_exe()?; + let exe = crate::exe().ok_or(std::io::ErrorKind::NotFound)?; Ok(std::iter::once(format!("\"{}\"", exe.display())) .chain(args.iter().map(|arg| arg.to_string())) .collect::>() @@ -58,10 +58,15 @@ fn apply(args: Option<&[&str]>) -> std::io::Result<()> { }; let content = format!( "\n\nLabel{LABEL}ProgramArguments{}RunAtLoad\n", - std::iter::once(std::env::current_exe()?.display().to_string()) - .chain(args.iter().map(|arg| arg.to_string())) - .map(|arg| format!("{arg}")) - .collect::() + std::iter::once( + crate::exe() + .ok_or(std::io::ErrorKind::NotFound)? + .display() + .to_string() + ) + .chain(args.iter().map(|arg| arg.to_string())) + .map(|arg| format!("{arg}")) + .collect::() ); crate::logo::put(&path, &content) } diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 37ce990..0757883 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -25,7 +25,7 @@ use super::{ }; use crate::{ gui::style::{self, Theme, radius, size, space, stroke, text}, - settings::{self, FontSize, Launch, ShareAudio, ShareCodec}, + settings::{self, FontSize, Launch, ShareAudio, ShareCodec, Updates}, share::encode::capabilities, }; @@ -42,7 +42,7 @@ pub(super) fn settings_titles() -> [&'static str; 5] { ] } -pub(super) fn setting_rows() -> [(usize, &'static str); 25] { +pub(super) fn setting_rows() -> [(usize, &'static str); 26] { let s = &w().settings_page; let v = &w().voice_settings; [ @@ -69,6 +69,7 @@ pub(super) fn setting_rows() -> [(usize, &'static str); 25] { (3, s.language), (3, s.close_to_tray), (3, s.launch), + (3, s.updates), (3, s.clock_seconds), (3, s.your_hue), ] @@ -221,6 +222,16 @@ impl Yumush { Yumush::set_launch, ), ), + row( + w().settings_page.updates, + segmented( + Updates::options().map(|updates| (updates, updates.label())), + self.settings.updates, + entity, + palette, + Yumush::set_updates, + ), + ), row( w().settings_page.clock_seconds, super::parts::toggle( @@ -388,6 +399,11 @@ impl Yumush { self.commit_settings(cx); } + pub(super) fn set_updates(&mut self, updates: Updates, cx: &mut Context) { + self.settings.updates = updates; + self.commit_settings(cx); + } + pub(super) fn toggle_clock_seconds(&mut self, cx: &mut Context) { self.settings.clock_seconds = !self.settings.clock_seconds; self.commit_settings(cx); diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index c743eb2..1608ad1 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -18,11 +18,19 @@ pub mod net; pub mod settings; pub mod share; pub mod tray; +pub mod update; pub use usage; pub mod voice; pub const NAME: &str = "Yumush"; +static EXE: std::sync::LazyLock> = + std::sync::LazyLock::new(|| std::env::current_exe().ok()); + +pub fn exe() -> Option<&'static std::path::Path> { + EXE.as_deref() +} + pub fn config_dir() -> Option { std::env::var_os("YUMUSH_CONFIG_DIR") .map(PathBuf::from) diff --git a/crates/client/src/logo.rs b/crates/client/src/logo.rs index 54f252e..d9c44f0 100644 --- a/crates/client/src/logo.rs +++ b/crates/client/src/logo.rs @@ -20,7 +20,7 @@ pub fn window_icon() -> std::sync::Arc { #[cfg(target_os = "linux")] pub fn install() -> std::io::Result<()> { let data = dirs::data_dir().ok_or(std::io::ErrorKind::NotFound)?; - let exe = std::env::current_exe()?; + let exe = crate::exe().ok_or(std::io::ErrorKind::NotFound)?; put( &data .join("icons/hicolor/scalable/apps") diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 8c2692d..05edd47 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -18,6 +18,9 @@ use tracing::Level; use tracing_subscriber::{filter::Targets, layer::SubscriberExt, util::SubscriberInitExt}; fn main() { + if client::update::selftest() || client::update::boot() { + return; + } tracing_subscriber::registry() .with(tracing_subscriber::fmt::layer()) .with( @@ -42,8 +45,10 @@ fn main() { } let client::instance::Instance::First(mut wake) = client::instance::claim() else { + client::update::claimed(false); return; }; + client::update::claimed(true); #[cfg(target_os = "linux")] if let Err(error) = client::logo::install() { @@ -75,6 +80,7 @@ fn main() { if hidden { hide(&view, cx); } + client::update::ready(); let (mut tray_receiver, tray_handle) = tray::start(); let mut tray_state = TrayState::default(); diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index 1c89359..e03d406 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -110,9 +110,17 @@ async fn backoff(attempt: &mut u32) { *attempt += 1; } +pub(crate) async fn dial( + server: &crate::Server, + alpn: &[u8], +) -> Result { + connect(server, &mut Endpoints::default(), alpn).await +} + async fn connect( server: &crate::Server, endpoints: &mut Endpoints, + alpn: &[u8], ) -> Result { let mut addresses: Vec = tokio::net::lookup_host(server.address.as_str()) .await @@ -130,7 +138,7 @@ async fn connect( } }; let connecting = - match endpoint.connect_with(config(server.any_cert)?, address, server.host()) { + match endpoint.connect_with(config(server.any_cert, alpn)?, address, server.host()) { Ok(connecting) => connecting, Err(_) => { endpoints.forget(address); @@ -209,7 +217,7 @@ impl ServerCertVerifier for AcceptAnyCertificate { } } -fn config(any_cert: bool) -> Result { +fn config(any_cert: bool, alpn: &[u8]) -> Result { let provider = Arc::new(rustls::crypto::ring::default_provider()); let verifier: Arc = if any_cert { Arc::new(AcceptAnyCertificate { @@ -225,7 +233,7 @@ fn config(any_cert: bool) -> Result { .dangerous() .with_custom_certificate_verifier(verifier) .with_no_client_auth(); - tls.alpn_protocols = vec![ALPN.to_vec()]; + tls.alpn_protocols = vec![alpn.to_vec()]; let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?; let mut client_config = quinn::ClientConfig::new(Arc::new(crypto)); @@ -383,7 +391,7 @@ async fn actor( let connection = loop { let address = server.borrow_and_update().clone(); let result = tokio::select! { - result = connect(&address, &mut endpoints) => result, + result = connect(&address, &mut endpoints, ALPN) => result, _ = server.changed() => { attempt = 0; token = None; diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs index 8a5c73f..32127dd 100644 --- a/crates/client/src/net/mod.rs +++ b/crates/client/src/net/mod.rs @@ -16,6 +16,7 @@ mod link; mod media; pub use fail::{Fail, LinkError}; +pub(crate) use link::dial; pub use link::start; use media::Media; diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index 0c81538..c2d63db 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -90,6 +90,27 @@ impl Launch { } } +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + Updates { + Off => "off", + Auto => "auto", + } +} + +impl Updates { + pub fn options() -> impl Iterator { + Self::ALL.into_iter() + } + + pub fn label(self) -> &'static str { + match self { + Updates::Off => w().settings_page.updates_off, + Updates::Auto => w().settings_page.updates_auto, + } + } +} + string_enum! { #[derive(Debug, Clone, Copy, PartialEq, Eq)] Activation { @@ -221,6 +242,7 @@ pub struct Settings { pub share: ShareSettings, pub close_to_tray: bool, pub launch: Launch, + pub updates: Updates, pub clock_seconds: bool, pub jump_usage: BTreeMap, pub last_chats: BTreeMap, @@ -250,6 +272,7 @@ impl Default for Settings { } else { Launch::Window }, + updates: Updates::Auto, clock_seconds: false, jump_usage: BTreeMap::new(), last_chats: BTreeMap::new(), @@ -368,6 +391,9 @@ pub fn load() -> Settings { .and_then(|value| Launch::parse(&value)) .filter(|launch| Launch::options().any(|option| option == *launch)) .unwrap_or(defaults.launch), + updates: text("updates") + .and_then(|value| Updates::parse(&value)) + .unwrap_or(defaults.updates), clock_seconds: text("clock_seconds") .map_or(defaults.clock_seconds, |value| value == "true"), jump_usage: text("jump.usage") @@ -410,6 +436,7 @@ pub fn save(settings: &Settings) { line("language", settings.language.as_str()), line("close_to_tray", settings.close_to_tray), line("launch", settings.launch.as_str()), + line("updates", settings.updates.as_str()), line("clock_seconds", settings.clock_seconds), line("voice.sensitivity", voice.sensitivity_db), line("voice.input_volume", voice.input_volume), diff --git a/crates/client/src/update.rs b/crates/client/src/update.rs new file mode 100644 index 0000000..05492d3 --- /dev/null +++ b/crates/client/src/update.rs @@ -0,0 +1,594 @@ +use std::{ + fs, + io::{Read, Write}, + path::{Path, PathBuf}, + process::{Command, Stdio}, + time::{Duration, Instant}, +}; + +use common::update::{self as wire, FILE_MAX, MANIFEST, MANIFEST_MAX}; +use ring::{digest, signature}; +use tracing::{info, warn}; + +mod keys; + +pub const SELFTEST: &str = "--selftest"; +const MAGIC: &str = "yumush-update 1"; +const SIGNATURE_BYTES: usize = 64; +const FIRST_CHECK: Duration = Duration::from_secs(60); +const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60); +const SELFTEST_LIMIT: Duration = Duration::from_secs(20); +const PACKAGED_ENV: [&str; 3] = ["FLATPAK_ID", "SNAP", "APPIMAGE"]; +const PACKAGED_ROOTS: [&str; 2] = ["/usr/", "/nix/"]; + +pub const SEQ: Option = match option_env!("YUMUSH_RELEASE_SEQ") { + Some(text) => Some(parse_seq(text)), + None => None, +}; + +const _: () = assert!( + SEQ.is_none() || !keys::KEYS.is_empty(), + "release build needs update keys" +); + +const fn parse_seq(text: &str) -> u64 { + let bytes = text.as_bytes(); + assert!(!bytes.is_empty() && bytes.len() <= 18, "YUMUSH_RELEASE_SEQ"); + let mut value = 0u64; + let mut index = 0; + while index < bytes.len() { + assert!(bytes[index].is_ascii_digit(), "YUMUSH_RELEASE_SEQ"); + value = value * 10 + (bytes[index] - b'0') as u64; + index += 1; + } + assert!(value > 0, "YUMUSH_RELEASE_SEQ"); + value +} + +#[derive(Debug)] +enum Off { + Unofficial, + Platform, + Multi, + Packaged, + NoExe, +} + +#[allow(dead_code)] +#[derive(Debug)] +enum Fail { + Link(crate::net::LinkError), + Connection(quinn::ConnectionError), + Wire(wire::UpdateError), + Reject(Reject), + Hash, + Selftest, + Io(std::io::Error), +} + +#[derive(Debug)] +enum Reject { + Short, + Signature, + Format, + Target, +} + +enum Check { + Current, + Staged(u64), +} + +#[derive(Debug, PartialEq)] +struct Release { + seq: u64, + version: String, + size: u64, + sha256: [u8; 32], +} + +impl From for Fail { + fn from(error: std::io::Error) -> Self { + Self::Io(error) + } +} + +impl From for Fail { + fn from(error: wire::UpdateError) -> Self { + Self::Wire(error) + } +} + +impl From for Fail { + fn from(error: quinn::ConnectionError) -> Self { + Self::Connection(error) + } +} + +fn mode() -> Result<(u64, &'static Path), Off> { + let seq = SEQ.ok_or(Off::Unofficial)?; + if cfg!(target_os = "macos") { + return Err(Off::Platform); + } + if std::env::args().any(|arg| arg == crate::instance::MULTI) { + return Err(Off::Multi); + } + if PACKAGED_ENV + .iter() + .any(|name| std::env::var_os(name).is_some()) + { + return Err(Off::Packaged); + } + let exe = crate::exe().ok_or(Off::NoExe)?; + let shown = exe.to_string_lossy(); + if PACKAGED_ROOTS.iter().any(|root| shown.starts_with(root)) { + return Err(Off::Packaged); + } + Ok((seq, exe)) +} + +fn target() -> String { + format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS) +} + +fn sibling(exe: &Path, tag: &str) -> PathBuf { + let stem = exe.file_stem().unwrap_or_default().to_string_lossy(); + let name = match exe.extension() { + Some(extension) => format!("{stem}.{tag}.{}", extension.to_string_lossy()), + None => format!("{stem}.{tag}"), + }; + exe.with_file_name(name) +} + +fn state(exe: &Path, tag: &str) -> PathBuf { + let name = exe.file_name().unwrap_or_default().to_string_lossy(); + exe.with_file_name(format!("{name}.{tag}")) +} + +fn read(path: &Path) -> Option { + fs::read_to_string(path) + .ok() + .map(|text| text.trim().to_string()) +} + +fn number(path: &Path) -> Option { + read(path)?.parse().ok() +} + +fn sync_dir(path: &Path) { + #[cfg(unix)] + if let Some(dir) = path.parent() { + let _ = fs::File::open(dir).and_then(|dir| dir.sync_all()); + } + #[cfg(not(unix))] + let _ = path; +} + +fn put(path: &Path, text: &str) -> std::io::Result<()> { + let part = path.with_added_extension("part"); + let mut file = fs::File::create(&part)?; + file.write_all(text.as_bytes())?; + file.sync_all()?; + drop(file); + fs::rename(&part, path)?; + sync_dir(path); + Ok(()) +} + +fn trial(exe: &Path) -> Option<(u64, u32)> { + let text = read(&state(exe, "trial"))?; + let (seq, pid) = text.split_once(' ')?; + Some((seq.parse().ok()?, pid.parse().ok()?)) +} + +fn claim_trial(exe: &Path, seq: u64) -> std::io::Result<()> { + put( + &state(exe, "trial"), + &format!("{seq} {}", std::process::id()), + ) +} + +fn alive(pid: u32) -> bool { + let pid = sysinfo::Pid::from_u32(pid); + let Ok(mut system) = sysinfo::System::new() else { + return false; + }; + system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true); + system.process(pid).is_some() +} + +pub fn selftest() -> bool { + if !std::env::args().any(|arg| arg == SELFTEST) { + return false; + } + println!("{}", SEQ.unwrap_or(0)); + true +} + +pub fn boot() -> bool { + let Ok((seq, exe)) = mode() else { + return false; + }; + if let Some((trying, pid)) = trial(exe) + && trying == seq + && !alive(pid) + { + return rollback(seq, exe); + } + let pending = state(exe, "pending"); + if number(&pending) == Some(seq) && claim_trial(exe, seq).is_ok() { + let _ = fs::remove_file(&pending); + sync_dir(exe); + } + false +} + +pub fn claimed(first: bool) { + let Ok((seq, exe)) = mode() else { + return; + }; + let me = std::process::id(); + match trial(exe) { + Some((trying, pid)) if trying == seq => { + if !first { + if pid == me && put(&state(exe, "pending"), &seq.to_string()).is_ok() { + let _ = fs::remove_file(state(exe, "trial")); + } + } else if pid != me { + let _ = claim_trial(exe, seq); + } + if first { + info!("update: trying {seq}"); + } + } + _ if first => { + for tag in ["trial", "pending"] { + let _ = fs::remove_file(state(exe, tag)); + } + for tag in ["new", "bad", "old"] { + let _ = fs::remove_file(sibling(exe, tag)); + } + } + _ => {} + } +} + +fn rollback(seq: u64, exe: &Path) -> bool { + let old = sibling(exe, "old"); + if !old.exists() { + let _ = fs::remove_file(state(exe, "trial")); + return false; + } + let _ = put(&state(exe, "skip"), &seq.to_string()); + if let Err(error) = restore(exe, &old) { + warn!("update: rollback {error}"); + return false; + } + sync_dir(exe); + let _ = fs::remove_file(state(exe, "trial")); + Command::new(exe) + .args(std::env::args_os().skip(1)) + .spawn() + .is_ok() +} + +#[cfg(unix)] +fn restore(exe: &Path, old: &Path) -> std::io::Result<()> { + fs::rename(old, exe) +} + +#[cfg(not(unix))] +fn restore(exe: &Path, old: &Path) -> std::io::Result<()> { + let bad = sibling(exe, "bad"); + let _ = fs::remove_file(&bad); + fs::rename(exe, &bad)?; + fs::rename(old, exe).inspect_err(|_| { + let _ = fs::rename(&bad, exe); + }) +} + +pub fn ready() { + let Ok((seq, exe)) = mode() else { + return; + }; + if trial(exe) == Some((seq, std::process::id())) { + let _ = fs::remove_file(sibling(exe, "old")); + let _ = fs::remove_file(state(exe, "trial")); + info!("update: {seq} is healthy"); + } + let _ = std::thread::Builder::new() + .name("update".to_string()) + .spawn(move || watch(seq, exe)); +} + +fn watch(seq: u64, exe: &'static Path) { + let Ok(runtime) = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + else { + return; + }; + std::thread::sleep(FIRST_CHECK); + loop { + if crate::settings::load().updates != crate::settings::Updates::Off { + match runtime.block_on(check(seq, exe)) { + Ok(Check::Staged(next)) => { + info!("update: {next} staged, applies on restart"); + return; + } + Ok(Check::Current) => {} + Err(fail) => warn!("update: {fail:?}"), + } + } + std::thread::sleep(CHECK_EVERY); + } +} + +async fn fetch(connection: &quinn::Connection, name: &str, maximum: u64) -> Result, Fail> { + let (mut send, mut receive) = connection.open_bi().await?; + wire::ask(&mut send, name).await?; + Ok(wire::receive(&mut receive, maximum).await?) +} + +async fn check(seq: u64, exe: &Path) -> Result { + let connection = crate::net::dial(&crate::Server::load(), wire::ALPN) + .await + .map_err(Fail::Link)?; + let checked = fetch_release(&connection, seq, exe).await; + connection.close(0u32.into(), b""); + let Some((release, file, bytes)) = checked? else { + return Ok(Check::Current); + }; + stage(exe, file, &bytes, release.seq)?; + Ok(Check::Staged(release.seq)) +} + +async fn fetch_release( + connection: &quinn::Connection, + seq: u64, + exe: &Path, +) -> Result)>, Fail> { + let manifest = fetch(connection, MANIFEST, MANIFEST_MAX).await?; + let release = verify(&manifest, &target(), keys::KEYS).map_err(Fail::Reject)?; + if release.seq <= seq || number(&state(exe, "skip")) == Some(release.seq) { + return Ok(None); + } + let file = open_new(exe)?; + info!("update: downloading {} ({})", release.version, release.seq); + let bytes = fetch(connection, &target(), release.size).await; + let bytes = bytes.inspect_err(|_| { + let _ = fs::remove_file(sibling(exe, "new")); + })?; + if bytes.len() as u64 != release.size + || digest::digest(&digest::SHA256, &bytes).as_ref() != release.sha256 + { + let _ = fs::remove_file(sibling(exe, "new")); + return Err(Fail::Hash); + } + Ok(Some((release, file, bytes))) +} + +fn verify(signed: &[u8], target: &str, keys: &[[u8; 32]]) -> Result { + let (sig, body) = signed + .split_at_checked(SIGNATURE_BYTES) + .ok_or(Reject::Short)?; + let signed_by_us = keys.iter().any(|key| { + signature::UnparsedPublicKey::new(&signature::ED25519, key) + .verify(body, sig) + .is_ok() + }); + if !signed_by_us { + return Err(Reject::Signature); + } + let text = std::str::from_utf8(body).map_err(|_| Reject::Format)?; + let mut lines = text.split('\n'); + if lines.next() != Some(MAGIC) { + return Err(Reject::Format); + } + let seq = field(lines.next(), "seq") + .and_then(|value| value.parse::().ok()) + .ok_or(Reject::Format)?; + let version = field(lines.next(), "version") + .filter(|value| !value.is_empty()) + .ok_or(Reject::Format)? + .to_string(); + let mut found = None; + let mut seen = Vec::new(); + for line in lines { + if line.is_empty() { + continue; + } + let mut parts = line.split(' '); + let (Some(name), Some(size), Some(hash), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(Reject::Format); + }; + if !wire::valid_name(name) || name == MANIFEST || seen.contains(&name) { + return Err(Reject::Format); + } + seen.push(name); + let size = size + .parse::() + .ok() + .filter(|size| (1..=FILE_MAX).contains(size)) + .ok_or(Reject::Format)?; + let sha256 = hex32(hash).ok_or(Reject::Format)?; + if name == target { + found = Some((size, sha256)); + } + } + let (size, sha256) = found.ok_or(Reject::Target)?; + Ok(Release { + seq, + version, + size, + sha256, + }) +} + +fn field<'a>(line: Option<&'a str>, key: &str) -> Option<&'a str> { + line?.strip_prefix(key)?.strip_prefix(' ') +} + +fn hex32(text: &str) -> Option<[u8; 32]> { + let bytes = text.as_bytes(); + if bytes.len() != 64 { + return None; + } + let mut out = [0u8; 32]; + for (index, pair) in bytes.chunks(2).enumerate() { + let digit = |byte: u8| match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + _ => None, + }; + out[index] = digit(pair[0])? << 4 | digit(pair[1])?; + } + Some(out) +} + +fn open_new(exe: &Path) -> std::io::Result { + let new = sibling(exe, "new"); + let _ = fs::remove_file(&new); + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o755); + options.open(&new) +} + +fn stage(exe: &Path, mut file: fs::File, bytes: &[u8], seq: u64) -> Result<(), Fail> { + let new = sibling(exe, "new"); + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + let staged = written.map_err(Fail::Io).and_then(|()| { + run_selftest(&new, seq).inspect_err(|_| { + let _ = put(&state(exe, "skip"), &seq.to_string()); + }) + }); + let staged = staged.and_then(|()| swap(exe, &new, seq)); + if staged.is_err() { + let _ = fs::remove_file(&new); + } + staged +} + +fn run_selftest(new: &Path, seq: u64) -> Result<(), Fail> { + let mut child = Command::new(new) + .arg(SELFTEST) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn()?; + let started = Instant::now(); + let status = loop { + if let Some(status) = child.try_wait()? { + break status; + } + if started.elapsed() > SELFTEST_LIMIT { + let _ = child.kill(); + let _ = child.wait(); + return Err(Fail::Selftest); + } + std::thread::sleep(Duration::from_millis(100)); + }; + let mut out = String::new(); + if let Some(mut stdout) = child.stdout.take() { + let _ = stdout.read_to_string(&mut out); + } + if !status.success() || out.trim() != seq.to_string() { + return Err(Fail::Selftest); + } + Ok(()) +} + +fn swap(exe: &Path, new: &Path, seq: u64) -> Result<(), Fail> { + let old = sibling(exe, "old"); + let pending = state(exe, "pending"); + let _ = fs::remove_file(&old); + put(&pending, &seq.to_string())?; + let swapped = replace(exe, new, &old); + if swapped.is_err() { + let _ = fs::remove_file(&pending); + } + sync_dir(exe); + Ok(swapped?) +} + +#[cfg(unix)] +fn replace(exe: &Path, new: &Path, old: &Path) -> std::io::Result<()> { + fs::hard_link(exe, old).or_else(|_| fs::copy(exe, old).map(drop))?; + fs::rename(new, exe).inspect_err(|_| { + let _ = fs::remove_file(old); + }) +} + +#[cfg(not(unix))] +fn replace(exe: &Path, new: &Path, old: &Path) -> std::io::Result<()> { + fs::rename(exe, old)?; + fs::rename(new, exe).inspect_err(|_| { + let _ = fs::rename(old, exe); + }) +} + +#[cfg(test)] +mod tests { + use ring::{ + rand::SystemRandom, + signature::{Ed25519KeyPair, KeyPair}, + }; + + use super::*; + + fn signed(key: &Ed25519KeyPair, body: &str) -> Vec { + let mut out = key.sign(body.as_bytes()).as_ref().to_vec(); + out.extend_from_slice(body.as_bytes()); + out + } + + fn pair() -> (Ed25519KeyPair, [u8; 32]) { + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap(); + let key = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(); + let public = key.public_key().as_ref().try_into().unwrap(); + (key, public) + } + + const HASH: &str = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; + + #[test] + fn verifies() { + let (key, public) = pair(); + let body = format!( + "{MAGIC}\nseq 7\nversion 0.2.0\nx86_64-linux 10 {HASH}\nx86_64-windows 20 {HASH}\n" + ); + let release = verify(&signed(&key, &body), "x86_64-windows", &[public]).unwrap(); + assert_eq!( + (release.seq, release.size, release.sha256[1]), + (7, 20, 0x11) + ); + } + + #[test] + fn rejects() { + let (key, public) = pair(); + let (other, _) = pair(); + let good = format!("{MAGIC}\nseq 7\nversion 1\nx86_64-linux 10 {HASH}\n"); + let mut tampered = signed(&key, &good); + *tampered.last_mut().unwrap() ^= 1; + let cases = [ + signed(&other, &good), + tampered, + signed(&key, &good)[..63].to_vec(), + signed(&key, &good.replace("x86_64-linux", "aarch64-linux")), + signed(&key, &format!("{good}x86_64-linux 10 {HASH}\n")), + signed(&key, &good.replace(" 10 ", " 0 ")), + signed(&key, &good.replace("seq 7", "seq x")), + signed(&key, &good.replace(MAGIC, "yumush-update 2")), + signed(&key, &format!("{good}manifest 10 {HASH}\n")), + ]; + for case in cases { + assert!(verify(&case, "x86_64-linux", &[public]).is_err()); + } + } +} diff --git a/crates/client/src/update/keys.rs b/crates/client/src/update/keys.rs new file mode 100644 index 0000000..f166434 --- /dev/null +++ b/crates/client/src/update/keys.rs @@ -0,0 +1 @@ +pub const KEYS: &[[u8; 32]] = &[]; diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 9a81d2d..dc46231 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -13,4 +13,5 @@ pub mod share; pub mod stats; pub mod time; pub mod transport; +pub mod update; pub mod validate; diff --git a/crates/common/src/update.rs b/crates/common/src/update.rs new file mode 100644 index 0000000..4a8a948 --- /dev/null +++ b/crates/common/src/update.rs @@ -0,0 +1,83 @@ +use quinn::{RecvStream, SendStream}; + +pub const ALPN: &[u8] = b"yumush-update/1"; +pub const MANIFEST: &str = "manifest"; +pub const MANIFEST_MAX: u64 = 64 << 10; +pub const FILE_MAX: u64 = 512 << 20; +const NAME_MAX: usize = 32; +const MISSING: u64 = u64::MAX; + +#[derive(Debug, thiserror::Error)] +pub enum UpdateError { + #[error(transparent)] + Write(#[from] quinn::WriteError), + #[error(transparent)] + Read(#[from] quinn::ReadExactError), + #[error(transparent)] + ReadToEnd(#[from] quinn::ReadToEndError), + #[error(transparent)] + Closed(#[from] quinn::ClosedStream), + #[error("invalid name")] + Name, + #[error("missing")] + Missing, + #[error("size {0}")] + Size(u64), +} + +pub fn valid_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= NAME_MAX + && name.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-' + }) +} + +pub async fn ask(send: &mut SendStream, name: &str) -> Result<(), UpdateError> { + if !valid_name(name) { + return Err(UpdateError::Name); + } + send.write_all(&[name.len() as u8]).await?; + send.write_all(name.as_bytes()).await?; + send.finish()?; + Ok(()) +} + +pub async fn asked(receive: &mut RecvStream) -> Result { + let mut length = [0u8; 1]; + receive.read_exact(&mut length).await?; + let length = length[0] as usize; + if length > NAME_MAX { + return Err(UpdateError::Name); + } + let mut name = vec![0u8; length]; + receive.read_exact(&mut name).await?; + let name = String::from_utf8(name).map_err(|_| UpdateError::Name)?; + if !valid_name(&name) { + return Err(UpdateError::Name); + } + Ok(name) +} + +pub async fn answer_size(send: &mut SendStream, size: Option) -> Result<(), UpdateError> { + send.write_all(&size.unwrap_or(MISSING).to_le_bytes()) + .await?; + Ok(()) +} + +pub async fn receive(receive: &mut RecvStream, maximum: u64) -> Result, UpdateError> { + let mut size = [0u8; 8]; + receive.read_exact(&mut size).await?; + let size = u64::from_le_bytes(size); + if size == MISSING { + return Err(UpdateError::Missing); + } + if size > maximum { + return Err(UpdateError::Size(size)); + } + let bytes = receive.read_to_end(maximum as usize).await?; + if bytes.len() as u64 != size { + return Err(UpdateError::Size(bytes.len() as u64)); + } + Ok(bytes) +} diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index d7e5580..83a4a91 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -234,6 +234,7 @@ mod tests { services: Services::default(), directory: test::directory(), backups: test::directory(), + updates: test::directory(), }; let client = Client::detached(None); diff --git a/crates/server/src/certificate.rs b/crates/server/src/certificate.rs index 9e1095a..6f96aa9 100644 --- a/crates/server/src/certificate.rs +++ b/crates/server/src/certificate.rs @@ -115,7 +115,10 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result Result<(), ServerError> { let certificate = certificate::load(&config.certificate_path, &config.key_path)?; let attachments = sibling_directory(&config.database_path, "attachments")?; let backups = sibling_directory(&config.database_path, "backups")?; + let updates = sibling_directory(&config.database_path, "updates")?; tokio::spawn(files::collect(database.clone(), attachments.clone())); network::serve( @@ -81,6 +83,7 @@ pub async fn showtime() -> Result<(), ServerError> { database, attachments, backups, + updates, ) .await } diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index f97db17..0c1465f 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -48,6 +48,7 @@ pub(crate) struct Shared { pub(crate) services: Services, pub(crate) directory: PathBuf, pub(crate) backups: PathBuf, + pub(crate) updates: PathBuf, } struct Pending { @@ -63,6 +64,7 @@ pub async fn serve( db: Db, directory: PathBuf, backups: PathBuf, + updates: PathBuf, ) -> Result<(), ServerError> { let endpoint = transport::endpoint( server_address.parse()?, @@ -76,6 +78,7 @@ pub async fn serve( services: Services::default(), directory, backups, + updates, }; shared.services.machine.watch(shared.directory.clone()); @@ -108,6 +111,14 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv return Ok(()); } let connection = incoming.await?; + let alpn = connection + .handshake_data() + .and_then(|data| data.downcast::().ok()) + .and_then(|data| data.protocol); + if alpn.as_deref() == Some(common::update::ALPN) { + crate::update::serve(connection, shared.updates.clone()).await; + return Ok(()); + } let pending = match tokio::time::timeout(HELLO_DEADLINE, greet(&connection, &shared)).await { Ok(Ok(Some(pending))) => pending, Ok(Ok(None)) => return Ok(()), diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 83a5ed8..de478c5 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -373,6 +373,7 @@ mod tests { services: services.clone(), directory: test::directory(), backups: test::directory(), + updates: test::directory(), } } diff --git a/crates/server/src/update.rs b/crates/server/src/update.rs new file mode 100644 index 0000000..81ae46d --- /dev/null +++ b/crates/server/src/update.rs @@ -0,0 +1,108 @@ +use std::{ + collections::HashSet, + net::IpAddr, + path::{Path, PathBuf}, + sync::Mutex, + time::Duration, +}; + +use common::update::{self, FILE_MAX, MANIFEST, MANIFEST_MAX}; +use quinn::{Connection, RecvStream, SendStream}; +use tokio::{io::AsyncReadExt, sync::Semaphore, time::timeout}; +use tracing::warn; + +use crate::error::ServerError; + +const STREAMS: usize = 4; +const ACCEPT_DEADLINE: Duration = Duration::from_secs(30); +const ASK_DEADLINE: Duration = Duration::from_secs(5); +const TRANSFER_DEADLINE: Duration = Duration::from_secs(15 * 60); +const STALL_DEADLINE: Duration = Duration::from_secs(30); +const CHUNK: usize = 64 << 10; +static PERMITS: Semaphore = Semaphore::const_new(16); +static PEERS: Mutex>> = Mutex::new(None); + +struct Peer(IpAddr); + +impl Peer { + fn claim(ip: IpAddr) -> Option { + let mut peers = PEERS.lock().unwrap(); + peers.get_or_insert_default().insert(ip).then_some(Self(ip)) + } +} + +impl Drop for Peer { + fn drop(&mut self) { + if let Some(peers) = PEERS.lock().unwrap().as_mut() { + peers.remove(&self.0); + } + } +} + +pub async fn serve(connection: Connection, directory: PathBuf) { + let (Some(_peer), Ok(_permit)) = ( + Peer::claim(connection.remote_address().ip()), + PERMITS.try_acquire(), + ) else { + connection.close(0u32.into(), b"busy"); + return; + }; + for _ in 0..STREAMS { + let Ok(Ok((mut send, mut receive))) = + timeout(ACCEPT_DEADLINE, connection.accept_bi()).await + else { + break; + }; + let sent = timeout( + TRANSFER_DEADLINE, + transfer(&mut send, &mut receive, &directory), + ) + .await; + if let Err(error) = sent.map_err(ServerError::from).and_then(|sent| sent) { + warn!("update: {error}"); + break; + } + } + let _ = timeout(ACCEPT_DEADLINE, connection.closed()).await; + connection.close(0u32.into(), b""); +} + +async fn transfer( + send: &mut SendStream, + receive: &mut RecvStream, + directory: &Path, +) -> Result<(), ServerError> { + let name = timeout(ASK_DEADLINE, update::asked(receive)).await??; + let maximum = if name == MANIFEST { + MANIFEST_MAX + } else { + FILE_MAX + }; + let path = directory.join(&name); + let metadata = tokio::fs::metadata(&path) + .await + .ok() + .filter(|metadata| metadata.is_file() && metadata.len() <= maximum); + let Some(metadata) = metadata else { + update::answer_size(send, None).await?; + send.finish()?; + return Ok(()); + }; + + update::answer_size(send, Some(metadata.len())).await?; + let mut file = tokio::fs::File::open(&path).await?; + let mut remaining = metadata.len(); + let mut chunk = vec![0u8; CHUNK]; + while remaining > 0 { + let want = remaining.min(CHUNK as u64) as usize; + let read = file.read(&mut chunk[..want]).await?; + if read == 0 { + break; + } + timeout(STALL_DEADLINE, send.write_all(&chunk[..read])).await??; + remaining -= read as u64; + } + send.finish()?; + + Ok(()) +} diff --git a/packaging/keygen.sh b/packaging/keygen.sh new file mode 100755 index 0000000..0734e2b --- /dev/null +++ b/packaging/keygen.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}" +OUT="$ROOT/crates/client/src/update/keys.rs" +umask 077 +mkdir -p "$KEYS" +if grep -q 0x "$OUT"; then + echo "$OUT already holds keys; rotating them is a release of its own" >&2 + exit 1 +fi +for name in primary backup; do + [[ -e "$KEYS/$name.pem" ]] && continue + echo "passphrase for $name key:" + openssl genpkey -algorithm ed25519 | openssl pkcs8 -topk8 -v2 aes-256-cbc -iter 2000000 -out "$KEYS/$name.pem.part" + mv "$KEYS/$name.pem.part" "$KEYS/$name.pem" +done +{ + echo "pub const KEYS: &[[u8; 32]] = &[" + for name in primary backup; do + echo "unlock $name key to export its public half:" >&2 + 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/,$//') + echo " [$bytes]," + done + echo "];" +} > "$OUT.tmp" +mv "$OUT.tmp" "$OUT" +echo "keys in $KEYS, public keys in $OUT" +echo "copy $KEYS/backup.pem to offline storage, then delete it from this machine" diff --git a/packaging/release-windows.ps1 b/packaging/release-windows.ps1 new file mode 100644 index 0000000..06b9d0d --- /dev/null +++ b/packaging/release-windows.ps1 @@ -0,0 +1,14 @@ +param([Parameter(Mandatory)][ValidatePattern('^[1-9][0-9]{0,17}$')][string]$Seq) +$ErrorActionPreference = 'Stop' +Set-Location (Split-Path $PSScriptRoot) +if (git status --porcelain) { throw 'working tree is dirty' } +$env:RUSTFLAGS = '-C target-feature=+crt-static -C target-cpu=x86-64-v3 -C link-arg=/OPT:REF -C link-arg=/OPT:ICF' +$env:YUMUSH_RELEASE_SEQ = $Seq +cargo build --release --locked -p client +if ($LASTEXITCODE -ne 0) { throw 'build failed' } +$out = (& .\target\release\client.exe --selftest | Out-String).Trim() +if ($out -ne $Seq) { throw "selftest printed '$out'" } +New-Item -ItemType Directory -Force "dist\$Seq" | Out-Null +Copy-Item .\target\release\client.exe "dist\$Seq\x86_64-windows" +Set-Content -NoNewline "dist\$Seq\x86_64-windows.seq" $out +Write-Output "copy dist\$Seq\x86_64-windows and x86_64-windows.seq into dist/$Seq on the signing machine" diff --git a/packaging/release.sh b/packaging/release.sh new file mode 100755 index 0000000..1d382bf --- /dev/null +++ b/packaging/release.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +KEYS="${YUMUSH_SIGNING_DIR:-$HOME/.local/share/yumush-signing}" +cd "$ROOT" +usage() { + echo "usage: $0 build | sign [primary|backup]" >&2 + exit 1 +} +[[ $# -ge 2 && "$2" =~ ^[1-9][0-9]{0,17}$ ]] || usage +SEQ="$2" +DIST="$ROOT/dist/$SEQ" + +case "$1" in +build) + [[ -z "$(git status --porcelain)" ]] || { echo "working tree is dirty" >&2; exit 1; } + for done in "$ROOT"/dist/*/; do + [[ -d "$done" ]] || continue + (( $(basename "$done") < SEQ )) || { echo "seq $SEQ is not above $(basename "$done")" >&2; exit 1; } + done + TARGET="$(uname -m)-linux" + RUSTFLAGS="-C target-cpu=x86-64-v3 -C link-arg=-Wl,--gc-sections -C link-arg=-Wl,-O2" \ + YUMUSH_RELEASE_SEQ="$SEQ" cargo build --release --locked -p client + mkdir -p "$DIST" + cp target/release/client "$DIST/$TARGET" + [[ "$("$DIST/$TARGET" --selftest)" == "$SEQ" ]] || { echo "selftest failed" >&2; exit 1; } + echo "$DIST/$TARGET" + ;; +sign) + KEY="$KEYS/${3:-primary}.pem" + VERSION=$(cargo pkgid -p client | sed 's/.*[#@]//') + BODY="$DIST/manifest.body" + { + printf 'yumush-update 1\nseq %s\nversion %s\n' "$SEQ" "$VERSION" + for file in "$DIST"/*; do + name=$(basename "$file") + [[ "$name" =~ ^[a-z0-9_]+-[a-z0-9_]+$ ]] || continue + if [[ "$name" == "$(uname -m)-linux" ]]; then + built=$("$file" --selftest) + else + built=$(cat "$file.seq") + fi + [[ "$built" == "$SEQ" ]] || { echo "$name was built as seq '$built', not $SEQ" >&2; exit 1; } + printf '%s %s %s\n' "$name" "$(stat -c %s "$file")" "$(sha256sum "$file" | cut -d' ' -f1)" + done + } > "$BODY" + grep -q ' ' <(tail -n +4 "$BODY") || { echo "no binaries in $DIST" >&2; exit 1; } + cat "$BODY" + SIG=$(mktemp) + PUBLIC=$(mktemp) + trap 'rm -f "$SIG" "$PUBLIC"' EXIT + openssl pkeyutl -sign -rawin -inkey "$KEY" -in "$BODY" -out "$SIG" + [[ $(stat -c %s "$SIG") == 64 ]] || { echo "bad signature size" >&2; exit 1; } + TRUSTED=0 + while read -r hex; do + { printf '302a300506032b6570032100'; printf '%s' "$hex"; } | xxd -r -p > "$PUBLIC" + openssl pkeyutl -verify -rawin -pubin -keyform DER -inkey "$PUBLIC" -in "$BODY" -sigfile "$SIG" >/dev/null 2>&1 && TRUSTED=1 + done < <(grep -o '\[0x[^]]*\]' crates/client/src/update/keys.rs | tr -d '[], ' | sed 's/0x//g') + [[ $TRUSTED == 1 ]] || { echo "signature does not match any key in keys.rs" >&2; exit 1; } + cat "$SIG" "$BODY" > "$DIST/manifest" + rm "$BODY" + echo "upload the binaries in $DIST to the server's updates/ directory first, then manifest last" + ;; +*) usage ;; +esac