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 devices = match conn::list_raw().await {
336        Ok(devices) => devices,
337        Err(error) => {
338            out["listing"] = json!({ "ok": false, "error": format!("{error:#}") });
339            return out;
340        }
341    };
342    out["listing"] = json!({ "ok": true, "devices": conn::describe_raw(&devices) });
343    if chosen.is_none() {
344        let ids: BTreeSet<_> = devices.iter().map(|d| d.udid.clone()).collect();
345        if ids.len() == 1 {
346            *chosen = ids.into_iter().next();
347        }
348    }
349    out["selected_udid"] = json!(chosen);
350    let Some(udid) = chosen.as_ref() else {
351        out["selection"] = json!(if devices.is_empty() {
352            "no_device"
353        } else {
354            "multiple_devices; choose --udid to probe one"
355        });
356        return out;
357    };
358    if !probe {
359        out["probe_note"] = json!("Active probes deferred until after the reproduction command");
360        return out;
361    }
362    for device in devices.iter().filter(|d| &d.udid == udid) {
363        let addr = match conn::mux_addr() {
364            Ok(addr) => addr,
365            Err(e) => {
366                out["error"] = json!(format!("{e:#}"));
367                return out;
368            }
369        };
370        let provider = device.to_provider(addr, conn::LABEL);
371        let mut probe =
372            probe_provider(udid, conn::conn_name(&device.connection_type), &provider).await;
373        if let idevice::usbmuxd::Connection::Network(ip) = device.connection_type {
374            if matches!(ip, std::net::IpAddr::V6(v6) if v6.is_unicast_link_local()) {
375                probe["direct_tcp"] = json!({ "status": "skipped", "reason": "usbmuxd's parsed address omits the IPv6 scope; see the raw NetworkAddress and Bonjour interface probes" });
376            } else {
377                probe["direct_tcp"] = tcp_probe(SocketAddr::new(ip, 62078)).await;
378            }
379        }
380        out["probes"].as_array_mut().unwrap().push(probe);
381    }
382    // A known phone can still be reachable at its cached address when the
383    // system temporarily omits it. Record that route separately from discovery.
384    if out["probes"].as_array().unwrap().is_empty() {
385        match conn::route(udid).await {
386            Ok(route) => out["probes"]
387                .as_array_mut()
388                .unwrap()
389                .push(probe_provider(udid, "cached_wifi", &*route.provider).await),
390            Err(e) => out["route_error"] = json!(format!("{e:#}")),
391        }
392    }
393    out
394}
395
396/// Retain the actual ListDevices response as well as the library's parsed
397/// view: malformed NetworkAddress entries can otherwise be silently dropped.
398async fn raw_mux_listing() -> Result<Value> {
399    events::step("usbmuxd.raw_list", json!({}), PROBE_TIMEOUT, async {
400        let mut socket = conn::mux_addr()?.to_socket().await?;
401        let mut dict = plist::Dictionary::new();
402        dict.insert("MessageType".into(), "ListDevices".into());
403        dict.insert("ClientVersionString".into(), conn::LABEL.into());
404        dict.insert("kLibUSBMuxVersion".into(), 3u64.into());
405        let mut payload = Vec::new();
406        plist::Value::Dictionary(dict).to_writer_xml(&mut payload)?;
407        for word in [(payload.len() + 16) as u32, 1, 8, 1] {
408            socket.write_all(&word.to_le_bytes()).await?;
409        }
410        socket.write_all(&payload).await?;
411        let mut header = [0; 16];
412        socket.read_exact(&mut header).await?;
413        let length = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
414        anyhow::ensure!(
415            (16..=1024 * 1024).contains(&length),
416            "invalid usbmuxd response length {length}"
417        );
418        let mut payload = vec![0; length - 16];
419        socket.read_exact(&mut payload).await?;
420        let value = plist::Value::from_reader(std::io::Cursor::new(payload))?;
421        Ok::<_, anyhow::Error>(serde_json::to_value(value)?)
422    })
423    .await
424}
425
426async fn check<T, E: std::fmt::Debug>(
427    checks: &mut Vec<Value>,
428    name: &str,
429    future: impl Future<Output = std::result::Result<T, E>>,
430) -> Result<T> {
431    let started = Instant::now();
432    let result = events::step(name, json!({ "source": "diagnose" }), PROBE_TIMEOUT, future).await;
433    checks.push(
434        json!({ "stage": name, "ok": result.is_ok(), "elapsed_ms": started.elapsed().as_millis(),
435        "error": result.as_ref().err().map(|e| format!("{e:#}")) }),
436    );
437    result
438}
439
440async fn probe_provider(udid: &str, connection: &str, provider: &dyn IdeviceProvider) -> Value {
441    let mut checks = Vec::new();
442    let mut values = serde_json::Map::new();
443    let pairing = check(&mut checks, "pairing_record", provider.get_pairing_file()).await;
444    let paired = pairing.is_ok();
445    let lockdown = check(
446        &mut checks,
447        "lockdown.connect",
448        LockdownClient::connect(provider),
449    )
450    .await;
451    if let Ok(mut lockdown) = lockdown {
452        let session_ok = match &pairing {
453            Ok(pairing) => check(
454                &mut checks,
455                "lockdown.start_session",
456                lockdown.start_session(pairing),
457            )
458            .await
459            .is_ok(),
460            Err(_) => true,
461        };
462        if session_ok {
463            for (key, domain) in [
464                ("ProductType", None),
465                ("ProductVersion", None),
466                ("BuildVersion", None),
467                ("DeviceName", None),
468                ("WiFiAddress", None),
469                ("PasswordProtected", None),
470                (
471                    "EnableWifiConnections",
472                    Some("com.apple.mobile.wireless_lockdown"),
473                ),
474                (
475                    "EnableWifiDebugging",
476                    Some("com.apple.mobile.wireless_lockdown"),
477                ),
478            ] {
479                match check(
480                    &mut checks,
481                    &format!("lockdown.GetValue.{key}"),
482                    lockdown.get_value(Some(key), domain),
483                )
484                .await
485                {
486                    Ok(value) => {
487                        values.insert(
488                            key.into(),
489                            serde_json::to_value(value).unwrap_or(Value::Null),
490                        );
491                    }
492                    Err(_) => continue,
493                }
494            }
495        }
496    }
497    if paired {
498        if let Ok(mut mounter) = check(
499            &mut checks,
500            "image_mounter.connect",
501            ImageMounter::connect(provider),
502        )
503        .await
504            && let Ok(enabled) = check(
505                &mut checks,
506                "developer_mode",
507                mounter.query_developer_mode_status(),
508            )
509            .await
510        {
511            values.insert("DeveloperModeStatus".into(), json!(enabled));
512        }
513        let started = Instant::now();
514        let tunnel = conn::open_tunnel_with_provider(provider, connection).await;
515        checks.push(json!({ "stage": "tunnel", "ok": tunnel.is_ok(), "elapsed_ms": started.elapsed().as_millis(),
516            "error": tunnel.as_ref().err().map(|e| format!("{e:#}")) }));
517        if let Ok(tunnel) = tunnel {
518            values.insert(
519                "rsd_services".into(),
520                json!(tunnel.rsd.services.keys().collect::<Vec<_>>()),
521            );
522        }
523    }
524    json!({ "udid": udid, "connection": connection, "paired": paired, "values": values, "checks": checks })
525}
526
527#[derive(Default)]
528struct Capture {
529    bytes: VecDeque<u8>,
530    truncated: bool,
531}
532
533impl Capture {
534    fn push(&mut self, bytes: &[u8]) {
535        let excess = (self.bytes.len() + bytes.len()).saturating_sub(CAPTURE_BYTES);
536        self.truncated |= excess > 0;
537        self.bytes.drain(..excess.min(self.bytes.len()));
538        self.bytes
539            .extend(&bytes[bytes.len().saturating_sub(CAPTURE_BYTES)..]);
540    }
541}
542
543async fn drain(mut reader: impl tokio::io::AsyncRead + Unpin, output: Arc<Mutex<Capture>>) {
544    let mut bytes = [0; 8192];
545    while let Ok(n) = reader.read(&mut bytes).await {
546        if n == 0 {
547            break;
548        }
549        output.lock().unwrap().push(&bytes[..n]);
550    }
551}
552
553/// Keep partial stdout/stderr on timeout, drain both concurrently, and reap
554/// the child. This also bounds tools that leave their output pipes open.
555async fn capture(
556    program: impl AsRef<std::ffi::OsStr>,
557    argv: &[String],
558    timeout: Duration,
559) -> Value {
560    let started = Instant::now();
561    let mut out = json!({ "command": program.as_ref().to_string_lossy(), "args": argv,
562        "started_at": crate::clock::now_utc(), "started_unix_ms": events::now_ms(),
563        "timed_out": false, "exit_code": null, "stdout": "", "stderr": "" });
564    let mut child = match Command::new(&program)
565        .args(argv)
566        .stdin(Stdio::null())
567        .stdout(Stdio::piped())
568        .stderr(Stdio::piped())
569        .kill_on_drop(true)
570        .spawn()
571    {
572        Ok(child) => child,
573        Err(e) => {
574            out["error"] = json!(e.to_string());
575            out["elapsed_ms"] = json!(started.elapsed().as_millis());
576            return out;
577        }
578    };
579    let stdout = Arc::new(Mutex::new(Capture::default()));
580    let stderr = Arc::new(Mutex::new(Capture::default()));
581    let mut stdout_task = tokio::spawn(drain(child.stdout.take().unwrap(), stdout.clone()));
582    let mut stderr_task = tokio::spawn(drain(child.stderr.take().unwrap(), stderr.clone()));
583    match tokio::time::timeout(timeout, child.wait()).await {
584        Ok(Ok(status)) => out["exit_code"] = json!(status.code()),
585        Ok(Err(e)) => out["error"] = json!(e.to_string()),
586        Err(_) => {
587            out["timed_out"] = json!(true);
588            let _ = child.kill().await;
589            let _ = child.wait().await;
590        }
591    }
592    let drained = tokio::time::timeout(Duration::from_secs(1), async {
593        let _ = tokio::join!(&mut stdout_task, &mut stderr_task);
594    })
595    .await
596    .is_ok();
597    if !drained {
598        stdout_task.abort();
599        stderr_task.abort();
600    }
601    out["output_pipes_closed"] = json!(drained);
602    for (key, captured) in [("stdout", stdout), ("stderr", stderr)] {
603        let captured = captured.lock().unwrap();
604        out[key] = json!(String::from_utf8_lossy(
605            &captured.bytes.iter().copied().collect::<Vec<_>>()
606        ));
607        out[format!("{key}_truncated")] = json!(captured.truncated);
608    }
609    out["finished_at"] = json!(crate::clock::now_utc());
610    out["elapsed_ms"] = json!(started.elapsed().as_millis());
611    out
612}
613
614fn browse_instances(text: &str) -> Vec<String> {
615    let mut instances = BTreeSet::new();
616    for line in text.lines() {
617        if !line.split_whitespace().any(|word| word == "Add") {
618            continue;
619        }
620        if let Some((_, name)) = line.split_once("_apple-mobdev2._tcp.") {
621            let name = name.trim();
622            if !name.is_empty() {
623                instances.insert(name.to_string());
624            }
625        }
626    }
627    instances.into_iter().collect()
628}
629
630async fn resolve_services(text: &str) -> Value {
631    let instances = browse_instances(text);
632    // Preserve the full browse even on a busy LAN; bound active resolution.
633    let services =
634        futures_util::future::join_all(instances.iter().take(8).map(|instance| async move {
635            let resolved = capture(
636                "dns-sd",
637                &[
638                    "-L".into(),
639                    instance.clone(),
640                    "_apple-mobdev2._tcp".into(),
641                    "local.".into(),
642                ],
643                Duration::from_secs(2),
644            )
645            .await;
646            let mut service =
647                json!({ "instance": instance, "resolve": resolved, "tcp_probes": [] });
648            if let Some((host, port, interface)) =
649                service_endpoint(service["resolve"]["stdout"].as_str().unwrap_or(""))
650            {
651                service["host"] = json!(host);
652                service["port"] = json!(port);
653                service["interface"] = json!(interface);
654                let lookup = tokio::time::timeout(
655                    PROBE_TIMEOUT,
656                    tokio::net::lookup_host((host.as_str(), port)),
657                )
658                .await;
659                match lookup {
660                    Ok(Ok(addresses)) => {
661                        let probes = addresses.take(4).map(|mut addr| async move {
662                            if let SocketAddr::V6(ref mut v6) = addr
663                                && v6.ip().is_unicast_link_local()
664                                && v6.scope_id() == 0
665                            {
666                                v6.set_scope_id(interface.unwrap_or(0));
667                            }
668                            tcp_probe(addr).await
669                        });
670                        service["tcp_probes"] = json!(futures_util::future::join_all(probes).await);
671                    }
672                    Ok(Err(error)) => service["lookup_error"] = json!(error.to_string()),
673                    Err(_) => service["lookup_error"] = json!("address lookup timed out"),
674                }
675            }
676            service
677        }))
678        .await;
679    json!({ "instances_seen": instances.len(), "resolution_limit": 8, "services": services })
680}
681
682fn service_endpoint(text: &str) -> Option<(String, u16, Option<u32>)> {
683    for line in text.lines() {
684        let Some((_, rest)) = line.split_once("can be reached at ") else {
685            continue;
686        };
687        let endpoint = rest.split_whitespace().next()?;
688        let (host, port) = endpoint.rsplit_once(':')?;
689        let interface = line
690            .split_once("(interface ")
691            .and_then(|(_, value)| value.trim_end_matches(')').parse().ok());
692        return Some((
693            host.trim_end_matches('.').into(),
694            port.parse().ok()?,
695            interface,
696        ));
697    }
698    None
699}
700
701async fn tcp_probe(addr: SocketAddr) -> Value {
702    let started = Instant::now();
703    let result = events::step(
704        "direct_tcp.connect",
705        json!({ "address": addr.to_string() }),
706        PROBE_TIMEOUT,
707        tokio::net::TcpStream::connect(addr),
708    )
709    .await;
710    json!({ "address": addr.to_string(), "ok": result.is_ok(), "elapsed_ms": started.elapsed().as_millis(),
711        "error": result.err().map(|e| format!("{e:#}")) })
712}
713
714fn tail_file(path: &Path) -> Value {
715    let result = (|| -> std::io::Result<Value> {
716        let mut file = std::fs::File::open(path)?;
717        let bytes = file.metadata()?.len();
718        file.seek(SeekFrom::Start(bytes.saturating_sub(CAPTURE_BYTES as u64)))?;
719        let mut tail = Vec::new();
720        file.take(CAPTURE_BYTES as u64).read_to_end(&mut tail)?;
721        Ok(
722            json!({ "path": path, "bytes": bytes, "truncated": bytes > CAPTURE_BYTES as u64, "text": String::from_utf8_lossy(&tail) }),
723        )
724    })();
725    result.unwrap_or_else(|e| json!({ "path": path, "error": e.to_string() }))
726}
727
728fn recent_events() -> Value {
729    let dir = paths::state_dir().join("events");
730    let entries = match std::fs::read_dir(&dir) {
731        Ok(entries) => entries,
732        Err(e) => return json!({ "path": dir, "error": e.to_string() }),
733    };
734    let mut files: Vec<_> = entries
735        .flatten()
736        .filter(|e| e.path().extension().is_some_and(|s| s == "jsonl"))
737        .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
738        .collect();
739    files.sort_by_key(|(modified, _)| std::cmp::Reverse(*modified));
740    json!(
741        files
742            .into_iter()
743            .take(8)
744            .map(|(_, path)| tail_file(&path))
745            .collect::<Vec<_>>()
746    )
747}
748
749fn daemon_logs(udid: Option<&str>) -> Value {
750    match udid {
751        Some(udid) => json!([tail_file(&paths::daemon_log(udid))]),
752        None => {
753            json!({ "status": "unavailable", "reason": "no phone selected; connection events still include discovery failures" })
754        }
755    }
756}
757
758fn findings(report: &Value) -> Vec<String> {
759    let mut out = Vec::new();
760    let snapshots: Vec<_> = report["snapshots"]
761        .as_array()
762        .into_iter()
763        .flatten()
764        .collect();
765    if snapshots.iter().any(|s| s["listing"]["ok"] == false) {
766        out.push(
767            "usbmuxd could not be reached or listed devices; inspect the original listing error."
768                .into(),
769        );
770    }
771    for snapshot in &snapshots {
772        if let (Some(raw), Some(parsed)) = (
773            snapshot["raw_usbmuxd"]["response"]["DeviceList"].as_array(),
774            snapshot["listing"]["devices"].as_array(),
775        ) && raw.len() != parsed.len()
776        {
777            out.push("Raw and parsed usbmuxd device counts differ. Inspect NetworkAddress parsing and the discovery timeline for a device transition.".into());
778        }
779        for probe in snapshot["probes"].as_array().into_iter().flatten() {
780            if probe["values"]["EnableWifiConnections"] == false {
781                out.push("The phone reported EnableWifiConnections=false. The Wi-Fi setting is not enabled on the phone.".into());
782            }
783            if probe["checks"]
784                .as_array()
785                .into_iter()
786                .flatten()
787                .any(|c| c["stage"] == "lockdown.start_session" && c["ok"] == false)
788            {
789                out.push("A pairing/session handshake failed; inspect lockdown.start_session's original error.".into());
790            }
791        }
792    }
793    if let Some(last) = snapshots.last() {
794        if report["wifi_observation"] == true {
795            let selected_usb = |s: &&Value| {
796                s["listing"]["devices"]
797                    .as_array()
798                    .into_iter()
799                    .flatten()
800                    .any(|d| {
801                        d["connection"] == "usb"
802                            && (report["selected_udid"].is_null()
803                                || d["udid"] == report["selected_udid"])
804                    })
805            };
806            if !snapshots.first().is_some_and(selected_usb) {
807                out.push("No USB baseline was available for the selected phone. Run --wifi with USB connected to capture its wireless settings before unplugging.".into());
808            }
809            if selected_usb(last) {
810                out.push("USB was still listed after observation. The reproduction may have used USB; the wireless path was not isolated.".into());
811            }
812        }
813        let has_wifi = last["listing"]["devices"]
814            .as_array()
815            .into_iter()
816            .flatten()
817            .any(|d| {
818                d["connection"] == "wifi"
819                    && (report["selected_udid"].is_null() || d["udid"] == report["selected_udid"])
820            });
821        if !has_wifi && last["listing"]["ok"] == true {
822            let bonjour = &report["bonjour"];
823            if bonjour["error"].is_string()
824                || (bonjour["timed_out"] != true && bonjour["exit_code"] != 0)
825            {
826                out.push("Bonjour could not be tested (dns-sd unavailable or failed). This is not evidence that the phone did not advertise.".into());
827            } else if !browse_instances(bonjour["stdout"].as_str().unwrap_or("")).is_empty() {
828                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());
829            } else {
830                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());
831            }
832        }
833    }
834    if report["reproduction"]["timed_out"] == true {
835        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());
836    }
837    out
838}
839
840#[cfg(test)]
841mod tests {
842    use super::*;
843
844    #[test]
845    fn bonjour_names_with_spaces_and_interface_survive_parsing() {
846        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";
847        assert_eq!(browse_instances(browse), ["aa:bb@Phone with spaces"]);
848        assert_eq!(
849            service_endpoint("aa:bb can be reached at iPhone.local.:62078 (interface 6)"),
850            Some(("iPhone.local".into(), 62078, Some(6)))
851        );
852    }
853
854    #[test]
855    fn missing_bonjour_tool_is_not_reported_as_missing_phone_advertisement() {
856        let report = json!({ "snapshots": [{ "listing": { "ok": true, "devices": [] } }],
857            "bonjour": { "error": "No such file or directory" } });
858        let result = findings(&report).join("\n");
859        assert!(result.contains("could not be tested"));
860        assert!(!result.contains("No Wi-Fi usbmuxd entry or mobdev2 advertisement was observed"));
861        let mut report = report;
862        report["bonjour"] =
863            json!({ "exit_code": 1, "stderr": "DNSServiceBrowse failed: NotPermitted" });
864        assert!(findings(&report).join("\n").contains("could not be tested"));
865    }
866
867    #[test]
868    fn plist_values_keep_wireless_booleans_and_raw_address_bytes() {
869        assert_eq!(
870            serde_json::to_value(plist::Value::Boolean(false)).unwrap(),
871            false
872        );
873        assert_eq!(
874            serde_json::to_value(plist::Value::Data(vec![16, 2, 0, 0, 192, 168, 1, 4])).unwrap(),
875            json!([16, 2, 0, 0, 192, 168, 1, 4])
876        );
877    }
878
879    #[cfg(unix)]
880    #[tokio::test]
881    async fn timed_out_process_keeps_both_outputs_and_does_not_wait_for_inherited_pipes() {
882        let start = Instant::now();
883        let result = capture(
884            "/bin/sh",
885            &[
886                "-c".into(),
887                "printf partial-output; printf original-error >&2; sleep 5".into(),
888            ],
889            Duration::from_millis(200),
890        )
891        .await;
892        assert_eq!(result["timed_out"], true);
893        assert_eq!(result["stdout"], "partial-output");
894        assert_eq!(result["stderr"], "original-error");
895        assert!(start.elapsed() < Duration::from_secs(3));
896    }
897
898    #[cfg(unix)]
899    #[tokio::test]
900    async fn capture_drains_large_output_and_retains_the_final_failure() {
901        let result = capture(
902            "/bin/sh",
903            &[
904                "-c".into(),
905                "head -c 300000 /dev/zero; printf final-error; exit 7".into(),
906            ],
907            Duration::from_secs(5),
908        )
909        .await;
910        assert_eq!(result["exit_code"], 7);
911        assert_eq!(result["stdout_truncated"], true);
912        assert!(result["stdout"].as_str().unwrap().ends_with("final-error"));
913        assert_eq!(result["timed_out"], false);
914    }
915}