1use std::time::Duration;
8
9use idevice::{
10 IdeviceService, amfi::AmfiClient, lockdown::LockdownClient,
11 mobile_image_mounter::ImageMounter, provider::IdeviceProvider, usbmuxd::UsbmuxdConnection,
12};
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15
16use crate::{
17 actions::{LaunchArgs, ScrollArgs},
18 ax::tree::BuildOptions,
19 device::{
20 ax, conn,
21 session::{Fresh, Session},
22 },
23 fields,
24 i18n::t,
25 reply::Res,
26};
27
28#[derive(Debug, Default, Deserialize)]
29#[serde(default, deny_unknown_fields)]
30pub struct DoctorArgs {
31 pub no_touch_test: bool,
34}
35
36#[derive(Debug, Clone, Serialize)]
37pub struct Check {
38 pub check: &'static str,
39 pub status: &'static str,
41 pub required: bool,
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub user_action: Option<String>,
44 pub auto_fixed: bool,
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub detail: Option<String>,
47}
48
49impl Check {
50 fn new(check: &'static str, required: bool) -> Self {
51 Self {
52 check,
53 status: "ok",
54 required,
55 user_action: None,
56 auto_fixed: false,
57 detail: None,
58 }
59 }
60
61 fn status(mut self, status: &'static str) -> Self {
62 self.status = status;
63 self
64 }
65
66 fn action(mut self, ko: &str, en: &str) -> Self {
67 self.user_action = Some(t(ko, en).to_string());
68 self
69 }
70
71 fn detail(mut self, detail: impl Into<String>) -> Self {
72 self.detail = Some(detail.into());
73 self
74 }
75}
76
77const SETTINGS: &str = "com.apple.Preferences";
78const NEEDED_SERVICES: &[&str] = &[
79 ax::SERVICE,
80 "com.apple.coredevice.displayservice",
81 "com.apple.coredevice.hid.universalhidservice",
82 "com.apple.coredevice.appservice",
83];
84
85async fn with_timeout<T>(fut: impl std::future::Future<Output = T>) -> Option<T> {
86 tokio::time::timeout(Duration::from_secs(15), fut).await.ok()
87}
88
89struct LockdownFacts {
90 developer_mode: Option<bool>,
91 locked: Option<bool>,
93}
94
95async fn lockdown_facts(provider: &dyn IdeviceProvider) -> LockdownFacts {
97 let mut facts = LockdownFacts { developer_mode: None, locked: None };
98 if let Some(Ok(mut mounter)) = with_timeout(ImageMounter::connect(provider)).await {
101 facts.developer_mode = with_timeout(mounter.query_developer_mode_status())
102 .await
103 .and_then(|r| r.ok());
104 }
105 if let Some(Ok(mut lockdown)) = with_timeout(LockdownClient::connect(provider)).await {
106 if let Some(Ok(pairing)) = with_timeout(provider.get_pairing_file()).await {
107 let _ = with_timeout(lockdown.start_session(&pairing)).await;
108 }
109 if facts.developer_mode.is_none() {
110 facts.developer_mode = with_timeout(
111 lockdown.get_value(Some("DeveloperModeStatus"), Some("com.apple.security.mac.amfi")),
112 )
113 .await
114 .and_then(|r| r.ok())
115 .and_then(|v| v.as_boolean());
116 }
117 }
118 facts.locked = conn::passcode_locked(provider).await;
119 facts
120}
121
122async fn missing_services(s: &mut Session) -> Result<Vec<&'static str>, String> {
125 match s.ensure_tunnel().await {
126 Ok(tunnel) => Ok(NEEDED_SERVICES
127 .iter()
128 .filter(|name| !tunnel.rsd.services.contains_key(**name))
129 .copied()
130 .collect()),
131 Err(f) => Err(f.message),
132 }
133}
134
135fn hex_field(v: Option<&plist::Value>) -> Option<u64> {
136 match v? {
137 plist::Value::String(s) => u64::from_str_radix(s.trim_start_matches("0x"), 16).ok(),
138 plist::Value::Integer(i) => i.as_unsigned(),
139 _ => None,
140 }
141}
142
143async fn mount_ddi(provider: &dyn IdeviceProvider) -> anyhow::Result<()> {
149 use anyhow::{Context, anyhow};
150 let restore = crate::ddi::xcode_restore()
151 .ok_or_else(|| anyhow!("no Xcode developer disk image on this computer"))?;
152
153 let manifest_bytes = std::fs::read(restore.join("BuildManifest.plist"))?;
154 let manifest: plist::Value = plist::from_bytes(&manifest_bytes).context("BuildManifest.plist")?;
155
156 let mut lockdown = LockdownClient::connect(provider)
157 .await
158 .map_err(|e| anyhow!("lockdown: {e:?}"))?;
159 if let Ok(pairing) = provider.get_pairing_file().await {
160 let _ = lockdown.start_session(&pairing).await;
161 }
162 let number = |v: plist::Value| v.as_unsigned_integer();
163 let board = lockdown.get_value(Some("BoardId"), None).await.ok().and_then(number);
164 let chip = lockdown.get_value(Some("ChipID"), None).await.ok().and_then(number);
165 let ecid = lockdown
166 .get_value(Some("UniqueChipID"), None)
167 .await
168 .ok()
169 .and_then(number)
170 .ok_or_else(|| anyhow!("the phone did not report its chip id"))?;
171
172 let identities = manifest
173 .as_dictionary()
174 .and_then(|d| d.get("BuildIdentities"))
175 .and_then(|v| v.as_array())
176 .ok_or_else(|| anyhow!("BuildManifest has no BuildIdentities"))?;
177 let identity = identities
178 .iter()
179 .filter_map(|i| i.as_dictionary())
180 .find(|i| hex_field(i.get("ApBoardID")) == board && hex_field(i.get("ApChipID")) == chip)
181 .ok_or_else(|| anyhow!("no Xcode developer disk image on this computer matches this phone model"))?;
182 let path_of = |component: &str| -> anyhow::Result<std::path::PathBuf> {
183 identity
184 .get("Manifest")
185 .and_then(|m| m.as_dictionary())
186 .and_then(|m| m.get(component))
187 .and_then(|c| c.as_dictionary())
188 .and_then(|c| c.get("Info"))
189 .and_then(|i| i.as_dictionary())
190 .and_then(|i| i.get("Path"))
191 .and_then(|p| p.as_string())
192 .map(|p| restore.join(p))
193 .ok_or_else(|| anyhow!("BuildManifest has no path for {component}"))
194 };
195 let image = std::fs::read(path_of("PersonalizedDMG")?)?;
196 let trust_cache = std::fs::read(path_of("LoadableTrustCache")?)?;
197
198 let mut mounter = ImageMounter::connect(provider)
199 .await
200 .map_err(|e| anyhow!("image mounter: {e:?}"))?;
201 mounter
202 .mount_personalized(provider, image, trust_cache, &manifest_bytes, None, ecid)
203 .await
204 .map_err(|e| anyhow!("mount: {e:?}"))
205}
206
207fn front_checks(
215 locked: Option<bool>,
216 launched: Option<Result<bool, String>>,
217 read: Option<Result<bool, String>>,
218) -> (Vec<Check>, bool) {
219 let mut out = Vec::new();
220 if locked == Some(true) {
221 out.push(
222 Check::new("screen_unlocked", true)
223 .status("fail")
224 .detail("the phone reports that it is locked")
225 .action("폰 잠금을 풀어 주세요.", "Unlock the phone."),
226 );
227 return (out, false);
228 }
229 let unlocked = match locked {
230 Some(false) => Check::new("screen_unlocked", true).detail("lockdown: not locked"),
231 _ => Check::new("screen_unlocked", true).detail("lockdown did not say; Settings came to the front"),
232 };
233 if launched == Some(Ok(true)) || read == Some(Ok(true)) {
234 out.push(unlocked);
235 return (out, true);
236 }
237 match (&launched, &read) {
238 (_, Some(Err(why))) => {
239 out.push(match locked {
241 Some(false) => Check::new("screen_unlocked", true).detail("lockdown: not locked"),
242 _ => Check::new("screen_unlocked", true)
243 .status("skipped")
244 .detail("lockdown did not say, and the screen cannot be read"),
245 });
246 out.push(
247 Check::new("accessibility_tree", true)
248 .status("fail")
249 .detail(why.clone())
250 .action(
251 "화면 읽기 응답이 없습니다(폰의 화면 읽기 서비스 axauditd). iph가 그 서비스를 다시 띄웠거나 2분 안에 다시 띄웁니다. 잠시 뒤 `iph doctor`를 다시 실행하고, 계속되면 폰을 재시동하세요.",
252 "No answer from the phone's screen reading (its axauditd service). iph has restarted it or will within 2 minutes. Run `iph doctor` again shortly; if it keeps failing, restart the phone.",
253 ),
254 );
255 }
256 (Some(Err(why)), _) => {
257 out.push(unlocked);
258 out.push(
259 Check::new("settings_in_front", true)
260 .status("fail")
261 .detail(why.clone())
262 .action("설정 앱을 열지 못했습니다. 폰 화면을 확인하고 다시 시도하세요.", "Settings could not be opened. Check the phone's screen and try again."),
263 );
264 }
265 _ => {
266 out.push(unlocked);
268 out.push(
269 Check::new("settings_in_front", true)
270 .status("fail")
271 .detail("Settings was launched but another screen is in front")
272 .action(
273 "설정 앱이 앞에 나오지 않았습니다. 다른 창이나 알림이 가리고 있는지 폰 화면을 확인하세요.",
274 "Settings did not come to the front. Check the phone's screen for a window or alert in the way.",
275 ),
276 );
277 }
278 }
279 (out, false)
280}
281
282pub async fn run(s: &mut Session, args: DoctorArgs) -> Res {
283 let mut checks: Vec<Check> = Vec::new();
284 let skip = |name: &'static str, required: bool, why: &str| {
285 Check::new(name, required).status("skipped").detail(why.to_string())
286 };
287
288 let paired = match UsbmuxdConnection::default().await {
290 Ok(mut mux) => with_timeout(mux.get_pair_record(&s.udid)).await.is_some_and(|r| r.is_ok()),
291 Err(_) => false,
292 };
293 checks.push(if paired {
294 Check::new("pairing", true)
295 } else {
296 Check::new("pairing", true).status("fail").action(
297 "USB로 연결하고 폰에서 '이 컴퓨터를 신뢰'를 누르세요.",
298 "Connect the phone by USB and tap \"Trust This Computer\" on it.",
299 )
300 });
301
302 let route = conn::route(&s.udid).await;
304 let connection = route.as_ref().ok().map(|r| r.connection.clone());
305 checks.push(match &route {
306 Ok(r) => Check::new("connection", true).detail(r.connection.clone()),
307 Err(e) => Check::new("connection", true)
308 .status("fail")
309 .detail(format!("{e:#}"))
310 .action(
311 "폰을 USB로 연결하거나, 컴퓨터와 같은 Wi-Fi에 두고 화면을 켜 주세요.",
312 "Plug the phone in, or put it on the computer's Wi-Fi and wake its screen.",
313 ),
314 });
315
316 let facts = match &route {
318 Ok(r) => Some(lockdown_facts(&*r.provider).await),
319 Err(_) => None,
320 };
321 let dev_mode = facts.as_ref().and_then(|f| f.developer_mode);
322 checks.push(match dev_mode {
323 Some(true) => Check::new("developer_mode", true),
324 Some(false) => {
325 let mut revealed = false;
326 if let Ok(r) = &route
327 && let Some(Ok(mut amfi)) = with_timeout(AmfiClient::connect(&*r.provider)).await {
328 revealed = with_timeout(amfi.reveal_developer_mode_option_in_ui())
329 .await
330 .is_some_and(|r| r.is_ok());
331 }
332 let mut c = Check::new("developer_mode", true).status("fail").action(
333 "설정 → 개인정보 보호 및 보안 → 개발자 모드 → 켜기 → 재시동 후 비밀번호를 입력하세요.",
334 "Settings → Privacy & Security → Developer Mode → turn on → restart, then enter the passcode.",
335 );
336 c.auto_fixed = revealed;
337 if revealed {
338 c = c.detail("the Developer Mode switch was made visible in Settings");
339 }
340 c
341 }
342 None if route.is_ok() => Check::new("developer_mode", true)
343 .status("warn")
344 .detail("could not ask the phone; judged by the services below"),
345 None => skip("developer_mode", true, "phone not reachable"),
346 });
347
348 let mut services_ok = false;
350 if route.is_ok() && dev_mode != Some(false) {
351 let mut missing = missing_services(s).await;
352 let mut mounted_from = None;
353 let mut mount_note = None;
354 if matches!(&missing, Ok(m) if !m.is_empty()) {
355 let cryptex = match s.ensure_tunnel().await {
359 Ok(tunnel) => match tokio::time::timeout(Duration::from_secs(300), crate::ddi::install(tunnel)).await {
360 Ok(r) => r,
361 Err(_) => Err(anyhow::anyhow!("timed out")),
362 },
363 Err(f) => Err(anyhow::anyhow!(f.message)),
364 };
365 match cryptex {
366 Ok(source) => mounted_from = Some(source),
367 Err(e) => {
368 let mut note = format!("cryptex install failed: {e:#}");
369 if let Ok(r) = &route {
370 match tokio::time::timeout(Duration::from_secs(180), mount_ddi(&*r.provider)).await {
371 Ok(Ok(())) => mounted_from = Some("Xcode".to_string()),
372 Ok(Err(e)) => note.push_str(&format!("; image mounter: {e:#}")),
373 Err(_) => note.push_str("; image mounter timed out"),
374 }
375 }
376 if mounted_from.is_none() {
377 mount_note = Some(note);
378 }
379 }
380 }
381 if mounted_from.is_some() {
382 s.reset();
383 tokio::time::sleep(Duration::from_secs(2)).await;
384 missing = missing_services(s).await;
385 }
386 }
387 let mounted_now = mounted_from.is_some();
388 match missing {
389 Ok(m) if m.is_empty() => {
390 services_ok = true;
391 let mut c = Check::new("developer_disk_image", true);
392 c.auto_fixed = mounted_now;
393 if let Some(from) = &mounted_from {
394 c = c.detail(format!("installed the developer disk image ({from})"));
395 }
396 checks.push(c);
397 }
398 Ok(m) => {
399 let mut detail = format!("missing services: {}", m.join(", "));
400 if let Some(note) = mount_note {
401 detail.push_str("; ");
402 detail.push_str(¬e);
403 }
404 checks.push(Check::new("developer_disk_image", true).status("fail").detail(detail).action(
405 "개발자 디스크 이미지를 연결하지 못했습니다. 인터넷 연결(애플 서명 서버, GitHub)을 확인하고 다시 `iph doctor`를 실행하세요. 맥이라면 Xcode의 창 → 기기 및 시뮬레이터에서 이 폰을 한 번 골라도 됩니다.",
406 "Could not install the developer disk image. Check the internet connection (Apple's signing server, GitHub) and run `iph doctor` again. On a Mac, selecting this phone once in Xcode → Window → Devices and Simulators also works.",
407 ));
408 }
409 Err(message) => checks.push(
410 Check::new("developer_disk_image", true)
411 .status("fail")
412 .detail(message)
413 .action(
414 "폰 잠금을 풀고 다시 시도하세요. 계속 실패하면 USB로 연결하세요.",
415 "Unlock the phone and try again. If it keeps failing, connect by USB.",
416 ),
417 ),
418 }
419 } else {
420 checks.push(skip(
421 "developer_disk_image",
422 true,
423 if route.is_ok() { "Developer Mode is off" } else { "phone not reachable" },
424 ));
425 }
426
427 checks.push(match connection.as_deref() {
429 Some("wifi") => Check::new("wifi", false),
430 Some(_) => {
431 let also_wifi = conn::list_raw().await.ok().is_some_and(|all| {
432 all.iter().any(|d| {
433 d.udid == s.udid && matches!(d.connection_type, idevice::usbmuxd::Connection::Network(_))
434 })
435 });
436 if also_wifi {
437 Check::new("wifi", false).detail("reachable over Wi-Fi as well as USB")
438 } else {
439 Check::new("wifi", false).status("warn").action(
440 "케이블 없이 쓰려면 폰과 컴퓨터를 같은 Wi-Fi에 두세요. (맥은 Finder, 윈도는 Apple 기기 앱에서 폰을 고르고 'Wi-Fi에 있을 때 이 iPhone 보기'를 켜야 할 수 있습니다.)",
441 "To work without the cable, put the phone and the computer on the same Wi-Fi. (You may need \"Show this iPhone when on Wi-Fi\" in Finder on a Mac, or in the Apple Devices app on Windows.)",
442 )
443 }
444 }
445 None => skip("wifi", false, "phone not reachable"),
446 });
447
448 let locked = facts.as_ref().and_then(|f| f.locked);
454 let mut front_ok = false;
455 let mut tree_reported = false;
456 if locked == Some(true) || services_ok {
457 let launched = if locked == Some(true) {
458 None
459 } else {
460 Some(match s.cmd_launch(LaunchArgs { app: SETTINGS.into(), restart: false }).await {
461 Ok(r) => Ok((
462 r.get("foreground").and_then(|v| v.as_bool()) == Some(true),
463 r.get("pid").and_then(|v| v.as_i64()),
464 )),
465 Err(f) => Err(f.message),
466 })
467 };
468 let read = match &launched {
470 None | Some(Ok((true, _))) => None,
471 Some(other) => {
472 let pid = other.as_ref().ok().and_then(|(_, pid)| *pid);
473 Some(match s.screen(Fresh::Force, false, BuildOptions::default()).await {
474 Ok((_, screen)) => Ok(pid.is_some_and(|p| screen.apps.iter().any(|a| a.pid == p))),
475 Err(f) => Err(f.message),
476 })
477 }
478 };
479 let launched = launched.map(|l| l.map(|(front, _)| front));
480 let (found, front) = front_checks(locked, launched, read);
481 tree_reported = found.iter().any(|c| c.check == "accessibility_tree");
482 front_ok = front;
483 checks.extend(found);
484 } else {
485 checks.push(skip("screen_unlocked", true, "developer services unavailable"));
486 }
487
488 let mut tree_ok = false;
490 if front_ok {
491 match s.screen(Fresh::Force, false, BuildOptions::default()).await {
492 Ok((_, screen)) if screen.elements.len() > 1 => {
493 tree_ok = true;
494 checks.push(
495 Check::new("accessibility_tree", true)
496 .detail(format!("{} elements", screen.elements.len())),
497 );
498 }
499 Ok(_) => checks.push(Check::new("accessibility_tree", true).status("fail").action(
500 "폰 화면이 켜져 있는지 확인하고 다시 시도하세요.",
501 "Make sure the phone's screen is on and try again.",
502 )),
503 Err(f) => checks.push(
504 Check::new("accessibility_tree", true)
505 .status("fail")
506 .detail(f.message)
507 .action(
508 "폰 화면이 켜져 있는지 확인하고 다시 시도하세요.",
509 "Make sure the phone's screen is on and try again.",
510 ),
511 ),
512 }
513 } else if !tree_reported {
514 checks.push(skip("accessibility_tree", true, "Settings is not in front"));
515 }
516
517 if args.no_touch_test {
519 checks.push(skip("touch_input", true, "--no-touch-test"));
520 } else if tree_ok {
521 let mut verdict: Option<Check> = None;
524 let mut last_detail = String::new();
525 for (there, back) in [("down", "up"), ("up", "down")] {
526 let moved = s
527 .cmd_scroll(ScrollArgs { direction: there.into(), until: None, max: None })
528 .await;
529 match &moved {
530 Ok(r) if r.get("screen_changed").and_then(|v| v.as_bool()) == Some(true) => {
531 let _ = s
533 .cmd_scroll(ScrollArgs { direction: back.into(), until: None, max: None })
534 .await;
535 let mut check = Check::new("touch_input", true);
536 if there == "up" {
537 check = check.detail("the first drag did not move the screen; the second did");
538 }
539 verdict = Some(check);
540 break;
541 }
542 Ok(_) => last_detail = "the drags were sent but the screen did not move".to_string(),
543 Err(f) => last_detail = f.message.clone(),
544 }
545 }
546 checks.push(verdict.unwrap_or_else(|| {
547 Check::new("touch_input", true).status("fail").detail(last_detail).action(
548 "설정 → 개발자 → 'UI 자동화 활성화'를 켜고 다시 시도하세요. 그래도 안 되면 폰을 재시동하세요.",
549 "Turn on Settings → Developer → Enable UI Automation and try again. If it still fails, restart the phone.",
550 )
551 }));
552 } else {
553 checks.push(skip("touch_input", true, "no accessibility tree"));
554 }
555
556 checks.push(Check::new("auto_lock", false).status("info").action(
558 "오래 쓸 때는 설정 → 디스플레이 및 밝기 → 자동 잠금 → '안 함'을 권합니다. 폰이 잠기면 읽기와 입력이 멈춥니다.",
559 "For long sessions set Settings → Display & Brightness → Auto-Lock → Never. Reading and input stop when the phone locks.",
560 ));
561
562 if let Some(left) = &s.dnd.record {
565 checks.push(
566 Check::new("do_not_disturb", false)
567 .status("info")
568 .detail(format!("on since {}, set by iph", left.at))
569 .action(
570 "`iph dnd on`으로 켠 방해금지 모드가 켜져 있습니다. `iph dnd off`로 원래대로 되돌릴 수 있습니다.",
571 "Do Not Disturb from `iph dnd on` is on. `iph dnd off` puts the earlier Focus back.",
572 ),
573 );
574 }
575
576 let ok = checks
577 .iter()
578 .all(|c| !c.required || c.status == "ok");
579 let failing: Vec<Value> = checks
580 .iter()
581 .filter(|c| c.required && c.status != "ok")
582 .map(|c| json!(c.check))
583 .collect();
584 Ok(fields! {
585 "ready": ok,
586 "udid": s.udid.clone(),
587 "connection": connection,
588 "failing": failing,
589 "checks": checks,
590 })
591}
592
593#[cfg(test)]
594mod tests {
595 use super::*;
596
597 fn says(checks: &[Check]) -> String {
598 checks
599 .iter()
600 .map(|c| format!("{} {} {}", c.check, c.status, c.user_action.as_deref().unwrap_or("")))
601 .collect::<Vec<_>>()
602 .join("\n")
603 }
604
605 #[test]
606 fn an_unreadable_screen_on_an_unlocked_phone_is_not_called_a_lock() {
607 let (checks, front) = front_checks(
610 Some(false),
611 Some(Ok(false)),
612 Some(Err("no accessibility tree within 14000 ms (3 empty, 0 not understood)".into())),
613 );
614 let text = says(&checks);
615 assert!(!front);
616 assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
617 assert!(text.contains("screen_unlocked ok"), "{text}");
618 assert!(text.contains("accessibility_tree fail"), "{text}");
619 let (checks, _) = front_checks(None, Some(Ok(false)), Some(Err("ax_timeout".into())));
621 let text = says(&checks);
622 assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
623 assert!(text.contains("accessibility_tree fail"), "{text}");
624 }
625
626 #[test]
627 fn only_lockdown_makes_it_a_lock() {
628 let (checks, front) = front_checks(Some(true), None, None);
629 assert!(!front);
630 assert_eq!(checks.len(), 1);
631 assert_eq!(checks[0].check, "screen_unlocked");
632 assert_eq!(checks[0].status, "fail");
633 assert!(checks[0].user_action.is_some());
634 }
635
636 #[test]
637 fn another_screen_in_front_is_said_as_such() {
638 let (checks, front) = front_checks(Some(false), Some(Ok(false)), Some(Ok(false)));
639 let text = says(&checks);
640 assert!(!front);
641 assert!(text.contains("settings_in_front fail"), "{text}");
642 assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
643 }
644
645 #[test]
646 fn settings_in_front_passes() {
647 assert!(front_checks(Some(false), Some(Ok(true)), None).1);
648 assert!(front_checks(None, Some(Ok(false)), Some(Ok(true))).1);
650 }
651}