Skip to main content

iphone_cli/device/
conn.rs

1//! Device discovery and the rootless userspace tunnel.
2//!
3//! lockdown (via usbmuxd, USB or Wi-Fi) → CoreDeviceProxy → CDTunnel →
4//! software TCP stack → RSD. Nothing here needs root or a utun interface, and
5//! nothing depends on Xcode's own CoreDevice tunnel.
6
7use 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    /// "usb" | "wifi" | "unknown"
28    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
39/// Every (udid, transport) pair usbmuxd knows about. A phone reachable over
40/// both USB and Wi-Fi shows up twice.
41pub 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
48/// Connected devices, one entry per phone, USB preferred.
49pub 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
72/// Remember the phone's Wi-Fi address. usbmuxd forgets Wi-Fi devices now and
73/// then while the phone is still reachable; the address gets us back in.
74fn 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
84/// What lockdown says about the passcode lock (`PasswordProtected`: true
85/// while the phone is locked). `None` when lockdown did not say. Read-only.
86pub 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    /// "usb" | "wifi"
103    pub connection: String,
104}
105
106/// How to reach `udid`: USB when plugged in, otherwise Wi-Fi.
107pub 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    // The cable first, unless `IPH_PREFER=wifi` asks for the other way round
114    // (to compare the two with the cable left in).
115    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    // Not listed. Try the last Wi-Fi address with the pairing record usbmuxd
131    // keeps for this phone.
132    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        // Stop the background packet task; clones of the handle die with it.
163        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
185/// Open the userspace tunnel and read the RSD service list.
186pub 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    // Room for the IPv6 and TCP headers.
196    adapter.set_mss((info.mtu as usize).saturating_sub(60));
197    // `IPH_PCAP=<folder>`: every packet of this tunnel, for Wireshark. Holds
198    // whatever the phone sends, so only for a short look, then delete it.
199    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}