1use std::{net::IpAddr, time::Duration, time::Instant};
8
9use anyhow::{Context, Result, anyhow, bail};
10use idevice::{
11 IdeviceService,
12 core_device_proxy::CoreDeviceProxy,
13 provider::{IdeviceProvider, TcpProvider},
14 rsd::RsdHandshake,
15 usbmuxd::{Connection, UsbmuxdAddr, UsbmuxdConnection, UsbmuxdDevice},
16};
17
18use crate::{events, paths};
19use serde_json::json;
20use crate::tcp::{adapter::Adapter, handle::AdapterHandle};
21
22pub const LABEL: &str = "iphone-cli";
23const STEP_TIMEOUT: Duration = Duration::from_secs(12);
24
25#[derive(Debug, Clone, serde::Serialize)]
26pub struct DeviceEntry {
27 pub udid: String,
28 pub connection: String,
30}
31
32pub fn conn_name(c: &Connection) -> &'static str {
33 match c {
34 Connection::Usb => "usb",
35 Connection::Network(_) => "wifi",
36 Connection::Unknown(_) => "unknown",
37 }
38}
39
40pub async fn list_raw() -> Result<Vec<UsbmuxdDevice>> {
43 let mut mux = mux_connect().await?;
44 let devices = events::step("usbmuxd.ListDevices", json!({}), STEP_TIMEOUT, mux.get_devices()).await?;
45 events::record("discovery", "ok", 0, json!({ "devices": describe_raw(&devices) }));
46 Ok(devices)
47}
48
49pub fn mux_addr() -> Result<UsbmuxdAddr> {
50 UsbmuxdAddr::from_env_var().context("invalid USBMUXD_SOCKET_ADDRESS")
51}
52
53pub async fn mux_connect() -> Result<UsbmuxdConnection> {
54 let addr = mux_addr()?;
55 events::step("usbmuxd.connect", json!({ "address": format!("{addr:?}") }), STEP_TIMEOUT, addr.connect(0)).await
56}
57
58pub fn describe_raw(devices: &[UsbmuxdDevice]) -> Vec<serde_json::Value> {
59 devices.iter().map(|d| json!({
60 "udid": d.udid, "device_id": d.device_id, "connection": conn_name(&d.connection_type),
61 "address": match &d.connection_type { Connection::Network(ip) => Some(ip.to_string()), _ => None },
62 })).collect()
63}
64
65pub async fn list() -> Result<Vec<DeviceEntry>> {
67 let mut out: Vec<DeviceEntry> = Vec::new();
68 for d in list_raw().await? {
69 let name = conn_name(&d.connection_type);
70 match out.iter_mut().find(|e| e.udid == d.udid) {
71 Some(existing) => {
72 if name == "usb" {
73 existing.connection = "usb".into();
74 }
75 }
76 None => out.push(DeviceEntry {
77 udid: d.udid,
78 connection: name.to_string(),
79 }),
80 }
81 }
82 Ok(out)
83}
84
85fn ip_cache(udid: &str) -> std::path::PathBuf {
86 paths::state_dir().join(format!("{udid}.addr"))
87}
88
89fn remember_ip(udid: &str, ip: &IpAddr) {
92 if paths::ensure_private_dir(&paths::state_dir()).is_ok() {
93 let _ = std::fs::write(ip_cache(udid), ip.to_string());
94 }
95}
96
97fn recall_ip(udid: &str) -> Option<IpAddr> {
98 std::fs::read_to_string(ip_cache(udid)).ok()?.trim().parse().ok()
99}
100
101pub async fn passcode_locked(provider: &dyn IdeviceProvider) -> Option<bool> {
104 use idevice::lockdown::LockdownClient;
105 let wait = |secs| Duration::from_secs(secs);
106 let mut lockdown = tokio::time::timeout(wait(8), LockdownClient::connect(provider)).await.ok()?.ok()?;
107 if let Ok(Ok(pairing)) = tokio::time::timeout(wait(8), provider.get_pairing_file()).await {
108 let _ = tokio::time::timeout(wait(8), lockdown.start_session(&pairing)).await;
109 }
110 tokio::time::timeout(wait(8), lockdown.get_value(Some("PasswordProtected"), None))
111 .await
112 .ok()?
113 .ok()?
114 .as_boolean()
115}
116
117pub struct Route {
118 pub provider: Box<dyn IdeviceProvider>,
119 pub connection: String,
121}
122
123pub async fn route(udid: &str) -> Result<Route> {
125 let mut mine: Vec<UsbmuxdDevice> = list_raw()
126 .await?
127 .into_iter()
128 .filter(|d| d.udid == udid)
129 .collect();
130 let wifi_first = std::env::var("IPH_PREFER").is_ok_and(|v| v.eq_ignore_ascii_case("wifi"));
133 mine.sort_by_key(|d| match d.connection_type {
134 Connection::Usb => u8::from(wifi_first),
135 Connection::Network(_) => u8::from(!wifi_first),
136 Connection::Unknown(_) => 2,
137 });
138 if let Some(dev) = mine.into_iter().next() {
139 if let Connection::Network(ip) = &dev.connection_type {
140 remember_ip(udid, ip);
141 }
142 events::record("route", "ok", 0, json!({ "udid": udid, "source": "usbmuxd", "device": describe_raw(std::slice::from_ref(&dev)) }));
143 return Ok(Route {
144 connection: conn_name(&dev.connection_type).to_string(),
145 provider: Box::new(dev.to_provider(mux_addr()?, LABEL)),
146 });
147 }
148 let Some(ip) = recall_ip(udid) else {
151 events::record("route", "error", 0, json!({ "udid": udid, "error": "not listed by usbmuxd; no cached Wi-Fi address" }));
152 bail!("device {udid} is not connected (usbmuxd does not list it)");
153 };
154 events::record("route", "fallback", 0, json!({ "udid": udid, "address": ip, "source": "cached_wifi_address" }));
155 let mut mux = mux_connect().await?;
156 let pairing_file = mux
157 .get_pair_record(udid)
158 .await
159 .map_err(|e| anyhow!("device {udid} is not listed and has no pairing record: {e:?}"))?;
160 Ok(Route {
161 connection: "wifi".into(),
162 provider: Box::new(TcpProvider {
163 addr: ip,
164 scope_id: None,
165 pairing_file,
166 label: LABEL.into(),
167 }),
168 })
169}
170
171pub struct Tunnel {
172 pub adapter: AdapterHandle,
173 pub rsd: RsdHandshake,
174 pub connection: String,
175 pub open_ms: u128,
176}
177
178impl Drop for Tunnel {
179 fn drop(&mut self) {
180 let mut adapter = self.adapter.clone();
182 tokio::spawn(async move {
183 let _ = adapter.close().await;
184 });
185 }
186}
187
188async fn step<T, E: std::fmt::Debug>(
189 what: &str,
190 fut: impl std::future::Future<Output = std::result::Result<T, E>>,
191) -> Result<T> {
192 events::step(what, json!({}), STEP_TIMEOUT, fut).await
193}
194
195fn t0_stamp() -> u128 {
196 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0)
197}
198
199pub async fn open_tunnel(udid: &str) -> Result<Tunnel> {
201 let route = route(udid).await?;
202 open_tunnel_with_provider(&*route.provider, &route.connection).await
203}
204
205pub async fn open_tunnel_with_provider(provider: &dyn IdeviceProvider, connection: &str) -> Result<Tunnel> {
207 let t0 = Instant::now();
208 let proxy = step("CoreDeviceProxy", CoreDeviceProxy::connect(provider)).await?;
209 let info = proxy.tunnel_info().clone();
210 let rsd_port = info.server_rsd_port;
211 let ours: IpAddr = info.client_address.parse().context("tunnel client address")?;
212 let theirs: IpAddr = info.server_address.parse().context("tunnel server address")?;
213 let mut adapter = Adapter::new(Box::new(proxy.into_tunnel().into_inner()), ours, theirs);
214 adapter.set_mss((info.mtu as usize).saturating_sub(60));
216 if let Ok(dir) = std::env::var("IPH_PCAP") {
219 let path = std::path::Path::new(&dir).join(format!("tunnel-{}.pcap", t0_stamp()));
220 if let Err(e) = adapter.pcap(&path).await {
221 tracing::warn!("pcap {}: {e}", path.display());
222 }
223 }
224 let mut adapter = adapter.to_async_handle();
225 let stream = step("RSD connect", adapter.connect(rsd_port)).await?;
226 let rsd = step("RSD handshake", RsdHandshake::new(stream)).await?;
227 Ok(Tunnel {
228 adapter,
229 rsd,
230 connection: connection.into(),
231 open_ms: t0.elapsed().as_millis(),
232 })
233}