use super::{probe_version, Core};
use crate::core::herdr::tools::{release, HerdrInstallation, HerdrUpdate};
use anyhow::{ensure, Context, Result};
use fs2::FileExt;
use serde::Deserialize;
use std::{
collections::HashMap,
io::{Read, Write},
path::{Component, Path, PathBuf},
sync::Mutex,
};
const RELEASES: &str = "https://releases.herdr.dev/core";
static INSTALL: Mutex<()> = Mutex::new(());
#[derive(Deserialize)]
struct Manifest {
version: semver::Version,
generation: u64,
targets: HashMap<String, Asset>,
}
#[derive(Deserialize)]
struct Asset {
url: String,
sha256: String,
}
fn install_root() -> PathBuf {
crate::core::central_repo::home_base_dir().join("tools/herdr-core")
}
pub(crate) fn installed_path() -> Option<PathBuf> {
installed_at(&install_root()).map(|installation| PathBuf::from(installation.path))
}
fn installed_at(root: &Path) -> Option<HerdrInstallation> {
let record: HerdrInstallation =
serde_json::from_slice(&std::fs::read(root.join("current.json")).ok()?).ok()?;
let path = Path::new(&record.path);
(record.managed
&& crate::core::path_guard::is_path_safe(root, path)
&& crate::core::tool_detection::executable(path))
.then_some(record)
}
fn manifest(proxy: Option<&str>) -> Result<Manifest> {
let client = crate::core::skillssh_api::build_http_client(proxy, 15);
let response = client
.get(format!("{RELEASES}/latest.json"))
.send()?
.error_for_status()?;
let mut bytes = Vec::new();
response.take(1024 * 1024 + 1).read_to_end(&mut bytes)?;
ensure!(
bytes.len() <= 1024 * 1024,
"Herdr Core release metadata is too large"
);
let manifest: Manifest = serde_json::from_slice(&bytes)?;
ensure!(
manifest.generation == 1
&& manifest.version.pre.is_empty()
&& manifest.version.build.is_empty(),
"Unsupported Herdr Core release"
);
Ok(manifest)
}
impl Manifest {
fn asset(&self, target: &str) -> Result<&Asset> {
let asset = self
.targets
.get(target)
.context("Herdr Core does not provide a package for this platform")?;
let extension = if target.starts_with("windows-") {
"zip"
} else {
"tar.gz"
};
ensure!(
asset.url
== format!(
"{RELEASES}/{}/herdr-core-{target}.{extension}",
self.version
),
"Unexpected Herdr Core download source"
);
ensure!(
asset.sha256.len() == 64 && hex::decode(&asset.sha256)?.len() == 32,
"Invalid Herdr Core release checksum"
);
Ok(asset)
}
}
pub(crate) fn check_update(proxy: Option<&str>) -> Result<HerdrUpdate> {
let installed = Core::discover()
.context("Herdr Core (hc) is not installed")?
.installation()?;
let remote = manifest(proxy)?;
Ok(HerdrUpdate {
latest_version: remote.version.to_string(),
has_update: remote.version > semver::Version::parse(&installed.version)?,
managed: installed.managed,
})
}
pub(crate) fn install(proxy: Option<&str>, update: bool) -> Result<HerdrInstallation> {
let _guard = INSTALL.lock().unwrap_or_else(|error| error.into_inner());
if let Some(core) = Core::discover() {
let current = core.installation()?;
if !update {
return Ok(current);
}
ensure!(
current.managed,
"Update Herdr Core through its original installation channel"
);
}
let target = release::target()?;
let manifest = manifest(proxy)?;
let asset = manifest.asset(&target)?;
let client = crate::core::skillssh_api::build_http_client(proxy, 120);
let response = client.get(&asset.url).send()?.error_for_status()?;
prepare(&install_root(), &manifest, &target, response)
}
fn prepare(
root: &Path,
manifest: &Manifest,
target: &str,
source: impl Read,
) -> Result<HerdrInstallation> {
let asset = manifest.asset(target)?;
let archive = release::verified_archive(source, &asset.sha256)?;
std::fs::create_dir_all(root)?;
let stage = tempfile::tempdir_in(root)?;
let relative = if target.starts_with("windows-") {
release::unpack_windows(archive, stage.path(), "herdr-core.exe")?
} else {
extract_tar(archive, stage.path())?;
if target.starts_with("macos-") {
PathBuf::from("Herdr Core.app/Contents/MacOS/herdr-core")
} else {
PathBuf::from("herdr-core")
}
};
let staged_binary = stage.path().join(&relative);
ensure!(
probe_version(&staged_binary)? == manifest.version,
"Verified download reports a different Herdr Core version"
);
let destination = root.join("releases").join(format!(
"{}-{target}-{}",
manifest.version,
&asset.sha256[..12],
));
let publish_lock = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(root.join(".install.lock"))?;
FileExt::lock_exclusive(&publish_lock).context("Cannot lock Herdr Core installation")?;
if let Some(current) = installed_at(root) {
if semver::Version::parse(¤t.version).is_ok_and(|version| version > manifest.version)
{
return Ok(current);
}
}
let binary = destination.join(relative);
ensure!(
crate::core::path_guard::is_path_safe(root, &binary),
"Unsafe Herdr Core installation path"
);
std::fs::create_dir_all(
destination
.parent()
.context("Missing Core release directory")?,
)?;
if destination.exists() {
ensure!(
crate::core::path_guard::is_path_safe(root, &binary)
&& probe_version(&binary)? == manifest.version,
"Existing Herdr Core release is invalid"
);
} else {
std::fs::rename(stage.path(), destination)?;
}
let installed = HerdrInstallation {
path: binary
.to_str()
.context("Core installation path must be Unicode")?
.to_owned(),
version: manifest.version.to_string(),
managed: true,
};
let mut record = tempfile::NamedTempFile::new_in(root)?;
record.write_all(&serde_json::to_vec(&installed)?)?;
record.as_file().sync_all()?;
record.persist(root.join("current.json"))?;
super::discovery::invalidate();
Ok(installed)
}
fn extract_tar(archive: impl Read, root: &Path) -> Result<()> {
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(archive));
let mut total = 0_u64;
for (index, entry) in archive.entries()?.enumerate() {
ensure!(index < 512, "Herdr Core archive has too many entries");
let mut entry = entry?;
total = total.saturating_add(entry.size());
ensure!(
total <= release::MAX_DOWNLOAD,
"Herdr Core archive is too large"
);
let path = entry.path()?;
let kind = entry.header().entry_type();
ensure!(
path.components()
.all(|part| matches!(part, Component::Normal(_) | Component::CurDir))
&& (kind.is_file() || kind.is_dir()),
"Unsafe Herdr Core archive entry"
);
ensure!(
entry.unpack_in(root)?,
"Herdr Core archive entry escapes the installation directory"
);
}
Ok(())
}
#[cfg(test)]
#[path = "install_tests.rs"]
mod tests;