use std::collections::{BTreeSet, HashMap, VecDeque};
use std::fs;
use std::path::{Path, PathBuf};
use sim_core::hostfs::PermissionsExt;
use sim_core::platform::Platform;
use crate::{
COLD_BOOT, Captures, Contents, Device, Entry, EntryKind, Error, Extracted, FORMAT, GuestIdentity, Identity, IosSimulator, Manifest,
Options, Reader, Result, Secret, Summary, safe_path,
};
pub const DATA: &str = "data";
pub const GUEST_IDENTIFIERS: [&str; 2] = ["keychain items", "identifiers apps keep in their containers and preferences"];
pub const DUPLICATED_IDENTITY: &str = "the import has a new UDID, but its apps see the device they were exported from: the \
keychain and every app's container and preferences come along";
pub fn left_out(rel: &str) -> bool {
let parts: Vec<&str> = rel.split('/').collect();
matches!(parts.as_slice(), [.., "Library", "Caches"] | ["tmp"] | ["Containers", _, _, _, "tmp"])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Simulator {
pub udid: String,
pub name: String,
pub shut_down: bool,
pub state: String,
pub device_type: String,
pub runtime: String,
pub form_factor: Option<String>,
pub data_dir: PathBuf,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Runtime {
pub identifier: String,
pub name: String,
pub version: String,
pub build: String,
pub available: bool,
}
pub trait Service {
fn device(&self, udid: &str) -> std::result::Result<Simulator, String>;
fn names(&self) -> std::result::Result<Vec<String>, String>;
fn runtimes(&self) -> std::result::Result<Vec<Runtime>, String>;
fn create(&self, name: &str, device_type: &str, runtime: &Runtime) -> std::result::Result<Simulator, String>;
fn delete(&self, udid: &str) -> std::result::Result<(), String>;
}
#[derive(Clone, Debug)]
pub struct Exported {
pub manifest: Manifest,
pub summary: Summary,
pub left_out: Vec<String>,
}
#[derive(Clone, Debug)]
pub struct Imported {
pub device: Simulator,
pub runtime: Runtime,
pub extracted: Extracted,
pub manifest: Manifest,
}
#[derive(Default)]
struct Walk {
disks: Vec<(String, PathBuf)>,
tree: Vec<Entry>,
dropped: Vec<String>,
left_out: Vec<String>,
}
fn io(p: &Path) -> impl FnOnce(std::io::Error) -> Error + '_ {
move |e| Error::Io(p.to_path_buf(), e)
}
fn mode(meta: &fs::Metadata) -> Option<u32> {
Some(meta.permissions().mode() & 0o7777)
}
const HOST_ROOTS: [&str; 12] = [
"/Users",
"/Volumes",
"/private/var/folders",
"/var/folders",
"/private/var/tmp",
"/var/tmp",
"/private/tmp",
"/tmp",
"/Library/Caches",
"/opt/homebrew",
"/Applications",
"/.vol",
];
const DATA_VOLUME: &str = "/System/Volumes/Data";
const HOST_LINKS: [[&str; 2]; 1] = [["Library", "Logs"]];
fn host_linked(trail: &[&str]) -> bool {
let fold = crate::manifest::fold;
trail.len() == 2 && HOST_LINKS.iter().any(|h| fold(trail[0]) == fold(h[0]) && fold(trail[1]) == fold(h[1]))
}
const MAX_HOPS: usize = 32;
fn holds(outer: &str, inner: &str) -> bool {
outer == "/" || outer == inner || inner.strip_prefix(outer).is_some_and(|r| r.starts_with('/'))
}
fn names_host(t: &str) -> bool {
let fold = crate::manifest::fold;
let mut parts = Vec::new();
for c in t.split('/') {
match c {
"" | "." => {}
".." => return true,
c => parts.push(c),
}
}
let data_volume = fold(DATA_VOLUME);
let mut p = fold(&format!("/{}", parts.join("/")));
while let Some(rest) = p.strip_prefix(&data_volume).filter(|r| r.is_empty() || r.starts_with('/')) {
p = if rest.is_empty() { "/".to_owned() } else { rest.to_owned() };
}
holds(&p, &data_volume) || HOST_ROOTS.iter().map(|h| fold(h)).any(|h| holds(&h, &p) || holds(&p, &h))
}
fn under_data(p: &str) -> &str {
p.strip_prefix(DATA).and_then(|r| r.strip_prefix('/')).unwrap_or("")
}
const WALK_BUDGET: usize = 1 << 24;
struct Names<'a> {
nodes: Vec<Node<'a>>,
children: HashMap<(usize, String), usize>,
}
struct Node<'a> {
name: &'a str,
ambiguous: bool,
link: Option<&'a str>,
}
const ROOT: usize = 0;
impl<'a> Names<'a> {
fn new(tree: &'a [Entry]) -> Names<'a> {
let mut names = Names { nodes: vec![Node { name: "", ambiguous: false, link: None }], children: HashMap::new() };
for e in tree {
let rel = under_data(&e.path);
if rel.is_empty() {
continue;
}
let mut at = ROOT;
for c in rel.split('/') {
let next = names.nodes.len();
let n = *names.children.entry((at, crate::manifest::fold(c))).or_insert(next);
if n == next {
names.nodes.push(Node { name: c, ambiguous: false, link: None });
} else if names.nodes[n].name != c {
names.nodes[n].ambiguous = true;
}
at = n;
}
if let (EntryKind::Symlink, Some(t)) = (e.kind, &e.target) {
names.nodes[at].link.get_or_insert(t);
}
}
names
}
fn child(&self, dir: Option<usize>, c: &str) -> std::result::Result<Option<usize>, ()> {
let Some(dir) = dir else { return Ok(None) };
match self.children.get(&(dir, crate::manifest::fold(c))) {
None => Ok(None),
Some(&n) if self.nodes[n].name == c && !self.nodes[n].ambiguous => Ok(Some(n)),
Some(_) => Err(()),
}
}
}
fn charge(budget: &mut usize, n: usize) -> bool {
match budget.checked_sub(n) {
Some(left) => {
*budget = left;
true
}
None => false,
}
}
fn leaves_data(names: &Names, rel: &str, target: &str, budget: &mut usize) -> bool {
if !charge(budget, rel.len() + target.len() + 1) {
return true;
}
let mut parts = rel.split('/');
parts.next_back();
let mut at: Vec<Option<usize>> = Vec::new();
let mut trail: Vec<&str> = Vec::new();
for c in parts {
match names.child(at.last().copied().unwrap_or(Some(ROOT)), c) {
Ok(n) => at.push(n),
Err(()) => return true,
}
trail.push(c);
if host_linked(&trail) {
return true;
}
}
let mut todo: VecDeque<&str> = target.split('/').collect();
let mut hops = 0;
while let Some(c) = todo.pop_front() {
match c {
"" | "." => {}
".." => {
trail.pop();
if at.pop().is_none() {
return true;
}
}
name => {
let Ok(n) = names.child(at.last().copied().unwrap_or(Some(ROOT)), name) else { return true };
let Some(t) = n.and_then(|n| names.nodes[n].link) else {
at.push(n);
trail.push(name);
if host_linked(&trail) {
return true;
}
continue;
};
hops += 1;
if hops > MAX_HOPS || !charge(budget, t.len() + 1) {
return true;
}
if t.starts_with('/') {
let rest: Vec<&str> = todo.into_iter().collect();
return names_host(&format!("{t}/{}", rest.join("/")));
}
for c in t.split('/').rev() {
todo.push_front(c);
}
}
}
}
false
}
fn refused_links(tree: &[Entry]) -> Vec<&Entry> {
let names = Names::new(tree);
let mut budget = WALK_BUDGET;
tree.iter()
.filter(|e| match (e.kind, &e.target) {
(EntryKind::Symlink, Some(t)) if !crate::safe_target(t) => true,
(EntryKind::Symlink, Some(t)) if t.starts_with('/') => names_host(t),
(EntryKind::Symlink, Some(t)) => leaves_data(&names, under_data(&e.path), t, &mut budget),
_ => false,
})
.collect()
}
fn portable_target(root: &Path, rel: &str, target: &Path) -> Option<String> {
let t = target.to_str()?;
if !target.is_absolute() {
return Some(t.to_owned());
}
if let Ok(inside) = target.strip_prefix(root) {
let up = "../".repeat(rel.matches('/').count());
let inside = inside.to_str()?;
return Some(match (up.as_str(), inside) {
("", "") => ".".to_owned(),
(up, "") => up.trim_end_matches('/').to_owned(),
(up, inside) => format!("{up}{inside}"),
});
}
let device_dir = root.parent().filter(|d| d.parent().is_some());
if device_dir.is_some_and(|d| target.starts_with(d)) || names_host(t) {
return None;
}
Some(t.to_owned())
}
fn link_refusal(tree: &[Entry]) -> Option<String> {
let e = *refused_links(tree).first()?;
Some(format!(
"the bundle's symlink `{}` points at `{}`, which resolves to a host path or out of the device's data (through the \
bundle's own links), which an export never writes; it isn't imported",
e.path,
e.target.as_deref().unwrap_or_default()
))
}
fn walk(root: &Path) -> Result<Walk> {
let meta = fs::symlink_metadata(root).map_err(io(root))?;
if !meta.is_dir() {
return Err(Error::Refused(format!("{} isn't a directory", root.display())));
}
let mut w = Walk::default();
w.tree.push(Entry { path: DATA.into(), kind: EntryKind::Dir, mode: mode(&meta), target: None });
walk_dir(root, root, "", &mut w)?;
Ok(w)
}
fn walk_dir(root: &Path, dir: &Path, rel: &str, w: &mut Walk) -> Result<()> {
let mut names = Vec::new();
for e in fs::read_dir(dir).map_err(io(dir))? {
names.push(e.map_err(io(dir))?.file_name());
}
names.sort();
for name in names {
let path = dir.join(&name);
let Some(n) = name.to_str() else {
w.dropped.push(format!("{DATA}/{rel}/{} (a name that isn't UTF-8)", name.to_string_lossy()));
continue;
};
let r = if rel.is_empty() { n.to_owned() } else { format!("{rel}/{n}") };
let at = format!("{DATA}/{r}");
if !safe_path(&at) {
w.dropped.push(format!("{at} (a name a bundle can't hold)"));
continue;
}
let meta = fs::symlink_metadata(&path).map_err(io(&path))?;
let kind = meta.file_type();
if kind.is_symlink() {
let target = fs::read_link(&path).map_err(io(&path))?;
match portable_target(root, &r, &target) {
Some(t) if !crate::safe_target(&t) => w.dropped.push(format!("{at} (a symlink whose target a bundle can't hold)")),
Some(t) => w.tree.push(Entry { path: at, kind: EntryKind::Symlink, mode: None, target: Some(t) }),
None => w.dropped.push(format!("{at} (a symlink to a host path)")),
}
} else if kind.is_dir() {
w.tree.push(Entry { path: at.clone(), kind: EntryKind::Dir, mode: mode(&meta), target: None });
if left_out(&r) {
w.left_out.push(at);
} else {
walk_dir(root, &path, &r, w)?;
}
} else if kind.is_file() {
w.tree.push(Entry { path: at.clone(), kind: EntryKind::File, mode: mode(&meta), target: None });
w.disks.push((at, path));
} else {
w.dropped.push(format!("{at} (a socket, pipe or device node)"));
}
}
Ok(())
}
fn refuse_inside(d: &Simulator, to: &Path) -> Result<()> {
let Some(device_dir) = d.data_dir.parent().and_then(|p| fs::canonicalize(p).ok()) else { return Ok(()) };
let parent = match to.parent() {
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
_ => PathBuf::from("."),
};
if fs::canonicalize(&parent).is_ok_and(|p| p.starts_with(&device_dir)) {
return Err(Error::Refused(format!(
"{} is inside {}'s own directory; export never writes into the device it reads",
to.display(),
d.name
)));
}
Ok(())
}
pub fn export(svc: &dyn Service, udid: &str, to: &Path, opts: &Options) -> Result<Exported> {
let d = svc.device(udid).map_err(Error::Refused)?;
if !d.shut_down {
return Err(Error::Refused(format!("{} must be shut down to export it (it is {})", d.name, d.state)));
}
if !d.data_dir.is_dir() {
return Err(Error::Refused(format!("{} has no data directory yet (boot it once, then shut it down)", d.name)));
}
refuse_inside(&d, to)?;
let runtimes = svc.runtimes().map_err(Error::Refused)?;
let rt = runtimes.iter().find(|r| r.identifier.eq_ignore_ascii_case(&d.runtime)).ok_or_else(|| {
Error::Refused(format!("{}'s runtime {} isn't installed here, so the bundle can't name its build", d.name, d.runtime))
})?;
let mut walked = walk(&d.data_dir)?;
loop {
let refused: BTreeSet<String> = refused_links(&walked.tree).into_iter().map(|e| e.path.clone()).collect();
if refused.is_empty() {
break;
}
walked.tree.retain(|e| !refused.contains(&e.path));
walked.dropped.extend(refused.into_iter().map(|p| format!("{p} (a symlink to a host path)")));
}
let secrets = vec![
Secret {
item: format!("{DATA}/Library/Keychains"),
what: "the device's keychain: passwords, tokens and keys its apps stored".into(),
excludable: false,
},
Secret {
item: format!("{DATA}/Containers/Data"),
what: "each app's data container: may hold accounts, tokens and app data".into(),
excludable: false,
},
];
let header = Manifest {
format: FORMAT,
simee_version: env!("CARGO_PKG_VERSION").into(),
platform: Platform::Ios,
device: Device { name: d.name.clone(), form_factor: d.form_factor.clone() },
identity: Identity::Ios(IosSimulator {
device_type: d.device_type.clone(),
runtime: rt.identifier.clone(),
build: rt.build.clone(),
version: rt.version.clone(),
runtime_name: rt.name.clone(),
}),
captures: Captures { disks: true, ram: false },
resume: COLD_BOOT.into(),
secrets,
guest_identity: GuestIdentity {
on_import: "duplicated".into(),
identifiers: GUEST_IDENTIFIERS.iter().map(|s| (*s).to_owned()).collect(),
},
dropped: walked.dropped,
chunk_size: 0,
compression: String::new(),
disks: Vec::new(),
files: Vec::new(),
tree: walked.tree,
};
let contents = Contents { disks: walked.disks, files: Vec::new() };
let (manifest, summary) = crate::export(header, &contents, to, opts)?;
if !svc.device(udid).is_ok_and(|now| now.shut_down) {
let _ = if to.is_dir() { fs::remove_dir_all(to) } else { fs::remove_file(to) };
return Err(Error::Refused(format!("{} booted while it was exported; the bundle was removed", d.name)));
}
Ok(Exported { manifest, summary, left_out: walked.left_out })
}
fn in_data(p: &str) -> bool {
p == DATA || p.strip_prefix(DATA).is_some_and(|rest| rest.starts_with('/'))
}
pub fn find_runtime(have: &[Runtime], want: &IosSimulator) -> Result<Runtime> {
let same = |r: &&Runtime| r.identifier.eq_ignore_ascii_case(&want.runtime);
if let Some(r) = have.iter().filter(same).find(|r| r.build == want.build && r.available) {
return Ok(r.clone());
}
let near: Vec<String> = have
.iter()
.filter(same)
.map(|r| {
if r.build == want.build {
format!("{} ({}) is unavailable", r.name, r.build)
} else {
format!("{} is build {}", r.name, r.build)
}
})
.collect();
let near = if near.is_empty() { String::new() } else { format!(" (this host: {})", near.join("; ")) };
let platform = want.runtime_name.split_whitespace().next().filter(|p| !p.is_empty()).unwrap_or("iOS");
Err(Error::Refused(format!(
"the bundle needs the {} runtime, build {} ({}), which isn't installed{near}; install it (Xcode > Settings > Components, \
or `xcodebuild -downloadPlatform {platform} -buildVersion {}`) and import again",
want.runtime_name, want.build, want.runtime, want.build
)))
}
pub fn import(svc: &dyn Service, reader: Reader, name: &str) -> Result<Imported> {
if name.trim().is_empty() {
return Err(Error::Refused("give the new device a `name`".into()));
}
let m = reader.manifest().clone();
if m.platform != Platform::Ios {
return Err(Error::Refused(format!("the bundle is an {} device's; this imports iOS simulators", m.platform.label())));
}
let Identity::Ios(id) = &m.identity else {
return Err(Error::Refused("the bundle's manifest names no iOS runtime".into()));
};
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));
if let Some(p) = paths.find(|p| !in_data(p)) {
return Err(Error::Refused(format!("the bundle holds `{p}`, which isn't under {DATA}/ (a simulator's data directory)")));
}
if !m.tree.iter().any(|e| e.path == DATA && e.kind == EntryKind::Dir) {
return Err(Error::Refused(format!("the bundle has no {DATA}/ directory")));
}
if let Some(why) = link_refusal(&m.tree) {
return Err(Error::Refused(why));
}
let runtime = find_runtime(&svc.runtimes().map_err(Error::Refused)?, id)?;
if svc.names().map_err(Error::Refused)?.iter().any(|n| n == name) {
return Err(Error::Refused(format!("a device named `{name}` already exists in this set")));
}
let made = svc.create(name, &id.device_type, &runtime).map_err(Error::Refused)?;
let placed = place(reader, &m.tree, &made.data_dir).and_then(|x| Ok((x, svc.device(&made.udid).map_err(Error::Refused)?)));
match placed {
Ok((extracted, device)) => Ok(Imported { device, runtime, extracted, manifest: m }),
Err(e) => {
let _ = svc.delete(&made.udid);
Err(e)
}
}
}
fn place(reader: Reader, tree: &[Entry], data_dir: &Path) -> Result<Extracted> {
let device_dir = data_dir.parent().ok_or_else(|| Error::Refused(format!("{} has no parent", data_dir.display())))?;
let staging = device_dir.join(".simee-import.partial");
if staging.exists() {
fs::remove_dir_all(&staging).map_err(io(&staging))?;
}
fs::create_dir(&staging).map_err(io(&staging))?;
let done = (|| {
let extracted = reader.extract(&staging)?;
apply_tree(&staging, tree)?;
if fs::symlink_metadata(data_dir).is_ok() {
fs::remove_dir_all(data_dir).map_err(io(data_dir))?;
}
let data = staging.join(DATA);
fs::rename(&data, data_dir).map_err(io(data_dir))?;
Ok(extracted)
})();
let _ = fs::remove_dir_all(&staging);
done
}
#[cfg(unix)]
fn apply_tree(dest: &Path, tree: &[Entry]) -> Result<()> {
let root = crate::beneath::Beneath::new(dest)?;
for e in tree.iter().filter(|e| e.kind == EntryKind::Dir) {
root.mkdir_all(&e.path)?;
}
for e in tree {
match (e.kind, &e.target, e.mode) {
(EntryKind::Symlink, Some(t), _) => root.symlink(&e.path, t)?,
(EntryKind::File, _, Some(m)) => root.chmod(&e.path, m, false)?,
_ => {}
}
}
for e in tree.iter().rev().filter(|e| e.kind == EntryKind::Dir) {
if let Some(m) = e.mode {
root.chmod(&e.path, m, true)?;
}
}
Ok(())
}
#[cfg(not(unix))]
fn apply_tree(_: &Path, _: &[Entry]) -> Result<()> {
Err(Error::Unsupported("an iOS bundle's file tree (directories, symlinks, modes) is written on macOS only".into()))
}
#[cfg(all(test, unix))]
#[path = "ios_tests.rs"]
mod tests;