Skip to main content

kh_runtime/bottle/
manage.rs

1//! Create / destroy / query the single Kakehashi bottle.
2//!
3//! Guest `libSystem.B.dylib` is installed from disk discovery first, then from
4//! the freestanding dylib **embedded** in this crate (`resources/libSystem.B.dylib`).
5//! That file is published on crates.io with `kh-runtime`, so
6//! `cargo install kakehashi` → `kh bottle ensure` needs no separate dylib.
7
8use std::path::{Path, PathBuf};
9
10use thiserror::Error;
11
12use super::layout;
13use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
14use super::registry;
15use super::xcrun_tool::{self, XcrunInstall, XcrunOrigin};
16
17/// Freestanding guest libSystem shipped with this crate (crates.io / cargo install).
18///
19/// Refresh after rebuilding `kh-libsystem` with `./scripts/stage-libsystem.sh`.
20static EMBEDDED_LIBSYSTEM: &[u8] = include_bytes!("../../resources/libSystem.B.dylib");
21
22/// Clean-room guest `xcrun` shipped with this crate (crates.io / cargo install).
23///
24/// Refresh after rebuilding `kh-xcrun` with `./scripts/stage-xcrun.sh`.
25/// Empty file is treated as "not embedded" so Linux-only checkouts without a
26/// staged Mach-O still compile; `bottle ensure` then skips xcrun install.
27static EMBEDDED_XCRUN: &[u8] = include_bytes!("../../resources/xcrun");
28
29/// Bottle management errors.
30#[derive(Debug, Error)]
31pub enum BottleError {
32    /// A bottle is already registered (create refused).
33    #[error(
34        "a bottle already exists at {path}\n\
35         create a new one only after deleting the current bottle:\n\
36           kh bottle destroy"
37    )]
38    AlreadyExists {
39        /// Absolute path of the existing bottle.
40        path: PathBuf,
41    },
42
43    /// Destroy requested but no bottle is registered.
44    #[error("no bottle is registered (nothing to destroy)")]
45    NotRegistered,
46
47    /// Registry points at a path that is not a valid bottle.
48    #[error("path is not a kakehashi bottle (missing marker): {0}")]
49    NotABottle(PathBuf),
50
51    /// Destroy refused because confirmation was not given.
52    #[error("destroy cancelled (confirmation required)")]
53    NotConfirmed,
54
55    /// `--libsystem` / env pointed at a path that is not a readable file.
56    #[error("libSystem source not found: {0}")]
57    LibsystemNotFound(PathBuf),
58
59    /// Underlying I/O failure.
60    #[error(transparent)]
61    Io(#[from] std::io::Error),
62}
63
64/// Snapshot of the registered bottle.
65#[derive(Debug, Clone, PartialEq, Eq)]
66#[allow(clippy::struct_excessive_bools)] // independent presence flags for CLI/status
67pub struct BottleStatus {
68    /// Absolute path from the registry (directory name is user-chosen).
69    pub path: PathBuf,
70    /// Whether the path exists on disk.
71    pub exists: bool,
72    /// Whether the path has a valid `.kakehashi-bottle` marker.
73    pub valid_marker: bool,
74    /// Whether `{path}/usr/lib/libSystem.B.dylib` is present.
75    pub libsystem: bool,
76    /// Whether `{path}/usr/lib/libc++.1.dylib` → `libSystem.B.dylib` alias exists.
77    pub libcxx_alias: bool,
78    /// Whether `{path}/usr/lib/libcurl.4.dylib` → `libSystem.B.dylib` alias exists.
79    pub libcurl_alias: bool,
80}
81
82/// Options for [`create`].
83#[derive(Debug, Clone, Default)]
84pub struct CreateOptions<'a> {
85    /// Bottle directory (default data path when `None`).
86    pub path: Option<&'a Path>,
87    /// Explicit guest dylib to install (`--libsystem`).
88    pub libsystem: Option<&'a Path>,
89    /// Skip searching/installing libSystem (skeleton only).
90    pub skip_libsystem: bool,
91}
92
93/// Result of a successful [`create`].
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct CreateResult {
96    /// Absolute bottle root.
97    pub path: PathBuf,
98    /// libSystem install details when a source was found and copied.
99    pub libsystem: Option<LibsystemInstall>,
100    /// Guest `/usr/bin/xcrun` install details when a source was found.
101    pub xcrun: Option<XcrunInstall>,
102}
103
104/// Creates the single bottle at `path` (or the default data path when `None`).
105///
106/// Fails if a bottle is already registered and still present on disk. A stale
107/// registry entry (path missing) is cleared automatically so create can proceed.
108///
109/// After the skeleton is written, installs guest `libSystem.B.dylib` when a
110/// source is discovered (see [`libsystem::discover`]) or from the crate-embedded
111/// freestanding dylib, unless [`CreateOptions::skip_libsystem`] is set.
112/// An explicit `--libsystem` path that does not exist is an error.
113pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
114    create_with(&CreateOptions {
115        path,
116        ..CreateOptions::default()
117    })
118}
119
120/// Creates a bottle with full options (libSystem path / skip).
121pub fn create_with(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
122    if let Some(active) = registry::read_active()? {
123        if active.exists() {
124            return Err(BottleError::AlreadyExists { path: active });
125        }
126        // Stale pointer — drop it and continue.
127        registry::clear_active()?;
128    }
129
130    let target = match opts.path {
131        Some(p) => absolute(p)?,
132        None => registry::default_bottle_path()?,
133    };
134
135    if layout::is_bottle_root(&target) {
136        // Directory looks like a bottle but was not registered — refuse to
137        // clobber; register it only after explicit destroy of its tree, or
138        // treat as already-exists at that path.
139        return Err(BottleError::AlreadyExists { path: target });
140    }
141
142    if target.exists() && target.read_dir()?.next().is_some() {
143        // Non-empty non-bottle directory: do not silently overwrite.
144        return Err(BottleError::Io(std::io::Error::new(
145            std::io::ErrorKind::AlreadyExists,
146            format!(
147                "refusing to create bottle in non-empty directory: {}",
148                target.display()
149            ),
150        )));
151    }
152
153    layout::materialize(&target)?;
154
155    let libsystem = match install_libsystem_for_create(&target, opts) {
156        Ok(v) => v,
157        Err(err) => {
158            drop(layout::remove_tree(&target));
159            return Err(err);
160        }
161    };
162
163    let xcrun = match install_xcrun_for_create(&target) {
164        Ok(v) => v,
165        Err(err) => {
166            drop(layout::remove_tree(&target));
167            return Err(err);
168        }
169    };
170
171    if let Err(e) = super::ca_bundle::ensure_ca_bundle(&target) {
172        tracing::warn!(error = %e, "failed to seed bottle CA bundle");
173    }
174
175    registry::write_active(&target)?;
176    Ok(CreateResult {
177        path: target,
178        libsystem,
179        xcrun,
180    })
181}
182
183fn install_libsystem_for_create(
184    target: &Path,
185    opts: &CreateOptions<'_>,
186) -> Result<Option<LibsystemInstall>, BottleError> {
187    if opts.skip_libsystem {
188        return Ok(None);
189    }
190    if let Some(explicit) = opts.libsystem {
191        if !explicit.is_file() {
192            return Err(BottleError::LibsystemNotFound(explicit.to_path_buf()));
193        }
194        return Ok(Some(libsystem::install(
195            target,
196            explicit,
197            LibsystemOrigin::Explicit,
198        )?));
199    }
200    if let Some((src, origin)) = libsystem::discover(None) {
201        return Ok(Some(libsystem::install(target, &src, origin)?));
202    }
203
204    // crates.io / cargo install: freestanding dylib is vendored in this crate.
205    if !EMBEDDED_LIBSYSTEM.is_empty() {
206        return Ok(Some(libsystem::install_bytes(
207            target,
208            EMBEDDED_LIBSYSTEM,
209            LibsystemOrigin::Embedded,
210        )?));
211    }
212
213    Ok(None)
214}
215
216fn install_xcrun_for_create(target: &Path) -> Result<Option<XcrunInstall>, BottleError> {
217    if let Some((src, origin)) = xcrun_tool::discover(None) {
218        return Ok(Some(xcrun_tool::install(target, &src, origin)?));
219    }
220    if !EMBEDDED_XCRUN.is_empty() {
221        return Ok(Some(xcrun_tool::install_bytes(
222            target,
223            EMBEDDED_XCRUN,
224            XcrunOrigin::Embedded,
225        )?));
226    }
227    Ok(None)
228}
229
230/// Destroys the registered bottle after `confirmed` is true.
231///
232/// When `confirmed` is false, returns [`BottleError::NotConfirmed`] without
233/// touching the filesystem (CLI prompts, then retries with `true`).
234pub fn destroy(confirmed: bool) -> Result<PathBuf, BottleError> {
235    let Some(path) = registry::read_active()? else {
236        return Err(BottleError::NotRegistered);
237    };
238
239    if !confirmed {
240        return Err(BottleError::NotConfirmed);
241    }
242
243    if path.exists() {
244        if layout::is_bottle_root(&path) {
245            layout::remove_tree(&path)?;
246        } else if path.is_dir() {
247            // Registry path exists but marker missing — refuse blind rm -rf.
248            return Err(BottleError::NotABottle(path));
249        }
250        // If path is a leftover file or already gone after check, still clear.
251    }
252
253    registry::clear_active()?;
254    Ok(path)
255}
256
257/// Returns status of the registered bottle, if any.
258pub fn status() -> Result<Option<BottleStatus>, BottleError> {
259    let Some(path) = registry::read_active()? else {
260        return Ok(None);
261    };
262    let exists = path.exists();
263    let valid_marker = exists && layout::is_bottle_root(&path);
264    let libsystem = exists && path.join(libsystem::GUEST_LIBSYSTEM_REL).is_file();
265    let libcxx_alias = exists && layout::has_libcxx_symlink(&path);
266    let libcurl_alias = exists && layout::has_libcurl_symlink(&path);
267    Ok(Some(BottleStatus {
268        path,
269        exists,
270        valid_marker,
271        libsystem,
272        libcxx_alias,
273        libcurl_alias,
274    }))
275}
276
277/// Returns the active bottle path when registered and valid on disk.
278///
279/// Used by CLI root resolution as a fallback after `--root` / `KAKEHASHI_ROOT`.
280pub fn active_root() -> Result<Option<PathBuf>, BottleError> {
281    match status()? {
282        Some(s) if s.exists && s.valid_marker => Ok(Some(s.path)),
283        _ => Ok(None),
284    }
285}
286
287/// Idempotent bottle setup: create when missing, refresh libSystem when present.
288///
289/// ```text
290/// # After cargo install kakehashi (uses embedded freestanding libSystem):
291/// kh bottle ensure
292///
293/// # Dev: override with a just-built / staged dylib
294/// kh bottle ensure --libsystem crates/kh-runtime/resources/libSystem.B.dylib
295/// ```
296///
297/// * Valid registered bottle → reinstalls libSystem (unless `skip_libsystem`).
298/// * Unregistered path that already has a bottle marker → adopt + refresh.
299/// * Otherwise → same as [`create_with`].
300/// * Explicit `--libsystem` that is missing is always an error.
301pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
302    if let Some(path) = active_root()? {
303        return refresh_bottle(&path, opts);
304    }
305
306    // Adopt a marker'd bottle that is not in the registry (e.g. after wiping
307    // KAKEHASHI_CONFIG_DIR but keeping the tree, or a previous manual path).
308    if let Some(p) = opts.path {
309        let abs = absolute(p)?;
310        if layout::is_bottle_root(&abs) {
311            return refresh_bottle(&abs, opts);
312        }
313    } else if let Ok(def) = registry::default_bottle_path()
314        && layout::is_bottle_root(&def)
315    {
316        return refresh_bottle(&def, opts);
317    }
318
319    create_with(opts)
320}
321
322fn refresh_bottle(path: &Path, opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
323    layout::ensure_libcxx_symlink(path)?;
324    layout::ensure_libcurl_symlink(path)?;
325    layout::ensure_libxar_symlink(path)?;
326    layout::ensure_libz_symlink(path)?;
327    layout::ensure_dev_nodes(path)?;
328    layout::ensure_host_ssh_bridge(path)?;
329    layout::ensure_host_bin_bridges(path)?;
330    let libsystem = install_libsystem_for_create(path, opts)?;
331    let xcrun = install_xcrun_for_create(path)?;
332    // Mozilla / host CA bundle for OpenSSL CAfile + SecTrust host verify.
333    if let Err(e) = super::ca_bundle::ensure_ca_bundle(path) {
334        tracing::warn!(error = %e, "failed to seed bottle CA bundle");
335    }
336    registry::write_active(path)?;
337    Ok(CreateResult {
338        path: path.to_path_buf(),
339        libsystem,
340        xcrun,
341    })
342}
343
344fn absolute(path: &Path) -> Result<PathBuf, BottleError> {
345    if path.is_absolute() {
346        return Ok(path.to_path_buf());
347    }
348    let cwd = std::env::current_dir()?;
349    Ok(cwd.join(path))
350}
351
352#[cfg(test)]
353#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
354mod tests {
355    use super::*;
356    use crate::bottle::registry::test_env_lock;
357    use std::sync::atomic::{AtomicU64, Ordering};
358
359    fn unique(prefix: &str) -> PathBuf {
360        static N: AtomicU64 = AtomicU64::new(0);
361        let n = N.fetch_add(1, Ordering::Relaxed);
362        std::env::temp_dir().join(format!("kh-manage-{}-{}-{n}", prefix, std::process::id()))
363    }
364
365    struct EnvGuard {
366        cfg: PathBuf,
367        data: PathBuf,
368    }
369
370    impl EnvGuard {
371        fn new() -> Self {
372            let cfg = unique("cfg");
373            let data = unique("data");
374            drop(std::fs::remove_dir_all(&cfg));
375            drop(std::fs::remove_dir_all(&data));
376            std::fs::create_dir_all(&cfg).expect("cfg");
377            std::fs::create_dir_all(&data).expect("data");
378            // SAFETY: serialized by test_env_lock; EnvGuard restores on drop.
379            unsafe {
380                std::env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
381                std::env::set_var("KAKEHASHI_DATA_DIR", &data);
382            }
383            Self { cfg, data }
384        }
385    }
386
387    impl Drop for EnvGuard {
388        fn drop(&mut self) {
389            // SAFETY: paired with set_var in new(); still under test_env_lock.
390            unsafe {
391                std::env::remove_var("KAKEHASHI_CONFIG_DIR");
392                std::env::remove_var("KAKEHASHI_DATA_DIR");
393            }
394            drop(std::fs::remove_dir_all(&self.cfg));
395            drop(std::fs::remove_dir_all(&self.data));
396        }
397    }
398
399    #[test]
400    fn create_default_then_second_fails() {
401        let _lock = test_env_lock();
402        let g = EnvGuard::new();
403
404        let created = create_with(&CreateOptions {
405            skip_libsystem: true,
406            ..CreateOptions::default()
407        })
408        .expect("create");
409        let path = created.path;
410        assert!(layout::is_bottle_root(&path));
411        assert_eq!(path, g.data.join("bottle"));
412        assert!(path.join("Volumes/linux").is_symlink());
413        assert!(created.libsystem.is_none());
414
415        let err = create(None).expect_err("second create");
416        assert!(matches!(err, BottleError::AlreadyExists { .. }));
417
418        let destroyed = destroy(true).expect("destroy");
419        assert_eq!(destroyed, path);
420        assert!(!path.exists());
421        assert!(status().expect("status").is_none());
422    }
423
424    #[test]
425    fn create_custom_path_and_rename_survives_registry_update() {
426        let _lock = test_env_lock();
427        let _g = EnvGuard::new();
428
429        let custom = unique("custom-bottle-name");
430        let created = create_with(&CreateOptions {
431            path: Some(&custom),
432            skip_libsystem: true,
433            ..CreateOptions::default()
434        })
435        .expect("create custom");
436        let path = created.path;
437        assert_eq!(path, custom);
438        assert!(layout::is_bottle_root(&path));
439
440        // User renames the bottle directory — registry still points at old path.
441        let renamed = unique("renamed-by-user");
442        std::fs::rename(&path, &renamed).expect("rename");
443        // Stale: exists=false after rename of registered path.
444        let st = status().expect("status").expect("some");
445        assert!(!st.exists);
446
447        // Create should clear stale and succeed at a new path.
448        let again = unique("after-rename");
449        let path2 = create_with(&CreateOptions {
450            path: Some(&again),
451            skip_libsystem: true,
452            ..CreateOptions::default()
453        })
454        .expect("create after stale");
455        assert!(layout::is_bottle_root(&path2.path));
456
457        destroy(true).expect("destroy");
458        drop(std::fs::remove_dir_all(&renamed));
459    }
460
461    #[test]
462    fn destroy_requires_confirmation() {
463        let _lock = test_env_lock();
464        let _g = EnvGuard::new();
465
466        let path = create_with(&CreateOptions {
467            skip_libsystem: true,
468            ..CreateOptions::default()
469        })
470        .expect("create")
471        .path;
472        let err = destroy(false).expect_err("need confirm");
473        assert!(matches!(err, BottleError::NotConfirmed));
474        assert!(path.exists());
475        destroy(true).expect("destroy");
476    }
477
478    #[test]
479    fn volumes_linux_rw_outside_bottle() {
480        let _lock = test_env_lock();
481        let _g = EnvGuard::new();
482
483        let root = create_with(&CreateOptions {
484            skip_libsystem: true,
485            ..CreateOptions::default()
486        })
487        .expect("create")
488        .path;
489        let token = format!("kh-manage-vol-{}", std::process::id());
490        let host_file = std::env::temp_dir().join(&token);
491        let payload = b"rw-outside\n";
492        std::fs::write(&host_file, payload).expect("host write");
493
494        let via = root
495            .join(layout::VOLUMES_LINUX)
496            .join(host_file.strip_prefix("/").expect("abs"));
497        assert_eq!(std::fs::read(&via).expect("via read"), payload);
498
499        let payload2 = b"from-bottle-side\n";
500        std::fs::write(&via, payload2).expect("via write");
501        assert_eq!(std::fs::read(&host_file).expect("host read"), payload2);
502
503        drop(std::fs::remove_file(&host_file));
504        destroy(true).expect("destroy");
505    }
506
507    #[test]
508    fn create_installs_explicit_libsystem() {
509        let _lock = test_env_lock();
510        let _g = EnvGuard::new();
511
512        // Staged freestanding guest dylib (crate resources/).
513        let libsystem = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
514            .join("resources/libSystem.B.dylib");
515        assert!(
516            libsystem.is_file(),
517            "missing {}",
518            libsystem.display()
519        );
520
521        let created = create_with(&CreateOptions {
522            libsystem: Some(&libsystem),
523            ..CreateOptions::default()
524        })
525        .expect("create with libsystem");
526        assert!(created.libsystem.is_some());
527        let dest = created.path.join(libsystem::GUEST_LIBSYSTEM_REL);
528        assert!(dest.is_file());
529        let st = status().expect("status").expect("registered");
530        assert!(st.libsystem);
531        assert!(st.libcxx_alias);
532        assert!(st.libcurl_alias);
533        assert!(layout::has_libcxx_symlink(&created.path));
534        assert!(layout::has_libcurl_symlink(&created.path));
535
536        destroy(true).expect("destroy");
537    }
538
539    #[test]
540    fn ensure_creates_then_refreshes_libsystem() {
541        let _lock = test_env_lock();
542        let _g = EnvGuard::new();
543
544        let libsystem = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
545            .join("resources/libSystem.B.dylib");
546        assert!(libsystem.is_file());
547
548        let first = ensure(&CreateOptions {
549            libsystem: Some(&libsystem),
550            ..CreateOptions::default()
551        })
552        .expect("ensure create");
553        assert!(first.libsystem.is_some());
554        let dest = first.path.join(libsystem::GUEST_LIBSYSTEM_REL);
555        let before = std::fs::metadata(&dest).expect("meta").len();
556
557        // Second ensure reuses the same bottle and reinstalls the dylib.
558        let second = ensure(&CreateOptions {
559            libsystem: Some(&libsystem),
560            ..CreateOptions::default()
561        })
562        .expect("ensure refresh");
563        assert_eq!(second.path, first.path);
564        assert!(second.libsystem.is_some());
565        assert!(dest.is_file());
566        let after = std::fs::metadata(&dest).expect("meta2").len();
567        assert_eq!(before, after);
568
569        destroy(true).expect("destroy");
570    }
571}