Skip to main content

iphone_cli/
ipc.rs

1//! The channel between `iph` and its daemon: a Unix socket on macOS, a named
2//! pipe on Windows. Either way one connection carries one request line and
3//! one reply line.
4
5use tokio::io::{AsyncRead, AsyncWrite};
6
7pub trait Duplex: AsyncRead + AsyncWrite + Unpin + Send {}
8impl<T: AsyncRead + AsyncWrite + Unpin + Send> Duplex for T {}
9
10pub type Stream = Box<dyn Duplex>;
11
12pub use imp::{Listener, cleanup, connect};
13
14#[cfg(unix)]
15mod imp {
16    use std::os::unix::fs::PermissionsExt;
17
18    use anyhow::{Context, Result};
19    use tokio::net::{UnixListener, UnixStream};
20
21    use super::Stream;
22    use crate::paths;
23
24    pub async fn connect(udid: &str) -> std::io::Result<Stream> {
25        Ok(Box::new(UnixStream::connect(paths::socket(udid)).await?))
26    }
27
28    pub struct Listener(UnixListener);
29
30    impl Listener {
31        pub fn bind(udid: &str) -> Result<Self> {
32            let sock = paths::socket(udid);
33            let _ = std::fs::remove_file(&sock);
34            let listener = UnixListener::bind(&sock).with_context(|| format!("bind {}", sock.display()))?;
35            std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600))?;
36            Ok(Self(listener))
37        }
38
39        pub async fn accept(&mut self) -> std::io::Result<Stream> {
40            let (stream, _) = self.0.accept().await?;
41            Ok(Box::new(stream))
42        }
43    }
44
45    /// Remove what `bind` left behind.
46    pub fn cleanup(udid: &str) {
47        let _ = std::fs::remove_file(paths::socket(udid));
48    }
49}
50
51#[cfg(windows)]
52mod imp {
53    use std::time::Duration;
54
55    use anyhow::{Context, Result};
56    use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeServer, ServerOptions};
57
58    use super::Stream;
59
60    /// ERROR_PIPE_BUSY: every instance is taken; the server makes a new one
61    /// as soon as it accepts.
62    const PIPE_BUSY: i32 = 231;
63
64    fn name(udid: &str) -> String {
65        format!(r"\\.\pipe\iph-{udid}")
66    }
67
68    pub async fn connect(udid: &str) -> std::io::Result<Stream> {
69        for _ in 0..100 {
70            match ClientOptions::new().open(name(udid)) {
71                Ok(client) => return Ok(Box::new(client)),
72                Err(e) if e.raw_os_error() == Some(PIPE_BUSY) => tokio::time::sleep(Duration::from_millis(20)).await,
73                Err(e) => return Err(e),
74            }
75        }
76        Err(std::io::Error::other("the daemon's pipe stayed busy"))
77    }
78
79    pub struct Listener {
80        name: String,
81        next: NamedPipeServer,
82    }
83
84    impl Listener {
85        pub fn bind(udid: &str) -> Result<Self> {
86            let name = name(udid);
87            // First instance only: a second daemon for the same phone fails here.
88            let next = ServerOptions::new()
89                .first_pipe_instance(true)
90                .reject_remote_clients(true)
91                .create(&name)
92                .with_context(|| format!("create {name}"))?;
93            Ok(Self { name, next })
94        }
95
96        pub async fn accept(&mut self) -> std::io::Result<Stream> {
97            self.next.connect().await?;
98            let fresh = ServerOptions::new().reject_remote_clients(true).create(&self.name)?;
99            Ok(Box::new(std::mem::replace(&mut self.next, fresh)))
100        }
101    }
102
103    /// A pipe goes away with its process; nothing to remove.
104    pub fn cleanup(_udid: &str) {}
105}