1use std::fs;
15use std::io::Read;
16use std::path::{Path, PathBuf};
17use sha2::{Sha256, Digest};
18use serde::Deserialize;
19
20use crate::db;
21
22#[derive(Debug, Clone, PartialEq, Deserialize)]
24#[serde(rename_all = "lowercase")]
25pub enum ArchiveFormat {
26 Raw,
27 TarGz,
28 Zip,
29}
30
31impl std::fmt::Display for ArchiveFormat {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 match self {
34 ArchiveFormat::Raw => write!(f, "raw"),
35 ArchiveFormat::TarGz => write!(f, "tar.gz"),
36 ArchiveFormat::Zip => write!(f, "zip"),
37 }
38 }
39}
40
41#[derive(Debug, Clone, Deserialize)]
43pub struct Provider {
44 #[serde(rename = "type")]
45 pub provider_type: String,
46 #[serde(default)]
47 pub url: Option<String>,
48 #[serde(default)]
49 pub path: Option<String>,
50}
51
52#[derive(Debug, Clone, Deserialize)]
54pub struct PlatformEntry {
55 pub path: String,
56 pub hash: String,
57 pub size: u64,
58 pub format: ArchiveFormat,
59 pub providers: Vec<Provider>,
60}
61
62#[derive(Debug, Clone, Deserialize)]
64pub struct ExecutableManifest {
65 #[serde(default)]
66 pub name: Option<String>,
67 #[serde(default)]
68 pub version: Option<String>,
69 pub platforms: std::collections::HashMap<String, PlatformEntry>,
70}
71
72pub fn detect_platform() -> String {
74 let os = std::env::consts::OS;
75 let arch = std::env::consts::ARCH;
76 match (os, arch) {
77 ("macos", "aarch64") => "darwin-arm64".to_string(),
78 ("macos", "x86_64") => "darwin-x86_64".to_string(),
79 ("linux", "x86_64") => "linux-x86_64".to_string(),
80 ("windows", "x86_64") => "windows-amd64".to_string(),
81 _ => format!("{}-{}", os, arch),
82 }
83}
84
85pub fn compute_file_hash(path: &Path) -> Result<String, String> {
87 let mut file = fs::File::open(path)
88 .map_err(|e| format!("Failed to open file {:?}: {}", path, e))?;
89 let mut hasher = Sha256::new();
90 let mut buffer = [0u8; 8192];
91 loop {
92 let n = file.read(&mut buffer)
93 .map_err(|e| format!("Failed to read file: {}", e))?;
94 if n == 0 {
95 break;
96 }
97 hasher.update(&buffer[..n]);
98 }
99 Ok(format!("{:x}", hasher.finalize()))
100}
101
102pub fn verify_hash(path: &Path, expected_hash: &str) -> Result<(), String> {
104 let actual = compute_file_hash(path)?;
105 if actual == expected_hash {
106 Ok(())
107 } else {
108 Err(format!(
109 "Hash mismatch for {:?}: expected {}, got {}",
110 path, expected_hash, actual
111 ))
112 }
113}
114
115pub fn cache_binary(source: &Path, hash: &str) -> Result<PathBuf, String> {
118 let cache_dir = dirs_cache_dir()?;
119 let cache_path = cache_dir.join(hash);
120
121 if cache_path.exists() {
122 if verify_hash(&cache_path, hash).is_ok() {
124 return Ok(cache_path);
125 }
126 #[cfg(unix)]
128 {
129 use std::os::unix::fs::PermissionsExt;
130 let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
131 }
132 let _ = fs::remove_file(&cache_path);
133 }
134
135 fs::create_dir_all(&cache_dir)
137 .map_err(|e| format!("Failed to create cache dir: {}", e))?;
138
139 let nonce = std::time::SystemTime::now()
140 .duration_since(std::time::UNIX_EPOCH)
141 .map(|d| d.as_nanos())
142 .unwrap_or(0);
143 let tmp_path = cache_dir.join(format!("{}.tmp.{}.{}", hash, std::process::id(), nonce));
144
145 fs::copy(source, &tmp_path)
146 .map_err(|e| format!("Failed to copy to cache tmp file: {}", e))?;
147
148 if let Err(_e) = fs::rename(&tmp_path, &cache_path) {
150 let _ = fs::remove_file(&tmp_path);
151 if verify_hash(&cache_path, hash).is_err() {
153 #[cfg(unix)]
154 {
155 use std::os::unix::fs::PermissionsExt;
156 let _ = fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755));
157 }
158 let _ = fs::remove_file(&cache_path);
159 let _ = fs::copy(source, &cache_path);
160 }
161 }
162
163 #[cfg(unix)]
165 {
166 use std::os::unix::fs::PermissionsExt;
167 let perms = fs::Permissions::from_mode(0o555);
168 let _ = fs::set_permissions(&cache_path, perms);
169 }
170
171 Ok(cache_path)
172}
173
174fn dirs_cache_dir() -> Result<PathBuf, String> {
175 if let Ok(home) = crate::layer0::environment::var("HOME") {
176 Ok(PathBuf::from(home).join(".clm").join("cache").join("bin"))
177 } else if let Ok(user_profile) = crate::layer0::environment::var("USERPROFILE") {
178 Ok(PathBuf::from(user_profile).join(".clm").join("cache").join("bin"))
179 } else {
180 Ok(PathBuf::from("/tmp").join("clm-cache").join("bin"))
181 }
182}
183
184fn fetch_from_provider(
186 provider: &Provider,
187 clm_root: &str,
188 dest: &Path,
189) -> Result<PathBuf, String> {
190 match provider.provider_type.as_str() {
191 "local" => {
192 let local_path = provider.path.as_ref().ok_or("Local provider missing path")?;
193 let candidate = if Path::new(local_path).is_absolute() {
195 PathBuf::from(local_path)
196 } else {
197 PathBuf::from(clm_root).join(local_path)
198 };
199 if candidate.exists() && candidate.is_file() {
200 if dest != candidate {
202 fs::copy(&candidate, dest)
203 .map_err(|e| format!("Failed to copy from local provider: {}", e))?;
204 }
205 Ok(dest.to_path_buf())
206 } else {
207 Err(format!("Local provider path not found: {}", candidate.display()))
208 }
209 }
210 "http" | "github-release" => {
211 Err(format!("Provider type '{}' not yet implemented (requires HTTP dependency)", provider.provider_type))
214 }
215 _ => Err(format!("Unknown provider type: {}", provider.provider_type)),
216 }
217}
218
219#[allow(dead_code)]
221fn fetch_from_providers(
222 providers: &[Provider],
223 clm_root: &str,
224 dest: &Path,
225) -> Result<PathBuf, String> {
226 let mut errors = Vec::new();
227 for provider in providers {
228 match fetch_from_provider(provider, clm_root, dest) {
229 Ok(path) => return Ok(path),
230 Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
231 }
232 }
233 Err(format!("All providers failed: {}", errors.join("; ")))
234}
235
236pub fn lookup_manifest(handle: &str, clm_root: &str) -> Result<ExecutableManifest, String> {
238 let content = db::resolve_handle_content(crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY, clm_root, handle)
239 .map_err(|e| format!("DB error looking up handle '{}': {}", handle, e))?
240 .ok_or_else(|| format!("Handle '{}' not found in content_memory", handle))?;
241
242 let manifest: ExecutableManifest = serde_json::from_str(&content)
243 .map_err(|e| format!("Failed to parse manifest JSON: {}", e))?;
244
245 Ok(manifest)
246}
247
248pub fn resolve_binary(handle: &str, clm_root: &str) -> Result<PathBuf, String> {
257 let manifest = lookup_manifest(handle, clm_root)?;
258
259 let platform = detect_platform();
260 let entry = manifest.platforms.get(&platform)
261 .ok_or_else(|| format!("Platform '{}' not found in manifest for handle '{}'", platform, handle))?;
262
263 let temp_dir = std::env::temp_dir().join("clm-manifest-resolve");
265 let _ = fs::create_dir_all(&temp_dir);
266 let temp_dest = temp_dir.join(format!("{}_{}", handle.replace(':', "_"), &entry.hash[..12]));
267
268 let mut errors = Vec::new();
270 let fetched = {
271 let mut result: Option<PathBuf> = None;
272 for provider in &entry.providers {
273 match fetch_from_provider(provider, clm_root, &temp_dest) {
274 Ok(path) => {
275 if !entry.hash.chars().all(|c| c == '0') {
277 match verify_hash(&path, &entry.hash) {
278 Ok(()) => {
279 result = Some(path);
280 break;
281 }
282 Err(e) => {
283 errors.push(format!("{}: hash mismatch ({})", provider.provider_type, e));
284 continue;
285 }
286 }
287 } else {
288 result = Some(path);
289 break;
290 }
291 }
292 Err(e) => errors.push(format!("{}: {}", provider.provider_type, e)),
293 }
294 }
295 match result {
296 Some(p) => p,
297 None => return Err(format!("All providers failed: {}", errors.join("; "))),
298 }
299 };
300
301 let cached = cache_binary(&fetched, &entry.hash)?;
303
304 if cached != fetched {
306 let _ = fs::remove_file(&fetched);
307 }
308
309 Ok(cached)
310}
311
312#[cfg(test)]
313#[path = "manifest_tests.rs"]
314mod tests;