1use std::path::{Path, PathBuf};
15
16use anyhow::{Context, Result, anyhow, bail};
17use idevice::services::cryptexd::{Cryptex1Assets, install_ddi, installed_ddi};
18use sha2::{Digest, Sha256};
19
20use crate::{device::conn::Tunnel, paths};
21
22const REPO_COMMIT: &str = "a1020f81b6429f5ce40408cbe21c690512b613b5";
23const REPO_DIR: &str = "PersonalizedImages/Xcode_iOS_DDI_Cryptex";
24
25const FILES: [(&str, &str); 5] = [
27 ("BuildManifest.plist", "537391eb2f37e604fc693f422c1568af97220067853e663391ba3e8258569d6e"),
28 ("Image.dmg", "500d4139f7963650e6c796d950267ed38909e7d183ad26bba073257529bfe173"),
29 ("Image.dmg.cryptex_info", "0180ee20ce5daa7978fe38f24c742361726789ea6af82c3c1d2afc480734a531"),
30 ("Image.dmg.root_hash", "5f3281961396be5fe008e11641ffc25c7db24c11d3789ff0c4ff0fa6d47b94ca"),
31 ("Image.dmg.trustcache", "2719aa3f1c99245432512116fb8a56d55ec224c706e545772d4c17c1233ac475"),
32];
33
34pub fn xcode_restore() -> Option<PathBuf> {
36 [
37 PathBuf::from("/Library/Developer/DeveloperDiskImages/iOS_DDI/Restore"),
38 paths::home().join("Library/Developer/DeveloperDiskImages/iOS_DDI/Restore"),
39 ]
40 .into_iter()
41 .find(|p| p.join("BuildManifest.plist").exists())
42}
43
44fn sha256_of(path: &Path) -> Result<String> {
45 let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
46 Ok(format!("{:x}", Sha256::digest(&bytes)))
47}
48
49fn cache_ok(dir: &Path) -> bool {
50 FILES
51 .iter()
52 .all(|(name, sum)| sha256_of(&dir.join(name)).is_ok_and(|s| s == *sum))
53}
54
55pub async fn fetched() -> Result<PathBuf> {
58 let dir = paths::ddi_cache().join(&REPO_COMMIT[..12]);
59 if cache_ok(&dir) {
60 return Ok(dir);
61 }
62 paths::ensure_private_dir(&dir)?;
63 for (name, sum) in FILES {
64 let target = dir.join(name);
65 if sha256_of(&target).is_ok_and(|s| s == sum) {
66 continue;
67 }
68 let url = format!("https://raw.githubusercontent.com/doronz88/DeveloperDiskImage/{REPO_COMMIT}/{REPO_DIR}/{name}");
69 let partial = dir.join(format!("{name}.part"));
70 let status = tokio::process::Command::new("curl")
71 .args(["-fsSL", "--retry", "2", "-o"])
72 .arg(&partial)
73 .arg(&url)
74 .status()
75 .await
76 .context("run curl")?;
77 if !status.success() {
78 bail!("download {name} failed ({status})");
79 }
80 let got = sha256_of(&partial)?;
81 if got != sum {
82 let _ = std::fs::remove_file(&partial);
83 bail!("{name}: checksum {got} does not match {sum}");
84 }
85 std::fs::rename(&partial, &target)?;
86 }
87 Ok(dir)
88}
89
90pub async fn install(tunnel: &mut Tunnel) -> Result<String> {
92 let mut adapter = tunnel.adapter.clone();
93 if installed_ddi(&mut adapter, &mut tunnel.rsd).await.ok().flatten().is_some() {
94 return Ok("already installed".into());
95 }
96 let mut errors = Vec::new();
98 let mut sources = Vec::new();
99 if let Some(dir) = xcode_restore() {
100 sources.push(("Xcode", dir));
101 }
102 match fetched().await {
103 Ok(dir) => sources.push(("DeveloperDiskImage repository", dir)),
104 Err(e) => errors.push(format!("fetch: {e:#}")),
105 }
106 for (label, dir) in sources {
107 let assets = match Cryptex1Assets::load(&dir).await {
108 Ok(a) => a,
109 Err(e) => {
110 errors.push(format!("{label}: {e:?}"));
111 continue;
112 }
113 };
114 let mut adapter = tunnel.adapter.clone();
115 match install_ddi(&mut adapter, &mut tunnel.rsd, &assets).await {
116 Ok(_) => return Ok(label.to_string()),
117 Err(e) => errors.push(format!("{label}: {e:?}")),
118 }
119 }
120 Err(anyhow!(errors.join("; ")))
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126
127 #[tokio::test]
129 #[ignore]
130 async fn fetch_and_load() {
131 let dir = std::env::temp_dir().join(format!("iph-ddi-{}", std::process::id()));
132 unsafe { std::env::set_var("IPH_STATE_DIR", &dir) };
133 let restore = fetched().await.unwrap();
134 assert!(cache_ok(&restore));
135 let assets = Cryptex1Assets::load(&restore).await.unwrap();
136 assert!(assets.image.len() > 1_000_000);
137 assert_eq!(fetched().await.unwrap(), restore);
139 std::fs::remove_dir_all(&dir).unwrap();
140 }
141}