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