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_libxar_symlink(path)?;
293 layout::ensure_libz_symlink(path)?;
294 layout::ensure_dev_nodes(path)?;
295 layout::ensure_host_ssh_bridge(path)?;
296 layout::ensure_host_bin_bridges(path)?;
297 let libsystem = install_libsystem_for_create(path, opts)?;
298 if let Err(e) = super::ca_bundle::ensure_ca_bundle(path) {
300 tracing::warn!(error = %e, "failed to seed bottle CA bundle");
301 }
302 registry::write_active(path)?;
303 Ok(CreateResult {
304 path: path.to_path_buf(),
305 libsystem,
306 })
307}
308
309fn absolute(path: &Path) -> Result<PathBuf, BottleError> {
310 if path.is_absolute() {
311 return Ok(path.to_path_buf());
312 }
313 let cwd = std::env::current_dir()?;
314 Ok(cwd.join(path))
315}
316
317#[cfg(test)]
318#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
319mod tests {
320 use super::*;
321 use crate::bottle::registry::test_env_lock;
322 use std::sync::atomic::{AtomicU64, Ordering};
323
324 fn unique(prefix: &str) -> PathBuf {
325 static N: AtomicU64 = AtomicU64::new(0);
326 let n = N.fetch_add(1, Ordering::Relaxed);
327 std::env::temp_dir().join(format!("kh-manage-{}-{}-{n}", prefix, std::process::id()))
328 }
329
330 struct EnvGuard {
331 cfg: PathBuf,
332 data: PathBuf,
333 }
334
335 impl EnvGuard {
336 fn new() -> Self {
337 let cfg = unique("cfg");
338 let data = unique("data");
339 drop(std::fs::remove_dir_all(&cfg));
340 drop(std::fs::remove_dir_all(&data));
341 std::fs::create_dir_all(&cfg).expect("cfg");
342 std::fs::create_dir_all(&data).expect("data");
343 unsafe {
345 std::env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
346 std::env::set_var("KAKEHASHI_DATA_DIR", &data);
347 }
348 Self { cfg, data }
349 }
350 }
351
352 impl Drop for EnvGuard {
353 fn drop(&mut self) {
354 unsafe {
356 std::env::remove_var("KAKEHASHI_CONFIG_DIR");
357 std::env::remove_var("KAKEHASHI_DATA_DIR");
358 }
359 drop(std::fs::remove_dir_all(&self.cfg));
360 drop(std::fs::remove_dir_all(&self.data));
361 }
362 }
363
364 #[test]
365 fn create_default_then_second_fails() {
366 let _lock = test_env_lock();
367 let g = EnvGuard::new();
368
369 let created = create_with(&CreateOptions {
370 skip_libsystem: true,
371 ..CreateOptions::default()
372 })
373 .expect("create");
374 let path = created.path;
375 assert!(layout::is_bottle_root(&path));
376 assert_eq!(path, g.data.join("bottle"));
377 assert!(path.join("Volumes/linux").is_symlink());
378 assert!(created.libsystem.is_none());
379
380 let err = create(None).expect_err("second create");
381 assert!(matches!(err, BottleError::AlreadyExists { .. }));
382
383 let destroyed = destroy(true).expect("destroy");
384 assert_eq!(destroyed, path);
385 assert!(!path.exists());
386 assert!(status().expect("status").is_none());
387 }
388
389 #[test]
390 fn create_custom_path_and_rename_survives_registry_update() {
391 let _lock = test_env_lock();
392 let _g = EnvGuard::new();
393
394 let custom = unique("custom-bottle-name");
395 let created = create_with(&CreateOptions {
396 path: Some(&custom),
397 skip_libsystem: true,
398 ..CreateOptions::default()
399 })
400 .expect("create custom");
401 let path = created.path;
402 assert_eq!(path, custom);
403 assert!(layout::is_bottle_root(&path));
404
405 let renamed = unique("renamed-by-user");
407 std::fs::rename(&path, &renamed).expect("rename");
408 let st = status().expect("status").expect("some");
410 assert!(!st.exists);
411
412 let again = unique("after-rename");
414 let path2 = create_with(&CreateOptions {
415 path: Some(&again),
416 skip_libsystem: true,
417 ..CreateOptions::default()
418 })
419 .expect("create after stale");
420 assert!(layout::is_bottle_root(&path2.path));
421
422 destroy(true).expect("destroy");
423 drop(std::fs::remove_dir_all(&renamed));
424 }
425
426 #[test]
427 fn destroy_requires_confirmation() {
428 let _lock = test_env_lock();
429 let _g = EnvGuard::new();
430
431 let path = create_with(&CreateOptions {
432 skip_libsystem: true,
433 ..CreateOptions::default()
434 })
435 .expect("create")
436 .path;
437 let err = destroy(false).expect_err("need confirm");
438 assert!(matches!(err, BottleError::NotConfirmed));
439 assert!(path.exists());
440 destroy(true).expect("destroy");
441 }
442
443 #[test]
444 fn volumes_linux_rw_outside_bottle() {
445 let _lock = test_env_lock();
446 let _g = EnvGuard::new();
447
448 let root = create_with(&CreateOptions {
449 skip_libsystem: true,
450 ..CreateOptions::default()
451 })
452 .expect("create")
453 .path;
454 let token = format!("kh-manage-vol-{}", std::process::id());
455 let host_file = std::env::temp_dir().join(&token);
456 let payload = b"rw-outside\n";
457 std::fs::write(&host_file, payload).expect("host write");
458
459 let via = root
460 .join(layout::VOLUMES_LINUX)
461 .join(host_file.strip_prefix("/").expect("abs"));
462 assert_eq!(std::fs::read(&via).expect("via read"), payload);
463
464 let payload2 = b"from-bottle-side\n";
465 std::fs::write(&via, payload2).expect("via write");
466 assert_eq!(std::fs::read(&host_file).expect("host read"), payload2);
467
468 drop(std::fs::remove_file(&host_file));
469 destroy(true).expect("destroy");
470 }
471
472 #[test]
473 fn create_installs_explicit_libsystem() {
474 let _lock = test_env_lock();
475 let _g = EnvGuard::new();
476
477 let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
479 let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
480 assert!(fixture.is_file(), "missing fixture {}", fixture.display());
481
482 let created = create_with(&CreateOptions {
483 libsystem: Some(&fixture),
484 ..CreateOptions::default()
485 })
486 .expect("create with libsystem");
487 assert!(created.libsystem.is_some());
488 let dest = created.path.join(libsystem::GUEST_LIBSYSTEM_REL);
489 assert!(dest.is_file());
490 let st = status().expect("status").expect("registered");
491 assert!(st.libsystem);
492 assert!(st.libcxx_alias);
493 assert!(st.libcurl_alias);
494 assert!(layout::has_libcxx_symlink(&created.path));
495 assert!(layout::has_libcurl_symlink(&created.path));
496
497 destroy(true).expect("destroy");
498 }
499
500 #[test]
501 fn ensure_creates_then_refreshes_libsystem() {
502 let _lock = test_env_lock();
503 let _g = EnvGuard::new();
504
505 let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
506 let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
507 assert!(fixture.is_file());
508
509 let first = ensure(&CreateOptions {
510 libsystem: Some(&fixture),
511 ..CreateOptions::default()
512 })
513 .expect("ensure create");
514 assert!(first.libsystem.is_some());
515 let dest = first.path.join(libsystem::GUEST_LIBSYSTEM_REL);
516 let before = std::fs::metadata(&dest).expect("meta").len();
517
518 let second = ensure(&CreateOptions {
520 libsystem: Some(&fixture),
521 ..CreateOptions::default()
522 })
523 .expect("ensure refresh");
524 assert_eq!(second.path, first.path);
525 assert!(second.libsystem.is_some());
526 assert!(dest.is_file());
527 let after = std::fs::metadata(&dest).expect("meta2").len();
528 assert_eq!(before, after);
529
530 destroy(true).expect("destroy");
531 }
532}