Skip to main content

iphone_cli/
diagnose.rs

1//! Collect an issue attachment without needing a selected or reachable phone.
2
3use std::{
4    collections::{BTreeSet, VecDeque},
5    future::Future,
6    io::{Read, Seek, SeekFrom, Write},
7    net::SocketAddr,
8    path::{Path, PathBuf},
9    process::Stdio,
10    sync::{Arc, Mutex},
11    time::{Duration, Instant},
12};
13
14use anyhow::{Context, Result};
15use idevice::{
16    IdeviceService, lockdown::LockdownClient, mobile_image_mounter::ImageMounter,
17    provider::IdeviceProvider,
18};
19use serde_json::{Value, json};
20use tokio::{
21    io::{AsyncReadExt, AsyncWriteExt},
22    process::Command,
23};
24
25use crate::{
26    config::Config,
27    device::conn,
28    events, fields,
29    i18n::t,
30    paths,
31    reply::{Fail, Res},
32};
33
34const CAPTURE_BYTES: usize = 256 * 1024;
35const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
36
37#[derive(Debug, Clone, clap::Args)]
38pub struct Args {
39    /// Save the attachment here (default: iph-diagnostics-<time>-<pid>.txt).
40    #[arg(short, long)]
41    pub output: Option<PathBuf>,
42    /// Start with USB connected; observe discovery while you unplug it.
43    #[arg(long)]
44    pub wifi: bool,
45    /// Seconds to observe after the USB baseline with --wifi.
46    #[arg(long, default_value_t = 30, value_parser = clap::value_parser!(u64).range(1..=300))]
47    pub duration: u64,
48    /// Maximum run time of the iph command supplied after --.
49    #[arg(long, default_value_t = 120, value_parser = clap::value_parser!(u64).range(1..=900))]
50    pub command_timeout: u64,
51    /// Optional iph command to run once and capture, e.g. -- read --full.
52    #[arg(last = true, value_name = "IPH_COMMAND")]
53    pub command: Vec<String>,
54}
55
56struct Report {
57    path: PathBuf,
58    data: Value,
59}
60
61impl Report {
62    fn new(path: PathBuf, args: &Args) -> Result<Self> {
63        // Refuse accidental overwrites; reports can be compared across runs.
64        paths::private_file()
65            .write(true)
66            .create_new(true)
67            .open(&path)
68            .with_context(|| format!("cannot create {}", path.display()))?;
69        let report = Self {
70            path,
71            data: json!({
72                "schema_version": 1, "status": "collecting", "started_at": crate::clock::now_utc(),
73                "started_unix_ms": events::now_ms(), "wifi_observation": args.wifi,
74                "observation_seconds": if args.wifi { args.duration } else { 5 },
75                "environment": { "iph_version": env!("CARGO_PKG_VERSION"), "build": crate::daemon::build_stamp(),
76                    "os": std::env::consts::OS, "arch": std::env::consts::ARCH },
77                "snapshots": [], "discovery_timeline": [], "findings": [],
78            }),
79        };
80        report.save()?;
81        Ok(report)
82    }
83
84    fn save(&self) -> Result<()> {
85        let mut file = paths::private_file()
86            .write(true)
87            .truncate(true)
88            .open(&self.path)?;
89        serde_json::to_writer_pretty(&mut file, &self.data)?;
90        file.write_all(b"\n")?;
91        file.sync_data()?;
92        Ok(())
93    }
94
95    fn push(&mut self, key: &str, value: Value) {
96        self.data[key].as_array_mut().unwrap().push(value);
97    }
98}
99
100pub async fn run(args: Args, flag: Option<String>) -> Res {
101    let path = args.output.clone().unwrap_or_else(|| {
102        PathBuf::from(format!(
103            "iph-diagnostics-{}-{}.txt",
104            crate::clock::now_utc().replace([':', '-'], ""),
105            std::process::id(),
106        ))
107    });
108    let path =
109        std::path::absolute(path).map_err(|e| Fail::not_sent("diagnostic_file", e.to_string()))?;
110    let mut report = Report::new(path, &args)
111        .map_err(|e| Fail::not_sent("diagnostic_file", format!("{e:#}")))?;
112    eprintln!(
113        "{} {}",
114        t("진단 파일을 수집합니다:", "Collecting diagnostics:"),
115        report.path.display()
116    );
117    let interrupted = tokio::select! {
118        result = collect(&mut report, &args, flag) => {
119            if let Err(error) = result { report.data["collection_error"] = json!(format!("{error:#}")); }
120            false
121        }
122        result = tokio::signal::ctrl_c() => {
123            report.data["interrupt"] = json!(result.err().map(|e| e.to_string()));
124            true
125        }
126    };
127    report.data["status"] = json!(if interrupted {
128        "interrupted"
129    } else if report.data["collection_error"].is_string() {
130        "partial"
131    } else {
132        "complete"
133    });
134    report.data["finished_at"] = json!(crate::clock::now_utc());
135    report.data["recent_events"] = recent_events();
136    report.data["daemon_logs"] = daemon_logs(report.data["selected_udid"].as_str());
137    report.data["findings"] = json!(findings(&report.data));
138    report
139        .save()
140        .map_err(|e| Fail::not_sent("diagnostic_file", format!("{e:#}")))?;
141    Ok(
142        fields! { "report": report.path, "interrupted": interrupted, "findings": report.data["findings"],
143        "hint": t("GitHub 이슈에 이 파일을 첨부해 주세요.", "Attach this file to your GitHub issue.") },
144    )
145}
146
147async fn collect(report: &mut Report, args: &Args, flag: Option<String>) -> Result<()> {
148    let config = Config::load();
149    let mut chosen = flag
150        .filter(|s| !s.is_empty())
151        .or_else(|| std::env::var("IPH_UDID").ok().filter(|s| !s.is_empty()))
152        .or_else(|| config.as_ref().ok().and_then(|c| c.udid.clone()));
153    report.data["config"] = match &config {
154        Ok(c) => json!({ "path": paths::config_file(), "values": c }),
155        Err(e) => json!({ "error": format!("{e:#}") }),
156    };
157    let mut env = serde_json::Map::new();
158    for key in [
159        "IPH_UDID",
160        "IPH_PREFER",
161        "IPH_LOG",
162        "IPH_TRACE",
163        "IPH_STATE_DIR",
164        "IPH_CONFIG_DIR",
165        "IPH_INPUT_WARMUP_MS",
166        "IPH_INPUT_PRIME",
167        "IPH_REUSE_MS",
168        "IPH_REOPEN_GAP_MS",
169        "IPH_PCAP",
170        "IPH_DUMP_DIR",
171        "USBMUXD_SOCKET_ADDRESS",
172    ] {
173        if let Ok(value) = std::env::var(key) {
174            env.insert(key.into(), json!(value));
175        }
176    }
177    report.data["environment"]["variables"] = json!(env);
178    report.data["environment"]["usbmuxd_address"] = json!(format!("{:?}", conn::mux_addr()));
179    report.save()?;
180
181    if args.wifi {
182        eprintln!(
183            "{}",
184            t(
185                "USB 연결 상태를 먼저 기록합니다. 아직 케이블을 빼지 마세요.",
186                "Recording the USB baseline. Keep the cable connected for now."
187            )
188        );
189    }
190    // Preserve the original failure before opening diagnostic sessions. The
191    // Wi-Fi mode needs USB facts first, while that route is still available.
192    let before = snapshot("before", &mut chosen, args.wifi || args.command.is_empty()).await;
193    report.data["selected_udid"] = json!(chosen);
194    report.push("snapshots", before);
195    report.save()?;
196    if !args.wifi {
197        reproduce(report, args, &chosen).await?;
198    }
199    if args.wifi {
200        eprintln!(
201            "{} {} {}",
202            t("이제 USB 케이블을 빼세요.", "Unplug the USB cable now."),
203            args.duration,
204            t(
205                "초 동안 기기 목록과 Bonjour 변화를 기록합니다.",
206                "seconds of discovery and Bonjour changes will be recorded."
207            )
208        );
209    }
210
211    let window = Duration::from_secs(if args.wifi { args.duration } else { 5 });
212    let browse_args = ["-B".into(), "_apple-mobdev2._tcp".into(), "local.".into()];
213    let browse = capture("dns-sd", &browse_args, window);
214    let observe = async {
215        if args.wifi {
216            let start = Instant::now();
217            while start.elapsed() < window {
218                let listing = list_snapshot().await;
219                report.push("discovery_timeline", json!({ "at": crate::clock::now_utc(), "unix_ms": events::now_ms(), "listing": listing }));
220                report.save()?;
221                tokio::time::sleep(
222                    Duration::from_secs(1).min(window.saturating_sub(start.elapsed())),
223                )
224                .await;
225            }
226        }
227        Ok::<_, anyhow::Error>(())
228    };
229    let (mut bonjour, observation) = tokio::join!(browse, observe);
230    observation?;
231    bonjour["observation_complete"] = bonjour["timed_out"].clone();
232    bonjour["note"] = json!(
233        "Advertisements may belong to other devices. Absence alone does not identify whether the phone, network, or host blocked discovery."
234    );
235    report.data["bonjour"] = bonjour;
236    report.save()?;
237    report.data["bonjour"]["resolved_services"] =
238        resolve_services(report.data["bonjour"]["stdout"].as_str().unwrap_or("")).await;
239    report.save()?;
240
241    if args.wifi {
242        reproduce(report, args, &chosen).await?;
243    }
244    report.push("snapshots", snapshot("after", &mut chosen, true).await);
245    report.data["selected_udid"] = json!(chosen);
246    report.save()?;
247
248    let commands: &[(&str, &[&str])] = if cfg!(target_os = "macos") {
249        &[
250            ("sw_vers", &[]),
251            ("uname", &["-a"]),
252            ("ifconfig", &[]),
253            ("scutil", &["--nwi"]),
254            ("scutil", &["--nc", "list"]),
255            ("route", &["-n", "get", "default"]),
256        ]
257    } else if cfg!(windows) {
258        &[
259            ("cmd", &["/C", "ver"]),
260            ("ipconfig", &["/all"]),
261            ("route", &["print"]),
262        ]
263    } else {
264        &[("uname", &["-a"]), ("ip", &["address"]), ("ip", &["route"])]
265    };
266    let host = futures_util::future::join_all(commands.iter().map(|(program, argv)| async move {
267        capture(
268            program,
269            &argv.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
270            PROBE_TIMEOUT,
271        )
272        .await
273    }))
274    .await;
275    report.data["environment"]["host_commands"] = json!(host);
276    report.save()?;
277    if cfg!(target_os = "macos") {
278        report.data["system_logs"] = capture("log", &[
279            "show", "--last", "10m", "--style", "compact", "--info", "--predicate",
280            "process == 'usbmuxd' OR process == 'mDNSResponder' OR process == 'AMPDevicesAgent'",
281        ].map(String::from), Duration::from_secs(10)).await;
282    } else {
283        report.data["system_logs"] = json!({ "status": "unavailable", "reason": "macOS unified logs are not available on this platform" });
284    }
285    Ok(())
286}
287
288async fn list_snapshot() -> Value {
289    match conn::list_raw().await {
290        Ok(devices) => json!({ "ok": true, "devices": conn::describe_raw(&devices) }),
291        Err(error) => json!({ "ok": false, "error": format!("{error:#}") }),
292    }
293}
294
295async fn reproduce(report: &mut Report, args: &Args, chosen: &Option<String>) -> Result<()> {
296    if args.command.is_empty() {
297        return Ok(());
298    }
299    let exe = std::env::current_exe()?;
300    let mut argv = Vec::new();
301    if let Some(udid) = chosen
302        && !args
303            .command
304            .iter()
305            .any(|s| s == "--udid" || s.starts_with("--udid="))
306    {
307        argv.extend(["--udid".into(), udid.clone()]);
308    }
309    argv.extend(args.command.iter().cloned());
310    report.data["reproduction"] = json!({ "command": exe, "args": argv, "status": "started", "started_at": crate::clock::now_utc() });
311    report.save()?;
312    eprintln!(
313        "{} {:?}",
314        t(
315            "문제 명령을 한 번 실행합니다:",
316            "Running the reproduction command once:"
317        ),
318        args.command
319    );
320    report.data["reproduction"] = capture(
321        exe.as_os_str(),
322        &argv,
323        Duration::from_secs(args.command_timeout),
324    )
325    .await;
326    report.save()
327}
328
329async fn snapshot(phase: &str, chosen: &mut Option<String>, probe: bool) -> Value {
330    let mut out = json!({ "phase": phase, "at": crate::clock::now_utc(), "unix_ms": events::now_ms(), "probes": [] });
331    out["raw_usbmuxd"] = match raw_mux_listing().await {
332        Ok(value) => json!({ "ok": true, "response": value }),
333        Err(e) => json!({ "ok": false, "error": format!("{e:#}") }),
334    };
335    let (discovered, listing_error) = match crate::device::discovery::read().await {
336        Ok(devices) => (devices, None),
337        Err(error) => {
338            let error = format!("{error:#}");
339            out["listing"] = json!({ "ok": false, "error": error });
340            (crate::device::discovery::Discovery::default(), Some(error))
341        }
342    };
343    let devices: Vec<_> = discovered.devices.iter().map(|d| d.mux.clone()).collect();
344    if listing_error.is_none() {
345        out["listing"] = json!({ "ok": true, "devices": conn::describe_raw(&devices), "warnings": discovered.warnings });
346    }
347    if chosen.is_none() {
348        let ids: BTreeSet<_> = devices.iter().map(|d| d.udid.clone()).collect();
349        if ids.len() == 1 {
350            *chosen = ids.into_iter().next();
351        }
352    }
353    out["selected_udid"] = json!(chosen);
354    let Some(udid) = chosen.as_ref() else {
355        out["selection"] = json!(if devices.is_empty() {
356            "no_device"
357        } else {
358            "multiple_devices; choose --udid to probe one"
359        });
360        return out;
361    };
362    if !probe {
363        out["probe_note"] = json!("Active probes deferred until after the reproduction command");
364        return out;
365    }
366    for device in discovered.devices.iter().filter(|d| &d.mux.udid == udid) {
367        let route = match conn::route_device(device).await {
368            Ok(route) => route,
369            Err(e) => {
370                out["probes"].as_array_mut().unwrap().push(json!({ "connection": conn::conn_name(&device.mux.connection_type), "error": format!("{e:#}") }));
371                continue;
372            }
373        };
374        let mut probe = probe_provider(udid, &route.connection, &*route.provider).await;
375        probe["transport"] = json!(if route.address.is_some() { "tcp" } else { "usbmuxd" });
376        if let Some(address) = route.address {
377            probe["direct_tcp"] = tcp_probe(address.socket_addr(62078)).await;
378        }
379        out["probes"].as_array_mut().unwrap().push(probe);
380    }
381    // A known phone can still be reachable at its cached address when the
382    // system temporarily omits it. Record that route separately from discovery.
383    if out["probes"].as_array().unwrap().iter().all(|p| p.get("transport").is_none()) {
384        let found = match listing_error {
385            Some(error) => Err(anyhow::anyhow!(error)),
386            None => Ok(discovered),
387        };
388        match conn::route_from(udid, found).await {
389            Ok(route) => {
390                let mut probe = probe_provider(udid, &route.connection, &*route.provider).await;
391                probe["source"] = json!(route.source);
392                probe["transport"] = json!(if route.address.is_some() { "tcp" } else { "usbmuxd" });
393                out["probes"].as_array_mut().unwrap().push(probe);
394            }
395            Err(e) => out["route_error"] = json!(format!("{e:#}")),
396        }
397    }
398    out
399}
400
401/// Retain the actual ListDevices response as well as the library's parsed
402/// view: malformed NetworkAddress entries can otherwise be silently dropped.
403async fn raw_mux_listing() -> Result<Value> {
404    events::step("usbmuxd.raw_list", json!({}), PROBE_TIMEOUT, async {
405        let mut socket = conn::mux_addr()?.to_socket().await?;
406        let mut dict = plist::Dictionary::new();
407        dict.insert("MessageType".into(), "ListDevices".into());
408        dict.insert("ClientVersionString".into(), conn::LABEL.into());
409        dict.insert("kLibUSBMuxVersion".into(), 3u64.into());
410        let mut payload = Vec::new();
411        plist::Value::Dictionary(dict).to_writer_xml(&mut payload)?;
412        for word in [(payload.len() + 16) as u32, 1, 8, 1] {
413            socket.write_all(&word.to_le_bytes()).await?;
414        }
415        socket.write_all(&payload).await?;
416        let mut header = [0; 16];
417        socket.read_exact(&mut header).await?;
418        let length = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
419        anyhow::ensure!(
420            (16..=1024 * 1024).contains(&length),
421            "invalid usbmuxd response length {length}"
422        );
423        let mut payload = vec![0; length - 16];
424        socket.read_exact(&mut payload).await?;
425        let value = plist::Value::from_reader(std::io::Cursor::new(payload))?;
426        Ok::<_, anyhow::Error>(serde_json::to_value(value)?)
427    })
428    .await
429}
430
431async fn check<T, E: std::fmt::Debug>(
432    checks: &mut Vec<Value>,
433    name: &str,
434    future: impl Future<Output = std::result::Result<T, E>>,
435) -> Result<T> {
436    let started = Instant::now();
437    let result = events::step(name, json!({ "source": "diagnose" }), PROBE_TIMEOUT, future).await;
438    checks.push(
439        json!({ "stage": name, "ok": result.is_ok(), "elapsed_ms": started.elapsed().as_millis(),
440        "error": result.as_ref().err().map(|e| format!("{e:#}")) }),
441    );
442    result
443}
444
445async fn probe_provider(udid: &str, connection: &str, provider: &dyn IdeviceProvider) -> Value {
446    let mut checks = Vec::new();
447    let mut values = serde_json::Map::new();
448    let pairing = check(&mut checks, "pairing_record", provider.get_pairing_file()).await;
449    let paired = pairing.is_ok();
450    let lockdown = check(
451        &mut checks,
452        "lockdown.connect",
453        LockdownClient::connect(provider),
454    )
455    .await;
456    if let Ok(mut lockdown) = lockdown {
457        let session_ok = match &pairing {
458            Ok(pairing) => check(
459                &mut checks,
460                "lockdown.start_session",
461                lockdown.start_session(pairing),
462            )
463            .await
464            .is_ok(),
465            Err(_) => true,
466        };
467        if session_ok {
468            for (key, domain) in [
469                ("ProductType", None),
470                ("ProductVersion", None),
471                ("BuildVersion", None),
472                ("DeviceName", None),
473                ("WiFiAddress", None),
474                ("PasswordProtected", None),
475                (
476                    "EnableWifiConnections",
477                    Some("com.apple.mobile.wireless_lockdown"),
478                ),
479                (
480                    "EnableWifiDebugging",
481                    Some("com.apple.mobile.wireless_lockdown"),
482                ),
483            ] {
484                match check(
485                    &mut checks,
486                    &format!("lockdown.GetValue.{key}"),
487                    lockdown.get_value(Some(key), domain),
488                )
489                .await
490                {
491                    Ok(value) => {
492                        values.insert(
493                            key.into(),
494                            serde_json::to_value(value).unwrap_or(Value::Null),
495                        );
496                    }
497                    Err(_) => continue,
498                }
499            }
500        }
501    }
502    if paired {
503        if let Ok(mut mounter) = check(
504            &mut checks,
505            "image_mounter.connect",
506            ImageMounter::connect(provider),
507        )
508        .await
509            && let Ok(enabled) = check(
510                &mut checks,
511                "developer_mode",
512                mounter.query_developer_mode_status(),
513            )
514            .await
515        {
516            values.insert("DeveloperModeStatus".into(), json!(enabled));
517        }
518        let started = Instant::now();
519        let tunnel = conn::open_tunnel_with_provider(provider, connection).await;
520        checks.push(json!({ "stage": "tunnel", "ok": tunnel.is_ok(), "elapsed_ms": started.elapsed().as_millis(),
521            "error": tunnel.as_ref().err().map(|e| format!("{e:#}")) }));
522        if let Ok(tunnel) = tunnel {
523            values.insert(
524                "rsd_services".into(),
525                json!(tunnel.rsd.services.keys().collect::<Vec<_>>()),
526            );
527        }
528    }
529    json!({ "udid": udid, "connection": connection, "paired": paired, "values": values, "checks": checks })
530}
531
532#[derive(Default)]
533struct Capture {
534    bytes: VecDeque<u8>,
535    truncated: bool,
536}
537
538impl Capture {
539    fn push(&mut self, bytes: &[u8]) {
540        let excess = (self.bytes.len() + bytes.len()).saturating_sub(CAPTURE_BYTES);
541        self.truncated |= excess > 0;
542        self.bytes.drain(..excess.min(self.bytes.len()));
543        self.bytes
544            .extend(&bytes[bytes.len().saturating_sub(CAPTURE_BYTES)..]);
545    }
546}
547
548async fn drain(mut reader: impl tokio::io::AsyncRead + Unpin, output: Arc<Mutex<Capture>>) {
549    let mut bytes = [0; 8192];
550    while let Ok(n) = reader.read(&mut bytes).await {
551        if n == 0 {
552            break;
553        }
554        output.lock().unwrap().push(&bytes[..n]);
555    }
556}
557
558/// Keep partial stdout/stderr on timeout, drain both concurrently, and reap
559/// the child. This also bounds tools that leave their output pipes open.
560async fn capture(
561    program: impl AsRef<std::ffi::OsStr>,
562    argv: &[String],
563    timeout: Duration,
564) -> Value {
565    let started = Instant::now();
566    let mut out = json!({ "command": program.as_ref().to_string_lossy(), "args": argv,
567        "started_at": crate::clock::now_utc(), "started_unix_ms": events::now_ms(),
568        "timed_out": false, "exit_code": null, "stdout": "", "stderr": "" });
569    let mut child = match Command::new(&program)
570        .args(argv)
571        .stdin(Stdio::null())
572        .stdout(Stdio::piped())
573        .stderr(Stdio::piped())
574        .kill_on_drop(true)
575        .spawn()
576    {
577        Ok(child) => child,
578        Err(e) => {
579            out["error"] = json!(e.to_string());
580            out["elapsed_ms"] = json!(started.elapsed().as_millis());
581            return out;
582        }
583    };
584    let stdout = Arc::new(Mutex::new(Capture::default()));
585    let stderr = Arc::new(Mutex::new(Capture::default()));
586    let mut stdout_task = tokio::spawn(drain(child.stdout.take().unwrap(), stdout.clone()));
587    let mut stderr_task = tokio::spawn(drain(child.stderr.take().unwrap(), stderr.clone()));
588    match tokio::time::timeout(timeout, child.wait()).await {
589        Ok(Ok(status)) => out["exit_code"] = json!(status.code()),
590        Ok(Err(e)) => out["error"] = json!(e.to_string()),
591        Err(_) => {
592            out["timed_out"] = json!(true);
593            let _ = child.kill().await;
594            let _ = child.wait().await;
595        }
596    }
597    let drained = tokio::time::timeout(Duration::from_secs(1), async {
598        let _ = tokio::join!(&mut stdout_task, &mut stderr_task);
599    })
600    .await
601    .is_ok();
602    if !drained {
603        stdout_task.abort();
604        stderr_task.abort();
605    }
606    out["output_pipes_closed"] = json!(drained);
607    for (key, captured) in [("stdout", stdout), ("stderr", stderr)] {
608        let captured = captured.lock().unwrap();
609        out[key] = json!(String::from_utf8_lossy(
610            &captured.bytes.iter().copied().collect::<Vec<_>>()
611        ));
612        out[format!("{key}_truncated")] = json!(captured.truncated);
613    }
614    out["finished_at"] = json!(crate::clock::now_utc());
615    out["elapsed_ms"] = json!(started.elapsed().as_millis());
616    out
617}
618
619fn browse_instances(text: &str) -> Vec<String> {
620    let mut instances = BTreeSet::new();
621    for line in text.lines() {
622        if !line.split_whitespace().any(|word| word == "Add") {
623            continue;
624        }
625        if let Some((_, name)) = line.split_once("_apple-mobdev2._tcp.") {
626            let name = name.trim();
627            if !name.is_empty() {
628                instances.insert(name.to_string());
629            }
630        }
631    }
632    instances.into_iter().collect()
633}
634
635async fn resolve_services(text: &str) -> Value {
636    let instances = browse_instances(text);
637    // Preserve the full browse even on a busy LAN; bound active resolution.
638    let services =
639        futures_util::future::join_all(instances.iter().take(8).map(|instance| async move {
640            let resolved = capture(
641                "dns-sd",
642                &[
643                    "-L".into(),
644                    instance.clone(),
645                    "_apple-mobdev2._tcp".into(),
646                    "local.".into(),
647                ],
648                Duration::from_secs(2),
649            )
650            .await;
651            let mut service =
652                json!({ "instance": instance, "resolve": resolved, "tcp_probes": [] });
653            if let Some((host, port, interface)) =
654                service_endpoint(service["resolve"]["stdout"].as_str().unwrap_or(""))
655            {
656                service["host"] = json!(host);
657                service["port"] = json!(port);
658                service["interface"] = json!(interface);
659                let lookup = tokio::time::timeout(
660                    PROBE_TIMEOUT,
661                    tokio::net::lookup_host((host.as_str(), port)),
662                )
663                .await;
664                match lookup {
665                    Ok(Ok(addresses)) => {
666                        let probes = addresses.take(4).map(|mut addr| async move {
667                            if let SocketAddr::V6(ref mut v6) = addr
668                                && v6.ip().is_unicast_link_local()
669                                && v6.scope_id() == 0
670                            {
671                                v6.set_scope_id(interface.unwrap_or(0));
672                            }
673                            tcp_probe(addr).await
674                        });
675                        service["tcp_probes"] = json!(futures_util::future::join_all(probes).await);
676                    }
677                    Ok(Err(error)) => service["lookup_error"] = json!(error.to_string()),
678                    Err(_) => service["lookup_error"] = json!("address lookup timed out"),
679                }
680            }
681            service
682        }))
683        .await;
684    json!({ "instances_seen": instances.len(), "resolution_limit": 8, "services": services })
685}
686
687fn service_endpoint(text: &str) -> Option<(String, u16, Option<u32>)> {
688    for line in text.lines() {
689        let Some((_, rest)) = line.split_once("can be reached at ") else {
690            continue;
691        };
692        let endpoint = rest.split_whitespace().next()?;
693        let (host, port) = endpoint.rsplit_once(':')?;
694        let interface = line
695            .split_once("(interface ")
696            .and_then(|(_, value)| value.trim_end_matches(')').parse().ok());
697        return Some((
698            host.trim_end_matches('.').into(),
699            port.parse().ok()?,
700            interface,
701        ));
702    }
703    None
704}
705
706async fn tcp_probe(addr: SocketAddr) -> Value {
707    let started = Instant::now();
708    let result = events::step(
709        "direct_tcp.connect",
710        json!({ "address": addr.to_string() }),
711        PROBE_TIMEOUT,
712        tokio::net::TcpStream::connect(addr),
713    )
714    .await;
715    json!({ "address": addr.to_string(), "ok": result.is_ok(), "elapsed_ms": started.elapsed().as_millis(),
716        "error": result.err().map(|e| format!("{e:#}")) })
717}
718
719fn tail_file(path: &Path) -> Value {
720    let result = (|| -> std::io::Result<Value> {
721        let mut file = std::fs::File::open(path)?;
722        let bytes = file.metadata()?.len();
723        file.seek(SeekFrom::Start(bytes.saturating_sub(CAPTURE_BYTES as u64)))?;
724        let mut tail = Vec::new();
725        file.take(CAPTURE_BYTES as u64).read_to_end(&mut tail)?;
726        Ok(
727            json!({ "path": path, "bytes": bytes, "truncated": bytes > CAPTURE_BYTES as u64, "text": String::from_utf8_lossy(&tail) }),
728        )
729    })();
730    result.unwrap_or_else(|e| json!({ "path": path, "error": e.to_string() }))
731}
732
733fn recent_events() -> Value {
734    let dir = paths::state_dir().join("events");
735    let entries = match std::fs::read_dir(&dir) {
736        Ok(entries) => entries,
737        Err(e) => return json!({ "path": dir, "error": e.to_string() }),
738    };
739    let mut files: Vec<_> = entries
740        .flatten()
741        .filter(|e| e.path().extension().is_some_and(|s| s == "jsonl"))
742        .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
743        .collect();
744    files.sort_by_key(|(modified, _)| std::cmp::Reverse(*modified));
745    json!(
746        files
747            .into_iter()
748            .take(8)
749            .map(|(_, path)| tail_file(&path))
750            .collect::<Vec<_>>()
751    )
752}
753
754fn daemon_logs(udid: Option<&str>) -> Value {
755    match udid {
756        Some(udid) => json!([tail_file(&paths::daemon_log(udid))]),
757        None => {
758            json!({ "status": "unavailable", "reason": "no phone selected; connection events still include discovery failures" })
759        }
760    }
761}
762
763fn findings(report: &Value) -> Vec<String> {
764    let mut out = Vec::new();
765    let snapshots: Vec<_> = report["snapshots"]
766        .as_array()
767        .into_iter()
768        .flatten()
769        .collect();
770    if snapshots.iter().any(|s| s["listing"]["ok"] == false) {
771        out.push(
772            "usbmuxd could not be reached or listed devices; inspect the original listing error."
773                .into(),
774        );
775    }
776    for snapshot in &snapshots {
777        if let (Some(raw), Some(parsed)) = (
778            snapshot["raw_usbmuxd"]["response"]["DeviceList"].as_array(),
779            snapshot["listing"]["devices"].as_array(),
780        ) && raw.len() != parsed.len()
781        {
782            out.push("Raw and parsed usbmuxd device counts differ. Inspect NetworkAddress parsing and the discovery timeline for a device transition.".into());
783        }
784        for probe in snapshot["probes"].as_array().into_iter().flatten() {
785            if probe["values"]["EnableWifiConnections"] == false {
786                out.push("The phone reported EnableWifiConnections=false. The Wi-Fi setting is not enabled on the phone.".into());
787            }
788            if probe["checks"]
789                .as_array()
790                .into_iter()
791                .flatten()
792                .any(|c| c["stage"] == "lockdown.start_session" && c["ok"] == false)
793            {
794                out.push("A pairing/session handshake failed; inspect lockdown.start_session's original error.".into());
795            }
796        }
797    }
798    if let Some(last) = snapshots.last() {
799        if report["wifi_observation"] == true {
800            let selected_usb = |s: &&Value| {
801                s["listing"]["devices"]
802                    .as_array()
803                    .into_iter()
804                    .flatten()
805                    .any(|d| {
806                        d["connection"] == "usb"
807                            && (report["selected_udid"].is_null()
808                                || d["udid"] == report["selected_udid"])
809                    })
810            };
811            if !snapshots.first().is_some_and(selected_usb) {
812                out.push("No USB baseline was available for the selected phone. Run --wifi with USB connected to capture its wireless settings before unplugging.".into());
813            }
814            if selected_usb(last) {
815                out.push("USB was still listed after observation. The reproduction may have used USB; the wireless path was not isolated.".into());
816            }
817        }
818        let has_wifi = last["listing"]["devices"]
819            .as_array()
820            .into_iter()
821            .flatten()
822            .any(|d| {
823                d["connection"] == "wifi"
824                    && (report["selected_udid"].is_null() || d["udid"] == report["selected_udid"])
825            });
826        if !has_wifi && last["listing"]["ok"] == true {
827            let bonjour = &report["bonjour"];
828            if bonjour["error"].is_string()
829                || (bonjour["timed_out"] != true && bonjour["exit_code"] != 0)
830            {
831                out.push("Bonjour could not be tested (dns-sd unavailable or failed). This is not evidence that the phone did not advertise.".into());
832            } else if !browse_instances(bonjour["stdout"].as_str().unwrap_or("")).is_empty() {
833                out.push("usbmuxd has no Wi-Fi entry for the selected phone, while mobdev2 advertisements were seen. Verify their identity, then investigate host registration/pairing.".into());
834            } else {
835                out.push("No Wi-Fi usbmuxd entry or mobdev2 advertisement was observed. Compare the phone's wireless setting, network multicast, and host discovery on another Wi-Fi network.".into());
836            }
837        }
838    }
839    if report["reproduction"]["timed_out"] == true {
840        out.push("The reproduction command timed out. It was run only once; its action may still have reached the phone. Inspect the output before retrying.".into());
841    }
842    out
843}
844
845#[cfg(test)]
846mod tests {
847    use super::*;
848
849    #[test]
850    fn bonjour_names_with_spaces_and_interface_survive_parsing() {
851        let browse = "12:34:56.000 Add 2 6 local. _apple-mobdev2._tcp. aa:bb@Phone with spaces\n12:34:57.000 Rmv 0 6 local. _apple-mobdev2._tcp. another\n";
852        assert_eq!(browse_instances(browse), ["aa:bb@Phone with spaces"]);
853        assert_eq!(
854            service_endpoint("aa:bb can be reached at iPhone.local.:62078 (interface 6)"),
855            Some(("iPhone.local".into(), 62078, Some(6)))
856        );
857    }
858
859    #[test]
860    fn missing_bonjour_tool_is_not_reported_as_missing_phone_advertisement() {
861        let report = json!({ "snapshots": [{ "listing": { "ok": true, "devices": [] } }],
862            "bonjour": { "error": "No such file or directory" } });
863        let result = findings(&report).join("\n");
864        assert!(result.contains("could not be tested"));
865        assert!(!result.contains("No Wi-Fi usbmuxd entry or mobdev2 advertisement was observed"));
866        let mut report = report;
867        report["bonjour"] =
868            json!({ "exit_code": 1, "stderr": "DNSServiceBrowse failed: NotPermitted" });
869        assert!(findings(&report).join("\n").contains("could not be tested"));
870    }
871
872    #[test]
873    fn plist_values_keep_wireless_booleans_and_raw_address_bytes() {
874        assert_eq!(
875            serde_json::to_value(plist::Value::Boolean(false)).unwrap(),
876            false
877        );
878        assert_eq!(
879            serde_json::to_value(plist::Value::Data(vec![16, 2, 0, 0, 192, 168, 1, 4])).unwrap(),
880            json!([16, 2, 0, 0, 192, 168, 1, 4])
881        );
882    }
883
884    #[cfg(unix)]
885    #[tokio::test]
886    async fn timed_out_process_keeps_both_outputs_and_does_not_wait_for_inherited_pipes() {
887        let start = Instant::now();
888        let result = capture(
889            "/bin/sh",
890            &[
891                "-c".into(),
892                "printf partial-output; printf original-error >&2; sleep 5".into(),
893            ],
894            Duration::from_millis(200),
895        )
896        .await;
897        assert_eq!(result["timed_out"], true);
898        assert_eq!(result["stdout"], "partial-output");
899        assert_eq!(result["stderr"], "original-error");
900        assert!(start.elapsed() < Duration::from_secs(3));
901    }
902
903    #[cfg(unix)]
904    #[tokio::test]
905    async fn capture_drains_large_output_and_retains_the_final_failure() {
906        let result = capture(
907            "/bin/sh",
908            &[
909                "-c".into(),
910                "head -c 300000 /dev/zero; printf final-error; exit 7".into(),
911            ],
912            Duration::from_secs(5),
913        )
914        .await;
915        assert_eq!(result["exit_code"], 7);
916        assert_eq!(result["stdout_truncated"], true);
917        assert!(result["stdout"].as_str().unwrap().ends_with("final-error"));
918        assert_eq!(result["timed_out"], false);
919    }
920}