1use std::path::{Path, PathBuf};
9
10use thiserror::Error;
11
12use super::layout;
13use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
14use super::registry;
15use super::xcrun_tool::{self, XcrunInstall, XcrunOrigin};
16
17static EMBEDDED_LIBSYSTEM: &[u8] = include_bytes!("../../resources/libSystem.B.dylib");
21
22static EMBEDDED_XCRUN: &[u8] = include_bytes!("../../resources/xcrun");
28
29#[derive(Debug, Error)]
31pub enum BottleError {
32 #[error(
34 "a bottle already exists at {path}\n\
35 create a new one only after deleting the current bottle:\n\
36 kh bottle destroy"
37 )]
38 AlreadyExists {
39 path: PathBuf,
41 },
42
43 #[error("no bottle is registered (nothing to destroy)")]
45 NotRegistered,
46
47 #[error("path is not a kakehashi bottle (missing marker): {0}")]
49 NotABottle(PathBuf),
50
51 #[error("destroy cancelled (confirmation required)")]
53 NotConfirmed,
54
55 #[error("libSystem source not found: {0}")]
57 LibsystemNotFound(PathBuf),
58
59 #[error(transparent)]
61 Io(#[from] std::io::Error),
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
66#[allow(clippy::struct_excessive_bools)] pub struct BottleStatus {
68 pub path: PathBuf,
70 pub exists: bool,
72 pub valid_marker: bool,
74 pub libsystem: bool,
76 pub libcxx_alias: bool,
78 pub libcurl_alias: bool,
80}
81
82#[derive(Debug, Clone, Default)]
84pub struct CreateOptions<'a> {
85 pub path: Option<&'a Path>,
87 pub libsystem: Option<&'a Path>,
89 pub skip_libsystem: bool,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct CreateResult {
96 pub path: PathBuf,
98 pub libsystem: Option<LibsystemInstall>,
100 pub xcrun: Option<XcrunInstall>,
102}
103
104pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
114 create_with(&CreateOptions {
115 path,
116 ..CreateOptions::default()
117 })
118}
119
120pub fn create_with(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
122 if let Some(active) = registry::read_active()? {
123 if active.exists() {
124 return Err(BottleError::AlreadyExists { path: active });
125 }
126 registry::clear_active()?;
128 }
129
130 let target = match opts.path {
131 Some(p) => absolute(p)?,
132 None => registry::default_bottle_path()?,
133 };
134
135 if layout::is_bottle_root(&target) {
136 return Err(BottleError::AlreadyExists { path: target });
140 }
141
142 if target.exists() && target.read_dir()?.next().is_some() {
143 return Err(BottleError::Io(std::io::Error::new(
145 std::io::ErrorKind::AlreadyExists,
146 format!(
147 "refusing to create bottle in non-empty directory: {}",
148 target.display()
149 ),
150 )));
151 }
152
153 layout::materialize(&target)?;
154
155 let libsystem = match install_libsystem_for_create(&target, opts) {
156 Ok(v) => v,
157 Err(err) => {
158 drop(layout::remove_tree(&target));
159 return Err(err);
160 }
161 };
162
163 let xcrun = match install_xcrun_for_create(&target) {
164 Ok(v) => v,
165 Err(err) => {
166 drop(layout::remove_tree(&target));
167 return Err(err);
168 }
169 };
170
171 if let Err(e) = super::ca_bundle::ensure_ca_bundle(&target) {
172 tracing::warn!(error = %e, "failed to seed bottle CA bundle");
173 }
174
175 registry::write_active(&target)?;
176 Ok(CreateResult {
177 path: target,
178 libsystem,
179 xcrun,
180 })
181}
182
183fn install_libsystem_for_create(
184 target: &Path,
185 opts: &CreateOptions<'_>,
186) -> Result<Option<LibsystemInstall>, BottleError> {
187 if opts.skip_libsystem {
188 return Ok(None);
189 }
190 if let Some(explicit) = opts.libsystem {
191 if !explicit.is_file() {
192 return Err(BottleError::LibsystemNotFound(explicit.to_path_buf()));
193 }
194 return Ok(Some(libsystem::install(
195 target,
196 explicit,
197 LibsystemOrigin::Explicit,
198 )?));
199 }
200 if let Some((src, origin)) = libsystem::discover(None) {
201 return Ok(Some(libsystem::install(target, &src, origin)?));
202 }
203
204 if !EMBEDDED_LIBSYSTEM.is_empty() {
206 return Ok(Some(libsystem::install_bytes(
207 target,
208 EMBEDDED_LIBSYSTEM,
209 LibsystemOrigin::Embedded,
210 )?));
211 }
212
213 Ok(None)
214}
215
216fn install_xcrun_for_create(target: &Path) -> Result<Option<XcrunInstall>, BottleError> {
217 if let Some((src, origin)) = xcrun_tool::discover(None) {
218 return Ok(Some(xcrun_tool::install(target, &src, origin)?));
219 }
220 if !EMBEDDED_XCRUN.is_empty() {
221 return Ok(Some(xcrun_tool::install_bytes(
222 target,
223 EMBEDDED_XCRUN,
224 XcrunOrigin::Embedded,
225 )?));
226 }
227 Ok(None)
228}
229
230pub fn destroy(confirmed: bool) -> Result<PathBuf, BottleError> {
235 let Some(path) = registry::read_active()? else {
236 return Err(BottleError::NotRegistered);
237 };
238
239 if !confirmed {
240 return Err(BottleError::NotConfirmed);
241 }
242
243 if path.exists() {
244 if layout::is_bottle_root(&path) {
245 layout::remove_tree(&path)?;
246 } else if path.is_dir() {
247 return Err(BottleError::NotABottle(path));
249 }
250 }
252
253 registry::clear_active()?;
254 Ok(path)
255}
256
257pub fn status() -> Result<Option<BottleStatus>, BottleError> {
259 let Some(path) = registry::read_active()? else {
260 return Ok(None);
261 };
262 let exists = path.exists();
263 let valid_marker = exists && layout::is_bottle_root(&path);
264 let libsystem = exists && path.join(libsystem::GUEST_LIBSYSTEM_REL).is_file();
265 let libcxx_alias = exists && layout::has_libcxx_symlink(&path);
266 let libcurl_alias = exists && layout::has_libcurl_symlink(&path);
267 Ok(Some(BottleStatus {
268 path,
269 exists,
270 valid_marker,
271 libsystem,
272 libcxx_alias,
273 libcurl_alias,
274 }))
275}
276
277pub fn active_root() -> Result<Option<PathBuf>, BottleError> {
281 match status()? {
282 Some(s) if s.exists && s.valid_marker => Ok(Some(s.path)),
283 _ => Ok(None),
284 }
285}
286
287pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
302 if let Some(path) = active_root()? {
303 return refresh_bottle(&path, opts);
304 }
305
306 if let Some(p) = opts.path {
309 let abs = absolute(p)?;
310 if layout::is_bottle_root(&abs) {
311 return refresh_bottle(&abs, opts);
312 }
313 } else if let Ok(def) = registry::default_bottle_path()
314 && layout::is_bottle_root(&def)
315 {
316 return refresh_bottle(&def, opts);
317 }
318
319 create_with(opts)
320}
321
322fn refresh_bottle(path: &Path, opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
323 layout::ensure_libcxx_symlink(path)?;
324 layout::ensure_libcurl_symlink(path)?;
325 layout::ensure_libxar_symlink(path)?;
326 layout::ensure_libz_symlink(path)?;
327 layout::ensure_dev_nodes(path)?;
328 layout::ensure_host_ssh_bridge(path)?;
329 layout::ensure_host_bin_bridges(path)?;
330 let libsystem = install_libsystem_for_create(path, opts)?;
331 let xcrun = install_xcrun_for_create(path)?;
332 if let Err(e) = super::ca_bundle::ensure_ca_bundle(path) {
334 tracing::warn!(error = %e, "failed to seed bottle CA bundle");
335 }
336 registry::write_active(path)?;
337 Ok(CreateResult {
338 path: path.to_path_buf(),
339 libsystem,
340 xcrun,
341 })
342}
343
344fn absolute(path: &Path) -> Result<PathBuf, BottleError> {
345 if path.is_absolute() {
346 return Ok(path.to_path_buf());
347 }
348 let cwd = std::env::current_dir()?;
349 Ok(cwd.join(path))
350}
351
352#[cfg(test)]
353#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
354mod tests {
355 use super::*;
356 use crate::bottle::registry::test_env_lock;
357 use std::sync::atomic::{AtomicU64, Ordering};
358
359 fn unique(prefix: &str) -> PathBuf {
360 static N: AtomicU64 = AtomicU64::new(0);
361 let n = N.fetch_add(1, Ordering::Relaxed);
362 std::env::temp_dir().join(format!("kh-manage-{}-{}-{n}", prefix, std::process::id()))
363 }
364
365 struct EnvGuard {
366 cfg: PathBuf,
367 data: PathBuf,
368 }
369
370 impl EnvGuard {
371 fn new() -> Self {
372 let cfg = unique("cfg");
373 let data = unique("data");
374 drop(std::fs::remove_dir_all(&cfg));
375 drop(std::fs::remove_dir_all(&data));
376 std::fs::create_dir_all(&cfg).expect("cfg");
377 std::fs::create_dir_all(&data).expect("data");
378 unsafe {
380 std::env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
381 std::env::set_var("KAKEHASHI_DATA_DIR", &data);
382 }
383 Self { cfg, data }
384 }
385 }
386
387 impl Drop for EnvGuard {
388 fn drop(&mut self) {
389 unsafe {
391 std::env::remove_var("KAKEHASHI_CONFIG_DIR");
392 std::env::remove_var("KAKEHASHI_DATA_DIR");
393 }
394 drop(std::fs::remove_dir_all(&self.cfg));
395 drop(std::fs::remove_dir_all(&self.data));
396 }
397 }
398
399 #[test]
400 fn create_default_then_second_fails() {
401 let _lock = test_env_lock();
402 let g = EnvGuard::new();
403
404 let created = create_with(&CreateOptions {
405 skip_libsystem: true,
406 ..CreateOptions::default()
407 })
408 .expect("create");
409 let path = created.path;
410 assert!(layout::is_bottle_root(&path));
411 assert_eq!(path, g.data.join("bottle"));
412 assert!(path.join("Volumes/linux").is_symlink());
413 assert!(created.libsystem.is_none());
414
415 let err = create(None).expect_err("second create");
416 assert!(matches!(err, BottleError::AlreadyExists { .. }));
417
418 let destroyed = destroy(true).expect("destroy");
419 assert_eq!(destroyed, path);
420 assert!(!path.exists());
421 assert!(status().expect("status").is_none());
422 }
423
424 #[test]
425 fn create_custom_path_and_rename_survives_registry_update() {
426 let _lock = test_env_lock();
427 let _g = EnvGuard::new();
428
429 let custom = unique("custom-bottle-name");
430 let created = create_with(&CreateOptions {
431 path: Some(&custom),
432 skip_libsystem: true,
433 ..CreateOptions::default()
434 })
435 .expect("create custom");
436 let path = created.path;
437 assert_eq!(path, custom);
438 assert!(layout::is_bottle_root(&path));
439
440 let renamed = unique("renamed-by-user");
442 std::fs::rename(&path, &renamed).expect("rename");
443 let st = status().expect("status").expect("some");
445 assert!(!st.exists);
446
447 let again = unique("after-rename");
449 let path2 = create_with(&CreateOptions {
450 path: Some(&again),
451 skip_libsystem: true,
452 ..CreateOptions::default()
453 })
454 .expect("create after stale");
455 assert!(layout::is_bottle_root(&path2.path));
456
457 destroy(true).expect("destroy");
458 drop(std::fs::remove_dir_all(&renamed));
459 }
460
461 #[test]
462 fn destroy_requires_confirmation() {
463 let _lock = test_env_lock();
464 let _g = EnvGuard::new();
465
466 let path = create_with(&CreateOptions {
467 skip_libsystem: true,
468 ..CreateOptions::default()
469 })
470 .expect("create")
471 .path;
472 let err = destroy(false).expect_err("need confirm");
473 assert!(matches!(err, BottleError::NotConfirmed));
474 assert!(path.exists());
475 destroy(true).expect("destroy");
476 }
477
478 #[test]
479 fn volumes_linux_rw_outside_bottle() {
480 let _lock = test_env_lock();
481 let _g = EnvGuard::new();
482
483 let root = create_with(&CreateOptions {
484 skip_libsystem: true,
485 ..CreateOptions::default()
486 })
487 .expect("create")
488 .path;
489 let token = format!("kh-manage-vol-{}", std::process::id());
490 let host_file = std::env::temp_dir().join(&token);
491 let payload = b"rw-outside\n";
492 std::fs::write(&host_file, payload).expect("host write");
493
494 let via = root
495 .join(layout::VOLUMES_LINUX)
496 .join(host_file.strip_prefix("/").expect("abs"));
497 assert_eq!(std::fs::read(&via).expect("via read"), payload);
498
499 let payload2 = b"from-bottle-side\n";
500 std::fs::write(&via, payload2).expect("via write");
501 assert_eq!(std::fs::read(&host_file).expect("host read"), payload2);
502
503 drop(std::fs::remove_file(&host_file));
504 destroy(true).expect("destroy");
505 }
506
507 #[test]
508 fn create_installs_explicit_libsystem() {
509 let _lock = test_env_lock();
510 let _g = EnvGuard::new();
511
512 let libsystem = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
514 .join("resources/libSystem.B.dylib");
515 assert!(
516 libsystem.is_file(),
517 "missing {}",
518 libsystem.display()
519 );
520
521 let created = create_with(&CreateOptions {
522 libsystem: Some(&libsystem),
523 ..CreateOptions::default()
524 })
525 .expect("create with libsystem");
526 assert!(created.libsystem.is_some());
527 let dest = created.path.join(libsystem::GUEST_LIBSYSTEM_REL);
528 assert!(dest.is_file());
529 let st = status().expect("status").expect("registered");
530 assert!(st.libsystem);
531 assert!(st.libcxx_alias);
532 assert!(st.libcurl_alias);
533 assert!(layout::has_libcxx_symlink(&created.path));
534 assert!(layout::has_libcurl_symlink(&created.path));
535
536 destroy(true).expect("destroy");
537 }
538
539 #[test]
540 fn ensure_creates_then_refreshes_libsystem() {
541 let _lock = test_env_lock();
542 let _g = EnvGuard::new();
543
544 let libsystem = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
545 .join("resources/libSystem.B.dylib");
546 assert!(libsystem.is_file());
547
548 let first = ensure(&CreateOptions {
549 libsystem: Some(&libsystem),
550 ..CreateOptions::default()
551 })
552 .expect("ensure create");
553 assert!(first.libsystem.is_some());
554 let dest = first.path.join(libsystem::GUEST_LIBSYSTEM_REL);
555 let before = std::fs::metadata(&dest).expect("meta").len();
556
557 let second = ensure(&CreateOptions {
559 libsystem: Some(&libsystem),
560 ..CreateOptions::default()
561 })
562 .expect("ensure refresh");
563 assert_eq!(second.path, first.path);
564 assert!(second.libsystem.is_some());
565 assert!(dest.is_file());
566 let after = std::fs::metadata(&dest).expect("meta2").len();
567 assert_eq!(before, after);
568
569 destroy(true).expect("destroy");
570 }
571}