use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use sha2::{Sha256, Digest};
use serde::Deserialize;
use crate::db;
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ArchiveFormat {
Raw,
TarGz,
Zip,
}
impl std::fmt::Display for ArchiveFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ArchiveFormat::Raw => write!(f, "raw"),
ArchiveFormat::TarGz => write!(f, "tar.gz"),
ArchiveFormat::Zip => write!(f, "zip"),
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Provider {
#[serde(rename = "type")]
pub provider_type: String,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub path: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct PlatformEntry {
pub path: String,
pub hash: String,
pub size: u64,
pub format: ArchiveFormat,
pub providers: Vec<Provider>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ExecutableManifest {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub version: Option<String>,
pub platforms: std::collections::HashMap<String, PlatformEntry>,
}
pub fn detect_platform() -> String {
let os = std::env::consts::OS;
let arch = std::env::consts::ARCH;
match (os, arch) {
("macos", "aarch64") => "darwin-arm64".to_string(),
("macos", "x86_64") => "darwin-x86_64".to_string(),
("linux", "x86_64") => "linux-x86_64".to_string(),
("windows", "x86_64") => "windows-amd64".to_string(),
_ => format!("{}-{}", os, arch),
}
}
pub fn compute_file_hash(path: &Path) -> Result<String, String> {
let mut file = fs::File::open(path)
.map_err(|e| format!("Failed to open file {:?}: {}", path, e))?;
let mut hasher = Sha256::new();
let mut buffer = [0u8; 8192];
loop {
let n = file.read(&mut buffer)
.map_err(|e| format!("Failed to read file: {}", e))?;
if n == 0 {
break;
}
hasher.update(&buffer[..n]);
}
Ok(format!("{:x}", hasher.finalize()))
}
pub fn verify_hash(path: &Path, expected_hash: &str) -> Result<(), String> {
let actual = compute_file_hash(path)?;
if actual == expected_hash {
Ok(())
} else {
Err(format!(
"Hash mismatch for {:?}: expected {}, got {}",
path, expected_hash, actual
))
}
}
pub fn cache_binary(source: &Path, hash: &str) -> Result<PathBuf, String> {
let cache_dir = dirs_cache_dir()?;
let cache_path = cache_dir.join(hash);
if cache_path.exists() {
if verify_hash(&cache_path, hash).is_ok() {
return Ok(cache_path);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
}
let _ = fs::remove_file(&cache_path);
}
fs::create_dir_all(&cache_dir)
.map_err(|e| format!("Failed to create cache dir: {}", e))?;
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let tmp_path = cache_dir.join(format!("{}.tmp.{}.{}", hash, std::process::id(), nonce));
fs::copy(source, &tmp_path)
.map_err(|e| format!("Failed to copy to cache tmp file: {}", e))?;
if let Err(_e) = fs::rename(&tmp_path, &cache_path) {
let _ = fs::remove_file(&tmp_path);
if verify_hash(&cache_path, hash).is_err() {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
}
let _ = fs::remove_file(&cache_path);
let _ = fs::copy(source, &cache_path);
}
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = fs::Permissions::from_mode(0o555);
let _ = fs::set_permissions(&cache_path, perms);
}
Ok(cache_path)
}
fn dirs_cache_dir() -> Result<PathBuf, String> {
if let Ok(home) = std::env::var("HOME") {
Ok(PathBuf::from(home).join(".clm").join("cache").join("bin"))
} else if let Ok(user_profile) = std::env::var("USERPROFILE") {
Ok(PathBuf::from(user_profile).join(".clm").join("cache").join("bin"))
} else {
Ok(PathBuf::from("/tmp").join("clm-cache").join("bin"))
}
}
fn fetch_from_provider(
provider: &Provider,
clm_root: &str,
dest: &Path,
) -> Result<PathBuf, String> {
match provider.provider_type.as_str() {
"local" => {
let local_path = provider.path.as_ref().ok_or("Local provider missing path")?;
let candidate = if Path::new(local_path).is_absolute() {
PathBuf::from(local_path)
} else {
PathBuf::from(clm_root).join(local_path)
};
if candidate.exists() && candidate.is_file() {
if dest != candidate {
fs::copy(&candidate, dest)
.map_err(|e| format!("Failed to copy from local provider: {}", e))?;
}
Ok(dest.to_path_buf())
} else {
Err(format!("Local provider path not found: {}", candidate.display()))
}
}
"http" | "github-release" => {
Err(format!("Provider type '{}' not yet implemented (requires HTTP dependency)", provider.provider_type))
}
_ => Err(format!("Unknown provider type: {}", provider.provider_type)),
}
}
#[allow(dead_code)]
fn fetch_from_providers(
providers: &[Provider],
clm_root: &str,
dest: &Path,
) -> Result<PathBuf, String> {
let mut errors = Vec::new();
for provider in providers {
match fetch_from_provider(provider, clm_root, dest) {
Ok(path) => return Ok(path),
Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
}
}
Err(format!("All providers failed: {}", errors.join("; ")))
}
pub fn lookup_manifest(handle: &str, clm_root: &str) -> Result<ExecutableManifest, String> {
let content = db::resolve_handle_content("content_memory", clm_root, handle)
.map_err(|e| format!("DB error looking up handle '{}': {}", handle, e))?
.ok_or_else(|| format!("Handle '{}' not found in content_memory", handle))?;
let manifest: ExecutableManifest = serde_json::from_str(&content)
.map_err(|e| format!("Failed to parse manifest JSON: {}", e))?;
Ok(manifest)
}
pub fn resolve_binary(handle: &str, clm_root: &str) -> Result<PathBuf, String> {
let manifest = lookup_manifest(handle, clm_root)?;
let platform = detect_platform();
let entry = manifest.platforms.get(&platform)
.ok_or_else(|| format!("Platform '{}' not found in manifest for handle '{}'", platform, handle))?;
let temp_dir = std::env::temp_dir().join("clm-manifest-resolve");
let _ = fs::create_dir_all(&temp_dir);
let temp_dest = temp_dir.join(format!("{}_{}", handle.replace(':', "_"), &entry.hash[..12]));
let mut errors = Vec::new();
let fetched = {
let mut result: Option<PathBuf> = None;
for provider in &entry.providers {
match fetch_from_provider(provider, clm_root, &temp_dest) {
Ok(path) => {
if !entry.hash.chars().all(|c| c == '0') {
match verify_hash(&path, &entry.hash) {
Ok(()) => {
result = Some(path);
break;
}
Err(e) => {
errors.push(format!("{}: hash mismatch ({})", provider.provider_type, e));
continue;
}
}
} else {
result = Some(path);
break;
}
}
Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
}
}
match result {
Some(p) => p,
None => return Err(format!("All providers failed: {}", errors.join("; "))),
}
};
let cached = cache_binary(&fetched, &entry.hash)?;
if cached != fetched {
let _ = fs::remove_file(&fetched);
}
Ok(cached)
}
#[cfg(test)]
#[path = "manifest_tests.rs"]
mod tests;