1use std::{future::Future, net::IpAddr, time::Duration, time::Instant};
8
9use anyhow::{Context, Result, bail};
10use idevice::{
11 IdeviceService,
12 core_device_proxy::CoreDeviceProxy,
13 heartbeat::HeartbeatClient,
14 provider::{IdeviceProvider, TcpProvider},
15 rsd::RsdHandshake,
16 usbmuxd::{Connection, UsbmuxdAddr, UsbmuxdConnection, UsbmuxdDevice},
17};
18
19use super::{
20 address::{self, WifiAddress},
21 discovery::{self, Discovery},
22 identity::{self, Identity},
23};
24use crate::tcp::{adapter::Adapter, handle::AdapterHandle};
25use crate::{events, paths};
26use serde_json::json;
27
28pub const LABEL: &str = "iphone-cli";
29const STEP_TIMEOUT: Duration = Duration::from_secs(12);
30const HEARTBEAT_FIRST_SECS: u64 = 10;
32const HEARTBEAT_GRACE_SECS: u64 = 5;
33
34#[derive(Debug, Clone, serde::Serialize)]
35pub struct DeviceEntry {
36 pub udid: String,
37 pub connection: String,
39}
40
41pub fn conn_name(c: &Connection) -> &'static str {
42 match c {
43 Connection::Usb => "usb",
44 Connection::Network(_) => "wifi",
45 Connection::Unknown(_) => "unknown",
46 }
47}
48
49pub async fn list_raw() -> Result<Vec<UsbmuxdDevice>> {
52 Ok(discovery::read()
53 .await?
54 .devices
55 .into_iter()
56 .map(|d| d.mux)
57 .collect())
58}
59
60pub fn mux_addr() -> Result<UsbmuxdAddr> {
61 UsbmuxdAddr::from_env_var().context("invalid USBMUXD_SOCKET_ADDRESS")
62}
63
64pub async fn mux_connect() -> Result<UsbmuxdConnection> {
65 let addr = mux_addr()?;
66 events::step(
67 "usbmuxd.connect",
68 json!({ "address": format!("{addr:?}") }),
69 STEP_TIMEOUT,
70 addr.connect(0),
71 )
72 .await
73}
74
75pub fn describe_raw(devices: &[UsbmuxdDevice]) -> Vec<serde_json::Value> {
76 devices.iter().map(|d| json!({
77 "udid": d.udid, "device_id": d.device_id, "connection": conn_name(&d.connection_type),
78 "address": match &d.connection_type { Connection::Network(ip) => Some(ip.to_string()), _ => None },
79 })).collect()
80}
81
82pub async fn list() -> Result<Vec<DeviceEntry>> {
84 Ok(summarize(list_raw().await?))
85}
86
87pub(crate) fn summarize(devices: impl IntoIterator<Item = UsbmuxdDevice>) -> Vec<DeviceEntry> {
88 let mut out: Vec<DeviceEntry> = Vec::new();
89 for d in devices {
90 let name = conn_name(&d.connection_type);
91 match out.iter_mut().find(|e| e.udid == d.udid) {
92 Some(existing) => {
93 if name == "usb" {
94 existing.connection = "usb".into();
95 }
96 }
97 None => out.push(DeviceEntry {
98 udid: d.udid,
99 connection: name.to_string(),
100 }),
101 }
102 }
103 out
104}
105
106pub(crate) fn recall_ip(udid: &str) -> Option<WifiAddress> {
107 address::cached(udid)
108}
109
110pub async fn passcode_locked(provider: &dyn IdeviceProvider) -> Option<bool> {
113 use idevice::lockdown::LockdownClient;
114 let wait = |secs| Duration::from_secs(secs);
115 let mut lockdown = tokio::time::timeout(wait(8), LockdownClient::connect(provider))
116 .await
117 .ok()?
118 .ok()?;
119 if let Ok(Ok(pairing)) = tokio::time::timeout(wait(8), provider.get_pairing_file()).await {
120 let _ = tokio::time::timeout(wait(8), lockdown.start_session(&pairing)).await;
121 }
122 tokio::time::timeout(wait(8), lockdown.get_value(Some("PasswordProtected"), None))
123 .await
124 .ok()?
125 .ok()?
126 .as_boolean()
127}
128
129pub struct Route {
130 pub provider: Box<dyn IdeviceProvider>,
131 pub connection: String,
133 pub(crate) source: &'static str,
134 pub(crate) address: Option<WifiAddress>,
135 pub(crate) identity: Option<Identity>,
136 pub heartbeat: Option<Heartbeat>,
138}
139
140pub struct Heartbeat(tokio::task::JoinHandle<()>);
145
146impl Drop for Heartbeat {
147 fn drop(&mut self) {
148 self.0.abort();
149 }
150}
151
152impl Heartbeat {
153 async fn start(provider: &dyn IdeviceProvider) -> Result<Self> {
156 let mut client = step("Heartbeat", HeartbeatClient::connect(provider)).await?;
157 let interval = step("Heartbeat Marco", client.get_marco(HEARTBEAT_FIRST_SECS)).await?;
158 step("Heartbeat Polo", client.send_polo()).await?;
159 Ok(Self::keep(client, interval))
160 }
161
162 pub(crate) fn is_closed(&self) -> bool {
163 self.0.is_finished()
164 }
165
166 fn keep(mut client: HeartbeatClient, mut interval: u64) -> Self {
167 Self(tokio::spawn(async move {
168 loop {
170 let result = async {
171 interval = client
172 .get_marco(interval.saturating_add(HEARTBEAT_GRACE_SECS))
173 .await?;
174 client.send_polo().await
175 }
176 .await;
177 if let Err(e) = result {
178 events::record(
179 "heartbeat",
180 "closed",
181 0,
182 json!({ "error": format!("{e:?}") }),
183 );
184 break;
185 }
186 }
187 }))
188 }
189}
190
191#[derive(Debug, Clone)]
193pub(crate) enum Candidate {
194 Usb(UsbmuxdDevice),
195 Wifi {
196 address: WifiAddress,
197 source: &'static str,
198 },
199}
200
201pub(crate) fn candidates(
202 udid: &str,
203 found: &Discovery,
204 saved: Option<WifiAddress>,
205 wifi_first: bool,
206) -> Vec<Candidate> {
207 let mut usb = Vec::new();
208 let mut wifi = Vec::new();
209 for device in found.devices.iter().filter(|d| d.mux.udid == udid) {
210 if device.mux.connection_type == Connection::Usb {
211 usb.push(Candidate::Usb(device.mux.clone()));
212 } else if let Some(address) = device.address
213 && !wifi
214 .iter()
215 .any(|c| matches!(c, Candidate::Wifi { address: a, .. } if *a == address))
216 {
217 wifi.push(Candidate::Wifi {
218 address,
219 source: "usbmuxd",
220 });
221 }
222 }
223 wifi.sort_by_key(|c| matches!(c, Candidate::Wifi { address, .. } if address.ip.is_ipv6()));
225 if let Some(address) = saved
226 && !wifi
227 .iter()
228 .any(|c| matches!(c, Candidate::Wifi { address: a, .. } if *a == address))
229 {
230 wifi.push(Candidate::Wifi {
231 address,
232 source: "cached_wifi_address",
233 });
234 }
235 if wifi_first {
236 wifi.extend(usb);
237 wifi
238 } else {
239 usb.extend(wifi);
240 usb
241 }
242}
243
244async fn try_candidates<T, F: Future<Output = Result<T>>>(
246 plan: Vec<Candidate>,
247 mut open: impl FnMut(Candidate) -> F,
248) -> Result<T> {
249 let mut failures = Vec::new();
250 for candidate in plan {
251 let description = match &candidate {
252 Candidate::Usb(_) => "USB".to_string(),
253 Candidate::Wifi { address, source } => format!("TCP {address} ({source})"),
254 };
255 match open(candidate).await {
256 Ok(value) => return Ok(value),
257 Err(e) => failures.push(format!("{description}: {e:#}")),
258 }
259 }
260 bail!("no usable connection: {}", failures.join("; "))
261}
262
263async fn open_candidate(udid: &str, candidate: &Candidate) -> Result<Route> {
264 match candidate {
265 Candidate::Usb(device) => Ok(Route {
266 provider: Box::new(device.to_provider(mux_addr()?, LABEL)),
267 connection: "usb".into(),
268 source: "usbmuxd",
269 address: None,
270 identity: None,
271 heartbeat: None,
272 }),
273 Candidate::Wifi { address, source } => {
274 let provider = direct_provider(udid, *address).await?;
275 let identity = identity::identify(&provider)
276 .await
277 .map_err(|f| anyhow::anyhow!(f.to_string()))?;
278 if !identity.udid.eq_ignore_ascii_case(udid) {
279 bail!("paired-session UDID does not match the selected iPhone");
280 }
281 let heartbeat = Heartbeat::start(&provider).await?;
282 events::record(
283 "route",
284 "ok",
285 0,
286 json!({ "udid": udid, "transport": "tcp", "source": source, "address": address.to_string() }),
287 );
288 Ok(Route {
289 provider: Box::new(provider),
290 connection: "wifi".into(),
291 source,
292 address: Some(*address),
293 identity: Some(identity),
294 heartbeat: Some(heartbeat),
295 })
296 }
297 }
298}
299
300async fn with_discovery<T, F: Future<Output = Result<T>>>(
301 udid: &str,
302 found: Result<Discovery>,
303 finish: impl Fn(Route) -> F + Copy,
304) -> Result<T> {
305 let (found, discovery_error) = match found {
306 Ok(found) => (found, None),
307 Err(e) => {
308 let message = format!("{e:#}");
309 events::record("discovery", "error", 0, json!({ "error": message }));
310 (Discovery::default(), Some(message))
311 }
312 };
313 let wifi_first = std::env::var("IPH_PREFER").is_ok_and(|v| v.eq_ignore_ascii_case("wifi"));
314 let plan = candidates(udid, &found, recall_ip(udid), wifi_first);
315 if plan.is_empty() {
316 if let Some(e) = discovery_error {
317 bail!("device {udid}: discovery failed ({e}); no cached Wi-Fi address");
318 }
319 bail!("device {udid} is not connected (usbmuxd does not list it); no cached Wi-Fi address");
320 }
321 let result = try_candidates(plan, |candidate| async move {
322 let route = open_candidate(udid, &candidate).await?;
323 let result = finish(route).await?;
324 if let Candidate::Wifi { address, .. } = candidate
325 && let Err(e) = address::save(&paths::state_dir(), udid, address)
326 {
327 events::record(
328 "wifi_address.save",
329 "error",
330 0,
331 json!({ "udid": udid, "error": e.to_string() }),
332 );
333 }
334 Ok(result)
335 })
336 .await;
337 result.with_context(|| match discovery_error {
338 Some(e) => format!("discovery unavailable: {e}"),
339 None => format!("connection candidates for {udid} failed"),
340 })
341}
342
343pub async fn route(udid: &str) -> Result<Route> {
346 route_from(udid, discovery::read().await).await
347}
348
349pub(crate) async fn route_from(udid: &str, found: Result<Discovery>) -> Result<Route> {
350 with_discovery(udid, found, |route| std::future::ready(Ok(route))).await
351}
352
353pub(crate) async fn route_device(device: &discovery::Device) -> Result<Route> {
354 let candidate = if device.mux.connection_type == Connection::Usb {
355 Candidate::Usb(device.mux.clone())
356 } else {
357 Candidate::Wifi {
358 address: device
359 .address
360 .context("device has no usable Wi-Fi address")?,
361 source: "usbmuxd",
362 }
363 };
364 open_candidate(&device.mux.udid, &candidate).await
365}
366
367pub(crate) async fn direct_provider(udid: &str, address: WifiAddress) -> Result<TcpProvider> {
368 let mut mux = mux_connect().await?;
369 let pairing_file = step("usbmuxd.ReadPairRecord", mux.get_pair_record(udid))
370 .await
371 .with_context(|| format!("no readable pairing record for device {udid}"))?;
372 Ok(TcpProvider {
373 addr: address.ip,
374 scope_id: Some(address.scope_id),
375 pairing_file,
376 label: LABEL.into(),
377 })
378}
379
380pub struct Tunnel {
381 pub adapter: AdapterHandle,
382 pub rsd: RsdHandshake,
383 pub connection: String,
384 pub open_ms: u128,
385 pub heartbeat: Option<Heartbeat>,
387}
388
389impl Tunnel {
390 pub(crate) fn is_closed(&self) -> bool {
391 self.heartbeat.as_ref().is_some_and(Heartbeat::is_closed)
392 }
393}
394
395impl Drop for Tunnel {
396 fn drop(&mut self) {
397 let mut adapter = self.adapter.clone();
399 tokio::spawn(async move {
400 let _ = adapter.close().await;
401 });
402 }
403}
404
405async fn step<T, E: std::fmt::Debug>(
406 what: &str,
407 fut: impl std::future::Future<Output = std::result::Result<T, E>>,
408) -> Result<T> {
409 events::step(what, json!({}), STEP_TIMEOUT, fut).await
410}
411
412fn t0_stamp() -> u128 {
413 std::time::SystemTime::now()
414 .duration_since(std::time::UNIX_EPOCH)
415 .map(|d| d.as_millis())
416 .unwrap_or(0)
417}
418
419pub async fn open_tunnel(udid: &str) -> Result<Tunnel> {
421 with_discovery(udid, discovery::read().await, |mut route| async move {
422 let mut tunnel = open_tunnel_with_provider(&*route.provider, &route.connection).await?;
423 tunnel.heartbeat = route.heartbeat.take();
424 Ok(tunnel)
425 })
426 .await
427}
428
429pub async fn open_tunnel_with_provider(
431 provider: &dyn IdeviceProvider,
432 connection: &str,
433) -> Result<Tunnel> {
434 let t0 = Instant::now();
435 let proxy = step("CoreDeviceProxy", CoreDeviceProxy::connect(provider)).await?;
436 let info = proxy.tunnel_info().clone();
437 let rsd_port = info.server_rsd_port;
438 let ours: IpAddr = info
439 .client_address
440 .parse()
441 .context("tunnel client address")?;
442 let theirs: IpAddr = info
443 .server_address
444 .parse()
445 .context("tunnel server address")?;
446 let mut adapter = Adapter::new(Box::new(proxy.into_tunnel().into_inner()), ours, theirs);
447 adapter.set_mss((info.mtu as usize).saturating_sub(60));
449 if let Ok(dir) = std::env::var("IPH_PCAP") {
452 let path = std::path::Path::new(&dir).join(format!("tunnel-{}.pcap", t0_stamp()));
453 if let Err(e) = adapter.pcap(&path).await {
454 tracing::warn!("pcap {}: {e}", path.display());
455 }
456 }
457 let mut adapter = adapter.to_async_handle();
458 let stream = step("RSD connect", adapter.connect(rsd_port)).await?;
459 let rsd = step("RSD handshake", RsdHandshake::new(stream)).await?;
460 Ok(Tunnel {
461 adapter,
462 rsd,
463 connection: connection.into(),
464 open_ms: t0.elapsed().as_millis(),
465 heartbeat: None,
466 })
467}
468
469#[cfg(test)]
470mod tests {
471 use idevice::Idevice;
472 use tokio::io::{AsyncReadExt, AsyncWriteExt, duplex};
473
474 use super::*;
475
476 fn discovered(
477 udid: &str,
478 connection: Connection,
479 address: Option<WifiAddress>,
480 ) -> discovery::Device {
481 discovery::Device {
482 mux: UsbmuxdDevice {
483 udid: udid.into(),
484 device_id: 1,
485 connection_type: connection,
486 },
487 address,
488 }
489 }
490
491 fn label(candidate: &Candidate) -> String {
492 match candidate {
493 Candidate::Usb(_) => "usb".into(),
494 Candidate::Wifi { address, source } => format!("{address}:{source}"),
495 }
496 }
497
498 #[test]
499 fn priority_is_usb_then_fresh_addresses_then_cache_unless_wifi_is_requested() {
500 let v4: WifiAddress = "192.0.2.1".parse().unwrap();
501 let v6: WifiAddress = "fe80::1%7".parse().unwrap();
502 let saved: WifiAddress = "192.0.2.2".parse().unwrap();
503 let found = Discovery {
504 devices: vec![
505 discovered("OTHER", Connection::Network(saved.ip), Some(saved)),
506 discovered("PHONE", Connection::Network(v6.ip), Some(v6)),
507 discovered("PHONE", Connection::Network(v4.ip), Some(v4)),
508 discovered("PHONE", Connection::Usb, None),
509 discovered("PHONE", Connection::Network(v4.ip), Some(v4)),
510 ],
511 warnings: vec![],
512 };
513 let names: Vec<_> = candidates("PHONE", &found, Some(saved), false)
514 .iter()
515 .map(label)
516 .collect();
517 assert_eq!(
518 names,
519 [
520 "usb",
521 "192.0.2.1:usbmuxd",
522 "fe80::1%7:usbmuxd",
523 "192.0.2.2:cached_wifi_address"
524 ]
525 );
526 let names: Vec<_> = candidates("PHONE", &found, Some(v4), true)
527 .iter()
528 .map(label)
529 .collect();
530 assert_eq!(names, ["192.0.2.1:usbmuxd", "fe80::1%7:usbmuxd", "usb"]);
531 assert!(candidates("MISSING", &found, None, false).is_empty());
532 }
533
534 #[tokio::test]
535 async fn only_failed_connection_setups_fall_through_and_success_stops_the_loop() {
536 let address: WifiAddress = "192.0.2.1".parse().unwrap();
537 let found = Discovery {
538 devices: vec![discovered("PHONE", Connection::Usb, None)],
539 warnings: vec![],
540 };
541 let mut calls = Vec::new();
542 let got = try_candidates(candidates("PHONE", &found, Some(address), false), |c| {
543 calls.push(label(&c));
544 std::future::ready(if matches!(c, Candidate::Usb(_)) {
545 Err(anyhow::anyhow!("USB failed before command"))
546 } else {
547 Ok("tcp")
548 })
549 })
550 .await
551 .unwrap();
552 assert_eq!(got, "tcp");
553 assert_eq!(calls, ["usb", "192.0.2.1:cached_wifi_address"]);
554 calls.clear();
555 try_candidates(candidates("PHONE", &found, Some(address), false), |c| {
556 calls.push(label(&c));
557 std::future::ready(Ok(()))
558 })
559 .await
560 .unwrap();
561 assert_eq!(calls, ["usb"]);
562 }
563
564 #[tokio::test]
565 async fn connection_failure_keeps_each_candidate_error() {
566 let plan = vec![
567 Candidate::Wifi {
568 address: "192.0.2.1".parse().unwrap(),
569 source: "usbmuxd",
570 },
571 Candidate::Wifi {
572 address: "192.0.2.2".parse().unwrap(),
573 source: "cached_wifi_address",
574 },
575 ];
576 let error = try_candidates(plan, |_| {
577 std::future::ready(Err::<(), _>(anyhow::anyhow!("session rejected")))
578 })
579 .await
580 .unwrap_err();
581 let text = format!("{error:#}");
582 assert!(
583 text.contains("192.0.2.1")
584 && text.contains("192.0.2.2")
585 && text.contains("session rejected")
586 );
587 }
588
589 #[tokio::test(start_paused = true)]
590 async fn heartbeat_timeout_is_observable_instead_of_leaving_a_live_flag() {
591 let (host, _phone) = duplex(4096);
592 let heartbeat = Heartbeat::keep(
593 HeartbeatClient::new(Idevice::new(Box::new(host), "test")),
594 1,
595 );
596 tokio::task::yield_now().await;
597 assert!(!heartbeat.is_closed());
598 tokio::time::advance(Duration::from_secs(7)).await;
599 tokio::task::yield_now().await;
600 assert!(heartbeat.is_closed());
601 }
602
603 #[tokio::test]
604 async fn sleepy_time_or_eof_invalidates_the_cached_session_before_the_next_command() {
605 tokio::task::LocalSet::new()
606 .run_until(async {
607 for sleepy in [false, true] {
608 let (host, mut phone) = duplex(4096);
609 let heartbeat = Heartbeat::keep(
610 HeartbeatClient::new(Idevice::new(Box::new(host), "test")),
611 1,
612 );
613 let (transport, _peer) = duplex(4096);
614 let rsd = RsdHandshake {
615 services: Default::default(),
616 properties: Default::default(),
617 protocol_version: 1,
618 uuid: "test".into(),
619 };
620 let adapter = Adapter::new(
621 Box::new(transport),
622 "fd00::1".parse().unwrap(),
623 "fd00::2".parse().unwrap(),
624 )
625 .to_async_handle();
626 let mut session = crate::device::session::Session::new(
627 "TEST-PHONE".into(),
628 crate::config::Config::default(),
629 );
630 session.tunnel = Some(Tunnel {
631 adapter,
632 rsd,
633 connection: "wifi".into(),
634 open_ms: 0,
635 heartbeat: Some(heartbeat),
636 });
637 session.refresh_connection();
638 assert!(
639 session.tunnel.is_some(),
640 "a live heartbeat must keep the existing session"
641 );
642 if sleepy {
643 send(
644 &mut phone,
645 plist::Dictionary::from_iter([(
646 "Command".to_string(),
647 plist::Value::from("SleepyTime"),
648 )]),
649 )
650 .await;
651 }
652 drop(phone);
653 tokio::time::timeout(Duration::from_secs(1), async {
654 while !session.tunnel.as_ref().unwrap().is_closed() {
655 tokio::task::yield_now().await;
656 }
657 })
658 .await
659 .unwrap();
660 session.refresh_connection();
661 assert!(session.tunnel.is_none());
662 assert!(session.connection().is_none());
663 }
664 })
665 .await;
666 }
667
668 async fn send(phone: &mut (impl AsyncWriteExt + Unpin), dict: plist::Dictionary) {
670 let mut body = Vec::new();
671 plist::Value::Dictionary(dict)
672 .to_writer_xml(&mut body)
673 .unwrap();
674 phone
675 .write_all(&(body.len() as u32).to_be_bytes())
676 .await
677 .unwrap();
678 phone.write_all(&body).await.unwrap();
679 }
680
681 async fn recv(phone: &mut (impl AsyncReadExt + Unpin)) -> plist::Dictionary {
682 let mut len = [0u8; 4];
683 phone.read_exact(&mut len).await.unwrap();
684 let mut body = vec![0u8; u32::from_be_bytes(len) as usize];
685 phone.read_exact(&mut body).await.unwrap();
686 plist::Value::from_reader(std::io::Cursor::new(body))
687 .unwrap()
688 .into_dictionary()
689 .unwrap()
690 }
691
692 #[tokio::test]
693 async fn heartbeat_answers_every_marco_with_a_polo_until_dropped() {
694 let (host, mut phone) = duplex(4096);
695 let client = HeartbeatClient::new(Idevice::new(Box::new(host), "test"));
696 let heartbeat = Heartbeat::keep(client, 1);
697 for _ in 0..2 {
698 let marco =
699 plist::Dictionary::from_iter([("Interval".to_string(), plist::Value::from(1u64))]);
700 send(&mut phone, marco).await;
701 let polo = recv(&mut phone).await;
702 assert_eq!(
703 polo.get("Command").and_then(|v| v.as_string()),
704 Some("Polo")
705 );
706 }
707 drop(heartbeat);
708 let mut rest = Vec::new();
710 assert_eq!(phone.read_to_end(&mut rest).await.unwrap(), 0);
711 }
712}