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}
71
72#[derive(Debug, Clone, Default)]
74pub struct CreateOptions<'a> {
75 pub path: Option<&'a Path>,
77 pub libsystem: Option<&'a Path>,
79 pub skip_libsystem: bool,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct CreateResult {
86 pub path: PathBuf,
88 pub libsystem: Option<LibsystemInstall>,
90}
91
92pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
102 create_with(&CreateOptions {
103 path,
104 ..CreateOptions::default()
105 })
106}
107
108pub 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 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 return Err(BottleError::AlreadyExists { path: target });
128 }
129
130 if target.exists() && target.read_dir()?.next().is_some() {
131 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 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
195pub 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 return Err(BottleError::NotABottle(path));
214 }
215 }
217
218 registry::clear_active()?;
219 Ok(path)
220}
221
222pub 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
240pub 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
250pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
265 if let Some(path) = active_root()? {
266 return refresh_bottle(&path, opts);
267 }
268
269 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 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 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 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 let renamed = unique("renamed-by-user");
398 std::fs::rename(&path, &renamed).expect("rename");
399 let st = status().expect("status").expect("some");
401 assert!(!st.exists);
402
403 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 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 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}