//! aKode self-update. //! //! Releases are read from the configured Gitea repository only (`[update] repo_url`): the //! latest-release API, then the release's own assets, which must live on the same host. //! Nothing is ever installed automatically: callers decide when to call [`install_release`]. //! There is no telemetry; the only request is the release lookup and the asset downloads. use std::path::Path; use std::path::PathBuf; use std::time::Duration; use anyhow::Context; use anyhow::Result; use anyhow::anyhow; use anyhow::bail; use anyhow::ensure; use chrono::DateTime; use chrono::Utc; use semver::Version; use serde::Deserialize; use serde::Serialize; use sha2::Digest; use sha2::Sha256; /// The startup check contacts the repository at most once per interval. pub const CHECK_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); /// Timeout for the non-blocking startup check. pub const STARTUP_CHECK_TIMEOUT: Duration = Duration::from_secs(5); /// Timeout for the explicit `akode update` requests (asset downloads included). pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(300); const STATE_FILE_NAME: &str = "update-check.json"; const PACKAGE_MANIFEST_FILE_NAME: &str = "akode-package.json"; const USER_AGENT: &str = concat!("akode/", env!("CARGO_PKG_VERSION")); /// A downloadable file attached to a release. #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct ReleaseAsset { pub name: String, pub browser_download_url: String, } /// The latest published release of the repository. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Release { pub version: Version, pub tag: String, pub assets: Vec, } #[derive(Deserialize)] struct GiteaRelease { tag_name: String, #[serde(default)] assets: Vec, } /// Result of comparing the running version with the latest release. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CheckResult { /// No release is published, or none is newer than the running version. UpToDate { latest: Option, }, Available(Release), } /// Where the running installation lives. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InstallTarget { /// The binary to replace. pub exe: PathBuf, /// Package directory (with `akode-package.json`) when the binary belongs to a package layout. pub package_dir: Option, } /// What [`install_release`] replaced, and where the previous version was kept. #[derive(Debug, Clone, PartialEq, Eq)] pub enum InstallOutcome { Binary { backup: PathBuf }, Package { backup: PathBuf }, } /// HTTP client for update requests. Honors the standard proxy environment variables. pub fn http_client(timeout: Duration) -> Result { akode_utils_rustls_provider::ensure_rustls_crypto_provider(); reqwest::Client::builder() .use_rustls_tls() .user_agent(USER_AGENT) .connect_timeout(timeout.min(Duration::from_secs(10))) .timeout(timeout) .build() .context("impossibile creare il client HTTP per gli aggiornamenti") } /// Gitea API URL for the latest release of `repo_url` (`https://host/owner/repo`). pub fn latest_release_api_url(repo_url: &str) -> Result { let repo = parse_repo_url(repo_url)?; let segments: Vec<&str> = repo .path_segments() .map(|segments| segments.filter(|segment| !segment.is_empty()).collect()) .unwrap_or_default(); let [prefix @ .., owner, name] = segments.as_slice() else { bail!( "[update] repo_url deve avere la forma https://host/proprietario/repository: {repo_url}" ); }; let name = name.strip_suffix(".git").unwrap_or(name); let prefix: String = prefix.iter().map(|segment| format!("/{segment}")).collect(); let mut api = repo.clone(); api.set_path(&format!( "{prefix}/api/v1/repos/{owner}/{name}/releases/latest" )); api.set_query(None); api.set_fragment(None); Ok(api) } fn parse_repo_url(repo_url: &str) -> Result { let url = reqwest::Url::parse(repo_url.trim().trim_end_matches('/')) .with_context(|| format!("[update] repo_url non valido: {repo_url}"))?; ensure!( matches!(url.scheme(), "https" | "http") && url.host_str().is_some(), "[update] repo_url deve essere un URL http(s): {repo_url}" ); Ok(url) } /// Reads the latest release. A repository without releases (HTTP 404) yields `None`. pub async fn fetch_latest_release( client: &reqwest::Client, repo_url: &str, ) -> Result> { let url = latest_release_api_url(repo_url)?; let response = client .get(url.clone()) .header(reqwest::header::ACCEPT, "application/json") .send() .await .with_context(|| { format!( "impossibile contattare {}", url.origin().ascii_serialization() ) })?; if response.status() == reqwest::StatusCode::NOT_FOUND { return Ok(None); } ensure!( response.status().is_success(), "il server delle release ha risposto {}", response.status() ); let release: GiteaRelease = response .json() .await .context("risposta non valida dal server delle release")?; let version = parse_version(&release.tag_name).with_context(|| { format!( "il tag della release {} non è una versione valida", release.tag_name ) })?; Ok(Some(Release { version, tag: release.tag_name, assets: release.assets, })) } fn parse_version(tag: &str) -> Result { let trimmed = tag.trim(); let trimmed = trimmed .strip_prefix('v') .or_else(|| trimmed.strip_prefix('V')) .unwrap_or(trimmed); Ok(Version::parse(trimmed)?) } /// Whether `latest` is newer than the running `current` version. /// Unparseable current versions never report an update. pub fn is_newer(current: &str, latest: &Version) -> bool { Version::parse(current.trim()).is_ok_and(|current| *latest > current) } /// [`is_newer`] for a version string; unparseable versions are never newer. pub fn is_newer_str(current: &str, latest: &str) -> bool { Version::parse(latest.trim()).is_ok_and(|latest| is_newer(current, &latest)) } /// Compares the latest release with `current_version`. pub async fn check( client: &reqwest::Client, repo_url: &str, current_version: &str, ) -> Result { Ok(match fetch_latest_release(client, repo_url).await? { Some(release) if is_newer(current_version, &release.version) => { CheckResult::Available(release) } Some(release) => CheckResult::UpToDate { latest: Some(release.version), }, None => CheckResult::UpToDate { latest: None }, }) } /// Target triple used in release asset names, for the platforms aKode publishes. pub fn current_target() -> Option<&'static str> { if cfg!(all(target_os = "macos", target_arch = "aarch64")) { Some("aarch64-apple-darwin") } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) { Some("x86_64-apple-darwin") } else if cfg!(all( target_os = "linux", target_arch = "x86_64", target_env = "musl" )) { Some("x86_64-unknown-linux-musl") } else if cfg!(all( target_os = "linux", target_arch = "aarch64", target_env = "musl" )) { Some("aarch64-unknown-linux-musl") } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) { Some("x86_64-unknown-linux-gnu") } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) { Some("aarch64-unknown-linux-gnu") } else if cfg!(all(target_os = "windows", target_arch = "x86_64")) { Some("x86_64-pc-windows-msvc") } else if cfg!(all(target_os = "windows", target_arch = "aarch64")) { Some("aarch64-pc-windows-msvc") } else { None } } /// Name of the archive asset for `version` on `target`. pub fn archive_asset_name(version: &Version, target: &str) -> String { format!("akode-{version}-{target}.tar.gz") } /// Downloads the release archive for `target` and verifies it against its `.sha256` asset. pub async fn download_verified_archive( client: &reqwest::Client, repo_url: &str, release: &Release, target: &str, ) -> Result> { let archive_name = archive_asset_name(&release.version, target); let checksum_name = format!("{archive_name}.sha256"); let find = |name: &str| { release .assets .iter() .find(|asset| asset.name == name) .ok_or_else(|| { anyhow!( "la release {} non contiene {name} per questa piattaforma", release.tag ) }) }; let archive_asset = find(&archive_name)?; let checksum_asset = find(&checksum_name)?; let repo = parse_repo_url(repo_url)?; let checksum_text = download(client, &repo, checksum_asset).await?; let checksum_text = String::from_utf8(checksum_text).context("il file .sha256 non è testo UTF-8")?; let expected = parse_sha256(&checksum_text, &archive_name)?; let archive = download(client, &repo, archive_asset).await?; let actual = hex(&Sha256::digest(&archive)); ensure!( actual == expected, "checksum SHA-256 non corrispondente per {archive_name} (atteso {expected}, ottenuto {actual}): aggiornamento annullato" ); Ok(archive) } async fn download( client: &reqwest::Client, repo: &reqwest::Url, asset: &ReleaseAsset, ) -> Result> { let url = reqwest::Url::parse(&asset.browser_download_url) .with_context(|| format!("URL non valido per {}", asset.name))?; // Downloads stay on the configured repository's origin. ensure!( url.origin() == repo.origin(), "{} è ospitato fuori dal repository configurato ({}): download rifiutato", asset.name, url.origin().ascii_serialization() ); let response = client .get(url) .send() .await .with_context(|| format!("download di {} non riuscito", asset.name))?; ensure!( response.status().is_success(), "download di {} non riuscito: HTTP {}", asset.name, response.status() ); Ok(response .bytes() .await .with_context(|| format!("download di {} interrotto", asset.name))? .to_vec()) } /// Accepts `` or `sha256sum` output (` `), possibly listing several files. fn parse_sha256(text: &str, archive_name: &str) -> Result { let lines: Vec> = text .lines() .map(|line| line.split_whitespace().collect::>()) .filter(|tokens| !tokens.is_empty()) .collect(); let line = match lines.as_slice() { [only] => only, many => many .iter() .find(|tokens| { tokens .get(1) .is_some_and(|file| file.trim_start_matches('*') == archive_name) }) .ok_or_else(|| anyhow!("il file .sha256 non elenca {archive_name}"))?, }; let digest = line[0].to_ascii_lowercase(); ensure!( digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()), "il file .sha256 di {archive_name} non contiene un hash SHA-256 valido" ); Ok(digest) } fn hex(bytes: &[u8]) -> String { bytes.iter().map(|byte| format!("{byte:02x}")).collect() } /// Downloads, verifies and installs `release`. Nothing on disk changes unless the /// archive matches its published checksum. pub async fn install_release( client: &reqwest::Client, repo_url: &str, release: &Release, target: &str, install: &InstallTarget, ) -> Result { let archive = download_verified_archive(client, repo_url, release, target).await?; install_archive(&archive, install, &release.version) } /// Extracts a verified `.tar.gz` and swaps it in. The previous binary (or package) is kept /// as `*.old` and restored if the swap fails. pub fn install_archive( archive: &[u8], install: &InstallTarget, version: &Version, ) -> Result { let exe_dir = install .exe .parent() .context("il binario installato non ha una cartella")?; // Stage next to the destination so the final renames never cross file systems. let staging_parent = match &install.package_dir { Some(package_dir) => package_dir .parent() .context("il pacchetto installato non ha una cartella")?, None => exe_dir, }; let staging = tempfile::Builder::new() .prefix(".akode-update-") .tempdir_in(staging_parent) .with_context(|| { format!( "impossibile scrivere in {} (servono i permessi di scrittura)", staging_parent.display() ) })?; let extract_dir = staging.path().join("extract"); std::fs::create_dir(&extract_dir)?; let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(archive)); tar.set_preserve_permissions(true); tar.unpack(&extract_dir) .context("l'archivio della release non è un .tar.gz valido")?; let root = archive_root(&extract_dir)?; if let Some(package_dir) = &install.package_dir && root.join(PACKAGE_MANIFEST_FILE_NAME).is_file() { let backup = replace_package_dir(&root, package_dir)?; return Ok(InstallOutcome::Package { backup }); } let new_binary = find_binary(&root)?; let staged_manifest = match &install.package_dir { Some(package_dir) => Some(stage_manifest_version( package_dir, version, staging.path(), )?), None => None, }; let backup = replace_binary(&new_binary, &install.exe)?; if let (Some(staged), Some(package_dir)) = (staged_manifest, &install.package_dir) && let Err(err) = std::fs::rename(&staged, package_dir.join(PACKAGE_MANIFEST_FILE_NAME)) { restore_binary(&backup, &install.exe); return Err(err).context("impossibile aggiornare akode-package.json; binario ripristinato"); } Ok(InstallOutcome::Binary { backup }) } /// Archives may wrap their content in a single top-level directory. fn archive_root(extract_dir: &Path) -> Result { let entries: Vec<_> = std::fs::read_dir(extract_dir)?.collect::>()?; match entries.as_slice() { [] => bail!("l'archivio della release è vuoto"), [single] if single.file_type()?.is_dir() => Ok(single.path()), _ => Ok(extract_dir.to_path_buf()), } } fn binary_file_name() -> &'static str { if cfg!(windows) { "akode.exe" } else { "akode" } } fn find_binary(root: &Path) -> Result { let name = binary_file_name(); [root.join(name), root.join("bin").join(name)] .into_iter() .find(|candidate| candidate.is_file()) .ok_or_else(|| anyhow!("l'archivio della release non contiene {name}")) } fn backup_path(exe: &Path) -> PathBuf { let stem = exe .file_stem() .and_then(|stem| stem.to_str()) .unwrap_or("akode"); exe.with_file_name(format!("{stem}.old")) } /// Puts `new_binary` at `exe`. On Unix the final rename atomically replaces the binary; on /// Windows a running executable cannot be overwritten, so it is moved aside first. fn replace_binary(new_binary: &Path, exe: &Path) -> Result { let file_name = exe .file_name() .and_then(|name| name.to_str()) .unwrap_or("akode"); let staged = exe.with_file_name(format!(".{file_name}.new-{}", std::process::id())); std::fs::copy(new_binary, &staged) .with_context(|| format!("impossibile scrivere {}", staged.display()))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755))?; } let backup = backup_path(exe); let result = swap_into_place(&staged, exe, &backup); if result.is_err() { let _ = std::fs::remove_file(&staged); } result.map(|()| backup) } #[cfg(not(windows))] fn swap_into_place(staged: &Path, exe: &Path, backup: &Path) -> Result<()> { if backup.exists() { std::fs::remove_file(backup)?; } std::fs::copy(exe, backup) .with_context(|| format!("impossibile creare la copia {}", backup.display()))?; std::fs::rename(staged, exe) .with_context(|| format!("impossibile sostituire {}", exe.display())) } #[cfg(windows)] fn swap_into_place(staged: &Path, exe: &Path, backup: &Path) -> Result<()> { if backup.exists() { std::fs::remove_file(backup)?; } std::fs::rename(exe, backup) .with_context(|| format!("impossibile spostare {}", exe.display()))?; if let Err(err) = std::fs::rename(staged, exe) { restore_binary(backup, exe); return Err(err).with_context(|| format!("impossibile sostituire {}", exe.display())); } Ok(()) } fn restore_binary(backup: &Path, exe: &Path) { if cfg!(windows) { let _ = std::fs::rename(backup, exe); } else { // Copy to a fresh file and rename: overwriting the binary in place would corrupt a // running executable (and invalidate its code signature on macOS). let restored = exe.with_file_name(format!(".akode.restore-{}", std::process::id())); if std::fs::copy(backup, &restored).is_ok() && std::fs::rename(&restored, exe).is_err() { let _ = std::fs::remove_file(&restored); } } } fn stage_manifest_version( package_dir: &Path, version: &Version, staging: &Path, ) -> Result { let path = package_dir.join(PACKAGE_MANIFEST_FILE_NAME); let mut manifest: serde_json::Value = serde_json::from_slice( &std::fs::read(&path).with_context(|| format!("impossibile leggere {}", path.display()))?, ) .with_context(|| format!("{} non è JSON valido", path.display()))?; let object = manifest .as_object_mut() .with_context(|| format!("{} non è un oggetto JSON", path.display()))?; object.insert( "version".to_string(), serde_json::Value::String(version.to_string()), ); // Same file system as the package directory, so the later rename is atomic. let staged = staging.join(PACKAGE_MANIFEST_FILE_NAME); std::fs::write(&staged, serde_json::to_vec_pretty(&manifest)?)?; Ok(staged) } fn replace_package_dir(new_package: &Path, package_dir: &Path) -> Result { let name = package_dir .file_name() .and_then(|name| name.to_str()) .context("cartella del pacchetto non valida")?; let backup = package_dir.with_file_name(format!("{name}.old")); if backup.exists() { std::fs::remove_dir_all(&backup)?; } std::fs::rename(package_dir, &backup) .with_context(|| format!("impossibile spostare {}", package_dir.display()))?; if let Err(err) = std::fs::rename(new_package, package_dir) { let _ = std::fs::rename(&backup, package_dir); return Err(err) .with_context(|| format!("impossibile sostituire {}", package_dir.display())); } Ok(backup) } #[derive(Debug, Serialize, Deserialize)] struct CheckState { last_checked_at: DateTime, #[serde(default)] latest_version: Option, } /// Startup check: contacts the repository at most once per [`CHECK_INTERVAL`] and returns a /// newer version to announce, if any. Never installs anything. pub struct StartupCheck<'a> { pub akode_home: &'a Path, pub repo_url: &'a str, pub enabled: bool, pub current_version: &'a str, } impl StartupCheck<'_> { pub async fn run(&self, client: &reqwest::Client, now: DateTime) -> Option { if !self.enabled { return None; } let state_path = self.akode_home.join(STATE_FILE_NAME); let previous: Option = std::fs::read(&state_path) .ok() .and_then(|bytes| serde_json::from_slice(&bytes).ok()); let interval = chrono::Duration::from_std(CHECK_INTERVAL).ok()?; let latest = match &previous { Some(state) if state.last_checked_at <= now && now - state.last_checked_at < interval => { state.latest_version.clone() } _ => { let latest = match fetch_latest_release(client, self.repo_url).await { Ok(release) => release.map(|release| release.version.to_string()), Err(_) => previous.and_then(|state| state.latest_version), }; let state = CheckState { last_checked_at: now, latest_version: latest.clone(), }; if let Ok(bytes) = serde_json::to_vec(&state) { let _ = std::fs::create_dir_all(self.akode_home); let _ = std::fs::write(&state_path, bytes); } latest } }; let latest = Version::parse(&latest?).ok()?; is_newer(self.current_version, &latest).then_some(latest) } } #[cfg(test)] #[path = "lib_tests.rs"] mod tests;