use std::{ io::Read, path::Path, sync::{LazyLock, Mutex}, }; use common::{ frame::{self, Sending, UP_MAX}, update::{ALPN, Ask, FILE_MAX, Install, Me, Offer, Progress, Sha, Status, sha256}, }; use tokio::sync::watch; use tracing::{info, warn}; pub const RESTART: &str = "--restart"; const MARK: &str = concat!("yumush-target:", env!("YUMUSH_TARGET"), ";"); const CHUNK: usize = 256 << 10; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Phase { Idle, Available(Offer), Downloading { offer: Offer, done: u64 }, Installing { offer: Offer, done: u64 }, Ready(Offer), Failed(Offer), } impl Phase { pub fn offer(self) -> Option { match self { Self::Idle => None, Self::Available(offer) | Self::Downloading { offer, .. } | Self::Installing { offer, .. } | Self::Ready(offer) | Self::Failed(offer) => Some(offer), } } pub fn required(self) -> bool { self.offer().is_some_and(|offer| offer.required) } pub fn progress(self) -> Option { let fraction = |done: u64, total: u64| (done as f32 / total.max(1) as f32).clamp(0., 1.); match self { Self::Downloading { offer, done } => Some(fraction(done, offer.packed)), Self::Installing { offer, done } => Some(fraction(done, offer.size)), _ => None, } } fn busy(self) -> bool { matches!( self, Self::Downloading { .. } | Self::Installing { .. } | Self::Ready(_) ) } } static PHASE: LazyLock> = LazyLock::new(|| watch::channel(Phase::Idle).0); static SERVER: Mutex> = Mutex::new(None); static TOKEN: Mutex> = Mutex::new(None); static INSTALL: LazyLock = LazyLock::new(|| { if let Some(saved) = crate::read_config_bytes("install").and_then(|bytes| Install::try_from(bytes).ok()) { return saved; } let random = |salt: u64| { use std::hash::BuildHasher; std::collections::hash_map::RandomState::new() .hash_one((salt, std::time::SystemTime::now())) }; let mut fresh = [0u8; 16]; fresh[..8].copy_from_slice(&random(1).to_le_bytes()); fresh[8..].copy_from_slice(&random(2).to_le_bytes()); crate::write_config("install", fresh); fresh }); static BUILD: LazyLock> = LazyLock::new(|| { if cfg!(debug_assertions) { return None; } let exe = crate::exe()?; let bytes = std::fs::read(exe).ok()?; std::hint::black_box(MARK); std::hint::black_box(common::transport::PROTOCOL_MARK); Some(sha256(&bytes)) }); pub fn phase() -> Phase { *PHASE.borrow() } pub fn subscribe() -> watch::Receiver { PHASE.subscribe() } pub fn build() -> Option { *BUILD } pub fn install_id() -> Install { *INSTALL } pub(crate) fn set_token(token: Option) { *TOKEN.lock().unwrap() = token; } fn me() -> Option { Some(Me { install: install_id(), device: crate::net::device_name(), token: TOKEN.lock().unwrap().clone(), build: build().filter(|_| usable())?, }) } fn set(phase: Phase) { PHASE.send_replace(phase); } fn targets() -> Vec { let os = std::env::consts::OS; let arch = std::env::consts::ARCH; if arch != "x86_64" { return vec![crate::TARGET.to_string()]; } let mut targets = Vec::new(); if v3() { targets.push(format!("{arch}_v3-{os}")); } targets.push(format!("{arch}_v1-{os}")); targets } #[cfg(target_arch = "x86_64")] fn v3() -> bool { 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") } #[cfg(not(target_arch = "x86_64"))] fn v3() -> bool { false } fn usable() -> bool { !std::env::args().any(|arg| arg == crate::instance::MULTI) } pub(crate) async fn check(server: crate::Server, outdated: bool) { let Some(me) = me() else { return; }; *SERVER.lock().unwrap() = Some(server.clone()); if phase().busy() { return; } let ask = Ask::Check { me, targets: targets(), }; let status = crate::net::dial(&server, ALPN, async |connection| { let (send, mut receive) = connection.open_bi().await.ok()?; let mut send = Sending::new(send); frame::write(&mut send, &ask, UP_MAX).await.ok()?; send.finish().ok()?; frame::read::(&mut receive, UP_MAX).await.ok() }) .await; let Ok(Some(status)) = status else { warn!("update: check failed"); return; }; if phase().busy() { return; } match status { Status::Offer(mut offer) => { offer.required |= outdated; let failed = matches!(phase(), Phase::Failed(old) if old.file == offer.file); if !failed { set(Phase::Available(offer)); } if offer.required && !failed { install(); } } Status::Latest | Status::Unknown => set(Phase::Idle), } } pub fn recheck() { let Some(server) = SERVER.lock().unwrap().clone() else { return; }; crate::spawn_runtime("update", move || check(server, false)); } pub fn install() { let Some(server) = SERVER.lock().unwrap().clone() else { return; }; let Some(exe) = crate::exe() else { return; }; let Some(me) = me() else { return; }; let mut claimed = None; PHASE.send_if_modified(|phase| { let (Phase::Available(offer) | Phase::Failed(offer)) = *phase else { return false; }; claimed = Some(offer); *phase = Phase::Downloading { offer, done: 0 }; true }); let Some(offer) = claimed else { return; }; std::thread::spawn(move || { let Ok(runtime) = tokio::runtime::Builder::new_current_thread() .enable_all() .build() else { set(Phase::Failed(offer)); return; }; let installed = runtime .block_on(download(&server, me.clone(), offer)) .and_then(|packed| { runtime.block_on(report(&server, me.clone(), Progress::Installing)); unpack(offer, &packed, exe) }); let progress = match installed { Ok(()) => { info!("update: release {} installed", offer.seq); set(Phase::Ready(offer)); Progress::Ready } Err(error) => { warn!("update: {error}"); set(Phase::Failed(offer)); Progress::Failed } }; runtime.block_on(report(&server, me, progress)); if progress == Progress::Ready && offer.required { restart(); } }); } type Fail = Box; async fn report(server: &crate::Server, me: Me, progress: Progress) { let _ = crate::net::dial(server, ALPN, async |connection| { let (send, mut receive) = connection.open_bi().await.ok()?; let mut send = Sending::new(send); frame::write(&mut send, &Ask::Report { me, progress }, UP_MAX) .await .ok()?; send.finish().ok()?; receive.read_to_end(0).await.ok()?; Some(()) }) .await; } async fn download(server: &crate::Server, me: Me, offer: Offer) -> Result, Fail> { if offer.packed > FILE_MAX || offer.size > FILE_MAX { return Err("too large".into()); } crate::net::dial(server, ALPN, async |connection| { let (send, mut receive) = connection.open_bi().await?; let mut send = Sending::new(send); frame::write( &mut send, &Ask::Download { me, file: offer.file, }, UP_MAX, ) .await?; send.finish()?; let mut packed = Vec::with_capacity(offer.packed as usize); let mut chunk = vec![0u8; CHUNK]; while let Some(read) = receive.read(&mut chunk).await? { packed.extend_from_slice(&chunk[..read]); if packed.len() as u64 > offer.packed { return Err::<_, Fail>("too long".into()); } set(Phase::Downloading { offer, done: packed.len() as u64, }); } if packed.len() as u64 != offer.packed { return Err("short download".into()); } Ok(packed) }) .await .map_err(|error| error.to_string())? } fn unpack(offer: Offer, packed: &[u8], exe: &Path) -> Result<(), Fail> { set(Phase::Installing { offer, done: 0 }); let mut decoder = ruzstd::decoding::StreamingDecoder::new(packed)?; let mut bytes = Vec::with_capacity(offer.size as usize); let mut chunk = vec![0u8; CHUNK]; loop { let read = decoder.read(&mut chunk)?; if read == 0 { break; } bytes.extend_from_slice(&chunk[..read]); if bytes.len() as u64 > offer.size { return Err("too long".into()); } set(Phase::Installing { offer, done: bytes.len() as u64, }); } if bytes.len() as u64 != offer.size || sha256(&bytes) != offer.file { return Err("corrupt download".into()); } let new = exe.with_extension("new"); write_executable(&new, &bytes)?; let replaced = self_replace::self_replace(&new); let _ = std::fs::remove_file(&new); Ok(replaced?) } fn write_executable(path: &Path, bytes: &[u8]) -> std::io::Result<()> { use std::io::Write; let mut options = std::fs::OpenOptions::new(); options.write(true).create(true).truncate(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o755); let mut file = options.open(path)?; file.write_all(bytes)?; file.sync_all() } pub 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}"), } }