use std::{
ffi::OsString,
fs,
io::{self, Cursor, Read},
path::{Path, PathBuf},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use anyhow::Context;
use bytes::Bytes;
use sha2::{Digest, Sha256};
use super::{Report, UpdateInfo};
use crate::daemon;
const RELEASE_DOWNLOAD_URL: &str = "https://github.com/matthewyjiang/rho/releases/download";
const ARCHIVE: &str = "rho-x86_64-pc-windows-msvc.zip";
const ARCHIVE_EXECUTABLE: &str = "rho.exe";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const READ_TIMEOUT: Duration = Duration::from_secs(30);
pub(super) async fn update(
update: &UpdateInfo,
installed: &Path,
report: &mut impl Report,
) -> anyhow::Result<PathBuf> {
let executable = fetch(&update.latest_tag, report).await?;
install(installed, &executable, &update.latest_version).await
}
async fn fetch(tag: &str, report: &mut impl Report) -> anyhow::Result<Vec<u8>> {
let url = format!("{RELEASE_DOWNLOAD_URL}/{tag}/{ARCHIVE}");
report.say(&format!("downloading {url}"));
let client = crate::reqwest_client_builder()
.user_agent("rho-coding-agent")
.connect_timeout(CONNECT_TIMEOUT)
.read_timeout(READ_TIMEOUT)
.build()?;
let archive = download(&client, &url).await?;
let checksum = download(&client, &format!("{url}.sha256")).await?;
verify_checksum(&archive, &String::from_utf8_lossy(&checksum))
.with_context(|| format!("could not verify {url}"))?;
extract_executable(&archive)
.with_context(|| format!("could not unpack {ARCHIVE_EXECUTABLE} from {url}"))
}
async fn install(installed: &Path, executable: &[u8], version: &str) -> anyhow::Result<PathBuf> {
remove_update_leftovers(installed);
let staged = stage(installed, executable).with_context(|| {
format!(
"could not write the new rho next to {}",
installed.display()
)
})?;
let placed = match daemon::probe_version(&staged).await {
Ok(printed) if printed == version => swap(installed, &staged).map_err(anyhow::Error::from),
Ok(printed) => Err(anyhow::anyhow!(
"the downloaded rho reports version {printed}, not {version}"
)),
Err(error) => Err(anyhow::Error::new(error).context("the downloaded rho does not run")),
};
if placed.is_err() {
let _ = fs::remove_file(&staged);
}
placed
}
async fn download(client: &reqwest::Client, url: &str) -> anyhow::Result<Bytes> {
client
.get(url)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.with_context(|| format!("could not download {url}"))?
.bytes()
.await
.with_context(|| format!("could not download {url}"))
}
fn verify_checksum(archive: &[u8], checksum: &str) -> anyhow::Result<()> {
let Some(expected) = checksum.split_whitespace().next() else {
anyhow::bail!("the published checksum is empty");
};
let actual = hex::encode(Sha256::digest(archive));
if !expected.eq_ignore_ascii_case(&actual) {
anyhow::bail!("its SHA-256 is {actual}, but the release publishes {expected}");
}
Ok(())
}
fn extract_executable(archive: &[u8]) -> anyhow::Result<Vec<u8>> {
let mut archive = zip::ZipArchive::new(Cursor::new(archive))?;
let mut entry = archive.by_name(ARCHIVE_EXECUTABLE)?;
let mut executable = Vec::new();
entry.read_to_end(&mut executable)?;
Ok(executable)
}
fn stage(installed: &Path, executable: &[u8]) -> io::Result<PathBuf> {
let staged = sibling(installed, &format!("{STAGED}{}", std::process::id()));
fs::write(&staged, executable)?;
Ok(staged)
}
#[derive(Debug, thiserror::Error)]
enum SwapError {
#[error("could not move {} aside: {error}; it was left as it was", installed.display())]
MoveAside {
installed: PathBuf,
error: io::Error,
},
#[error("could not move the new rho to {}: {error}; the previous rho was put back", installed.display())]
Place {
installed: PathBuf,
error: io::Error,
},
#[error(
"could not move the new rho to {}: {error}, nor put the previous rho back: {rollback}; move {} to {} to restore it",
installed.display(), aside.display(), installed.display()
)]
Stranded {
installed: PathBuf,
aside: PathBuf,
error: io::Error,
rollback: io::Error,
},
}
fn swap(installed: &Path, staged: &Path) -> Result<PathBuf, SwapError> {
let aside = sibling(installed, &format!("{MOVED_ASIDE}{}", unique_suffix()));
fs::rename(installed, &aside).map_err(|error| SwapError::MoveAside {
installed: installed.to_path_buf(),
error,
})?;
let Err(error) = fs::rename(staged, installed) else {
return Ok(aside);
};
match fs::rename(&aside, installed) {
Ok(()) => Err(SwapError::Place {
installed: installed.to_path_buf(),
error,
}),
Err(rollback) => Err(SwapError::Stranded {
installed: installed.to_path_buf(),
aside,
error,
rollback,
}),
}
}
const MOVED_ASIDE: &str = "old-";
const STAGED: &str = "new-";
#[derive(Debug, PartialEq, Eq)]
struct Leftover {
update_pid: u32,
}
pub(crate) fn remove_update_leftovers(installed: &Path) {
let Some(dir) = installed.parent() else {
return;
};
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
match leftover(installed, &entry.file_name()) {
Some(Leftover { update_pid }) if !process_runs(update_pid) => {}
Some(_) | None => continue,
}
let path = entry.path();
if let Err(error) = fs::remove_file(&path) {
tracing::debug!(path = %path.display(), %error, "kept a rho executable an update left");
}
}
}
fn leftover(installed: &Path, name: &std::ffi::OsStr) -> Option<Leftover> {
let stem = installed.file_stem()?.to_str()?;
let rest = name.to_str()?.strip_prefix(stem)?.strip_prefix('.')?;
let tagged = match installed.extension() {
Some(extension) => rest.strip_suffix(extension.to_str()?)?.strip_suffix('.')?,
None => rest,
};
let update_pid = match tagged.strip_prefix(MOVED_ASIDE) {
Some(suffix) => {
let (nanos, pid) = suffix.split_once('-')?;
number::<u128>(nanos)?;
number(pid)?
}
None => number(tagged.strip_prefix(STAGED)?)?,
};
Some(Leftover { update_pid })
}
fn number<T: std::str::FromStr>(text: &str) -> Option<T> {
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
text.parse().ok()
}
#[cfg(unix)]
fn process_runs(pid: u32) -> bool {
let Some(pid) = i32::try_from(pid).ok().filter(|pid| *pid > 0) else {
return false;
};
if unsafe { libc::kill(pid, 0) } == 0 {
return true;
}
io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(windows)]
fn process_runs(pid: u32) -> bool {
use windows_sys::Win32::{
Foundation::{CloseHandle, WAIT_TIMEOUT},
System::Threading::{OpenProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE},
};
let process = unsafe {
OpenProcess(PROCESS_SYNCHRONIZE, 0, pid)
};
if process.is_null() {
return false;
}
unsafe {
let waited = WaitForSingleObject(process, 0);
CloseHandle(process);
waited == WAIT_TIMEOUT
}
}
fn sibling(installed: &Path, tag: &str) -> PathBuf {
let mut name = sibling_prefix(installed, tag).unwrap_or_else(|| OsString::from(tag));
if let Some(extension) = installed.extension() {
name.push(".");
name.push(extension);
}
installed.with_file_name(name)
}
fn sibling_prefix(installed: &Path, tag: &str) -> Option<OsString> {
let mut prefix = installed.file_stem()?.to_os_string();
prefix.push(".");
prefix.push(tag);
Some(prefix)
}
fn unique_suffix() -> String {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_nanos());
format!("{nanos}-{}", std::process::id())
}
#[cfg(test)]
#[path = "update_in_place_tests.rs"]
mod tests;