forge
Explore
Log in

Don't you dare go Hollow

Server-delivered auto update. New stable yumush-update/1 ALPN (survives protocol bumps): on every connect (or Outdated) a YUMUSH_RELEASE client sends its target (x86_64_v3/v1-<os>) and the sha256 of its own exe

Browse files at this commit

b9f353c01656eae3ed6b861507e5286e4b48000cAhmet Kaan GümüşParent: cad17ea
  • feat
    • server-delivered auto update. New stable yumush-update/1 ALPN (survives protocol bumps): on every connect (or Outdated) a YUMUSH_RELEASE client sends its target (x86_64_v3/v1-<os>) and the sha256 of its own exe
    • the server answers Current, Missing or streams clients/<target> (hashed at startup). The client verifies size+sha256, swaps itself in with self-replace and re-execs with --restart, which waits for the old instance to let go. packaging/release.sh linux|windows builds v1 and v3 into dist/
Show full message
✨ feat: server-delivered auto update. New stable yumush-update/1 ALPN (survives protocol bumps): on every connect (or Outdated) a YUMUSH_RELEASE client sends its target (x86_64_v3/v1-<os>) and the sha256 of its own exe; the server answers Current, Missing or streams clients/<target> (hashed at startup). The client verifies size+sha256, swaps itself in with self-replace and re-execs with --restart, which waits for the old instance to let go. packaging/release.sh linux|windows builds v1 and v3 into dist/
Cargo.lockmodified+13 -0
@@ -1297,6 +1297,7 @@ dependencies = [
12971297 "resvg 0.50.0",
12981298 "rtrb",
12991299 "rustls-platform-verifier",
1300+ "self-replace",
13001301 "spectrum",
13011302 "sys-locale",
13021303 "sysinfo 0.40.4",
@@ -1423,6 +1424,7 @@ dependencies = [
14231424 "quinn",
14241425 "quinn-proto",
14251426 "reed-solomon-simd",
1427+ "sha2 0.11.2",
14261428 "socket2",
14271429 "thiserror 2.0.21",
14281430 "tracing",
@@ -8019,6 +8021,17 @@ dependencies = [
80198021 "libc",
80208022 ]
80218023
8024+[[package]]
8025+name = "self-replace"
8026+version = "1.5.1"
8027+source = "registry+https://github.com/rust-lang/crates.io-index"
8028+checksum = "609c5606d9d357b26e4ee1a7a01beac396628d0fa01ebbade2a09cefb88e65af"
8029+dependencies = [
8030+ "fastrand",
8031+ "tempfile",
8032+ "windows-sys 0.61.2",
8033+]
8034+
80228035 [[package]]
80238036 name = "self_cell"
80248037 version = "1.3.0"
crates/client/Cargo.tomlmodified+1 -0
@@ -34,6 +34,7 @@ sys-locale = "0.3.2"
3434 image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] }
3535 rtrb = "0.4.1"
3636 gethostname = "1.1.0"
37+self-replace = "1.5.1"
3738 rustls-platform-verifier = "0.7.1"
3839 flate2 = "1.1.11"
3940 emojis = "0.9.1"
crates/client/src/instance.rsmodified+11 -3
@@ -11,10 +11,18 @@ pub fn claim() -> Instance {
1111 if std::env::args().any(|arg| arg == MULTI) {
1212 return alone();
1313 }
14- match crate::config_dir() {
15- Some(dir) => claim_in(dir),
16- None => alone(),
14+ let Some(dir) = crate::config_dir() else {
15+ return alone();
16+ };
17+ if std::env::args().any(|arg| arg == crate::update::RESTART) {
18+ for _ in 0..100 {
19+ if let Instance::First(wake) = claim_in(dir.clone()) {
20+ return Instance::First(wake);
21+ }
22+ std::thread::sleep(std::time::Duration::from_millis(100));
23+ }
1724 }
25+ claim_in(dir)
1826 }
1927
2028 fn alone() -> Instance {
crates/client/src/lib.rsmodified+1 -0
@@ -18,6 +18,7 @@ pub mod net;
1818 pub mod settings;
1919 pub mod share;
2020 pub mod tray;
21+pub mod update;
2122 pub use usage;
2223 pub mod voice;
2324
crates/client/src/net/link.rsmodified+23 -4
@@ -110,9 +110,25 @@ async fn backoff(attempt: &mut u32) {
110110 *attempt += 1;
111111 }
112112
113+pub(crate) async fn dial<T>(
114+ server: &crate::Server,
115+ alpn: &[u8],
116+ work: impl AsyncFnOnce(&quinn::Connection) -> T,
117+) -> Result<T, LinkError> {
118+ let mut endpoints = Endpoints::default();
119+ let connection = connect(server, &mut endpoints, alpn).await?;
120+ let done = work(&connection).await;
121+ connection.close(0u32.into(), b"");
122+ for endpoint in [endpoints.v4, endpoints.v6].into_iter().flatten() {
123+ endpoint.wait_idle().await;
124+ }
125+ Ok(done)
126+}
127+
113128 async fn connect(
114129 server: &crate::Server,
115130 endpoints: &mut Endpoints,
131+ alpn: &[u8],
116132 ) -> Result<quinn::Connection, LinkError> {
117133 let mut addresses: Vec<SocketAddr> = tokio::net::lookup_host(server.address.as_str())
118134 .await
@@ -130,7 +146,7 @@ async fn connect(
130146 }
131147 };
132148 let connecting =
133- match endpoint.connect_with(config(server.any_cert)?, address, server.host()) {
149+ match endpoint.connect_with(config(server.any_cert, alpn)?, address, server.host()) {
134150 Ok(connecting) => connecting,
135151 Err(_) => {
136152 endpoints.forget(address);
@@ -209,7 +225,7 @@ impl ServerCertVerifier for AcceptAnyCertificate {
209225 }
210226 }
211227
212-fn config(any_cert: bool) -> Result<quinn::ClientConfig, LinkError> {
228+fn config(any_cert: bool, alpn: &[u8]) -> Result<quinn::ClientConfig, LinkError> {
213229 let provider = Arc::new(rustls::crypto::ring::default_provider());
214230 let verifier: Arc<dyn ServerCertVerifier> = if any_cert {
215231 Arc::new(AcceptAnyCertificate {
@@ -225,7 +241,7 @@ fn config(any_cert: bool) -> Result<quinn::ClientConfig, LinkError> {
225241 .dangerous()
226242 .with_custom_certificate_verifier(verifier)
227243 .with_no_client_auth();
228- tls.alpn_protocols = vec![ALPN.to_vec()];
244+ tls.alpn_protocols = vec![alpn.to_vec()];
229245
230246 let crypto = QuicClientConfig::try_from(tls).map_err(tls_error)?;
231247 let mut client_config = quinn::ClientConfig::new(Arc::new(crypto));
@@ -383,13 +399,16 @@ async fn actor(
383399 let connection = loop {
384400 let address = server.borrow_and_update().clone();
385401 let result = tokio::select! {
386- result = connect(&address, &mut endpoints) => result,
402+ result = connect(&address, &mut endpoints, ALPN) => result,
387403 _ = server.changed() => {
388404 attempt = 0;
389405 token = None;
390406 continue;
391407 }
392408 };
409+ if matches!(result, Ok(_) | Err(LinkError::Outdated)) {
410+ tokio::spawn(crate::update::check(address));
411+ }
393412 match result {
394413 Ok(connection) => break connection,
395414 Err(LinkError::Outdated) => {
crates/client/src/net/mod.rsmodified+1 -0
@@ -16,6 +16,7 @@ mod link;
1616 mod media;
1717
1818 pub use fail::{Fail, LinkError};
19+pub(crate) use link::dial;
1920 pub use link::start;
2021 use media::Media;
2122
crates/client/src/update.rsadded+122 -0
@@ -0,0 +1,122 @@
1+use std::{
2+ path::Path,
3+ sync::atomic::{AtomicBool, Ordering},
4+};
5+
6+use common::{
7+ frame::{self, Sending, UP_MAX},
8+ update::{ALPN, Answer, Ask, FILE_MAX, sha256},
9+};
10+use tracing::{info, warn};
11+
12+pub const RESTART: &str = "--restart";
13+const RELEASE: bool = option_env!("YUMUSH_RELEASE").is_some();
14+
15+static CHECKING: AtomicBool = AtomicBool::new(false);
16+
17+pub async fn check(server: crate::Server) {
18+ if !RELEASE
19+ || std::env::args().any(|arg| arg == crate::instance::MULTI)
20+ || CHECKING.swap(true, Ordering::AcqRel)
21+ {
22+ return;
23+ }
24+ let result = match crate::exe() {
25+ Some(exe) => update(&server, exe).await,
26+ None => Err("no exe".into()),
27+ };
28+ match result {
29+ Ok(true) => restart(),
30+ Ok(false) => {}
31+ Err(error) => warn!("update: {error}"),
32+ }
33+ CHECKING.store(false, Ordering::Release);
34+}
35+
36+type Fail = Box<dyn std::error::Error + Send + Sync>;
37+
38+async fn update(server: &crate::Server, exe: &Path) -> Result<bool, Fail> {
39+ let own = tokio::fs::read(exe).await?;
40+ let ask = Ask {
41+ target: target(),
42+ sha256: sha256(&own),
43+ };
44+ drop(own);
45+ let fetched = crate::net::dial(server, ALPN, async |connection| {
46+ fetch(connection, ask).await
47+ })
48+ .await
49+ .map_err(|error| error.to_string())?;
50+ let Some(bytes) = fetched? else {
51+ return Ok(false);
52+ };
53+ let new = exe.with_extension("new");
54+ tokio::fs::write(&new, &bytes).await?;
55+ let replaced = self_replace::self_replace(&new);
56+ let _ = tokio::fs::remove_file(&new).await;
57+ replaced?;
58+ info!("update: installed");
59+ Ok(true)
60+}
61+
62+async fn fetch(connection: &quinn::Connection, ask: Ask) -> Result<Option<Vec<u8>>, Fail> {
63+ let (send, mut receive) = connection.open_bi().await?;
64+ let mut send = Sending::new(send);
65+ frame::write(&mut send, &ask, UP_MAX).await?;
66+ send.finish()?;
67+ match frame::read::<Answer>(&mut receive, UP_MAX).await? {
68+ Answer::Current => Ok(None),
69+ Answer::Missing => Err(format!("server has no {}", ask.target).into()),
70+ Answer::File { size, sha256: want } => {
71+ if size > FILE_MAX {
72+ return Err("too large".into());
73+ }
74+ info!("update: downloading {size} bytes");
75+ let bytes = receive.read_to_end(size as usize).await?;
76+ if bytes.len() as u64 != size || sha256(&bytes) != want {
77+ return Err("corrupt download".into());
78+ }
79+ Ok(Some(bytes))
80+ }
81+ }
82+}
83+
84+fn target() -> String {
85+ let os = std::env::consts::OS;
86+ let arch = std::env::consts::ARCH;
87+ match level() {
88+ Some(level) => format!("{arch}_{level}-{os}"),
89+ None => format!("{arch}-{os}"),
90+ }
91+}
92+
93+#[cfg(target_arch = "x86_64")]
94+fn level() -> Option<&'static str> {
95+ let v3 = std::arch::is_x86_feature_detected!("avx2")
96+ && std::arch::is_x86_feature_detected!("bmi1")
97+ && std::arch::is_x86_feature_detected!("bmi2")
98+ && std::arch::is_x86_feature_detected!("fma")
99+ && std::arch::is_x86_feature_detected!("lzcnt")
100+ && std::arch::is_x86_feature_detected!("movbe")
101+ && std::arch::is_x86_feature_detected!("f16c");
102+ Some(if v3 { "v3" } else { "v1" })
103+}
104+
105+#[cfg(not(target_arch = "x86_64"))]
106+fn level() -> Option<&'static str> {
107+ None
108+}
109+
110+fn restart() {
111+ let Some(exe) = crate::exe() else {
112+ return;
113+ };
114+ let args = std::env::args_os()
115+ .skip(1)
116+ .filter(|arg| arg != RESTART)
117+ .chain([RESTART.into()]);
118+ match std::process::Command::new(exe).args(args).spawn() {
119+ Ok(_) => std::process::exit(0),
120+ Err(error) => warn!("update: restart {error}"),
121+ }
122+}
crates/common/Cargo.tomlmodified+1 -0
@@ -12,6 +12,7 @@ tracing = "0.1.44"
1212 thiserror = "2.0.21"
1313 reed-solomon-simd = "3.1.0"
1414 socket2 = "0.6.5"
15+sha2 = "0.11.2"
1516
1617 [lints]
1718 workspace = true
crates/common/src/lib.rsmodified+1 -0
@@ -13,4 +13,5 @@ pub mod share;
1313 pub mod stats;
1414 pub mod time;
1515 pub mod transport;
16+pub mod update;
1617 pub mod validate;
crates/common/src/update.rsadded+30 -0
@@ -0,0 +1,30 @@
1+use bitcode::{Decode, Encode};
2+
3+pub const ALPN: &[u8] = b"yumush-update/1";
4+pub const FILE_MAX: u64 = 512 << 20;
5+
6+#[derive(Debug, Clone, Encode, Decode)]
7+pub struct Ask {
8+ pub target: String,
9+ pub sha256: [u8; 32],
10+}
11+
12+#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
13+pub enum Answer {
14+ Current,
15+ Missing,
16+ File { size: u64, sha256: [u8; 32] },
17+}
18+
19+pub fn valid_target(target: &str) -> bool {
20+ !target.is_empty()
21+ && target.len() <= 32
22+ && target.bytes().all(|byte| {
23+ byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-'
24+ })
25+}
26+
27+pub fn sha256(bytes: &[u8]) -> [u8; 32] {
28+ use sha2::Digest;
29+ sha2::Sha256::digest(bytes).into()
30+}
crates/server/src/authentication.rsmodified+1 -0
@@ -234,6 +234,7 @@ mod tests {
234234 services: Services::default(),
235235 directory: test::directory(),
236236 backups: test::directory(),
237+ clients: Default::default(),
237238 };
238239 let client = Client::detached(None);
239240
crates/server/src/certificate.rsmodified+4 -1
@@ -115,7 +115,10 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfi
115115 .with_no_client_auth()
116116 .with_cert_resolver(reloader.clone());
117117 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+ ];
119122
120123 let crypto =
121124 quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;
crates/server/src/lib.rsmodified+3 -0
@@ -14,6 +14,7 @@ pub mod request;
1414 pub mod retention;
1515 pub mod rooms;
1616 pub mod stats;
17+pub mod update;
1718
1819 #[cfg(test)]
1920 mod test;
@@ -73,6 +74,7 @@ pub async fn showtime() -> Result<(), ServerError> {
7374 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;
7475 let attachments = sibling_directory(&config.database_path, "attachments")?;
7576 let backups = sibling_directory(&config.database_path, "backups")?;
77+ let clients = update::Clients::load(sibling_directory(&config.database_path, "clients")?).await;
7678 tokio::spawn(files::collect(database.clone(), attachments.clone()));
7779
7880 network::serve(
@@ -81,6 +83,7 @@ pub async fn showtime() -> Result<(), ServerError> {
8183 database,
8284 attachments,
8385 backups,
86+ clients,
8487 )
8588 .await
8689 }
crates/server/src/network.rsmodified+11 -0
@@ -48,6 +48,7 @@ pub(crate) struct Shared {
4848 pub(crate) services: Services,
4949 pub(crate) directory: PathBuf,
5050 pub(crate) backups: PathBuf,
51+ pub(crate) clients: crate::update::Clients,
5152 }
5253
5354 struct Pending {
@@ -63,6 +64,7 @@ pub async fn serve(
6364 db: Db,
6465 directory: PathBuf,
6566 backups: PathBuf,
67+ clients: crate::update::Clients,
6668 ) -> Result<(), ServerError> {
6769 let endpoint = transport::endpoint(
6870 server_address.parse()?,
@@ -76,6 +78,7 @@ pub async fn serve(
7678 services: Services::default(),
7779 directory,
7880 backups,
81+ clients,
7982 };
8083 shared.services.machine.watch(shared.directory.clone());
8184
@@ -108,6 +111,14 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv
108111 return Ok(());
109112 }
110113 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+ shared.clients.serve(connection).await;
120+ return Ok(());
121+ }
111122 let pending = match tokio::time::timeout(HELLO_DEADLINE, greet(&connection, &shared)).await {
112123 Ok(Ok(Some(pending))) => pending,
113124 Ok(Ok(None)) => return Ok(()),
crates/server/src/request.rsmodified+1 -0
@@ -373,6 +373,7 @@ mod tests {
373373 services: services.clone(),
374374 directory: test::directory(),
375375 backups: test::directory(),
376+ clients: Default::default(),
376377 }
377378 }
378379
crates/server/src/update.rsadded+70 -0
@@ -0,0 +1,70 @@
1+use std::{collections::HashMap, path::PathBuf, sync::Arc};
2+
3+use common::{
4+ frame::{self, Sending, UP_MAX},
5+ update::{Answer, Ask, valid_target},
6+};
7+use quinn::Connection;
8+use tracing::{info, warn};
9+
10+#[derive(Clone, Default)]
11+pub struct Clients {
12+ directory: PathBuf,
13+ files: Arc<HashMap<String, (u64, [u8; 32])>>,
14+}
15+
16+impl Clients {
17+ pub async fn load(directory: PathBuf) -> Self {
18+ let mut files = HashMap::new();
19+ if let Ok(mut entries) = tokio::fs::read_dir(&directory).await {
20+ while let Ok(Some(entry)) = entries.next_entry().await {
21+ let target = entry.file_name().to_string_lossy().into_owned();
22+ if !valid_target(&target) {
23+ continue;
24+ }
25+ match tokio::fs::read(entry.path()).await {
26+ Ok(bytes) => {
27+ info!("client {target} ready");
28+ files.insert(target, (bytes.len() as u64, common::update::sha256(&bytes)));
29+ }
30+ Err(error) => warn!("client {target}: {error}"),
31+ }
32+ }
33+ }
34+ Self {
35+ directory,
36+ files: Arc::new(files),
37+ }
38+ }
39+
40+ pub async fn serve(&self, connection: Connection) {
41+ while let Ok((send, mut receive)) = connection.accept_bi().await {
42+ let Ok(ask) = frame::read::<Ask>(&mut receive, UP_MAX).await else {
43+ return;
44+ };
45+ if let Err(error) = self.answer(ask, Sending::new(send)).await {
46+ warn!("update: {error}");
47+ return;
48+ }
49+ }
50+ }
51+
52+ async fn answer(&self, ask: Ask, mut send: Sending) -> Result<(), Box<dyn std::error::Error>> {
53+ let answer = match self.files.get(&ask.target) {
54+ None => Answer::Missing,
55+ Some((_, sha256)) if *sha256 == ask.sha256 => Answer::Current,
56+ Some((size, sha256)) => Answer::File {
57+ size: *size,
58+ sha256: *sha256,
59+ },
60+ };
61+ frame::write(&mut send, &answer, UP_MAX).await?;
62+ if let Answer::File { .. } = answer {
63+ info!("update: sending {}", ask.target);
64+ let mut file = tokio::fs::File::open(self.directory.join(&ask.target)).await?;
65+ tokio::io::copy(&mut file, send.get()).await?;
66+ }
67+ send.finish()?;
68+ Ok(())
69+ }
70+}
packaging/release-windows.ps1added+14 -0
@@ -0,0 +1,14 @@
1+param([Parameter(Mandatory)][string]$Levels)
2+$ErrorActionPreference = 'Stop'
3+Set-Location (Split-Path $PSScriptRoot)
4+$env:Path += ";$env:USERPROFILE\.cargo\bin"
5+$env:YUMUSH_RELEASE = '1'
6+New-Item -ItemType Directory -Force dist | Out-Null
7+foreach ($level in $Levels.Split(' ')) {
8+ $cpu = if ($level -eq 'v1') { 'x86-64' } else { "x86-64-$level" }
9+ $env:RUSTFLAGS = "-C target-feature=+crt-static -C target-cpu=$cpu"
10+ $env:CARGO_TARGET_DIR = "..\target-release-$level"
11+ cargo build --release --locked -p client
12+ if ($LASTEXITCODE -ne 0) { throw 'build failed' }
13+ Copy-Item "..\target-release-$level\release\client.exe" "dist\x86_64_$level-windows"
14+}
packaging/release.shadded+34 -0
@@ -0,0 +1,34 @@
1+#!/usr/bin/env bash
2+set -euo pipefail
3+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
4+LEVELS="v1 v3"
5+DIST="$ROOT/dist"
6+cd "$ROOT"
7+[[ $# -eq 1 ]] || { echo "usage: $0 linux|windows" >&2; exit 1; }
8+mkdir -p "$DIST"
9+
10+case "$1" in
11+linux)
12+ for level in $LEVELS; do
13+ cpu="x86-64-$level"; [[ $level == v1 ]] && cpu="x86-64"
14+ RUSTFLAGS="-C target-cpu=$cpu" CARGO_TARGET_DIR="target/release-$level" YUMUSH_RELEASE=1 \
15+ cargo build --release --locked -p client
16+ cp "target/release-$level/release/client" "$DIST/x86_64_$level-linux"
17+ done
18+ ;;
19+windows)
20+ 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 "$@"; }
21+ scp_win() { scp -q -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -P 2222 "$@"; }
22+ TAR="$(mktemp --suffix=.tgz)"
23+ trap 'rm -f "$TAR"' EXIT
24+ git ls-files | tar czf "$TAR" -T -
25+ ssh_win 'Remove-Item -Recurse -Force release -ErrorAction SilentlyContinue; New-Item -ItemType Directory release | Out-Null'
26+ scp_win "$TAR" yumush@127.0.0.1:release.tgz
27+ ssh_win "tar xmzf release.tgz -C release; powershell -NoProfile -ExecutionPolicy Bypass -File release\\packaging\\release-windows.ps1 -Levels '$LEVELS'"
28+ for level in $LEVELS; do
29+ scp_win "yumush@127.0.0.1:release/dist/x86_64_$level-windows" "$DIST/"
30+ done
31+ ;;
32+*) echo "usage: $0 linux|windows" >&2; exit 1 ;;
33+esac
34+echo "copy $DIST/* into the server's clients/ (next to the database), then restart the server"