Skip to main content

simee_bundle/
ios.rs

1//! iOS simulators as portable bundles (#421): a shut-down simulator's data directory (its
2//! settings, its installed apps and their containers) less what the system regenerates
3//! ([`left_out`]), as `data/` in the bundle with its directories, symlinks and modes in the
4//! manifest's tree; and its device type and runtime by identifier and build, which an import
5//! finds on the receiving host or refuses.
6//!
7//! The simulator service is behind [`Service`] (`sim-coresim` implements it over CoreSimulator,
8//! tests over a fake), so all of it builds and tests on any host.
9
10use 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
22/// Where the device's data directory goes in the bundle.
23pub const DATA: &str = "data";
24
25/// What an import keeps of the exported device that makes it the same device to its apps.
26pub const GUEST_IDENTIFIERS: [&str; 2] = ["keychain items", "identifiers apps keep in their containers and preferences"];
27
28/// What an import says about guest identity, in its result.
29pub 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
32/// Where a directory's contents stay out of a bundle (the directory itself goes in, empty): the
33/// system's and each app's `Library/Caches`, the device's `tmp` and each container's, all of which
34/// iOS may purge and rebuilds.
35pub 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/// A simulator as an export or import sees it.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct Simulator {
43    pub udid: String,
44    pub name: String,
45    pub shut_down: bool,
46    /// Its state, for messages (`Booted`).
47    pub state: String,
48    /// Its device type's identifier.
49    pub device_type: String,
50    /// Its runtime's identifier.
51    pub runtime: String,
52    pub form_factor: Option<String>,
53    /// Its data directory on this host (`<set>/<udid>/data`).
54    pub data_dir: PathBuf,
55}
56
57/// An installed runtime.
58#[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
67/// The simulator service, on one device set.
68pub trait Service {
69    /// The device with UDID `udid`, as it is now.
70    fn device(&self, udid: &str) -> std::result::Result<Simulator, String>;
71    /// Every device's name in the set.
72    fn names(&self) -> std::result::Result<Vec<String>, String>;
73    fn runtimes(&self) -> std::result::Result<Vec<Runtime>, String>;
74    /// Creates a device (shut down, never booted) of `device_type` (an identifier) on `runtime`:
75    /// the installed runtime with its identifier and build, never another build of it.
76    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/// What an export wrote.
81#[derive(Clone, Debug)]
82pub struct Exported {
83    pub manifest: Manifest,
84    pub summary: Summary,
85    /// The directories whose contents stayed out ([`left_out`]), at their paths in the bundle.
86    pub left_out: Vec<String>,
87}
88
89/// What an import made.
90#[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
114/// Absolute link targets that name this host rather than the device: its users' homes, volumes,
115/// temporary directories, the directories anyone (`/Library/Caches`), its user (`/opt/homebrew`,
116/// which holds what they run) or an admin (`/Applications`) can write, and any file by its inode
117/// (`/.vol/<device>/<inode>`).
118const 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
133/// The firmlink that is the data volume's root: `/System/Volumes/Data/Users` is `/Users`.
134const DATA_VOLUME: &str = "/System/Volumes/Data";
135
136/// Paths under the data directory that CoreSimulator turns into a link to the host when a device
137/// boots (`Library/Logs` becomes `~/Library/Logs/CoreSimulator/<UDID>`). An export drops that link
138/// and the bundle's tree has no such name, but once the imported device boots a target that goes
139/// through it resolves on the host, so a walk treats each as an absolute host link.
140const HOST_LINKS: [[&str; 2]; 1] = [["Library", "Logs"]];
141
142/// Whether `trail` (names from the data directory, in the tree's or the target's spelling) is one
143/// of [`HOST_LINKS`], as a volume compares names.
144fn 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
149/// The most links one path may follow, as the kernel's `MAXSYMLINKS` on macOS: a target that
150/// takes more of the tree's own links is refused.
151const MAX_HOPS: usize = 32;
152
153/// Whether `outer` is `inner` or one of its ancestors (both absolute, folded, no trailing `/`).
154fn holds(outer: &str, inner: &str) -> bool {
155    outer == "/" || outer == inner || inner.strip_prefix(outer).is_some_and(|r| r.starts_with('/'))
156}
157
158/// Whether absolute link target `t` names the host, or can't be judged without the host's disk.
159/// It is compared as the volume compares names ([`fold`](crate::manifest::fold)), with `//` and
160/// `.` collapsed and the [`DATA_VOLUME`] prefix taken for `/`: a path under one of
161/// [`HOST_ROOTS`], or one that holds one (`/`, `/private`, `/System/Volumes`), names the host. So
162/// does any `..`, which only the host's own links resolve (`/var/..` is `/private`).
163fn 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
181/// Bundle path `p` relative to the data directory (`""` for `data` itself).
182fn under_data(p: &str) -> &str {
183    p.strip_prefix(DATA).and_then(|r| r.strip_prefix('/')).unwrap_or("")
184}
185
186/// The most bytes of link paths and targets the walks of one [`refused_links`] may take in all
187/// ([`leaves_data`] charges each link's path and target, and each target it follows): a tree of
188/// many links that each go through a long chain refuses the rest once it is spent, rather than
189/// costing more than a multiple of the manifest's own bytes. A real device's links take a few
190/// kilobytes.
191const WALK_BUDGET: usize = 1 << 24;
192
193/// The bundle's tree under `data/` as a walk looks names up, built once per [`refused_links`]:
194/// each entry's components [folded](crate::manifest::fold) once, keyed by their directory's node
195/// and the folded name, so a walk finds a name in time linear in its length.
196struct Names<'a> {
197    nodes: Vec<Node<'a>>,
198    children: HashMap<(usize, String), usize>,
199}
200
201struct Node<'a> {
202    /// The name as the tree spells it.
203    name: &'a str,
204    /// Whether the tree spells it in two ways that fold alike (`data/Docs` and `data/docs/x`): a
205    /// volume that keeps them apart has two directories there, so no walk goes through it.
206    ambiguous: bool,
207    /// The target, if it is a symlink.
208    link: Option<&'a str>,
209}
210
211/// The node of the data directory itself.
212const 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    /// What name `c` in directory `dir` is: `Ok(Some)` a node of the tree, spelt exactly as the
241    /// tree spells it; `Ok(None)` a name the tree doesn't have, in any spelling a volume could
242    /// take for it (or in a directory the tree doesn't have), which the walk takes as a directory
243    /// (on the disk it doesn't resolve at all); `Err` a name the tree has only in another
244    /// spelling that folds alike (`ı` for `i`, another case), or in two, which one volume
245    /// follows and another doesn't, so the walk can't say where it leads.
246    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
256/// Takes `n` bytes from `budget`, or says it is spent.
257fn 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
267/// Whether a link at `rel` (relative to the data directory) to the relative `target` leads out
268/// of the data directory once resolved as the host resolves it: component by component, through
269/// the tree's own links ([`Names`]: a name followed only as the tree spells it, and refused in
270/// another spelling that folds alike), a `..` past the root leaving it, an absolute link's target
271/// judged by [`names_host`] with what is left of the path, and more than [`MAX_HOPS`] links
272/// refused. Its work is linear in the bytes it charges to `budget` (`rel`, `target` and each
273/// target it follows); a walk that would spend more than is left is refused.
274fn 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
330/// The symlinks in `tree` an import refuses, in tree order: one whose target a bundle can't hold
331/// ([`safe_target`](crate::safe_target)), an absolute one that names the host ([`names_host`]),
332/// a relative one that leads out of `data/` through the tree's links ([`leaves_data`], all of
333/// them within [`WALK_BUDGET`]). The device's daemons run as the host user and would read and
334/// write through them.
335fn 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
348/// What the bundle holds for a symlink at `rel` (relative to the data directory `root`) to
349/// `target`: a relative target as it is (the export then drops those that lead out of the data
350/// directory, [`refused_links`]); an absolute one into the data directory as the same place
351/// relative to the link; another absolute one as it is, unless it names the host (under the
352/// device's own directory, or [`names_host`]). `None` is left out.
353fn 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
374/// Why an import refuses `tree`, if it holds a symlink an export leaves out ([`refused_links`]).
375fn 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
385/// The data directory `root` as bundle contents: every regular file a disk at `data/<path>`,
386/// every directory and symlink and every file's mode an entry, in a stable (sorted) order.
387fn 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
442/// Refuses a bundle path inside the device's own directory (`<set>/<udid>`): an export never
443/// writes into the device it reads.
444fn 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
460/// Exports simulator `udid`, shut down, to a bundle at `to` (a `.tar` file, else a new
461/// directory): its data directory as `data/` ([`left_out`] directories empty), its device type
462/// and runtime (whose build must be installed here, to be recorded). It only reads the device:
463/// a booted one is refused, `to` may not be inside its directory, and a device that boots while
464/// it is read fails the export and its bundle is removed.
465pub 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    // Drop what an import would refuse; dropping a link changes where others lead, so again
480    // until none is left.
481    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
536/// Whether bundle path `p` is the data directory or under it.
537fn in_data(p: &str) -> bool {
538    p == DATA || p.strip_prefix(DATA).is_some_and(|rest| rest.starts_with('/'))
539}
540
541/// The installed runtime that is `want`'s identifier and build, or a refusal that says what to
542/// install (and what this host has instead).
543pub 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
568/// Imports the bundle `reader` opened as a new simulator `name` in the service's set. Before
569/// anything is made: the bundle must be an iOS simulator's with everything under `data/`, its
570/// runtime installed ([`find_runtime`]) and `name` free in the set. Then the device is created
571/// of the bundle's type on that runtime, the bundle extracted and checked beside it, its tree
572/// (directories, symlinks, modes) applied, and the result put in place as its data directory.
573/// A failure after the create deletes the device, so nothing is left behind.
574pub 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
610/// Extracts the bundle into a staging directory beside `data_dir` (in the new device's own
611/// directory), applies `tree`, and swaps the result in for the data directory the service made.
612fn 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/// Makes `tree`'s directories and symlinks under `dest` (where the files were extracted) and
634/// gives each file and directory its mode, directories last and deepest first, so a read-only
635/// one is set after what is in it. Every path is reached through directory fds without
636/// following a link (`beneath`), so even a tree that got past [`Manifest::validate`] can't make
637/// this write, link or chmod outside `dest`.
638#[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// The fake device set uses Unix modes and symlinks, as a simulator's data directory has them.
665#[cfg(all(test, unix))]
666#[path = "ios_tests.rs"]
667mod tests;