//! Updates and rollbacks (docs/server.md, section 7) for a `horizon-server` installed by install.sh or
//! install.ps1: each release in `
/releases/`, `/current` pointing at the one in use, and
//! `/previous` naming the one before it. An update downloads the newest stable release from GitHub, checks it
//! against the SHA-256 in the release's signed SHA256SUMS (docs/security.md), unpacks it beside the others and
//! switches `current`; the supervisor then restarts the game on it and switches back by itself if the new game
//! doesn't come up.
use crate::{api::Client, backup, config::Config, engine, supervisor};
use serde_json::{Value, json};
use std::{
io::Read,
path::{Path, PathBuf},
time::{Duration, Instant},
};
const REPO: &str = "ludovic111/horizon";
/// The release archives for this computer, most specific first: on Linux the server build (no ALSA or
/// udev), else the full game (releases before the server build).
const ASSETS: &[&str] = if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
&[
"horizon-server-linux-x86_64.tar.gz",
"horizon-linux-x86_64.tar.gz",
]
} else if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
&["horizon-macos-arm64.zip"]
} else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
&["horizon-windows-x64.zip"]
} else {
&[]
};
fn exe(name: &str) -> String {
format!("{name}{}", std::env::consts::EXE_SUFFIX)
}
/// The installer's folder: `releases/`, `current`, `previous` and `game-files/`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Install {
pub root: PathBuf,
}
impl Install {
/// The install this program runs from, if it runs from one.
pub fn find() -> Option {
Self::around(&std::env::current_exe().ok()?)
}
/// The install holding `program` (`/releases//horizon-server`, reached directly or through
/// `current`).
pub fn around(program: &Path) -> Option {
let program = std::fs::canonicalize(program).ok()?;
let releases = program.parent()?.parent()?;
if releases.file_name()? != "releases" {
return None;
}
let root = releases.parent()?.to_path_buf();
root.join("current").is_dir().then_some(Self { root })
}
/// The install, or why there is none to update.
pub fn required() -> Result {
Self::find().ok_or_else(|| {
"this horizon-server wasn't installed by install.sh or install.ps1 (no releases/ and current \
around it): update it the way you installed it"
.into()
})
}
pub fn release(&self, tag: &str) -> PathBuf {
self.root.join("releases").join(tag)
}
/// Where the game programs in use are: `current`, so a switch applies at the next start.
pub fn programs(&self) -> PathBuf {
self.root.join("current")
}
/// The release in use.
pub fn current(&self) -> Option {
let target = std::fs::canonicalize(self.root.join("current")).ok()?;
Some(target.file_name()?.to_string_lossy().into_owned())
}
/// The release used before the current one, if it is still there.
pub fn previous(&self) -> Option {
let tag = std::fs::read_to_string(self.root.join("previous")).ok()?;
let tag = tag.trim();
(!tag.is_empty() && self.release(tag).is_dir()).then(|| tag.to_owned())
}
/// Points `current` at the release `tag`, and remembers the one it pointed at as `previous`.
pub fn switch(&self, tag: &str) -> Result<(), String> {
let target = self.release(tag);
if !target.join(exe("horizon-server")).is_file() {
return Err(format!("{} holds no horizon-server", target.display()));
}
if let Some(old) = self.current().filter(|old| old != tag) {
std::fs::write(self.root.join("previous"), format!("{old}\n"))
.map_err(|e| format!("{}: {e}", self.root.join("previous").display()))?;
}
point(&self.root.join("current"), &target)
.map_err(|e| format!("switching current to {tag}: {e}"))
}
/// Undoes a [`Install::switch`]: `current` back on `from` and `previous` as it was before, so a later
/// rollback doesn't go to the release that failed.
pub fn switch_back(&self, from: &str, previous: Option<&str>) -> Result<(), String> {
point(&self.root.join("current"), &self.release(from))
.map_err(|e| format!("switching current back to {from}: {e}"))?;
let file = self.root.join("previous");
match previous {
Some(tag) => std::fs::write(&file, format!("{tag}\n")),
None => std::fs::remove_file(&file).or_else(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(())
} else {
Err(e)
}
}),
}
.map_err(|e| format!("{}: {e}", file.display()))
}
/// Deletes old releases after a successful update: it keeps the one `current` points at, the one
/// `previous` names (where `rollback` goes), the one this program runs from, and the `keep` newest of
/// the others. Returns the releases deleted, and what couldn't be (a program still running from it on
/// Windows), which stays for the next update to try again.
pub fn prune(&self, keep: u32) -> (Vec, Vec) {
let releases = self.root.join("releases");
let running = std::env::current_exe()
.ok()
.and_then(|e| std::fs::canonicalize(e).ok());
let Some(current) = self.current() else {
// `current` points nowhere: nothing is known to be safe to delete.
return (Vec::new(), Vec::new());
};
let previous = self.previous();
let mut others: Vec = std::fs::read_dir(&releases)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.map(|e| e.file_name().to_string_lossy().into_owned())
// `..unpacking` is an update in progress.
.filter(|tag| {
!tag.starts_with('.') && *tag != current && previous.as_deref() != Some(tag)
})
.filter(|tag| {
let dir = std::fs::canonicalize(releases.join(tag)).ok();
!running
.as_ref()
.zip(dir)
.is_some_and(|(exe, dir)| exe.starts_with(dir))
})
.collect();
// Newest first; names that aren't release tags (archives installed by hand) by name.
others.sort_by(|a, b| {
if newer(a, b) {
std::cmp::Ordering::Less
} else if newer(b, a) {
std::cmp::Ordering::Greater
} else {
b.cmp(a)
}
});
let (mut removed, mut failed) = (Vec::new(), Vec::new());
for tag in others.into_iter().skip(keep as usize) {
match std::fs::remove_dir_all(releases.join(&tag)) {
Ok(()) => removed.push(tag),
Err(e) => failed.push(format!("{tag} ({e})")),
}
}
(removed, failed)
}
}
/// What [`Install::prune`] did, for the log: empty when it deleted nothing.
pub fn pruned(removed: &[String], failed: &[String]) -> String {
let mut parts = Vec::new();
if !removed.is_empty() {
parts.push(format!("Deleted old releases: {}", removed.join(", ")));
}
if !failed.is_empty() {
parts.push(format!(
"Couldn't delete old releases: {}",
failed.join(", ")
));
}
parts.join(". ")
}
/// Makes `link` point at the folder `target`, replacing what it pointed at.
#[cfg(unix)]
fn point(link: &Path, target: &Path) -> std::io::Result<()> {
// A new link renamed over the old one: `current` always points at a whole release.
let fresh = link.with_extension("switching");
let _ = std::fs::remove_file(&fresh);
std::os::unix::fs::symlink(target, &fresh)?;
std::fs::rename(&fresh, link)
}
/// Makes `link` a junction to `target` (install.ps1's links: they need no admin rights).
#[cfg(windows)]
fn point(link: &Path, target: &Path) -> std::io::Result<()> {
if link.exists() || link.symlink_metadata().is_ok() {
std::fs::remove_dir(link)?;
}
let status = crate::process::command("cmd")
.arg("/C")
.arg("mklink")
.arg("/J")
.arg(link)
.arg(target)
.stdout(std::process::Stdio::null())
.status()?;
if status.success() {
Ok(())
} else {
Err(std::io::Error::other(format!(
"mklink /J failed ({status})"
)))
}
}
/// A release on GitHub: its tag and the archive for this computer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Release {
pub tag: String,
pub asset: String,
pub url: String,
pub sha256: String,
}
/// GitHub's API, or a release asset: the body of `url`.
fn fetch(url: &str) -> Result, String> {
let mut body = Vec::new();
ureq::get(url)
.set("Accept", "application/vnd.github+json")
.set("User-Agent", "horizon-server")
.call()
.map_err(|e| match e {
ureq::Error::Status(404, _) => "404".to_string(),
e => format!("GitHub didn't answer: {e}"),
})?
.into_reader()
.take(64 << 20)
.read_to_end(&mut body)
.map_err(|e| format!("GitHub's answer: {e}"))?;
Ok(body)
}
/// The newest stable release (or `tag`), from GitHub's API, with the SHA-256 its signed checksums
/// give for this computer's archive.
pub fn release(tag: Option<&str>) -> Result {
let url = match tag {
Some(tag) => format!("https://api.github.com/repos/{REPO}/releases/tags/{tag}"),
None => format!("https://api.github.com/repos/{REPO}/releases/latest"),
};
let text = fetch(&url).map_err(|e| match e.as_str() {
"404" => format!("no release {} on GitHub", tag.unwrap_or("")),
_ => e,
})?;
let json = serde_json::from_slice(&text).map_err(|e| format!("GitHub's answer: {e}"))?;
pick(&json, fetch, &horizon_release_sign::trusted_keys())
}
/// The archive for this computer in a release's JSON, with the SHA-256 the release's SHA256SUMS
/// gives for it, once its signature checks with one of `keys` (docs/security.md). A release from
/// before signing gets the SHA-256 pinned for it (legacy-releases.txt); any other release that
/// isn't signed, or not by Horizon's key, is refused.
fn pick(
release: &Value,
fetch: impl Fn(&str) -> Result, String>,
keys: &[horizon_release_sign::PublicKey],
) -> Result {
let tag = release["tag_name"]
.as_str()
.ok_or("GitHub's answer has no tag")?;
let assets = release["assets"].as_array().cloned().unwrap_or_default();
let asset = ASSETS
.iter()
.find_map(|name| assets.iter().find(|a| a["name"] == *name))
.ok_or_else(|| {
format!(
"release {tag} has no archive for this computer ({})",
ASSETS.join(", ")
)
})?;
let name = asset["name"].as_str().unwrap_or_default();
// A release from before signing: only the files pinned for it at the time (a rollback).
if let Some(hex) = horizon_release_sign::legacy_digest(tag, name) {
return Ok(Release {
tag: tag.to_owned(),
asset: name.to_owned(),
url: asset["browser_download_url"]
.as_str()
.unwrap_or_default()
.to_owned(),
sha256: hex.to_owned(),
});
}
let attached = |file: &str| -> Result