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