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