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