Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ idevice = { version = "=0.1.68", default-features = false, features = [
"core_device",
"display_stream",
"cryptexd",
"mobile_image_mounter",
"tss",
"installation_proxy",
"springboardservices",
Expand Down
36 changes: 30 additions & 6 deletions apps/iphone-control/src/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,17 @@ fn check(step: &str, t0: Instant, ok: bool, detail: String) -> anyhow::Result<()
}
}

async fn e2e(device: &Device, bundle_id: &str, out: &std::path::Path) -> anyhow::Result<()> {
async fn e2e(device: &Device, legacy_ddi: bool, bundle_id: &str, out: &std::path::Path) -> anyhow::Result<()> {
let t = Instant::now();
let mut tunnel = device.open_tunnel().await?;
check(ictl_l10n::tr!("建隧道", "open tunnel"), t, true, String::new())?;

let t = Instant::now();
let ddi = tunnel.ddi_mounted().await?;
let ddi = if legacy_ddi {
device.legacy_ddi_mounted().await?.then(|| "personalized".to_owned())
} else {
tunnel.ddi_mounted().await?
};
check(
ictl_l10n::tr!("开发者镜像", "developer disk image"),
t,
Expand Down Expand Up @@ -219,8 +223,16 @@ pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {
let screen = ScreenSize { width: args.width, height: args.height };
match args.check {
Check::Ddi { restore_dir, url } => {
// iOS 17–18: the classic personalized image through mobile_image_mounter, in `<restore_dir>/personalized`
let legacy = ictl_device::ddi::legacy(info.major_version());
let files = ictl_device::ddi::files_for(legacy);
let mut t = device.open_tunnel().await?;
match t.ddi_mounted().await? {
let mounted = if legacy {
device.legacy_ddi_mounted().await?.then(|| "personalized".to_owned())
} else {
t.ddi_mounted().await?
};
match mounted {
Some(v) => println!(
"{}",
ictl_l10n::trf!(
Expand All @@ -229,9 +241,20 @@ pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {
)
),
None => {
let dir = ictl_device::ddi::ensure_cache(&restore_dir, &url).await?;
let t0 = Instant::now();
let v = t.mount_ddi(&dir).await?;
let v = if legacy {
let dir = ictl_device::ddi::ensure_cache(
&restore_dir.join("personalized"),
&ictl_device::ddi::personalized_url(&url),
files,
)
.await?;
device.mount_legacy_ddi(&dir).await?;
"personalized".to_owned()
} else {
let dir = ictl_device::ddi::ensure_cache(&restore_dir, &url, files).await?;
t.mount_ddi(&dir).await?
};
println!(
"{}",
ictl_l10n::trf!(
Expand All @@ -242,6 +265,7 @@ pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {
);
}
}
t.close().await;
let t = device.open_tunnel().await?;
println!("universalhidservice: {}", t.has_service("com.apple.coredevice.hid.universalhidservice"));
}
Expand Down Expand Up @@ -477,7 +501,7 @@ pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {
}
Check::E2e { bundle_id, out } => {
let t0 = Instant::now();
e2e(&device, &bundle_id, &out).await?;
e2e(&device, ictl_device::ddi::legacy(info.major_version()), &bundle_id, &out).await?;
println!(
"{}",
ictl_l10n::trf!("全部通过,总耗时 {:.1}s", "All passed in {:.1}s", t0.elapsed().as_secs_f64())
Expand Down
5 changes: 5 additions & 0 deletions crates/ictl-daemon/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ impl Config {
pub fn ddi_cache(&self) -> PathBuf {
self.data_dir.join("ddi")
}
/// The cache of the image a phone takes: `ddi/personalized/` for the classic personalized image (iOS 17–18),
/// `ddi/` for the cryptex one
pub fn ddi_cache_for(&self, legacy: bool) -> PathBuf {
if legacy { self.ddi_cache().join("personalized") } else { self.ddi_cache() }
}
/// 旧版本的锁屏密码:只有一份,不知道是哪台设备的。USB 上只接着一台时归到那台名下(见
/// [`crate::core::Daemon::adopt_legacy_passcode`]),接着多台时不用,免得把一台的密码输进另一台
pub fn legacy_passcode_file(&self) -> PathBuf {
Expand Down
43 changes: 34 additions & 9 deletions crates/ictl-daemon/src/supervise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,9 @@ impl Daemon {
if !matches!(g.state, DeviceState::Preparing { .. }) {
self.set_state(g, DeviceState::Preparing { last_error: None });
}
let (cache, url, user_dir) = (self.cfg.ddi_cache(), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());
let legacy = ictl_device::ddi::legacy(g.info.as_ref().map_or(0, |i| i.major_version()));
let (cache, url, user_dir) =
(self.cfg.ddi_cache_for(legacy), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());
// a WDA launched in the background before (WDA control earlier): not wanted now, ended once the image is up
// (AppService needs it)
let known = g.persisted.detached_for(&device.udid);
Expand All @@ -455,7 +457,7 @@ impl Daemon {
g.preparing = Some(tokio::task::spawn_local(then_wake(wake, async move {
let _lease = lease;
let mut t = device.open_tunnel().await.map_err(|e| (e, false))?;
let r = ensure_ddi(&mut t, &cache, &url, user_dir.as_deref()).await;
let r = ensure_ddi(&device, &mut t, legacy, &cache, &url, user_dir.as_deref()).await;
let stopped = match (&r, known) {
(Ok(_), Some(pid)) => Some((device.udid.clone(), detached::stop(&mut t, pid).await)),
_ => None,
Expand Down Expand Up @@ -517,7 +519,9 @@ impl Daemon {
g.dev.ddi_failures += 1;
if g.dev.ddi_failures >= DDI_FAILURES_INVALIDATE {
self.log.log(&ictl_l10n::log_trf!("开发者镜像连续 {} 次挂载失败,清掉缓存,下次重新下载", "Mounting the developer disk image failed {} times in a row, clearing the cache to download it again", g.dev.ddi_failures));
ictl_device::ddi::invalidate(&self.cfg.ddi_cache());
// the cache of the image this phone takes (the classic personalized one on iOS 17–18)
let legacy = ictl_device::ddi::legacy(g.info.as_ref().map_or(0, |i| i.major_version()));
ictl_device::ddi::invalidate(&self.cfg.ddi_cache_for(legacy), ictl_device::ddi::files_for(legacy));
g.dev.ddi_failures = 0;
}
}
Expand Down Expand Up @@ -606,7 +610,9 @@ impl Daemon {
"The background WDA on the phone (pid {pid}) was launched by an older version and listens on every interface of the phone: launching it again, listening on the phone's loopback only"
));
}
let (cache, url, user_dir) = (self.cfg.ddi_cache(), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());
let legacy = ictl_device::ddi::legacy(g.info.as_ref().map_or(0, |i| i.major_version()));
let (cache, url, user_dir) =
(self.cfg.ddi_cache_for(legacy), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());
let Ok(lease) = crate::maintenance::shared() else { return };
let wake = self.wake.clone();
g.starting = Some(tokio::task::spawn_local(then_wake(wake, async move {
Expand All @@ -617,9 +623,15 @@ impl Daemon {
type Ready = (Option<String>, Result<Detached, DeviceError>, Option<LogStream>);
let ddi: Result<Ready, (DeviceError, bool)> = async {
let mut t = device.open_tunnel().await.map_err(|e| (e, false))?;
let r = ensure_ddi(&mut t, &cache, &url, user_dir.as_deref()).await;
let r = ensure_ddi(&device, &mut t, legacy, &cache, &url, user_dir.as_deref()).await;
let r = match r {
Ok(m) => {
if m.is_some() {
// a tunnel opened before the image was mounted doesn't list its services
// (dtservicehub): a new one, so WDA starts on the first attempt
t.close().await;
t = device.open_tunnel().await.map_err(|e| (e, false))?;
}
// 后台启动前先开系统日志流:认「Enable UI Automation」密码框靠它(见 WdaRunner::attach)
let log = open_log(&device).await;
Ok((m, prepare_detached(&mut t, known, &bundle).await, log))
Expand Down Expand Up @@ -1055,21 +1067,34 @@ fn now_secs() -> u64 {
}

/// 手机重启后开发者镜像可能掉了:没挂就挂上(返回挂上的版本),已挂载时只是一次查询。
/// 错误带上「是不是挂载这一步」(才可能是缓存坏了)
/// 错误带上「是不是挂载这一步」(才可能是缓存坏了)。`legacy`: iOS 17–18 (see [`ictl_device::ddi::legacy`]), `cache` is that
/// image's cache; cryptexd isn't asked on that path
async fn ensure_ddi(
device: &Device,
t: &mut Tunnel,
legacy: bool,
cache: &std::path::Path,
url: &str,
user_dir: Option<&std::path::Path>,
) -> Result<Option<String>, (DeviceError, bool)> {
if t.ddi_mounted().await.map_err(|e| (e, false))?.is_some() {
if legacy {
if device.legacy_ddi_mounted().await.map_err(|e| (e, false))? {
return Ok(None);
}
} else if t.ddi_mounted().await.map_err(|e| (e, false))?.is_some() {
return Ok(None);
}
let files = ictl_device::ddi::files_for(legacy);
let dir = match user_dir {
Some(d) => ictl_device::ddi::require_complete(d),
None => ictl_device::ddi::ensure_cache(cache, url).await,
Some(d) => ictl_device::ddi::require_complete(d, files),
None if legacy => ictl_device::ddi::ensure_cache(cache, &ictl_device::ddi::personalized_url(url), files).await,
None => ictl_device::ddi::ensure_cache(cache, url, files).await,
}
.map_err(|e| (e, false))?;
if legacy {
device.mount_legacy_ddi(&dir).await.map_err(|e| (e, true))?;
return Ok(Some("personalized".to_owned()));
}
Ok(Some(t.mount_ddi(&dir).await.map_err(|e| (e, true))?))
}

Expand Down
84 changes: 68 additions & 16 deletions crates/ictl-device/src/ddi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,42 @@ pub const DEFAULT_BASE_URL: &str =
pub const FILES: [&str; 5] =
["BuildManifest.plist", "Image.dmg", "Image.dmg.trustcache", "Image.dmg.cryptex_info", "Image.dmg.root_hash"];

/// iOS 17–18: the classic personalized image (mounted through `mobile_image_mounter`), next to the cryptex one
/// in the same upstream repository
pub const PERSONALIZED_FILES: [&str; 3] = ["BuildManifest.plist", "Image.dmg", "Image.dmg.trustcache"];

/// Whether a phone takes the classic personalized image through mobile_image_mounter: iOS 17–18 (Apple went from
/// 18 to 26; iOS 26 and later mount the cryptex image through cryptexd). 0 = version unreadable: cryptexd, as before
pub fn legacy(major: u32) -> bool {
(1..26).contains(&major)
}

/// The files of the image the phone takes (see [`legacy`])
pub fn files_for(legacy: bool) -> &'static [&'static str] {
if legacy { &PERSONALIZED_FILES } else { &FILES }
}

/// Where the classic personalized image is downloaded from: the `Xcode_iOS_DDI_Personalized` directory next to
/// the cryptex one (`ICTL_DDI_URL` points at a mirror of the upstream layout)
pub fn personalized_url(base_url: &str) -> String {
let base = base_url.trim_end_matches('/');
match base.rsplit_once('/') {
Some((parent, _)) if !parent.ends_with(":/") => format!("{parent}/Xcode_iOS_DDI_Personalized"),
_ => base.to_owned(),
}
}

/// 记录缓存来自哪个下载地址:换了地址就整套重新下载,免得新旧文件混在一起
const SOURCE_STAMP: &str = ".source";

/// 缓存是否完整
pub fn cache_complete(dir: &Path) -> bool {
FILES.iter().all(|f| dir.join(f).is_file())
pub fn cache_complete(dir: &Path, files: &[&str]) -> bool {
files.iter().all(|f| dir.join(f).is_file())
}

/// 用户自己提供的目录(`ICTL_DDI_DIR`):不下载、不改动,只检查文件齐不齐
pub fn require_complete(dir: &Path) -> Result<PathBuf> {
let missing: Vec<&str> = FILES.iter().copied().filter(|f| !dir.join(f).is_file()).collect();
pub fn require_complete(dir: &Path, files: &[&str]) -> Result<PathBuf> {
let missing: Vec<&str> = files.iter().copied().filter(|f| !dir.join(f).is_file()).collect();
if missing.is_empty() {
return Ok(dir.to_owned());
}
Expand All @@ -41,15 +66,15 @@ pub fn require_complete(dir: &Path) -> Result<PathBuf> {
}

/// 删掉缓存(挂载反复失败时调用,下次重新下载)。只用于守护进程自己下载的缓存目录
pub fn invalidate(dir: &Path) {
for f in FILES.iter().chain([&SOURCE_STAMP]) {
pub fn invalidate(dir: &Path, files: &[&str]) {
for f in files.iter().chain([&SOURCE_STAMP]) {
let _ = std::fs::remove_file(dir.join(f));
}
}

/// 确保 `dir` 里有完整的 DDI,缺的从 `base_url` 下载;返回该目录。
/// 下载先写临时文件再改名,中途失败不会留下半个文件。
pub async fn ensure_cache(dir: &Path, base_url: &str) -> Result<PathBuf> {
pub async fn ensure_cache(dir: &Path, base_url: &str, files: &[&str]) -> Result<PathBuf> {
let stamp = std::fs::read_to_string(dir.join(SOURCE_STAMP)).ok();
if stamp.as_deref().is_some_and(|s| s.trim() != base_url) {
tracing::info!(
Expand All @@ -59,9 +84,9 @@ pub async fn ensure_cache(dir: &Path, base_url: &str) -> Result<PathBuf> {
"The developer disk image download URL changed, downloading again"
)
);
invalidate(dir);
invalidate(dir, files);
}
if cache_complete(dir) {
if cache_complete(dir, files) {
if stamp.is_none() {
// 早期版本下载的缓存没有记录来源:认作当前地址
let _ = std::fs::write(dir.join(SOURCE_STAMP), base_url);
Expand All @@ -73,7 +98,7 @@ pub async fn ensure_cache(dir: &Path, base_url: &str) -> Result<PathBuf> {
.timeout(std::time::Duration::from_secs(600))
.build()
.map_err(|e| DeviceError::Download(e.to_string()))?;
for name in FILES {
for &name in files {
let dest = dir.join(name);
if dest.is_file() {
continue;
Expand Down Expand Up @@ -106,14 +131,41 @@ mod tests {
for f in &FILES[..4] {
std::fs::write(dir.join(f), b"x").unwrap();
}
assert!(!cache_complete(&dir));
assert!(!cache_complete(&dir, &FILES));
std::fs::write(dir.join(FILES[4]), b"x").unwrap();
assert!(cache_complete(&dir));
assert!(require_complete(&dir).is_ok());
invalidate(&dir);
assert!(!cache_complete(&dir));
let e = require_complete(&dir).unwrap_err().to_string();
assert!(cache_complete(&dir, &FILES));
assert!(require_complete(&dir, &FILES).is_ok());
invalidate(&dir, &FILES);
assert!(!cache_complete(&dir, &FILES));
let e = require_complete(&dir, &FILES).unwrap_err().to_string();
assert!(e.contains("BuildManifest.plist") && e.contains("Image.dmg.root_hash"), "{e}");
std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn only_ios_17_and_18_take_the_personalized_image_with_its_three_files_next_to_the_cryptex_one() {
let dir = std::env::temp_dir().join(format!("ictl-ddi-personalized-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
for f in &PERSONALIZED_FILES[..2] {
std::fs::write(dir.join(f), b"x").unwrap();
}
let e = require_complete(&dir, &PERSONALIZED_FILES).unwrap_err().to_string();
assert!(e.contains("Image.dmg.trustcache") && !e.contains("cryptex_info"), "{e}");
std::fs::write(dir.join(PERSONALIZED_FILES[2]), b"x").unwrap();
assert!(cache_complete(&dir, &PERSONALIZED_FILES) && !cache_complete(&dir, &FILES));
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(
personalized_url(DEFAULT_BASE_URL),
"https://raw.githubusercontent.com/doronz88/DeveloperDiskImage/main/PersonalizedImages/Xcode_iOS_DDI_Personalized"
);
assert_eq!(personalized_url("https://mirror.example"), "https://mirror.example");
assert!(legacy(17) && legacy(18));
assert!(!legacy(26) && !legacy(27) && !legacy(0));
assert_eq!(files_for(true), PERSONALIZED_FILES);
assert_eq!(files_for(false), FILES);
assert_eq!(
personalized_url("https://mirror.example/ddi/Xcode_iOS_DDI_Cryptex/"),
"https://mirror.example/ddi/Xcode_iOS_DDI_Personalized"
);
}
}
Loading
Loading