diff --git a/Cargo.lock b/Cargo.lock index e8f6f83..3ea0c8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1297,6 +1297,7 @@ dependencies = [ "resvg 0.50.0", "rtrb", "rustls-platform-verifier", + "self-replace", "spectrum", "sys-locale", "sysinfo 0.40.4", @@ -1423,6 +1424,7 @@ dependencies = [ "quinn", "quinn-proto", "reed-solomon-simd", + "sha2 0.11.2", "socket2", "thiserror 2.0.21", "tracing", @@ -8019,6 +8021,17 @@ dependencies = [ "libc", ] +[[package]] +name = "self-replace" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "609c5606d9d357b26e4ee1a7a01beac396628d0fa01ebbade2a09cefb88e65af" +dependencies = [ + "fastrand", + "tempfile", + "windows-sys 0.61.2", +] + [[package]] name = "self_cell" version = "1.3.0" diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 73e9ad1..91008cc 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -34,6 +34,7 @@ sys-locale = "0.3.2" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } rtrb = "0.4.1" gethostname = "1.1.0" +self-replace = "1.5.1" rustls-platform-verifier = "0.7.1" flate2 = "1.1.11" emojis = "0.9.1" diff --git a/crates/client/src/instance.rs b/crates/client/src/instance.rs index 2cac342..6a6d46b 100644 --- a/crates/client/src/instance.rs +++ b/crates/client/src/instance.rs @@ -11,10 +11,18 @@ pub fn claim() -> Instance { if std::env::args().any(|arg| arg == MULTI) { return alone(); } - match crate::config_dir() { - Some(dir) => claim_in(dir), - None => alone(), + let Some(dir) = crate::config_dir() else { + return alone(); + }; + if std::env::args().any(|arg| arg == crate::update::RESTART) { + for _ in 0..100 { + if let Instance::First(wake) = claim_in(dir.clone()) { + return Instance::First(wake); + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } } + claim_in(dir) } fn alone() -> Instance { diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 6ba8c07..27853b5 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -18,6 +18,7 @@ pub mod net; pub mod settings; pub mod share; pub mod tray; +pub mod update; pub use usage; pub mod voice; diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index e889063..a45c30e 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -110,9 +110,25 @@ async fn backoff(attempt: &mut u32) { *attempt += 1; } +pub(crate) async fn dial( + server: &crate::Server, + alpn: &[u8], + work: impl AsyncFnOnce(&quinn::Connection) -> T, +) -> Result { + let mut endpoints = Endpoints::default(); + let connection = connect(server, &mut endpoints, alpn).await?; + let done = work(&connection).await; + connection.close(0u32.into(), b""); + for endpoint in [endpoints.v4, endpoints.v6].into_iter().flatten() { + endpoint.wait_idle().await; + } + Ok(done) +} + 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 +146,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 +225,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 +241,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,13 +399,16 @@ 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; continue; } }; + if matches!(result, Ok(_) | Err(LinkError::Outdated)) { + tokio::spawn(crate::update::check(address)); + } match result { Ok(connection) => break connection, Err(LinkError::Outdated) => { 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/update.rs b/crates/client/src/update.rs new file mode 100644 index 0000000..5e9fe91 --- /dev/null +++ b/crates/client/src/update.rs @@ -0,0 +1,122 @@ +use std::{ + path::Path, + sync::atomic::{AtomicBool, Ordering}, +}; + +use common::{ + frame::{self, Sending, UP_MAX}, + update::{ALPN, Answer, Ask, FILE_MAX, sha256}, +}; +use tracing::{info, warn}; + +pub const RESTART: &str = "--restart"; +const RELEASE: bool = option_env!("YUMUSH_RELEASE").is_some(); + +static CHECKING: AtomicBool = AtomicBool::new(false); + +pub async fn check(server: crate::Server) { + if !RELEASE + || std::env::args().any(|arg| arg == crate::instance::MULTI) + || CHECKING.swap(true, Ordering::AcqRel) + { + return; + } + let result = match crate::exe() { + Some(exe) => update(&server, exe).await, + None => Err("no exe".into()), + }; + match result { + Ok(true) => restart(), + Ok(false) => {} + Err(error) => warn!("update: {error}"), + } + CHECKING.store(false, Ordering::Release); +} + +type Fail = Box; + +async fn update(server: &crate::Server, exe: &Path) -> Result { + let own = tokio::fs::read(exe).await?; + let ask = Ask { + target: target(), + sha256: sha256(&own), + }; + drop(own); + let fetched = crate::net::dial(server, ALPN, async |connection| { + fetch(connection, ask).await + }) + .await + .map_err(|error| error.to_string())?; + let Some(bytes) = fetched? else { + return Ok(false); + }; + let new = exe.with_extension("new"); + tokio::fs::write(&new, &bytes).await?; + let replaced = self_replace::self_replace(&new); + let _ = tokio::fs::remove_file(&new).await; + replaced?; + info!("update: installed"); + Ok(true) +} + +async fn fetch(connection: &quinn::Connection, ask: Ask) -> Result>, Fail> { + let (send, mut receive) = connection.open_bi().await?; + let mut send = Sending::new(send); + frame::write(&mut send, &ask, UP_MAX).await?; + send.finish()?; + match frame::read::(&mut receive, UP_MAX).await? { + Answer::Current => Ok(None), + Answer::Missing => Err(format!("server has no {}", ask.target).into()), + Answer::File { size, sha256: want } => { + if size > FILE_MAX { + return Err("too large".into()); + } + info!("update: downloading {size} bytes"); + let bytes = receive.read_to_end(size as usize).await?; + if bytes.len() as u64 != size || sha256(&bytes) != want { + return Err("corrupt download".into()); + } + Ok(Some(bytes)) + } + } +} + +fn target() -> String { + let os = std::env::consts::OS; + let arch = std::env::consts::ARCH; + match level() { + Some(level) => format!("{arch}_{level}-{os}"), + None => format!("{arch}-{os}"), + } +} + +#[cfg(target_arch = "x86_64")] +fn level() -> Option<&'static str> { + let v3 = std::arch::is_x86_feature_detected!("avx2") + && std::arch::is_x86_feature_detected!("bmi1") + && std::arch::is_x86_feature_detected!("bmi2") + && std::arch::is_x86_feature_detected!("fma") + && std::arch::is_x86_feature_detected!("lzcnt") + && std::arch::is_x86_feature_detected!("movbe") + && std::arch::is_x86_feature_detected!("f16c"); + Some(if v3 { "v3" } else { "v1" }) +} + +#[cfg(not(target_arch = "x86_64"))] +fn level() -> Option<&'static str> { + None +} + +fn restart() { + let Some(exe) = crate::exe() else { + return; + }; + let args = std::env::args_os() + .skip(1) + .filter(|arg| arg != RESTART) + .chain([RESTART.into()]); + match std::process::Command::new(exe).args(args).spawn() { + Ok(_) => std::process::exit(0), + Err(error) => warn!("update: restart {error}"), + } +} diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 2e38a1c..a9d03fd 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -12,6 +12,7 @@ tracing = "0.1.44" thiserror = "2.0.21" reed-solomon-simd = "3.1.0" socket2 = "0.6.5" +sha2 = "0.11.2" [lints] workspace = true 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..318b0fb --- /dev/null +++ b/crates/common/src/update.rs @@ -0,0 +1,30 @@ +use bitcode::{Decode, Encode}; + +pub const ALPN: &[u8] = b"yumush-update/1"; +pub const FILE_MAX: u64 = 512 << 20; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Ask { + pub target: String, + pub sha256: [u8; 32], +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] +pub enum Answer { + Current, + Missing, + File { size: u64, sha256: [u8; 32] }, +} + +pub fn valid_target(target: &str) -> bool { + !target.is_empty() + && target.len() <= 32 + && target.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-' + }) +} + +pub fn sha256(bytes: &[u8]) -> [u8; 32] { + use sha2::Digest; + sha2::Sha256::digest(bytes).into() +} diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index d7e5580..5e85331 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(), + clients: Default::default(), }; 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 clients = update::Clients::load(sibling_directory(&config.database_path, "clients")?).await; tokio::spawn(files::collect(database.clone(), attachments.clone())); network::serve( @@ -81,6 +83,7 @@ pub async fn showtime() -> Result<(), ServerError> { database, attachments, backups, + clients, ) .await } diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index ff89e8f..df32716 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) clients: crate::update::Clients, } struct Pending { @@ -63,6 +64,7 @@ pub async fn serve( db: Db, directory: PathBuf, backups: PathBuf, + clients: crate::update::Clients, ) -> Result<(), ServerError> { let endpoint = transport::endpoint( server_address.parse()?, @@ -76,6 +78,7 @@ pub async fn serve( services: Services::default(), directory, backups, + clients, }; 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) { + shared.clients.serve(connection).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..b16cd6d 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(), + clients: Default::default(), } } diff --git a/crates/server/src/update.rs b/crates/server/src/update.rs new file mode 100644 index 0000000..357f0a3 --- /dev/null +++ b/crates/server/src/update.rs @@ -0,0 +1,70 @@ +use std::{collections::HashMap, path::PathBuf, sync::Arc}; + +use common::{ + frame::{self, Sending, UP_MAX}, + update::{Answer, Ask, valid_target}, +}; +use quinn::Connection; +use tracing::{info, warn}; + +#[derive(Clone, Default)] +pub struct Clients { + directory: PathBuf, + files: Arc>, +} + +impl Clients { + pub async fn load(directory: PathBuf) -> Self { + let mut files = HashMap::new(); + if let Ok(mut entries) = tokio::fs::read_dir(&directory).await { + while let Ok(Some(entry)) = entries.next_entry().await { + let target = entry.file_name().to_string_lossy().into_owned(); + if !valid_target(&target) { + continue; + } + match tokio::fs::read(entry.path()).await { + Ok(bytes) => { + info!("client {target} ready"); + files.insert(target, (bytes.len() as u64, common::update::sha256(&bytes))); + } + Err(error) => warn!("client {target}: {error}"), + } + } + } + Self { + directory, + files: Arc::new(files), + } + } + + pub async fn serve(&self, connection: Connection) { + while let Ok((send, mut receive)) = connection.accept_bi().await { + let Ok(ask) = frame::read::(&mut receive, UP_MAX).await else { + return; + }; + if let Err(error) = self.answer(ask, Sending::new(send)).await { + warn!("update: {error}"); + return; + } + } + } + + async fn answer(&self, ask: Ask, mut send: Sending) -> Result<(), Box> { + let answer = match self.files.get(&ask.target) { + None => Answer::Missing, + Some((_, sha256)) if *sha256 == ask.sha256 => Answer::Current, + Some((size, sha256)) => Answer::File { + size: *size, + sha256: *sha256, + }, + }; + frame::write(&mut send, &answer, UP_MAX).await?; + if let Answer::File { .. } = answer { + info!("update: sending {}", ask.target); + let mut file = tokio::fs::File::open(self.directory.join(&ask.target)).await?; + tokio::io::copy(&mut file, send.get()).await?; + } + send.finish()?; + Ok(()) + } +} diff --git a/packaging/release-windows.ps1 b/packaging/release-windows.ps1 new file mode 100644 index 0000000..58ca037 --- /dev/null +++ b/packaging/release-windows.ps1 @@ -0,0 +1,14 @@ +param([Parameter(Mandatory)][string]$Levels) +$ErrorActionPreference = 'Stop' +Set-Location (Split-Path $PSScriptRoot) +$env:Path += ";$env:USERPROFILE\.cargo\bin" +$env:YUMUSH_RELEASE = '1' +New-Item -ItemType Directory -Force dist | Out-Null +foreach ($level in $Levels.Split(' ')) { + $cpu = if ($level -eq 'v1') { 'x86-64' } else { "x86-64-$level" } + $env:RUSTFLAGS = "-C target-feature=+crt-static -C target-cpu=$cpu" + $env:CARGO_TARGET_DIR = "..\target-release-$level" + cargo build --release --locked -p client + if ($LASTEXITCODE -ne 0) { throw 'build failed' } + Copy-Item "..\target-release-$level\release\client.exe" "dist\x86_64_$level-windows" +} diff --git a/packaging/release.sh b/packaging/release.sh new file mode 100755 index 0000000..4ece481 --- /dev/null +++ b/packaging/release.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +LEVELS="v1 v3" +DIST="$ROOT/dist" +cd "$ROOT" +[[ $# -eq 1 ]] || { echo "usage: $0 linux|windows" >&2; exit 1; } +mkdir -p "$DIST" + +case "$1" in +linux) + for level in $LEVELS; do + cpu="x86-64-$level"; [[ $level == v1 ]] && cpu="x86-64" + RUSTFLAGS="-C target-cpu=$cpu" CARGO_TARGET_DIR="target/release-$level" YUMUSH_RELEASE=1 \ + cargo build --release --locked -p client + cp "target/release-$level/release/client" "$DIST/x86_64_$level-linux" + done + ;; +windows) + ssh_win() { ssh -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o LogLevel=ERROR -p 2222 yumush@127.0.0.1 "$@"; } + scp_win() { scp -q -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -P 2222 "$@"; } + TAR="$(mktemp --suffix=.tgz)" + trap 'rm -f "$TAR"' EXIT + git ls-files | tar czf "$TAR" -T - + ssh_win 'Remove-Item -Recurse -Force release -ErrorAction SilentlyContinue; New-Item -ItemType Directory release | Out-Null' + scp_win "$TAR" yumush@127.0.0.1:release.tgz + ssh_win "tar xmzf release.tgz -C release; powershell -NoProfile -ExecutionPolicy Bypass -File release\\packaging\\release-windows.ps1 -Levels '$LEVELS'" + for level in $LEVELS; do + scp_win "yumush@127.0.0.1:release/dist/x86_64_$level-windows" "$DIST/" + done + ;; +*) echo "usage: $0 linux|windows" >&2; exit 1 ;; +esac +echo "copy $DIST/* into the server's clients/ (next to the database), then restart the server"