1use std::collections::{BTreeSet, HashMap, VecDeque};
11use std::fs;
12use std::path::{Path, PathBuf};
13
14use sim_core::hostfs::PermissionsExt;
15use sim_core::platform::Platform;
16
17use crate::{
18 COLD_BOOT, Captures, Contents, Device, Entry, EntryKind, Error, Extracted, FORMAT, GuestIdentity, Identity, IosSimulator, Manifest,
19 Options, Reader, Result, Secret, Summary, safe_path,
20};
21
22pub const DATA: &str = "data";
24
25pub const GUEST_IDENTIFIERS: [&str; 2] = ["keychain items", "identifiers apps keep in their containers and preferences"];
27
28pub const DUPLICATED_IDENTITY: &str = "the import has a new UDID, but its apps see the device they were exported from: the \
30 keychain and every app's container and preferences come along";
31
32pub fn left_out(rel: &str) -> bool {
36 let parts: Vec<&str> = rel.split('/').collect();
37 matches!(parts.as_slice(), [.., "Library", "Caches"] | ["tmp"] | ["Containers", _, _, _, "tmp"])
38}
39
40#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct Simulator {
43 pub udid: String,
44 pub name: String,
45 pub shut_down: bool,
46 pub state: String,
48 pub device_type: String,
50 pub runtime: String,
52 pub form_factor: Option<String>,
53 pub data_dir: PathBuf,
55}
56
57#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct Runtime {
60 pub identifier: String,
61 pub name: String,
62 pub version: String,
63 pub build: String,
64 pub available: bool,
65}
66
67pub trait Service {
69 fn device(&self, udid: &str) -> std::result::Result<Simulator, String>;
71 fn names(&self) -> std::result::Result<Vec<String>, String>;
73 fn runtimes(&self) -> std::result::Result<Vec<Runtime>, String>;
74 fn create(&self, name: &str, device_type: &str, runtime: &Runtime) -> std::result::Result<Simulator, String>;
77 fn delete(&self, udid: &str) -> std::result::Result<(), String>;
78}
79
80#[derive(Clone, Debug)]
82pub struct Exported {
83 pub manifest: Manifest,
84 pub summary: Summary,
85 pub left_out: Vec<String>,
87}
88
89#[derive(Clone, Debug)]
91pub struct Imported {
92 pub device: Simulator,
93 pub runtime: Runtime,
94 pub extracted: Extracted,
95 pub manifest: Manifest,
96}
97
98#[derive(Default)]
99struct Walk {
100 disks: Vec<(String, PathBuf)>,
101 tree: Vec<Entry>,
102 dropped: Vec<String>,
103 left_out: Vec<String>,
104}
105
106fn io(p: &Path) -> impl FnOnce(std::io::Error) -> Error + '_ {
107 move |e| Error::Io(p.to_path_buf(), e)
108}
109
110fn mode(meta: &fs::Metadata) -> Option<u32> {
111 Some(meta.permissions().mode() & 0o7777)
112}
113
114const HOST_ROOTS: [&str; 12] = [
119 "/Users",
120 "/Volumes",
121 "/private/var/folders",
122 "/var/folders",
123 "/private/var/tmp",
124 "/var/tmp",
125 "/private/tmp",
126 "/tmp",
127 "/Library/Caches",
128 "/opt/homebrew",
129 "/Applications",
130 "/.vol",
131];
132
133const DATA_VOLUME: &str = "/System/Volumes/Data";
135
136const HOST_LINKS: [[&str; 2]; 1] = [["Library", "Logs"]];
141
142fn host_linked(trail: &[&str]) -> bool {
145 let fold = crate::manifest::fold;
146 trail.len() == 2 && HOST_LINKS.iter().any(|h| fold(trail[0]) == fold(h[0]) && fold(trail[1]) == fold(h[1]))
147}
148
149const MAX_HOPS: usize = 32;
152
153fn holds(outer: &str, inner: &str) -> bool {
155 outer == "/" || outer == inner || inner.strip_prefix(outer).is_some_and(|r| r.starts_with('/'))
156}
157
158fn names_host(t: &str) -> bool {
164 let fold = crate::manifest::fold;
165 let mut parts = Vec::new();
166 for c in t.split('/') {
167 match c {
168 "" | "." => {}
169 ".." => return true,
170 c => parts.push(c),
171 }
172 }
173 let data_volume = fold(DATA_VOLUME);
174 let mut p = fold(&format!("/{}", parts.join("/")));
175 while let Some(rest) = p.strip_prefix(&data_volume).filter(|r| r.is_empty() || r.starts_with('/')) {
176 p = if rest.is_empty() { "/".to_owned() } else { rest.to_owned() };
177 }
178 holds(&p, &data_volume) || HOST_ROOTS.iter().map(|h| fold(h)).any(|h| holds(&h, &p) || holds(&p, &h))
179}
180
181fn under_data(p: &str) -> &str {
183 p.strip_prefix(DATA).and_then(|r| r.strip_prefix('/')).unwrap_or("")
184}
185
186const WALK_BUDGET: usize = 1 << 24;
192
193struct Names<'a> {
197 nodes: Vec<Node<'a>>,
198 children: HashMap<(usize, String), usize>,
199}
200
201struct Node<'a> {
202 name: &'a str,
204 ambiguous: bool,
207 link: Option<&'a str>,
209}
210
211const ROOT: usize = 0;
213
214impl<'a> Names<'a> {
215 fn new(tree: &'a [Entry]) -> Names<'a> {
216 let mut names = Names { nodes: vec![Node { name: "", ambiguous: false, link: None }], children: HashMap::new() };
217 for e in tree {
218 let rel = under_data(&e.path);
219 if rel.is_empty() {
220 continue;
221 }
222 let mut at = ROOT;
223 for c in rel.split('/') {
224 let next = names.nodes.len();
225 let n = *names.children.entry((at, crate::manifest::fold(c))).or_insert(next);
226 if n == next {
227 names.nodes.push(Node { name: c, ambiguous: false, link: None });
228 } else if names.nodes[n].name != c {
229 names.nodes[n].ambiguous = true;
230 }
231 at = n;
232 }
233 if let (EntryKind::Symlink, Some(t)) = (e.kind, &e.target) {
234 names.nodes[at].link.get_or_insert(t);
235 }
236 }
237 names
238 }
239
240 fn child(&self, dir: Option<usize>, c: &str) -> std::result::Result<Option<usize>, ()> {
247 let Some(dir) = dir else { return Ok(None) };
248 match self.children.get(&(dir, crate::manifest::fold(c))) {
249 None => Ok(None),
250 Some(&n) if self.nodes[n].name == c && !self.nodes[n].ambiguous => Ok(Some(n)),
251 Some(_) => Err(()),
252 }
253 }
254}
255
256fn charge(budget: &mut usize, n: usize) -> bool {
258 match budget.checked_sub(n) {
259 Some(left) => {
260 *budget = left;
261 true
262 }
263 None => false,
264 }
265}
266
267fn leaves_data(names: &Names, rel: &str, target: &str, budget: &mut usize) -> bool {
275 if !charge(budget, rel.len() + target.len() + 1) {
276 return true;
277 }
278 let mut parts = rel.split('/');
279 parts.next_back();
280 let mut at: Vec<Option<usize>> = Vec::new();
281 let mut trail: Vec<&str> = Vec::new();
282 for c in parts {
283 match names.child(at.last().copied().unwrap_or(Some(ROOT)), c) {
284 Ok(n) => at.push(n),
285 Err(()) => return true,
286 }
287 trail.push(c);
288 if host_linked(&trail) {
289 return true;
290 }
291 }
292 let mut todo: VecDeque<&str> = target.split('/').collect();
293 let mut hops = 0;
294 while let Some(c) = todo.pop_front() {
295 match c {
296 "" | "." => {}
297 ".." => {
298 trail.pop();
299 if at.pop().is_none() {
300 return true;
301 }
302 }
303 name => {
304 let Ok(n) = names.child(at.last().copied().unwrap_or(Some(ROOT)), name) else { return true };
305 let Some(t) = n.and_then(|n| names.nodes[n].link) else {
306 at.push(n);
307 trail.push(name);
308 if host_linked(&trail) {
309 return true;
310 }
311 continue;
312 };
313 hops += 1;
314 if hops > MAX_HOPS || !charge(budget, t.len() + 1) {
315 return true;
316 }
317 if t.starts_with('/') {
318 let rest: Vec<&str> = todo.into_iter().collect();
319 return names_host(&format!("{t}/{}", rest.join("/")));
320 }
321 for c in t.split('/').rev() {
322 todo.push_front(c);
323 }
324 }
325 }
326 }
327 false
328}
329
330fn refused_links(tree: &[Entry]) -> Vec<&Entry> {
336 let names = Names::new(tree);
337 let mut budget = WALK_BUDGET;
338 tree.iter()
339 .filter(|e| match (e.kind, &e.target) {
340 (EntryKind::Symlink, Some(t)) if !crate::safe_target(t) => true,
341 (EntryKind::Symlink, Some(t)) if t.starts_with('/') => names_host(t),
342 (EntryKind::Symlink, Some(t)) => leaves_data(&names, under_data(&e.path), t, &mut budget),
343 _ => false,
344 })
345 .collect()
346}
347
348fn portable_target(root: &Path, rel: &str, target: &Path) -> Option<String> {
354 let t = target.to_str()?;
355 if !target.is_absolute() {
356 return Some(t.to_owned());
357 }
358 if let Ok(inside) = target.strip_prefix(root) {
359 let up = "../".repeat(rel.matches('/').count());
360 let inside = inside.to_str()?;
361 return Some(match (up.as_str(), inside) {
362 ("", "") => ".".to_owned(),
363 (up, "") => up.trim_end_matches('/').to_owned(),
364 (up, inside) => format!("{up}{inside}"),
365 });
366 }
367 let device_dir = root.parent().filter(|d| d.parent().is_some());
368 if device_dir.is_some_and(|d| target.starts_with(d)) || names_host(t) {
369 return None;
370 }
371 Some(t.to_owned())
372}
373
374fn link_refusal(tree: &[Entry]) -> Option<String> {
376 let e = *refused_links(tree).first()?;
377 Some(format!(
378 "the bundle's symlink `{}` points at `{}`, which resolves to a host path or out of the device's data (through the \
379 bundle's own links), which an export never writes; it isn't imported",
380 e.path,
381 e.target.as_deref().unwrap_or_default()
382 ))
383}
384
385fn walk(root: &Path) -> Result<Walk> {
388 let meta = fs::symlink_metadata(root).map_err(io(root))?;
389 if !meta.is_dir() {
390 return Err(Error::Refused(format!("{} isn't a directory", root.display())));
391 }
392 let mut w = Walk::default();
393 w.tree.push(Entry { path: DATA.into(), kind: EntryKind::Dir, mode: mode(&meta), target: None });
394 walk_dir(root, root, "", &mut w)?;
395 Ok(w)
396}
397
398fn walk_dir(root: &Path, dir: &Path, rel: &str, w: &mut Walk) -> Result<()> {
399 let mut names = Vec::new();
400 for e in fs::read_dir(dir).map_err(io(dir))? {
401 names.push(e.map_err(io(dir))?.file_name());
402 }
403 names.sort();
404 for name in names {
405 let path = dir.join(&name);
406 let Some(n) = name.to_str() else {
407 w.dropped.push(format!("{DATA}/{rel}/{} (a name that isn't UTF-8)", name.to_string_lossy()));
408 continue;
409 };
410 let r = if rel.is_empty() { n.to_owned() } else { format!("{rel}/{n}") };
411 let at = format!("{DATA}/{r}");
412 if !safe_path(&at) {
413 w.dropped.push(format!("{at} (a name a bundle can't hold)"));
414 continue;
415 }
416 let meta = fs::symlink_metadata(&path).map_err(io(&path))?;
417 let kind = meta.file_type();
418 if kind.is_symlink() {
419 let target = fs::read_link(&path).map_err(io(&path))?;
420 match portable_target(root, &r, &target) {
421 Some(t) if !crate::safe_target(&t) => w.dropped.push(format!("{at} (a symlink whose target a bundle can't hold)")),
422 Some(t) => w.tree.push(Entry { path: at, kind: EntryKind::Symlink, mode: None, target: Some(t) }),
423 None => w.dropped.push(format!("{at} (a symlink to a host path)")),
424 }
425 } else if kind.is_dir() {
426 w.tree.push(Entry { path: at.clone(), kind: EntryKind::Dir, mode: mode(&meta), target: None });
427 if left_out(&r) {
428 w.left_out.push(at);
429 } else {
430 walk_dir(root, &path, &r, w)?;
431 }
432 } else if kind.is_file() {
433 w.tree.push(Entry { path: at.clone(), kind: EntryKind::File, mode: mode(&meta), target: None });
434 w.disks.push((at, path));
435 } else {
436 w.dropped.push(format!("{at} (a socket, pipe or device node)"));
437 }
438 }
439 Ok(())
440}
441
442fn refuse_inside(d: &Simulator, to: &Path) -> Result<()> {
445 let Some(device_dir) = d.data_dir.parent().and_then(|p| fs::canonicalize(p).ok()) else { return Ok(()) };
446 let parent = match to.parent() {
447 Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
448 _ => PathBuf::from("."),
449 };
450 if fs::canonicalize(&parent).is_ok_and(|p| p.starts_with(&device_dir)) {
451 return Err(Error::Refused(format!(
452 "{} is inside {}'s own directory; export never writes into the device it reads",
453 to.display(),
454 d.name
455 )));
456 }
457 Ok(())
458}
459
460pub fn export(svc: &dyn Service, udid: &str, to: &Path, opts: &Options) -> Result<Exported> {
466 let d = svc.device(udid).map_err(Error::Refused)?;
467 if !d.shut_down {
468 return Err(Error::Refused(format!("{} must be shut down to export it (it is {})", d.name, d.state)));
469 }
470 if !d.data_dir.is_dir() {
471 return Err(Error::Refused(format!("{} has no data directory yet (boot it once, then shut it down)", d.name)));
472 }
473 refuse_inside(&d, to)?;
474 let runtimes = svc.runtimes().map_err(Error::Refused)?;
475 let rt = runtimes.iter().find(|r| r.identifier.eq_ignore_ascii_case(&d.runtime)).ok_or_else(|| {
476 Error::Refused(format!("{}'s runtime {} isn't installed here, so the bundle can't name its build", d.name, d.runtime))
477 })?;
478 let mut walked = walk(&d.data_dir)?;
479 loop {
482 let refused: BTreeSet<String> = refused_links(&walked.tree).into_iter().map(|e| e.path.clone()).collect();
483 if refused.is_empty() {
484 break;
485 }
486 walked.tree.retain(|e| !refused.contains(&e.path));
487 walked.dropped.extend(refused.into_iter().map(|p| format!("{p} (a symlink to a host path)")));
488 }
489 let secrets = vec![
490 Secret {
491 item: format!("{DATA}/Library/Keychains"),
492 what: "the device's keychain: passwords, tokens and keys its apps stored".into(),
493 excludable: false,
494 },
495 Secret {
496 item: format!("{DATA}/Containers/Data"),
497 what: "each app's data container: may hold accounts, tokens and app data".into(),
498 excludable: false,
499 },
500 ];
501 let header = Manifest {
502 format: FORMAT,
503 simee_version: env!("CARGO_PKG_VERSION").into(),
504 platform: Platform::Ios,
505 device: Device { name: d.name.clone(), form_factor: d.form_factor.clone() },
506 identity: Identity::Ios(IosSimulator {
507 device_type: d.device_type.clone(),
508 runtime: rt.identifier.clone(),
509 build: rt.build.clone(),
510 version: rt.version.clone(),
511 runtime_name: rt.name.clone(),
512 }),
513 captures: Captures { disks: true, ram: false },
514 resume: COLD_BOOT.into(),
515 secrets,
516 guest_identity: GuestIdentity {
517 on_import: "duplicated".into(),
518 identifiers: GUEST_IDENTIFIERS.iter().map(|s| (*s).to_owned()).collect(),
519 },
520 dropped: walked.dropped,
521 chunk_size: 0,
522 compression: String::new(),
523 disks: Vec::new(),
524 files: Vec::new(),
525 tree: walked.tree,
526 };
527 let contents = Contents { disks: walked.disks, files: Vec::new() };
528 let (manifest, summary) = crate::export(header, &contents, to, opts)?;
529 if !svc.device(udid).is_ok_and(|now| now.shut_down) {
530 let _ = if to.is_dir() { fs::remove_dir_all(to) } else { fs::remove_file(to) };
531 return Err(Error::Refused(format!("{} booted while it was exported; the bundle was removed", d.name)));
532 }
533 Ok(Exported { manifest, summary, left_out: walked.left_out })
534}
535
536fn in_data(p: &str) -> bool {
538 p == DATA || p.strip_prefix(DATA).is_some_and(|rest| rest.starts_with('/'))
539}
540
541pub fn find_runtime(have: &[Runtime], want: &IosSimulator) -> Result<Runtime> {
544 let same = |r: &&Runtime| r.identifier.eq_ignore_ascii_case(&want.runtime);
545 if let Some(r) = have.iter().filter(same).find(|r| r.build == want.build && r.available) {
546 return Ok(r.clone());
547 }
548 let near: Vec<String> = have
549 .iter()
550 .filter(same)
551 .map(|r| {
552 if r.build == want.build {
553 format!("{} ({}) is unavailable", r.name, r.build)
554 } else {
555 format!("{} is build {}", r.name, r.build)
556 }
557 })
558 .collect();
559 let near = if near.is_empty() { String::new() } else { format!(" (this host: {})", near.join("; ")) };
560 let platform = want.runtime_name.split_whitespace().next().filter(|p| !p.is_empty()).unwrap_or("iOS");
561 Err(Error::Refused(format!(
562 "the bundle needs the {} runtime, build {} ({}), which isn't installed{near}; install it (Xcode > Settings > Components, \
563 or `xcodebuild -downloadPlatform {platform} -buildVersion {}`) and import again",
564 want.runtime_name, want.build, want.runtime, want.build
565 )))
566}
567
568pub fn import(svc: &dyn Service, reader: Reader, name: &str) -> Result<Imported> {
575 if name.trim().is_empty() {
576 return Err(Error::Refused("give the new device a `name`".into()));
577 }
578 let m = reader.manifest().clone();
579 if m.platform != Platform::Ios {
580 return Err(Error::Refused(format!("the bundle is an {} device's; this imports iOS simulators", m.platform.label())));
581 }
582 let Identity::Ios(id) = &m.identity else {
583 return Err(Error::Refused("the bundle's manifest names no iOS runtime".into()));
584 };
585 let mut paths = m.disks.iter().map(|d| &d.path).chain(m.files.iter().map(|f| &f.path)).chain(m.tree.iter().map(|e| &e.path));
586 if let Some(p) = paths.find(|p| !in_data(p)) {
587 return Err(Error::Refused(format!("the bundle holds `{p}`, which isn't under {DATA}/ (a simulator's data directory)")));
588 }
589 if !m.tree.iter().any(|e| e.path == DATA && e.kind == EntryKind::Dir) {
590 return Err(Error::Refused(format!("the bundle has no {DATA}/ directory")));
591 }
592 if let Some(why) = link_refusal(&m.tree) {
593 return Err(Error::Refused(why));
594 }
595 let runtime = find_runtime(&svc.runtimes().map_err(Error::Refused)?, id)?;
596 if svc.names().map_err(Error::Refused)?.iter().any(|n| n == name) {
597 return Err(Error::Refused(format!("a device named `{name}` already exists in this set")));
598 }
599 let made = svc.create(name, &id.device_type, &runtime).map_err(Error::Refused)?;
600 let placed = place(reader, &m.tree, &made.data_dir).and_then(|x| Ok((x, svc.device(&made.udid).map_err(Error::Refused)?)));
601 match placed {
602 Ok((extracted, device)) => Ok(Imported { device, runtime, extracted, manifest: m }),
603 Err(e) => {
604 let _ = svc.delete(&made.udid);
605 Err(e)
606 }
607 }
608}
609
610fn place(reader: Reader, tree: &[Entry], data_dir: &Path) -> Result<Extracted> {
613 let device_dir = data_dir.parent().ok_or_else(|| Error::Refused(format!("{} has no parent", data_dir.display())))?;
614 let staging = device_dir.join(".simee-import.partial");
615 if staging.exists() {
616 fs::remove_dir_all(&staging).map_err(io(&staging))?;
617 }
618 fs::create_dir(&staging).map_err(io(&staging))?;
619 let done = (|| {
620 let extracted = reader.extract(&staging)?;
621 apply_tree(&staging, tree)?;
622 if fs::symlink_metadata(data_dir).is_ok() {
623 fs::remove_dir_all(data_dir).map_err(io(data_dir))?;
624 }
625 let data = staging.join(DATA);
626 fs::rename(&data, data_dir).map_err(io(data_dir))?;
627 Ok(extracted)
628 })();
629 let _ = fs::remove_dir_all(&staging);
630 done
631}
632
633#[cfg(unix)]
639fn apply_tree(dest: &Path, tree: &[Entry]) -> Result<()> {
640 let root = crate::beneath::Beneath::new(dest)?;
641 for e in tree.iter().filter(|e| e.kind == EntryKind::Dir) {
642 root.mkdir_all(&e.path)?;
643 }
644 for e in tree {
645 match (e.kind, &e.target, e.mode) {
646 (EntryKind::Symlink, Some(t), _) => root.symlink(&e.path, t)?,
647 (EntryKind::File, _, Some(m)) => root.chmod(&e.path, m, false)?,
648 _ => {}
649 }
650 }
651 for e in tree.iter().rev().filter(|e| e.kind == EntryKind::Dir) {
652 if let Some(m) = e.mode {
653 root.chmod(&e.path, m, true)?;
654 }
655 }
656 Ok(())
657}
658
659#[cfg(not(unix))]
660fn apply_tree(_: &Path, _: &[Entry]) -> Result<()> {
661 Err(Error::Unsupported("an iOS bundle's file tree (directories, symlinks, modes) is written on macOS only".into()))
662}
663
664#[cfg(all(test, unix))]
666#[path = "ios_tests.rs"]
667mod tests;