1use std::path::{Path, PathBuf};
9
10use thiserror::Error;
11
12use super::layout;
13use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
14use super::registry;
15
16static EMBEDDED_LIBSYSTEM: &[u8] = include_bytes!("../../resources/libSystem.B.dylib");
20
21#[derive(Debug, Error)]
23pub enum BottleError {
24 #[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 path: PathBuf,
33 },
34
35 #[error("no bottle is registered (nothing to destroy)")]
37 NotRegistered,
38
39 #[error("path is not a kakehashi bottle (missing marker): {0}")]
41 NotABottle(PathBuf),
42
43 #[error("destroy cancelled (confirmation required)")]
45 NotConfirmed,
46
47 #[error("libSystem source not found: {0}")]
49 LibsystemNotFound(PathBuf),
50
51 #[error(transparent)]
53 Io(#[from] std::io::Error),
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58#[allow(clippy::struct_excessive_bools)] pub struct BottleStatus {
60 pub path: PathBuf,
62 pub exists: bool,
64 pub valid_marker: bool,
66 pub libsystem: bool,
68 pub libcxx_alias: bool,
70 pub libcurl_alias: bool,
72}
73
74#[derive(Debug, Clone, Default)]
76pub struct CreateOptions<'a> {
77 pub path: Option<&'a Path>,
79 pub libsystem: Option<&'a Path>,
81 pub skip_libsystem: bool,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct CreateResult {
88 pub path: PathBuf,
90 pub libsystem: Option<LibsystemInstall>,
92}
93
94pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
104 create_with(&CreateOptions {
105 path,
106 ..CreateOptions::default()
107 })
108}
109
110pub 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 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 return Err(BottleError::AlreadyExists { path: target });
130 }
131
132 if target.exists() && target.read_dir()?.next().is_some() {
133 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 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
197pub 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 return Err(BottleError::NotABottle(path));
216 }
217 }
219
220 registry::clear_active()?;
221 Ok(path)
222}
223
224pub 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
244pub 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
254pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
269 if let Some(path) = active_root()? {
270 return refresh_bottle(&path, opts);
271 }
272
273 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 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 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 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 let renamed = unique("renamed-by-user");
405 std::fs::rename(&path, &renamed).expect("rename");
406 let st = status().expect("status").expect("some");
408 assert!(!st.exists);
409
410 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 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 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}