Skip to main content

iphone_cli/device/
wifi.rs

1//! USB-only wireless lockdown inspection and setup. Network discovery is a
2//! separate observation: setting the flags alone does not prove Wi-Fi works.
3
4use std::{future::Future, time::Duration};
5
6use idevice::{
7    IdeviceError, IdeviceService,
8    lockdown::LockdownClient,
9    provider::IdeviceProvider,
10    usbmuxd::{Connection, UsbmuxdDevice},
11};
12
13use super::conn;
14
15const DOMAIN: &str = "com.apple.mobile.wireless_lockdown";
16const KEYS: [&str; 4] = [
17    "SupportsWifi",
18    "SupportsWifiSyncing",
19    "EnableWifiConnections",
20    "EnableWifiDebugging",
21];
22const STEP_TIMEOUT: Duration = Duration::from_secs(3);
23const DISCOVERY_WAIT: Duration = Duration::from_secs(4);
24
25#[derive(Debug, Default)]
26pub struct Wireless {
27    /// Missing, unreadable and non-boolean values stay unknown, never false.
28    pub values: [Option<bool>; 4],
29    pub changed: Vec<&'static str>,
30    pub errors: Vec<String>,
31}
32
33impl Wireless {
34    pub fn supported(&self) -> Option<bool> {
35        match (self.values[0], self.values[1]) {
36            (Some(true), _) | (_, Some(true)) => Some(true),
37            (Some(false), Some(false)) => Some(false),
38            _ => None,
39        }
40    }
41
42    pub fn disabled(&self) -> Vec<&'static str> {
43        (2..4)
44            .filter(|&i| self.values[i] == Some(false))
45            .map(|i| KEYS[i])
46            .collect()
47    }
48
49    pub fn enabled(&self) -> bool {
50        self.values[2..].iter().all(|v| *v == Some(true))
51    }
52
53    pub fn detail(&self) -> String {
54        let mut parts: Vec<String> = KEYS
55            .iter()
56            .zip(self.values)
57            .map(|(key, value)| {
58                format!(
59                    "{key}={}",
60                    match value {
61                        Some(true) => "true",
62                        Some(false) => "false",
63                        None => "unknown",
64                    }
65                )
66            })
67            .collect();
68        if !self.changed.is_empty() {
69            parts.push(format!(
70                "enabled and read back: {}",
71                self.changed.join(", ")
72            ));
73        }
74        parts.extend(self.errors.iter().cloned());
75        format!("{DOMAIN}: {}", parts.join("; "))
76    }
77}
78
79async fn step<T>(
80    name: &str,
81    fut: impl Future<Output = Result<T, IdeviceError>>,
82) -> Result<T, String> {
83    match tokio::time::timeout(STEP_TIMEOUT, fut).await {
84        Ok(Ok(value)) => Ok(value),
85        Ok(Err(e)) => Err(format!("{name}: {e:?}")),
86        Err(_) => Err(format!("{name}: timed out")),
87    }
88}
89
90async fn read_flag(client: &mut LockdownClient, key: &str) -> Result<bool, String> {
91    step(
92        &format!("GetValue({key})"),
93        client.get_value(Some(key), Some(DOMAIN)),
94    )
95    .await?
96    .as_boolean()
97    .ok_or_else(|| format!("GetValue({key}): expected a boolean"))
98}
99
100async fn inspect_client(client: &mut LockdownClient, fix: bool) -> Wireless {
101    let mut state = Wireless::default();
102    for (i, key) in KEYS.iter().enumerate() {
103        match read_flag(client, key).await {
104            Ok(value) => state.values[i] = Some(value),
105            Err(e) => {
106                let timed_out = e.ends_with(": timed out");
107                state.errors.push(e);
108                // A late reply must not be mistaken for the next request's.
109                if timed_out {
110                    return state;
111                }
112            }
113        }
114    }
115    if !fix || state.disabled().is_empty() {
116        return state;
117    }
118    if state.supported() != Some(true) {
119        state
120            .errors
121            .push("wireless support not confirmed; no flags were changed".into());
122        return state;
123    }
124    for i in 2..4 {
125        if state.values[i] != Some(false) {
126            continue;
127        }
128        let key = KEYS[i];
129        if let Err(e) = step(
130            &format!("SetValue({key}=true)"),
131            client.set_value(key, true.into(), Some(DOMAIN)),
132        )
133        .await
134        {
135            let timed_out = e.ends_with(": timed out");
136            state.errors.push(e);
137            if timed_out {
138                state.values[i] = None;
139                return state;
140            }
141            continue;
142        }
143        // Do not call an acknowledged write a fix until the device confirms it.
144        match read_flag(client, key).await {
145            Ok(true) => {
146                state.values[i] = Some(true);
147                state.changed.push(key);
148            }
149            Ok(false) => state
150                .errors
151                .push(format!("SetValue({key}=true): read back false")),
152            Err(e) => {
153                state.values[i] = None;
154                let timed_out = e.ends_with(": timed out");
155                state.errors.push(e);
156                if timed_out {
157                    return state;
158                }
159            }
160        }
161    }
162    state
163}
164
165pub async fn inspect(provider: &dyn IdeviceProvider, fix: bool) -> Wireless {
166    let result = async {
167        let mut client = step(
168            "wireless lockdown connect",
169            LockdownClient::connect(provider),
170        )
171        .await?;
172        let pairing = step("wireless pairing record", provider.get_pairing_file()).await?;
173        step("wireless lockdown session", client.start_session(&pairing)).await?;
174        Ok::<_, String>(inspect_client(&mut client, fix).await)
175    }
176    .await;
177    result.unwrap_or_else(|e| Wireless {
178        errors: vec![e],
179        ..Default::default()
180    })
181}
182
183/// Always select the target's USB entry, even with IPH_PREFER=wifi.
184pub fn usb_device<'a>(devices: &'a [UsbmuxdDevice], udid: &str) -> Option<&'a UsbmuxdDevice> {
185    devices
186        .iter()
187        .find(|d| d.udid == udid && matches!(d.connection_type, Connection::Usb))
188}
189
190pub fn has_network(devices: &[UsbmuxdDevice], udid: &str) -> bool {
191    devices
192        .iter()
193        .any(|d| d.udid == udid && matches!(d.connection_type, Connection::Network(_)))
194}
195
196async fn wait_for_network<F, Fut>(mut probe: F) -> Result<bool, String>
197where
198    F: FnMut() -> Fut,
199    Fut: Future<Output = Result<bool, String>>,
200{
201    let deadline = tokio::time::Instant::now() + DISCOVERY_WAIT;
202    loop {
203        match tokio::time::timeout_at(deadline, probe()).await {
204            Ok(Ok(true)) => return Ok(true),
205            Ok(Ok(false)) => {}
206            Ok(Err(e)) => return Err(e),
207            Err(_) => return Err("usbmuxd Network discovery timed out".into()),
208        }
209        if tokio::time::Instant::now() >= deadline {
210            return Ok(false);
211        }
212        tokio::time::sleep_until(
213            (tokio::time::Instant::now() + Duration::from_millis(250)).min(deadline),
214        )
215        .await;
216        if tokio::time::Instant::now() >= deadline {
217            return Ok(false);
218        }
219    }
220}
221
222pub async fn discover(udid: &str) -> Result<bool, String> {
223    wait_for_network(|| async {
224        conn::list_raw()
225            .await
226            .map(|all| has_network(&all, udid))
227            .map_err(|e| format!("{e:#}"))
228    })
229    .await
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use idevice::Idevice;
236    use plist::Value;
237    use tokio::io::{AsyncReadExt, AsyncWriteExt};
238
239    struct Exchange {
240        request: &'static str,
241        key: &'static str,
242        response: Value,
243    }
244
245    fn reply(key: &str, value: impl Into<Value>) -> Value {
246        Value::Dictionary([(key.to_string(), value.into())].into_iter().collect())
247    }
248
249    fn get(key: &'static str, value: impl Into<Value>) -> Exchange {
250        Exchange {
251            request: "GetValue",
252            key,
253            response: reply("Value", value),
254        }
255    }
256
257    fn set(key: &'static str) -> Exchange {
258        Exchange {
259            request: "SetValue",
260            key,
261            response: reply("Request", "SetValue"),
262        }
263    }
264
265    fn flags(values: [bool; 4]) -> Vec<Exchange> {
266        KEYS.into_iter()
267            .zip(values)
268            .map(|(key, value)| get(key, value))
269            .collect()
270    }
271
272    // Real LockdownClient over an in-memory plist stream: check the actual
273    // domain, keys, boolean type, protocol errors and read-back behavior.
274    async fn inspect_script(script: Vec<Exchange>, fix: bool) -> Wireless {
275        let (client, mut device) = tokio::io::duplex(1 << 16);
276        let server = tokio::spawn(async move {
277            for exchange in script {
278                let len = device.read_u32().await.unwrap();
279                let mut bytes = vec![0; len as usize];
280                device.read_exact(&mut bytes).await.unwrap();
281                let request: Value = plist::from_bytes(&bytes).unwrap();
282                let request = request.as_dictionary().unwrap();
283                assert_eq!(request["Request"].as_string(), Some(exchange.request));
284                assert_eq!(request["Domain"].as_string(), Some(DOMAIN));
285                assert_eq!(request["Key"].as_string(), Some(exchange.key));
286                if exchange.request == "SetValue" {
287                    assert_eq!(request["Value"].as_boolean(), Some(true));
288                }
289                let mut reply = Vec::new();
290                exchange.response.to_writer_xml(&mut reply).unwrap();
291                device.write_u32(reply.len() as u32).await.unwrap();
292                device.write_all(&reply).await.unwrap();
293            }
294        });
295        let mut client = LockdownClient::new(Idevice::new(Box::new(client), conn::LABEL));
296        let state = inspect_client(&mut client, fix).await;
297        drop(client);
298        server.await.unwrap();
299        state
300    }
301
302    #[tokio::test]
303    async fn ordinary_doctor_reads_all_four_flags_without_writing() {
304        let state = inspect_script(flags([true, true, false, false]), false).await;
305        assert_eq!(
306            state.disabled(),
307            ["EnableWifiConnections", "EnableWifiDebugging"]
308        );
309        assert!(state.changed.is_empty());
310        assert!(state.errors.is_empty());
311    }
312
313    #[tokio::test]
314    async fn setup_enables_both_flags_and_verifies_each_write() {
315        let mut script = flags([true, true, false, false]);
316        for key in &KEYS[2..] {
317            script.extend([set(key), get(key, true)]);
318        }
319        let state = inspect_script(script, true).await;
320        assert!(state.enabled());
321        assert_eq!(
322            state.changed,
323            ["EnableWifiConnections", "EnableWifiDebugging"]
324        );
325        assert!(state.errors.is_empty(), "{state:?}");
326    }
327
328    #[tokio::test]
329    async fn enabled_flags_are_idempotent_and_one_support_flag_is_enough() {
330        let state = inspect_script(flags([true, true, true, true]), true).await;
331        assert!(state.changed.is_empty());
332        assert!(state.errors.is_empty());
333        let mut script = flags([false, true, true, false]);
334        script.extend([set(KEYS[3]), get(KEYS[3], true)]);
335        let state = inspect_script(script, true).await;
336        assert_eq!(state.changed, ["EnableWifiDebugging"]);
337        assert!(state.enabled());
338        assert!(state.errors.is_empty());
339    }
340
341    #[tokio::test]
342    async fn unsupported_or_unknown_support_never_writes() {
343        let state = inspect_script(flags([false, false, false, false]), true).await;
344        assert_eq!(state.supported(), Some(false));
345        assert!(state.changed.is_empty());
346        let mut script = flags([false, false, false, false]);
347        script[0].response = reply("Error", "MissingValue");
348        let state = inspect_script(script, true).await;
349        assert_eq!(state.supported(), None);
350        assert_eq!(state.values[0], None);
351        assert!(state.changed.is_empty());
352        assert!(state.detail().contains("MissingValue"));
353    }
354
355    #[tokio::test]
356    async fn missing_and_non_boolean_flags_are_unknown_and_never_overwritten() {
357        let mut script = flags([true, true, false, false]);
358        script[2].response = reply("Error", "MissingValue");
359        script[3].response = reply("Value", "false");
360        let state = inspect_script(script, true).await;
361        assert_eq!(state.values[2..], [None, None]);
362        assert!(state.disabled().is_empty());
363        assert!(state.changed.is_empty());
364        assert!(state.errors.len() == 2, "{state:?}");
365    }
366
367    #[tokio::test]
368    async fn denied_write_reports_key_and_reason_but_other_flag_can_be_fixed() {
369        let mut script = flags([true, true, false, false]);
370        let mut denied = set(KEYS[2]);
371        denied.response = reply("Error", "SetProhibited");
372        script.extend([denied, set(KEYS[3]), get(KEYS[3], true)]);
373        let state = inspect_script(script, true).await;
374        assert_eq!(state.values[2..], [Some(false), Some(true)]);
375        assert_eq!(state.changed, ["EnableWifiDebugging"]);
376        assert!(
377            state
378                .detail()
379                .contains("SetValue(EnableWifiConnections=true)")
380        );
381        assert!(state.detail().contains("SetProhibited"));
382    }
383
384    #[tokio::test]
385    async fn acknowledged_write_is_not_a_fix_unless_read_back_true() {
386        let mut script = flags([true, true, true, false]);
387        script.extend([set(KEYS[3]), get(KEYS[3], false)]);
388        let state = inspect_script(script, true).await;
389        assert!(!state.enabled());
390        assert!(state.changed.is_empty());
391        assert!(state.detail().contains("read back false"));
392    }
393
394    #[tokio::test(start_paused = true)]
395    async fn a_timeout_stops_the_stream_instead_of_misreading_a_late_reply() {
396        let (client, _silent_device) = tokio::io::duplex(1 << 16);
397        let mut client = LockdownClient::new(Idevice::new(Box::new(client), conn::LABEL));
398        let state = inspect_client(&mut client, true).await;
399        assert_eq!(state.values, [None; 4]);
400        assert!(state.changed.is_empty());
401        assert_eq!(state.errors, ["GetValue(SupportsWifi): timed out"]);
402    }
403
404    #[test]
405    fn usb_and_network_selection_are_scoped_to_the_target_phone() {
406        let device = |udid: &str, connection_type| UsbmuxdDevice {
407            udid: udid.into(),
408            device_id: 1,
409            connection_type,
410        };
411        let devices = [
412            device("other", Connection::Usb),
413            device("other", Connection::Network("127.0.0.1".parse().unwrap())),
414            device("mine", Connection::Usb),
415        ];
416        assert_eq!(usb_device(&devices, "mine").unwrap().udid, "mine");
417        assert!(usb_device(&devices, "missing").is_none());
418        assert!(!has_network(&devices, "mine"));
419        assert!(has_network(&devices, "other"));
420        assert!(usb_device(&devices[1..2], "other").is_none());
421    }
422
423    #[tokio::test(start_paused = true)]
424    async fn discovery_waits_for_registration_and_has_a_deadline() {
425        let mut attempts = 0;
426        assert_eq!(
427            wait_for_network(|| {
428                attempts += 1;
429                std::future::ready(Ok(attempts == 3))
430            })
431            .await,
432            Ok(true)
433        );
434        assert_eq!(attempts, 3);
435        let started = tokio::time::Instant::now();
436        assert_eq!(wait_for_network(|| async { Ok(false) }).await, Ok(false));
437        assert_eq!(started.elapsed(), DISCOVERY_WAIT);
438        let stalled = wait_for_network(|| std::future::pending()).await;
439        assert!(stalled.unwrap_err().contains("timed out"));
440        assert_eq!(
441            wait_for_network(|| async { Err("service unavailable".into()) }).await,
442            Err("service unavailable".into())
443        );
444    }
445}