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