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) = std::env::var("HOME") {
176 Ok(PathBuf::from(home).join(".clm").join("cache").join("bin"))
177 } else if let Ok(user_profile) = std::env::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("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)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn test_detect_platform() {
318 let platform = detect_platform();
319 assert!(!platform.is_empty());
320 assert!(platform.contains('-'));
321 }
322
323 #[test]
324 fn test_verify_hash_match() {
325 let dir = std::env::temp_dir().join("clm_manifest_test_hash_match");
326 let _ = fs::create_dir_all(&dir);
327 let test_file = dir.join("test_binary.bin");
328 fs::write(&test_file, b"hello world").unwrap();
329
330 let mut hasher = Sha256::new();
331 hasher.update(b"hello world");
332 let expected = format!("{:x}", hasher.finalize());
333
334 assert!(verify_hash(&test_file, &expected).is_ok());
335
336 let _ = fs::remove_file(&test_file);
337 let _ = fs::remove_dir(&dir);
338 }
339
340 #[test]
341 fn test_verify_hash_mismatch() {
342 let dir = std::env::temp_dir().join("clm_manifest_test_hash_mismatch");
343 let _ = fs::create_dir_all(&dir);
344 let test_file = dir.join("test_binary_mismatch.bin");
345 fs::write(&test_file, b"hello world").unwrap();
346
347 let wrong_hash = "0".repeat(64);
348 let result = verify_hash(&test_file, &wrong_hash);
349 assert!(result.is_err());
350 assert!(result.unwrap_err().contains("Hash mismatch"));
351
352 let _ = fs::remove_file(&test_file);
353 let _ = fs::remove_dir(&dir);
354 }
355
356 #[test]
357 fn test_compute_file_hash() {
358 let dir = std::env::temp_dir().join("clm_manifest_test_compute_hash");
359 let _ = fs::create_dir_all(&dir);
360 let test_file = dir.join("compute_hash_test.bin");
361 fs::write(&test_file, b"test content for hashing").unwrap();
362
363 let hash = compute_file_hash(&test_file).unwrap();
364 assert_eq!(hash.len(), 64);
365 assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
366
367 let _ = fs::remove_file(&test_file);
368 let _ = fs::remove_dir(&dir);
369 }
370
371 #[test]
372 fn test_local_provider_found() {
373 let dir = std::env::temp_dir().join("clm_manifest_test_local_provider");
374 let _ = fs::create_dir_all(&dir);
375 let source = dir.join("source.bin");
376 fs::write(&source, b"binary content").unwrap();
377
378 let dest = dir.join("dest.bin");
379 let provider = Provider {
380 provider_type: "local".to_string(),
381 url: None,
382 path: Some(source.to_string_lossy().to_string()),
383 };
384
385 let result = fetch_from_provider(&provider, "/tmp", &dest);
386 assert!(result.is_ok());
387 assert!(dest.exists());
388
389 let _ = fs::remove_dir_all(&dir);
390 }
391
392 #[test]
393 fn test_local_provider_not_found() {
394 let provider = Provider {
395 provider_type: "local".to_string(),
396 url: None,
397 path: Some("/nonexistent/path/to/binary".to_string()),
398 };
399
400 let result = fetch_from_provider(&provider, "/tmp", Path::new("/tmp/dest.bin"));
401 assert!(result.is_err());
402 }
403
404 #[test]
405 fn test_provider_chain_fallback() {
406 let dir = std::env::temp_dir().join("clm_manifest_test_chain");
407 let _ = fs::create_dir_all(&dir);
408 let source = dir.join("source_chain.bin");
409 fs::write(&source, b"chain content").unwrap();
410
411 let dest = dir.join("dest_chain.bin");
412 let providers = vec![
413 Provider {
414 provider_type: "local".to_string(),
415 url: None,
416 path: Some("/nonexistent/path".to_string()),
417 },
418 Provider {
419 provider_type: "local".to_string(),
420 url: None,
421 path: Some(source.to_string_lossy().to_string()),
422 },
423 ];
424
425 let result = fetch_from_providers(&providers, "/tmp", &dest);
426 assert!(result.is_ok());
427 assert!(dest.exists());
428
429 let _ = fs::remove_dir_all(&dir);
430 }
431
432 #[test]
433 fn test_cache_hit() {
434 let dir = std::env::temp_dir().join("clm_manifest_test_cache_hit");
435 let _ = fs::create_dir_all(&dir);
436 let source = dir.join("source_cache.bin");
437 fs::write(&source, b"cacheable content").unwrap();
438
439 let mut hasher = Sha256::new();
440 hasher.update(b"cacheable content");
441 let hash = format!("{:x}", hasher.finalize());
442
443 let cached1 = cache_binary(&source, &hash).unwrap();
445 assert!(cached1.exists());
446
447 let cached2 = cache_binary(&source, &hash).unwrap();
449 assert_eq!(cached1, cached2);
450
451 let _ = fs::remove_dir_all(&dir);
452 let cache_dir = dirs_cache_dir().unwrap();
454 let _ = fs::remove_file(cache_dir.join(&hash));
455 }
456
457 #[test]
458 fn test_cache_miss_then_hit() {
459 let dir = std::env::temp_dir().join("clm_manifest_test_cache_miss");
460 let _ = fs::create_dir_all(&dir);
461 let source = dir.join("source_miss.bin");
462 fs::write(&source, b"miss then hit content").unwrap();
463
464 let mut hasher = Sha256::new();
465 hasher.update(b"miss then hit content");
466 let hash = format!("{:x}", hasher.finalize());
467
468 let cache_dir = dirs_cache_dir().unwrap();
469 let cache_path = cache_dir.join(&hash);
470 let _ = fs::remove_file(&cache_path);
471
472 let cached = cache_binary(&source, &hash).unwrap();
474 assert!(cached.exists());
475
476 let _ = fs::remove_dir_all(&dir);
478 let _ = fs::remove_file(&cache_path);
479 }
480
481 #[test]
482 fn test_manifest_deserialization() {
483 let json = r#"{
484 "name": "test_binary",
485 "version": "1.0.0",
486 "platforms": {
487 "darwin-arm64": {
488 "path": "/usr/local/bin/test",
489 "hash": "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",
490 "size": 1024,
491 "format": "raw",
492 "providers": [
493 {"type": "local", "path": "/usr/local/bin/test"}
494 ]
495 }
496 }
497 }"#;
498 let manifest: ExecutableManifest = serde_json::from_str(json).unwrap();
499 assert_eq!(manifest.name.as_deref(), Some("test_binary"));
500 assert_eq!(manifest.platforms.len(), 1);
501 let entry = manifest.platforms.get("darwin-arm64").unwrap();
502 assert_eq!(entry.format, ArchiveFormat::Raw);
503 assert_eq!(entry.providers.len(), 1);
504 }
505}