Skip to main content

iphone_cli/device/
address.rs

1//! A Wi-Fi address includes the IPv6 interface needed for link-local peers.
2
3use std::{
4    fmt,
5    io::Write,
6    net::{IpAddr, SocketAddr, SocketAddrV6},
7    path::Path,
8    str::FromStr,
9};
10
11use anyhow::{Result, bail};
12use serde::{Deserialize, Serialize};
13
14use crate::paths;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(try_from = "String", into = "String")]
18pub struct WifiAddress {
19    pub ip: IpAddr,
20    pub scope_id: u32,
21}
22
23impl WifiAddress {
24    pub fn new(ip: IpAddr, scope_id: u32) -> Result<Self> {
25        if ip.is_unspecified() || ip.is_multicast() {
26            bail!("use a unicast iPhone address");
27        }
28        if ip.is_ipv4() && scope_id != 0 {
29            bail!("an IPv4 address cannot have an interface scope");
30        }
31        if matches!(ip, IpAddr::V6(v) if v.is_unicast_link_local()) && scope_id == 0 {
32            bail!("a link-local IPv6 address needs a numeric interface, e.g. fe80::1%12");
33        }
34        Ok(Self { ip, scope_id })
35    }
36
37    pub fn socket_addr(self, port: u16) -> SocketAddr {
38        match self.ip {
39            IpAddr::V4(_) => SocketAddr::new(self.ip, port),
40            IpAddr::V6(ip) => SocketAddr::V6(SocketAddrV6::new(ip, port, 0, self.scope_id)),
41        }
42    }
43}
44
45impl FromStr for WifiAddress {
46    type Err = anyhow::Error;
47    fn from_str(s: &str) -> Result<Self> {
48        let (ip, scope) = match s.split_once('%') {
49            Some((ip, scope)) => (ip.parse()?, scope.parse()?),
50            None => (s.parse()?, 0),
51        };
52        Self::new(ip, scope)
53    }
54}
55
56impl TryFrom<String> for WifiAddress {
57    type Error = anyhow::Error;
58    fn try_from(s: String) -> Result<Self> {
59        s.parse()
60    }
61}
62
63impl From<WifiAddress> for String {
64    fn from(value: WifiAddress) -> Self {
65        value.to_string()
66    }
67}
68
69impl fmt::Display for WifiAddress {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        write!(f, "{}", self.ip)?;
72        if self.scope_id != 0 {
73            write!(f, "%{}", self.scope_id)?;
74        }
75        Ok(())
76    }
77}
78
79pub(crate) fn valid_udid(udid: &str) -> bool {
80    !udid.is_empty()
81        && udid.len() <= 128
82        && udid.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')
83}
84
85pub(crate) fn cached(udid: &str) -> Option<WifiAddress> {
86    if !valid_udid(udid) {
87        return None;
88    }
89    std::fs::read_to_string(paths::state_dir().join(format!("{udid}.addr")))
90        .ok()?
91        .trim()
92        .parse()
93        .ok()
94}
95
96/// Atomic replacement is shared by manual registration and verified discovery.
97pub(crate) fn save(state: &Path, udid: &str, address: WifiAddress) -> std::io::Result<()> {
98    if !valid_udid(udid) {
99        return Err(std::io::Error::new(
100            std::io::ErrorKind::InvalidInput,
101            "invalid UDID",
102        ));
103    }
104    paths::ensure_private_dir(state)?;
105    let temporary = state.join(format!("{udid}.addr.{}.tmp", uuid::Uuid::new_v4()));
106    let result = (|| {
107        let mut file = paths::private_file()
108            .write(true)
109            .create_new(true)
110            .open(&temporary)?;
111        file.write_all(address.to_string().as_bytes())?;
112        drop(file);
113        std::fs::rename(&temporary, state.join(format!("{udid}.addr")))
114    })();
115    if result.is_err() {
116        let _ = std::fs::remove_file(temporary);
117    }
118    result
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn old_cache_strings_and_scoped_ipv6_round_trip() {
127        for value in ["192.0.2.1", "2001:db8::1", "fe80::1234%12"] {
128            let addr: WifiAddress = value.parse().unwrap();
129            assert_eq!(addr.to_string(), value);
130            assert_eq!(
131                serde_json::from_str::<WifiAddress>(&serde_json::to_string(&addr).unwrap())
132                    .unwrap(),
133                addr
134            );
135        }
136        let addr: WifiAddress = "fe80::1234%12".parse().unwrap();
137        assert_eq!(addr.socket_addr(62078).to_string(), "[fe80::1234%12]:62078");
138    }
139
140    #[test]
141    fn invalid_or_unscoped_addresses_are_not_connection_candidates() {
142        for value in [
143            "0.0.0.0",
144            "::",
145            "224.0.0.251",
146            "ff02::fb%12",
147            "fe80::1",
148            "fe80::1%0",
149            "192.0.2.1%12",
150            "fe80::1%name",
151            "host.local",
152        ] {
153            assert!(value.parse::<WifiAddress>().is_err(), "{value}");
154        }
155    }
156}