Skip to main content

iphone_cli/
daemon.rs

1//! The resident process (`iph daemon`, started on demand by the first `iph`
2//! call). It keeps the tunnel, the accessibility subscription and the input
3//! session open for one phone and serves requests from a Unix socket (a named
4//! pipe on Windows), one at a time.
5
6use std::{
7    sync::{Arc, Mutex as StdMutex},
8    time::{Duration, Instant},
9};
10
11use anyhow::{Result, bail};
12use serde::{Deserialize, Serialize};
13use serde_json::{Map, Value, json};
14use tokio::{
15    io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
16    sync::Mutex,
17};
18
19use crate::{
20    actions::parse_args,
21    config::Config,
22    device::session::Session,
23    doctor, fields, ipc, paths,
24    reply::{Fail, Res, envelope},
25    script,
26};
27
28#[derive(Debug, Serialize, Deserialize)]
29pub struct Request {
30    /// Identifies the client's binary; a daemon from an older build steps down.
31    pub build: String,
32    pub cmd: String,
33    #[serde(default)]
34    pub args: Value,
35}
36
37/// Stamp of the running executable: version plus the file's size and mtime.
38pub fn build_stamp() -> String {
39    let meta = std::env::current_exe().and_then(std::fs::metadata);
40    let detail = match meta {
41        Ok(m) => {
42            let mtime = m
43                .modified()
44                .ok()
45                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
46                .map(|d| d.as_secs())
47                .unwrap_or(0);
48            format!("{}-{}", m.len(), mtime)
49        }
50        Err(_) => "unknown".into(),
51    };
52    format!("{}-{detail}", env!("CARGO_PKG_VERSION"))
53}
54
55fn log(msg: &str) {
56    eprintln!("[{}] {msg}", crate::clock::now_utc());
57}
58
59async fn dispatch(s: &mut Session, cmd: &str, args: &Value) -> Res {
60    match cmd {
61        "read" => Box::pin(s.cmd_read(parse_args(args)?)).await,
62        "find" => Box::pin(s.cmd_find(parse_args(args)?)).await,
63        "tap" => Box::pin(s.cmd_tap(parse_args(args)?)).await,
64        "swipe" => Box::pin(s.cmd_swipe(parse_args(args)?)).await,
65        "scroll" => Box::pin(s.cmd_scroll(parse_args(args)?)).await,
66        "type" => Box::pin(s.cmd_type(parse_args(args)?)).await,
67        "key" => Box::pin(s.cmd_key(parse_args(args)?)).await,
68        "button" => Box::pin(s.cmd_button(parse_args(args)?)).await,
69        "launch" => Box::pin(s.cmd_launch(parse_args(args)?)).await,
70        "apps" => s.cmd_apps().await,
71        "screenshot" => Box::pin(s.cmd_screenshot(parse_args(args)?)).await,
72        "batch" => {
73            let steps = args
74                .get("steps")
75                .and_then(|v| v.as_array())
76                .ok_or_else(|| Fail::invalid("batch needs a JSON array of steps"))?;
77            Box::pin(s.run_steps(steps, &Map::new())).await
78        }
79        // `iph script` and `iph run`: whoever asks sends the code along.
80        "script" => Box::pin(s.serve_script(args)).await,
81        "doctor" => Box::pin(doctor::run(s, parse_args(args)?)).await,
82        "dnd" => Box::pin(s.cmd_dnd(parse_args(args)?)).await,
83        "status" => Ok(fields! {
84            "udid": s.udid.clone(),
85            "connection": s.connection(),
86            "tunnel": s.tunnel.is_some(),
87            "accessibility": s.ax.as_ref().is_some_and(|a| !a.is_closed()),
88            "input_session": s.input.is_some(),
89            "connects": s.connects,
90            "ax_restarts": s.ax_restarts,
91            "pid": std::process::id(),
92            "build": build_stamp(),
93        }),
94        // For testing recovery: close the tunnel under the open connections,
95        // as a pulled cable or a Wi-Fi drop would.
96        "debug_drop_tunnel" if std::env::var("IPH_DEBUG").is_ok_and(|v| v == "1") => {
97            let closed = match s.tunnel.as_mut() {
98                Some(t) => t.adapter.close().await.is_ok(),
99                None => false,
100            };
101            Ok(fields! { "closed": closed })
102        }
103        other => Err(Fail::invalid(format!("unknown command `{other}`"))),
104    }
105}
106
107/// How long one request may run before the daemon gives up on it.
108pub fn budget(cmd: &str) -> Duration {
109    match cmd {
110        // A script stops itself first, at [script] timeout_secs.
111        "script" => Duration::from_secs(script::MAX_TIMEOUT_SECS + 60),
112        "batch" => Duration::from_secs(600),
113        "doctor" => Duration::from_secs(120),
114        _ => Duration::from_secs(90),
115    }
116}
117
118struct Shared {
119    session: Mutex<Session>,
120    last_request: StdMutex<Instant>,
121    build: String,
122    udid: String,
123}
124
125async fn handle(stream: ipc::Stream, shared: Arc<Shared>) -> Result<()> {
126    let (read, mut write) = tokio::io::split(stream);
127    let mut line = String::new();
128    BufReader::new(read).read_line(&mut line).await?;
129    if line.trim().is_empty() {
130        return Ok(());
131    }
132    let started = Instant::now();
133    let req: Request = match serde_json::from_str(&line) {
134        Ok(r) => r,
135        Err(e) => {
136            let out = envelope(Err(Fail::invalid(format!("bad request: {e}"))), started);
137            write.write_all(format!("{out}\n").as_bytes()).await?;
138            return Ok(());
139        }
140    };
141    *shared.last_request.lock().unwrap() = Instant::now();
142
143    let reply = match req.cmd.as_str() {
144        "ping" => json!({ "ok": true, "build": shared.build, "pid": std::process::id(), "udid": shared.udid }),
145        "shutdown" => {
146            log("shutdown requested");
147            let mut session = shared.session.lock().await;
148            let reply = json!({ "ok": true });
149            write.write_all(format!("{reply}\n").as_bytes()).await?;
150            write.shutdown().await.ok();
151            session.shutdown().await;
152            ipc::cleanup(&shared.udid);
153            let _ = std::fs::remove_file(paths::daemon_pid(&shared.udid));
154            std::process::exit(0);
155        }
156        _ if req.build != shared.build => envelope(
157            Err(Fail::not_sent("daemon_outdated", "the daemon runs an older build")),
158            started,
159        ),
160        cmd => {
161            let mut session = shared.session.lock().await;
162            let work = Box::pin(dispatch(&mut session, cmd, &req.args));
163            let result = match tokio::time::timeout(budget(cmd), work).await {
164                Ok(r) => r,
165                Err(_) => {
166                    // Whatever was in flight is abandoned with its connections.
167                    session.reset();
168                    Err(Fail::unknown(
169                        "timeout",
170                        format!("`{cmd}` did not finish within {} s", budget(cmd).as_secs()),
171                    )
172                    .hint(crate::i18n::t(
173                        "입력이 일부 나갔을 수 있습니다. `iph read`로 화면을 확인하세요.",
174                        "Some input may have gone out. Check the screen with `iph read`.",
175                    )))
176                }
177            };
178            if let Err(f) = &result {
179                log(&format!("{cmd} -> {} {}", f.outcome.as_str(), f.code));
180            }
181            let reply = envelope(result, started);
182            session.close_input_if_unheld().await;
183            session.sweep().await;
184            reply
185        }
186    };
187    *shared.last_request.lock().unwrap() = Instant::now();
188    write.write_all(format!("{reply}\n").as_bytes()).await?;
189    write.shutdown().await.ok();
190    Ok(())
191}
192
193/// The tunnel's TCP stack and the device library say why a connection went
194/// away ("timed out after 5 retransmissions", "RST on hp=…") as `tracing`
195/// warnings. Without a subscriber they are lost and all iph sees later is
196/// "not connected". They carry ports and byte counts, never screen contents.
197/// `IPH_LOG` takes a filter such as `iphone_cli::tcp=debug` for more.
198fn keep_library_warnings() {
199    let filter = std::env::var("IPH_LOG").unwrap_or_else(|_| "warn".into());
200    let _ = tracing_subscriber::fmt()
201        .with_env_filter(tracing_subscriber::EnvFilter::new(filter))
202        .with_writer(std::io::stderr)
203        .with_ansi(false)
204        .try_init();
205}
206
207pub async fn run(udid: String) -> Result<()> {
208    keep_library_warnings();
209    paths::ensure_private_dir(&paths::state_dir())?;
210    if ipc::connect(&udid).await.is_ok() {
211        bail!("a daemon for {udid} is already running");
212    }
213    let mut listener = ipc::Listener::bind(&udid)?;
214    // So a client can put down a daemon that stopped answering.
215    std::fs::write(paths::daemon_pid(&udid), std::process::id().to_string())?;
216
217    let config = Config::load()?;
218    let idle_exit = Duration::from_secs(config.daemon.idle_exit_secs.max(30));
219    let shared = Arc::new(Shared {
220        session: Mutex::new(Session::new(udid.clone(), config)),
221        last_request: StdMutex::new(Instant::now()),
222        build: build_stamp(),
223        udid: udid.clone(),
224    });
225    log(&format!("daemon for {udid} listening, build {}", shared.build));
226
227    // Requests run one at a time, so everything stays on this thread: the
228    // device futures need not be `Send`.
229    let local = tokio::task::LocalSet::new();
230    local
231        .run_until(async move {
232            // Housekeeping: close an idle input session, exit when unused.
233            let keeper = shared.clone();
234            tokio::task::spawn_local(async move {
235                loop {
236                    tokio::time::sleep(Duration::from_secs(5)).await;
237                    let idle = keeper.last_request.lock().unwrap().elapsed();
238                    if let Ok(mut session) = keeper.session.try_lock() {
239                        session.sweep().await;
240                        session.close_idle_input().await;
241                        if idle > idle_exit {
242                            log("idle, exiting");
243                            session.shutdown().await;
244                            ipc::cleanup(&keeper.udid);
245                            let _ = std::fs::remove_file(paths::daemon_pid(&keeper.udid));
246                            std::process::exit(0);
247                        }
248                    }
249                }
250            });
251
252            loop {
253                let stream = listener.accept().await?;
254                let shared = shared.clone();
255                tokio::task::spawn_local(async move {
256                    if let Err(e) = handle(stream, shared).await {
257                        log(&format!("connection error: {e:#}"));
258                    }
259                });
260            }
261        })
262        .await
263}