use crate::paths::Paths;
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const REPO: &str = "juninmd/egrix";
const CHECK_INTERVAL_SECS: u64 = 86_400;
const MAX_JSON_BYTES: u64 = 1024 * 1024;
const MAX_CHECKSUM_BYTES: u64 = 64 * 1024;
const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024;
#[derive(Debug, Serialize, Deserialize)]
pub struct Cache {
#[serde(default)]
last_checked: u64,
#[serde(default)]
latest: String,
#[serde(default = "enabled")]
auto_install: bool,
#[serde(default)]
just_updated: bool,
}
fn enabled() -> bool {
true
}
impl Default for Cache {
fn default() -> Self {
Self { last_checked: 0, latest: String::new(), auto_install: true, just_updated: false }
}
}
#[derive(Deserialize)]
struct Release {
tag_name: String,
html_url: String,
#[serde(default)]
assets: Vec<Asset>,
}
#[derive(Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
size: u64,
}
#[derive(Default)]
pub struct Options {
pub check: bool,
pub enable_auto: bool,
pub disable_auto: bool,
}
pub fn current_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
let mut parts = s.trim().trim_start_matches('v').split('.');
let major = parts.next()?.parse().ok()?;
let minor = parts.next()?.parse().ok()?;
let patch = parts.next()?.split('-').next()?.parse().ok()?;
Some((major, minor, patch))
}
fn env_value(name: &str) -> Option<String> {
std::env::var(name).ok().map(|v| v.trim().to_ascii_lowercase())
}
fn check_enabled() -> bool {
if matches!(env_value("EGRIX_NO_UPDATE").as_deref(), Some("1" | "true")) {
return false;
}
if matches!(env_value("CI").as_deref(), Some("1" | "true")) {
return false;
}
!matches!(env_value("EGRIX_AUTO_UPDATE").as_deref(), Some("0" | "false" | "off"))
}
fn install_enabled(cache: &Cache) -> bool {
if !check_enabled() {
return false;
}
match env_value("EGRIX_AUTO_UPDATE").as_deref() {
Some("0" | "false" | "off" | "no" | "notify") => false,
Some("1" | "true" | "auto" | "install") => true,
_ => cache.auto_install,
}
}
fn cache_path(paths: &Paths) -> PathBuf {
paths.config.join("update.json")
}
fn lock_path(paths: &Paths) -> PathBuf {
paths.config.join("update.lock")
}
fn load_cache(paths: &Paths) -> Cache {
std::fs::read_to_string(cache_path(paths)).ok().and_then(|text| serde_json::from_str(&text).ok()).unwrap_or_default()
}
fn save_cache(paths: &Paths, cache: &Cache) -> Result<()> {
std::fs::create_dir_all(&paths.config)?;
std::fs::write(cache_path(paths), serde_json::to_string_pretty(cache)?)?;
Ok(())
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
fn asset_name() -> Result<&'static str> {
match (std::env::consts::OS, std::env::consts::ARCH) {
("linux", "x86_64") => Ok("egrix-linux-x86_64"),
("linux", "aarch64") => Ok("egrix-linux-aarch64"),
("macos", "aarch64") => Ok("egrix-macos-aarch64"),
("windows", "x86_64") => Ok("egrix-windows-x86_64.exe"),
(os, arch) => bail!("no prebuilt binary for {os}-{arch}; use `cargo install --locked egrix`"),
}
}
fn agent(timeout: Duration, follow_redirects: bool) -> ureq::Agent {
use ureq::tls::{RootCerts, TlsConfig};
let mut config = ureq::Agent::config_builder()
.user_agent(concat!("egrix/", env!("CARGO_PKG_VERSION")))
.timeout_global(Some(timeout))
.http_status_as_error(false)
.tls_config(TlsConfig::builder().root_certs(RootCerts::PlatformVerifier).build());
if !follow_redirects {
config = config.max_redirects(0).max_redirects_will_error(false);
}
config.build().into()
}
fn read_capped(reader: impl Read, cap: u64) -> Result<Vec<u8>> {
let mut buf = Vec::new();
reader.take(cap + 1).read_to_end(&mut buf)?;
if buf.len() as u64 > cap {
bail!("response exceeds the {cap}-byte limit");
}
Ok(buf)
}
fn fetch_latest() -> Result<Release> {
let url = format!("https://api.github.com/repos/{REPO}/releases/latest");
let client = agent(Duration::from_secs(15), false);
let mut request = client.get(&url).header("Accept", "application/vnd.github+json");
let token = std::env::var("GITHUB_TOKEN").or_else(|_| std::env::var("GH_TOKEN")).ok();
if let Some(token) = token.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
request = request.header("Authorization", format!("Bearer {token}"));
}
let mut response = request.call().context("cannot reach GitHub releases")?;
if !response.status().is_success() {
bail!("GitHub API error: HTTP {}", response.status());
}
let body = read_capped(response.body_mut().as_reader(), MAX_JSON_BYTES)?;
serde_json::from_slice(&body).context("cannot parse the release JSON")
}
fn verified_url(release: &Release, asset: &Asset) -> Result<String> {
let prefix = format!("https://github.com/{REPO}/releases/download/{}/", release.tag_name);
let rest = asset.browser_download_url.strip_prefix(&prefix);
match rest {
Some(name) if name == asset.name && !name.contains(['?', '#', '@']) => Ok(asset.browser_download_url.clone()),
_ => bail!("unexpected download URL for {}", asset.name),
}
}
fn expected_hash(sums: &str, file: &str) -> Option<String> {
sums.lines().find_map(|line| {
let mut parts = line.split_whitespace();
let hash = parts.next()?;
let name = parts.next()?.trim_start_matches('*');
(name == file).then(|| hash.to_ascii_lowercase())
})
}
fn install(release: &Release, target: &Path) -> Result<()> {
let name = asset_name()?;
let binary =
release.assets.iter().find(|a| a.name == name).ok_or_else(|| anyhow!("asset {name} is missing from {}", release.tag_name))?;
let sums_asset = release
.assets
.iter()
.find(|a| a.name == "sha256sums.txt")
.ok_or_else(|| anyhow!("sha256sums.txt is missing from {}", release.tag_name))?;
let client = agent(Duration::from_secs(300), true);
let mut sums = client.get(&verified_url(release, sums_asset)?).call()?;
if !sums.status().is_success() {
bail!("cannot download sha256sums.txt: HTTP {}", sums.status());
}
let sums = String::from_utf8(read_capped(sums.body_mut().as_reader(), MAX_CHECKSUM_BYTES)?).context("sha256sums.txt is not UTF-8")?;
let expected = expected_hash(&sums, name).ok_or_else(|| anyhow!("{name} has no checksum entry"))?;
let dir = target.parent().ok_or_else(|| anyhow!("target has no parent directory"))?;
let temp = dir.join(format!("egrix_download_{}.tmp", std::process::id()));
let result = download_to(&client, &verified_url(release, binary)?, binary.size, &temp)
.and_then(
|actual| {
if actual == expected {
Ok(())
} else {
bail!("SHA-256 mismatch for {name}: expected {expected}, got {actual}")
}
},
)
.and_then(|()| replace(&temp, target));
if result.is_err() {
let _ = std::fs::remove_file(&temp);
}
result
}
fn download_to(client: &ureq::Agent, url: &str, declared_size: u64, temp: &Path) -> Result<String> {
let mut response = client.get(url).call().context("download failed")?;
if !response.status().is_success() {
bail!("download failed: HTTP {}", response.status());
}
let cap = declared_size.min(MAX_BINARY_BYTES);
let mut file = std::fs::File::create(temp).context("cannot create the temporary file")?;
let mut hasher = Sha256::new();
let mut reader = response.body_mut().as_reader();
let mut buffer = vec![0u8; 64 * 1024];
let mut total = 0u64;
loop {
let n = reader.read(&mut buffer)?;
if n == 0 {
break;
}
total += n as u64;
if total > cap {
bail!("download exceeds the {cap}-byte limit");
}
hasher.update(&buffer[..n]);
file.write_all(&buffer[..n])?;
}
file.flush()?;
Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
}
fn replace(temp: &Path, target: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(temp, std::fs::Permissions::from_mode(0o755))?;
std::fs::rename(temp, target).with_context(|| format!("cannot replace {}", target.display()))?;
}
#[cfg(windows)]
{
let old = target.with_file_name(format!("egrix.exe.old.{}", std::process::id()));
std::fs::rename(target, &old).with_context(|| format!("cannot move {} aside", target.display()))?;
if let Err(e) = std::fs::rename(temp, target) {
let _ = std::fs::rename(&old, target);
return Err(e).context("cannot install the new binary");
}
let _ = std::fs::remove_file(&old);
}
Ok(())
}
pub fn clean_stale_files(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let stale_name = name.starts_with("egrix.exe.old.") || (name.starts_with("egrix_download_") && name.ends_with(".tmp"));
let old_enough = entry
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age >= Duration::from_secs(86_400));
if stale_name && old_enough {
let _ = std::fs::remove_file(entry.path());
}
}
}
struct LockGuard(PathBuf);
impl Drop for LockGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
pub fn on_startup(paths: &Paths) {
if !check_enabled() {
return;
}
let mut cache = load_cache(paths);
if cache.just_updated {
cache.just_updated = false;
let _ = save_cache(paths, &cache);
eprintln!("✓ egrix was automatically updated to {}.", current_version());
return;
}
let stale = now().saturating_sub(cache.last_checked) > CHECK_INTERVAL_SECS;
if stale {
spawn_background_check(paths);
}
let newer = parse_version(&cache.latest) > parse_version(current_version());
if newer {
if install_enabled(&cache) {
eprintln!("tip: a newer egrix is available ({} -> {}). Automatic updates are enabled.", current_version(), cache.latest);
} else {
eprintln!("tip: a newer egrix is available ({} -> {}). Run `egrix update` to upgrade.", current_version(), cache.latest);
}
}
}
fn spawn_background_check(paths: &Paths) {
let lock = lock_path(paths);
let _ = std::fs::create_dir_all(&paths.config);
let acquire = || std::fs::OpenOptions::new().write(true).create_new(true).open(&lock);
if acquire().is_err() {
let stale = std::fs::metadata(&lock)
.and_then(|m| m.modified())
.and_then(|t| t.elapsed().map_err(std::io::Error::other))
.is_ok_and(|age| age >= Duration::from_secs(600));
if !stale {
return;
}
let _ = std::fs::remove_file(&lock);
if acquire().is_err() {
return;
}
}
let Ok(exe) = std::env::current_exe() else {
let _ = std::fs::remove_file(&lock);
return;
};
let mut cmd = std::process::Command::new(exe);
cmd.args(["update", "--check-background"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0000_0008 | 0x0800_0000);
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
if cmd.spawn().is_err() {
let _ = std::fs::remove_file(&lock);
}
}
fn background(paths: &Paths) -> Result<()> {
let _guard = LockGuard(lock_path(paths));
if !check_enabled() {
return Ok(());
}
let release = fetch_latest()?;
let latest = parse_version(&release.tag_name).ok_or_else(|| anyhow!("bad tag {}", release.tag_name))?;
let mut cache = load_cache(paths);
cache.last_checked = now();
cache.latest = release.tag_name.clone();
if latest > parse_version(current_version()).unwrap_or_default() && install_enabled(&cache) && !cfg!(debug_assertions) {
let target = std::env::current_exe()?;
if install(&release, &target).is_ok() {
cache.just_updated = true;
clean_stale_files(target.parent().unwrap_or(Path::new(".")));
}
}
save_cache(paths, &cache)
}
pub fn run(paths: &Paths, opts: Options, check_background: bool) -> Result<()> {
if check_background {
return background(paths);
}
if opts.enable_auto || opts.disable_auto {
let mut cache = load_cache(paths);
cache.auto_install = opts.enable_auto;
save_cache(paths, &cache)?;
println!("Automatic updates {}.", if opts.enable_auto { "enabled" } else { "disabled" });
return Ok(());
}
let release = fetch_latest()?;
let latest = parse_version(&release.tag_name).ok_or_else(|| anyhow!("bad tag {}", release.tag_name))?;
let mut cache = load_cache(paths);
cache.last_checked = now();
cache.latest = release.tag_name.clone();
save_cache(paths, &cache)?;
if latest <= parse_version(current_version()).unwrap_or_default() {
println!("egrix {} is up to date.", current_version());
return Ok(());
}
if opts.check {
println!("Update available: {} -> {} ({})", current_version(), release.tag_name, release.html_url);
return Ok(());
}
let target = std::env::current_exe()?;
install(&release, &target)?;
clean_stale_files(target.parent().unwrap_or(Path::new(".")));
println!("Updated egrix {} -> {}.", current_version(), release.tag_name);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions_compare_by_number_not_text() {
assert!(parse_version("v0.10.0") > parse_version("0.9.9"));
assert_eq!(parse_version("v1.2.3-rc1"), Some((1, 2, 3)));
assert_eq!(parse_version("nonsense"), None);
}
#[test]
fn checksum_lookup_matches_the_exact_asset() {
let sums = "AAAA egrix-linux-x86_64\nBBBB *egrix-windows-x86_64.exe\n";
assert_eq!(expected_hash(sums, "egrix-windows-x86_64.exe").as_deref(), Some("bbbb"));
assert_eq!(expected_hash(sums, "egrix-macos-aarch64"), None);
}
#[test]
fn only_the_release_own_asset_urls_are_fetched() {
let release = Release { tag_name: "v1.0.0".into(), html_url: String::new(), assets: vec![] };
let good = Asset {
name: "egrix-linux-x86_64".into(),
browser_download_url: format!("https://github.com/{REPO}/releases/download/v1.0.0/egrix-linux-x86_64"),
size: 1,
};
assert!(verified_url(&release, &good).is_ok());
let evil = Asset { browser_download_url: "https://evil.example/egrix-linux-x86_64".into(), ..good };
assert!(verified_url(&release, &evil).is_err());
}
}