Skip to main content

kh_runtime/bottle/
guest_tools.rs

1//! Optional guest tools installed **into the bottle** at real macOS paths.
2//!
3//! Example: Darwin `7zz` → `{bottle}/usr/local/bin/7zz`, which is guest path
4//! `/usr/local/bin/7zz` — the same place a real Mac would keep a CLI install.
5//! Kakehashi is not a 7-Zip product; packages are opt-in via `kh install`.
6
7use std::fs;
8use std::io;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use super::layout::is_bottle_root;
13use super::manage;
14use super::registry;
15
16/// Env override: host path of a Darwin `7zz` binary (skip download).
17pub const ENV_7ZZ: &str = "KAKEHASHI_7ZZ";
18
19/// Env override: host path of a Darwin `curl` binary (skip download).
20pub const ENV_CURL: &str = "KAKEHASHI_CURL";
21
22/// Legacy ad-hoc drop location (still checked by discovery helpers).
23pub const DEFAULT_7ZZ_PATH: &str = "/tmp/7zz";
24
25/// Official macOS console 7-Zip (universal arm64 / x86_64 Mach-O).
26pub const DARWIN_7ZZ_URL: &str =
27    "https://github.com/ip7z/7zip/releases/download/26.02/7z2602-mac.tar.xz";
28
29/// Public Darwin arm64 static-ish curl (stunnel/static-curl release).
30///
31/// Archive root contains a single `curl` Mach-O. Prefer this over Apple
32/// `/usr/bin/curl` (which needs `libcurl.4.dylib`). Still may link Apple
33/// frameworks for TLS — probe will surface that; see `docs/curl.md`.
34pub const DARWIN_CURL_URL: &str = "https://github.com/stunnel/static-curl/releases/download/8.21.0/curl-macos-arm64-8.21.0.tar.xz";
35
36/// Guest-relative install path for Darwin 7zz (under bottle root).
37///
38/// On a real Mac this is `/usr/local/bin/7zz`.
39pub const GUEST_7ZZ_REL: &str = "usr/local/bin/7zz";
40
41/// Guest-relative install path for Darwin curl (under bottle root).
42///
43/// On a real Mac this is `/usr/local/bin/curl`.
44pub const GUEST_CURL_REL: &str = "usr/local/bin/curl";
45
46/// Known installable package ids (`kh install <name>`).
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum InstallPackage {
49    /// Darwin 7-Zip console (`7zz`).
50    SevenZip,
51    /// Darwin `curl` (downloaded arm64 Mach-O; see `docs/curl.md`).
52    Curl,
53}
54
55impl InstallPackage {
56    /// Parse CLI package name (case-insensitive).
57    #[must_use]
58    pub fn parse(name: &str) -> Option<Self> {
59        match name.to_ascii_lowercase().as_str() {
60            "7zip" | "7zz" | "sevenzip" | "p7zip" => Some(Self::SevenZip),
61            "curl" => Some(Self::Curl),
62            _ => None,
63        }
64    }
65
66    /// Canonical name for messages.
67    #[must_use]
68    pub const fn as_str(self) -> &'static str {
69        match self {
70            Self::SevenZip => "7zip",
71            Self::Curl => "curl",
72        }
73    }
74
75    /// Guest absolute path after install (with leading `/`).
76    #[must_use]
77    pub const fn guest_path(self) -> &'static str {
78        match self {
79            Self::SevenZip => "/usr/local/bin/7zz",
80            Self::Curl => "/usr/local/bin/curl",
81        }
82    }
83}
84
85/// Errors from package install / download.
86#[derive(Debug, thiserror::Error)]
87pub enum ToolError {
88    /// Bottle lifecycle / registry.
89    #[error("{0}")]
90    Bottle(String),
91    /// I/O while creating dirs or writing the binary.
92    #[error("tool I/O: {0}")]
93    Io(#[from] io::Error),
94    /// `curl` / `tar` missing or failed.
95    #[error("{0}")]
96    Command(String),
97    /// Downloaded archive did not contain the expected binary.
98    #[error("expected binary not found in downloaded archive")]
99    MissingBinary,
100    /// Unknown package name.
101    #[error("unknown package `{0}` (known: 7zip, curl)")]
102    UnknownPackage(String),
103}
104
105/// Host path of an installed package inside a bottle, if present.
106#[must_use]
107pub fn package_host_path(bottle: &Path, package: InstallPackage) -> PathBuf {
108    match package {
109        InstallPackage::SevenZip => bottle.join(GUEST_7ZZ_REL),
110        InstallPackage::Curl => bottle.join(GUEST_CURL_REL),
111    }
112}
113
114/// Discover Darwin `7zz` for convenience helpers (not required for `kh run`).
115///
116/// Order: explicit → `KAKEHASHI_7ZZ` → active bottle `/usr/local/bin/7zz` →
117/// legacy `/tmp/7zz` → dev-tree fallbacks.
118#[must_use]
119pub fn discover_7zz(explicit: Option<&Path>) -> Option<PathBuf> {
120    if let Some(p) = explicit {
121        if p.is_file() {
122            return Some(p.to_path_buf());
123        }
124        return None;
125    }
126
127    if let Ok(raw) = std::env::var(ENV_7ZZ) {
128        let p = PathBuf::from(raw);
129        if p.is_file() {
130            return Some(p);
131        }
132    }
133
134    if let Ok(Some(root)) = manage::active_root() {
135        let p = package_host_path(&root, InstallPackage::SevenZip);
136        if p.is_file() {
137            return Some(p);
138        }
139    }
140
141    let default = Path::new(DEFAULT_7ZZ_PATH);
142    if default.is_file() {
143        return Some(default.to_path_buf());
144    }
145
146    for rel in [
147        "tests/clang-probe/7zz.bin",
148        "tests/fixtures/7zz",
149        "tests/fixtures/bin/7zz",
150        "tests/clang-probe/7zz",
151    ] {
152        let p = PathBuf::from(rel);
153        if p.is_file() {
154            return Some(p);
155        }
156    }
157
158    None
159}
160
161/// Install a named package into the active bottle (creating the bottle if needed).
162pub fn install_package(name: &str) -> Result<InstallReport, ToolError> {
163    let package =
164        InstallPackage::parse(name).ok_or_else(|| ToolError::UnknownPackage(name.to_owned()))?;
165    match package {
166        InstallPackage::SevenZip => install_sevenzip(),
167        InstallPackage::Curl => install_curl(),
168    }
169}
170
171/// Result of a successful [`install_package`].
172#[derive(Debug, Clone)]
173pub struct InstallReport {
174    /// Package id.
175    pub package: &'static str,
176    /// Absolute host path of the installed binary.
177    pub host_path: PathBuf,
178    /// Guest absolute path (macOS layout).
179    pub guest_path: &'static str,
180    /// Bottle root used.
181    pub bottle: PathBuf,
182}
183
184fn ensure_active_bottle() -> Result<PathBuf, ToolError> {
185    if let Ok(Some(root)) = manage::active_root()
186        && is_bottle_root(&root)
187    {
188        return Ok(root);
189    }
190    let created = manage::ensure(&manage::CreateOptions {
191        path: None,
192        libsystem: None,
193        skip_libsystem: false,
194    })
195    .map_err(|e| ToolError::Bottle(e.to_string()))?;
196    Ok(created.path)
197}
198
199fn install_sevenzip() -> Result<InstallReport, ToolError> {
200    let bottle = ensure_active_bottle()?;
201    let dest = package_host_path(&bottle, InstallPackage::SevenZip);
202    if let Some(parent) = dest.parent() {
203        fs::create_dir_all(parent)?;
204    }
205
206    // Prefer env override (already a binary) over download.
207    if let Ok(raw) = std::env::var(ENV_7ZZ) {
208        let src = PathBuf::from(raw);
209        if src.is_file() {
210            fs::copy(&src, &dest)?;
211            set_executable(&dest)?;
212            return Ok(InstallReport {
213                package: InstallPackage::SevenZip.as_str(),
214                host_path: dest,
215                guest_path: InstallPackage::SevenZip.guest_path(),
216                bottle,
217            });
218        }
219    }
220
221    let tmp_root = registry::data_dir()?.join(".kh-dl");
222    drop(fs::remove_dir_all(&tmp_root));
223    fs::create_dir_all(&tmp_root)?;
224    let archive = tmp_root.join("7z-mac.tar.xz");
225    download_url(DARWIN_7ZZ_URL, &archive)?;
226
227    let status = Command::new("tar")
228        .args(["-xJf"])
229        .arg(&archive)
230        .current_dir(&tmp_root)
231        .status()
232        .map_err(|e| ToolError::Command(format!("tar: {e}")))?;
233    if !status.success() {
234        drop(fs::remove_dir_all(&tmp_root));
235        return Err(ToolError::Command(format!(
236            "tar extract failed (status {status})"
237        )));
238    }
239
240    let found = find_named_file(&tmp_root, "7zz").ok_or(ToolError::MissingBinary)?;
241    if dest.exists() {
242        drop(fs::remove_file(&dest));
243    }
244    fs::copy(&found, &dest)?;
245    set_executable(&dest)?;
246    drop(fs::remove_dir_all(&tmp_root));
247
248    Ok(InstallReport {
249        package: InstallPackage::SevenZip.as_str(),
250        host_path: dest,
251        guest_path: InstallPackage::SevenZip.guest_path(),
252        bottle,
253    })
254}
255
256/// Install Darwin `curl` into the bottle at `/usr/local/bin/curl`.
257///
258/// Order: `KAKEHASHI_CURL` (already a binary) → download [`DARWIN_CURL_URL`]
259/// and extract the `curl` Mach-O from the tarball.
260fn install_curl() -> Result<InstallReport, ToolError> {
261    let bottle = ensure_active_bottle()?;
262    let dest = package_host_path(&bottle, InstallPackage::Curl);
263    if let Some(parent) = dest.parent() {
264        fs::create_dir_all(parent)?;
265    }
266
267    // Prefer env override (already a binary) over download.
268    if let Ok(raw) = std::env::var(ENV_CURL) {
269        let src = PathBuf::from(raw);
270        if src.is_file() {
271            if dest.exists() {
272                drop(fs::remove_file(&dest));
273            }
274            fs::copy(&src, &dest)?;
275            set_executable(&dest)?;
276            return Ok(InstallReport {
277                package: InstallPackage::Curl.as_str(),
278                host_path: dest,
279                guest_path: InstallPackage::Curl.guest_path(),
280                bottle,
281            });
282        }
283    }
284
285    let tmp_root = registry::data_dir()?.join(".kh-dl-curl");
286    drop(fs::remove_dir_all(&tmp_root));
287    fs::create_dir_all(&tmp_root)?;
288    let archive = tmp_root.join("curl-macos-arm64.tar.xz");
289    download_url(DARWIN_CURL_URL, &archive)?;
290
291    let status = Command::new("tar")
292        .args(["-xJf"])
293        .arg(&archive)
294        .current_dir(&tmp_root)
295        .status()
296        .map_err(|e| ToolError::Command(format!("tar: {e}")))?;
297    if !status.success() {
298        drop(fs::remove_dir_all(&tmp_root));
299        return Err(ToolError::Command(format!(
300            "tar extract failed (status {status})"
301        )));
302    }
303
304    let found = find_named_file(&tmp_root, "curl").ok_or(ToolError::MissingBinary)?;
305    // Avoid copying the archive itself if it were ever named `curl`.
306    if found == archive {
307        drop(fs::remove_dir_all(&tmp_root));
308        return Err(ToolError::MissingBinary);
309    }
310    if dest.exists() {
311        drop(fs::remove_file(&dest));
312    }
313    fs::copy(&found, &dest)?;
314    set_executable(&dest)?;
315    drop(fs::remove_dir_all(&tmp_root));
316
317    Ok(InstallReport {
318        package: InstallPackage::Curl.as_str(),
319        host_path: dest,
320        guest_path: InstallPackage::Curl.guest_path(),
321        bottle,
322    })
323}
324
325/// Discover Darwin `curl` for convenience helpers.
326///
327/// Order: explicit → `KAKEHASHI_CURL` → active bottle `/usr/local/bin/curl`.
328#[must_use]
329pub fn discover_curl(explicit: Option<&Path>) -> Option<PathBuf> {
330    if let Some(p) = explicit {
331        if p.is_file() {
332            return Some(p.to_path_buf());
333        }
334        return None;
335    }
336
337    if let Ok(raw) = std::env::var(ENV_CURL) {
338        let p = PathBuf::from(raw);
339        if p.is_file() {
340            return Some(p);
341        }
342    }
343
344    if let Ok(Some(root)) = manage::active_root() {
345        let p = package_host_path(&root, InstallPackage::Curl);
346        if p.is_file() {
347            return Some(p);
348        }
349    }
350
351    None
352}
353
354fn set_executable(path: &Path) -> io::Result<()> {
355    #[cfg(unix)]
356    {
357        use std::os::unix::fs::PermissionsExt;
358        let mut perms = fs::metadata(path)?.permissions();
359        perms.set_mode(0o755);
360        fs::set_permissions(path, perms)?;
361    }
362    let _ = path;
363    Ok(())
364}
365
366fn download_url(url: &str, dest: &Path) -> Result<(), ToolError> {
367    let curl = Command::new("curl")
368        .args(["-fsSL", "--retry", "3", "-o"])
369        .arg(dest)
370        .arg(url)
371        .status();
372    match curl {
373        Ok(st) if st.success() => return Ok(()),
374        Ok(_) | Err(_) => {}
375    }
376    let wget = Command::new("wget")
377        .args(["-q", "-O"])
378        .arg(dest)
379        .arg(url)
380        .status()
381        .map_err(|e| {
382            ToolError::Command(format!(
383                "download failed: need curl or wget ({e}); url={url}"
384            ))
385        })?;
386    if !wget.success() {
387        return Err(ToolError::Command(format!(
388            "download failed (curl/wget); url={url}"
389        )));
390    }
391    Ok(())
392}
393
394fn find_named_file(root: &Path, name: &str) -> Option<PathBuf> {
395    let mut stack = vec![root.to_path_buf()];
396    while let Some(dir) = stack.pop() {
397        let entries = fs::read_dir(&dir).ok()?;
398        for ent in entries.flatten() {
399            let p = ent.path();
400            if p.is_dir() {
401                stack.push(p);
402            } else if p.file_name().is_some_and(|n| n == name) {
403                return Some(p);
404            }
405        }
406    }
407    None
408}
409
410/// Default guest `PATH` components (macOS-like) used when resolving bare names.
411pub const GUEST_PATH_DIRS: &[&str] = &["/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"];
412
413/// Resolve a program path for `kh run`.
414///
415/// * Absolute or relative with `/` → unchanged (host path or guest path string).
416/// * Bare name → search bottle under [`GUEST_PATH_DIRS`] (host files that exist).
417#[must_use]
418pub fn resolve_guest_program(spec: &Path, bottle: Option<&Path>) -> PathBuf {
419    let s = spec.as_os_str();
420    // Has path separator → user gave an explicit path.
421    if spec.components().count() > 1 || s.to_string_lossy().contains('/') {
422        return spec.to_path_buf();
423    }
424    let name = spec.file_name().unwrap_or(s);
425    let Some(root) = bottle else {
426        return spec.to_path_buf();
427    };
428    for dir in GUEST_PATH_DIRS {
429        // dir is "/usr/local/bin" → relative "usr/local/bin"
430        let rel = dir.trim_start_matches('/');
431        let candidate = root.join(rel).join(name);
432        if candidate.is_file() {
433            // Return guest absolute path so loader + path translation stay consistent.
434            return PathBuf::from(dir).join(name);
435        }
436    }
437    spec.to_path_buf()
438}
439
440/// Map guest absolute path to host under bottle (for opening the Mach-O file).
441#[must_use]
442pub fn guest_path_to_host(bottle: &Path, guest: &Path) -> PathBuf {
443    let g = guest.to_string_lossy();
444    if g.starts_with('/') {
445        bottle.join(g.trim_start_matches('/'))
446    } else {
447        guest.to_path_buf()
448    }
449}
450
451#[cfg(test)]
452#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
453mod tests {
454    use super::*;
455    use std::sync::atomic::{AtomicU64, Ordering};
456
457    fn unique(prefix: &str) -> PathBuf {
458        static N: AtomicU64 = AtomicU64::new(0);
459        let n = N.fetch_add(1, Ordering::Relaxed);
460        std::env::temp_dir().join(format!("kh-7zz-{}-{}-{n}", prefix, std::process::id()))
461    }
462
463    #[test]
464    fn parse_package_names() {
465        assert_eq!(
466            InstallPackage::parse("7zip"),
467            Some(InstallPackage::SevenZip)
468        );
469        assert_eq!(InstallPackage::parse("7ZZ"), Some(InstallPackage::SevenZip));
470        assert_eq!(InstallPackage::parse("curl"), Some(InstallPackage::Curl));
471        assert_eq!(InstallPackage::parse("CURL"), Some(InstallPackage::Curl));
472        assert!(InstallPackage::parse("foo").is_none());
473    }
474
475    #[test]
476    fn resolve_bare_name_in_bottle() {
477        let root = unique("path");
478        let bin = root.join("usr/local/bin");
479        fs::create_dir_all(&bin).expect("dirs");
480        let tool = bin.join("7zz");
481        fs::write(&tool, b"x").expect("write");
482        let resolved = resolve_guest_program(Path::new("7zz"), Some(&root));
483        assert_eq!(resolved, PathBuf::from("/usr/local/bin/7zz"));
484        drop(fs::remove_dir_all(&root));
485    }
486
487    #[test]
488    fn discover_explicit_path() {
489        let path = unique("bin");
490        std::fs::write(&path, b"not-a-real-macho").expect("write");
491        let found = discover_7zz(Some(&path)).expect("explicit");
492        assert_eq!(found, path);
493        drop(std::fs::remove_file(&path));
494        assert!(discover_7zz(Some(&path)).is_none());
495    }
496
497    #[test]
498    fn find_nested_name() {
499        let root = unique("tree");
500        fs::create_dir_all(root.join("a/b")).expect("dirs");
501        let target = root.join("a/b/7zz");
502        fs::write(&target, b"x").expect("write");
503        assert_eq!(find_named_file(&root, "7zz"), Some(target));
504        drop(fs::remove_dir_all(&root));
505    }
506}