Skip to main content

iphone_cli/
connect.rs

1//! Register a paired phone's direct address when usbmuxd discovery is empty.
2
3use std::{future::Future, path::Path};
4
5use serde::Deserialize;
6
7use crate::{
8    client,
9    device::{
10        address::{self, WifiAddress},
11        conn,
12        identity::{self, Identity},
13    },
14    fields,
15    i18n::t,
16    paths,
17    reply::{Fail, Res},
18};
19
20#[derive(Debug, Clone, clap::Args, Deserialize)]
21#[serde(deny_unknown_fields)]
22pub struct Args {
23    /// The iPhone's IP address, shown in Settings > Wi-Fi > the network's info.
24    #[arg(long)]
25    pub ip: WifiAddress,
26}
27
28fn validate(udid: &str, _ip: WifiAddress) -> Res<()> {
29    if !address::valid_udid(udid) {
30        return Err(Fail::invalid(
31            "UDID must contain only ASCII letters, digits and hyphens",
32        ));
33    }
34    Ok(())
35}
36
37/// Persist only after both the paired session and reported identity succeeded.
38async fn register_at(
39    state: &Path,
40    udid: &str,
41    ip: WifiAddress,
42    probe: impl Future<Output = Res<Identity>>,
43) -> Res {
44    validate(udid, ip)?;
45    let identity = probe.await?;
46    if !identity.udid.eq_ignore_ascii_case(udid) {
47        return Err(Fail::not_sent(
48            "wifi_device_mismatch",
49            "the address belongs to a different iPhone",
50        )
51        .with("expected_udid", udid)
52        .with("observed_udid", identity.udid));
53    }
54    address::save(state, udid, ip).map_err(|e| {
55        Fail::not_sent(
56            "connection_save_failed",
57            format!("cannot save the verified address: {e}"),
58        )
59    })?;
60    Ok(fields! {
61        "udid": udid, "connection": "wifi", "source": "direct_ip",
62        "ip": ip.to_string(), "paired": true, "udid_verified": true, "address_saved": true,
63        "ios_version": identity.ios_version, "model": identity.model,
64        "hint": t("주소를 저장했습니다. 이후 같은 UDID로 read·doctor·MCP·스크립트를 실행할 수 있습니다. 개발자 서비스 준비 상태는 doctor로 확인하세요.",
65                  "Address saved. Use the same UDID for read, doctor, MCP and scripts. Check developer-service readiness with doctor.")
66    })
67}
68
69pub async fn run(udid: &str, args: Args) -> Res {
70    let probe = async {
71        let provider = conn::direct_provider(udid, args.ip).await.map_err(|e| {
72            Fail::not_sent(
73                "not_paired",
74                format!("cannot get this phone's pairing record: {e:#}"),
75            )
76        })?;
77        identity::identify(&provider).await.map_err(|f| f.hint(t(
78            "아이폰을 깨워 잠금을 풀고 IP 주소를 확인하세요. 처음 연결한다면 USB로 연결해 이 컴퓨터를 신뢰해야 합니다.",
79            "Wake and unlock the iPhone, confirm its IP address, and pair by USB first if needed.",
80        )))
81    };
82    let mut fields = register_at(&paths::state_dir(), udid, args.ip, probe).await?;
83    // An existing daemon may still hold a tunnel to the previous address.
84    fields.insert(
85        "daemon_stopped".into(),
86        client::stop_daemon(udid).await.is_some().into(),
87    );
88    Ok(fields)
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94
95    fn identity(udid: &str) -> Identity {
96        Identity {
97            udid: udid.into(),
98            ios_version: Some("27.2.1".into()),
99            model: Some("iPhone14,2".into()),
100        }
101    }
102
103    #[tokio::test]
104    async fn only_a_matching_paired_probe_replaces_the_saved_address() {
105        let dir = std::env::temp_dir().join(format!("iph-direct-{}", uuid::Uuid::new_v4()));
106        let udid = "TEST-PHONE";
107        let old: WifiAddress = "192.0.2.1".parse().unwrap();
108        let new: WifiAddress = "192.0.2.2".parse().unwrap();
109        let saved = dir.join(format!("{udid}.addr"));
110        let v = register_at(&dir, udid, old, async { Ok(identity(udid)) })
111            .await
112            .unwrap();
113        assert_eq!(v["address_saved"], true);
114        assert_eq!(std::fs::read_to_string(&saved).unwrap(), old.to_string());
115
116        for result in [
117            Err(Fail::not_sent("wifi_session_failed", "rejected")),
118            Err(Fail::not_sent("wifi_identity_unavailable", "unreadable")),
119            Ok(identity("OTHER-PHONE")),
120        ] {
121            assert!(
122                register_at(&dir, udid, new, async { result })
123                    .await
124                    .is_err()
125            );
126            assert_eq!(std::fs::read_to_string(&saved).unwrap(), old.to_string());
127        }
128        register_at(&dir, udid, new, async { Ok(identity(udid)) })
129            .await
130            .unwrap();
131        assert_eq!(std::fs::read_to_string(&saved).unwrap(), new.to_string());
132        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
133        std::fs::remove_dir_all(dir).unwrap();
134    }
135
136    #[tokio::test]
137    async fn invalid_target_is_rejected_before_probing_or_creating_files() {
138        let dir = std::env::temp_dir().join(format!("iph-direct-{}", uuid::Uuid::new_v4()));
139        let result = register_at(&dir, "../escape", "192.0.2.1".parse().unwrap(), async {
140            panic!("must not probe")
141        })
142        .await;
143        assert_eq!(result.unwrap_err().code, "invalid_argument");
144        assert!(!dir.exists());
145    }
146
147    #[tokio::test]
148    async fn failed_cache_commit_preserves_existing_data_and_removes_the_temporary_file() {
149        let dir = std::env::temp_dir().join(format!("iph-direct-{}", uuid::Uuid::new_v4()));
150        let destination = dir.join("TEST-PHONE.addr");
151        std::fs::create_dir_all(&destination).unwrap();
152        std::fs::write(destination.join("keep"), "previous data").unwrap();
153        let result = register_at(&dir, "TEST-PHONE", "192.0.2.1".parse().unwrap(), async {
154            Ok(identity("TEST-PHONE"))
155        })
156        .await;
157        assert_eq!(result.unwrap_err().code, "connection_save_failed");
158        assert_eq!(
159            std::fs::read_to_string(destination.join("keep")).unwrap(),
160            "previous data"
161        );
162        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
163        std::fs::remove_dir_all(dir).unwrap();
164    }
165}