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, events, 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    s.refresh_connection();
61    match cmd {
62        "read" => Box::pin(s.cmd_read(parse_args(args)?)).await,
63        "find" => Box::pin(s.cmd_find(parse_args(args)?)).await,
64        "tap" => Box::pin(s.cmd_tap(parse_args(args)?)).await,
65        "swipe" => Box::pin(s.cmd_swipe(parse_args(args)?)).await,
66        "pinch" => Box::pin(s.cmd_pinch(parse_args(args)?)).await,
67        "scroll" => Box::pin(s.cmd_scroll(parse_args(args)?)).await,
68        "type" => Box::pin(s.cmd_type(parse_args(args)?)).await,
69        "key" => Box::pin(s.cmd_key(parse_args(args)?)).await,
70        "button" => Box::pin(s.cmd_button(parse_args(args)?)).await,
71        "launch" => Box::pin(s.cmd_launch(parse_args(args)?)).await,
72        "apps" => s.cmd_apps().await,
73        "screenshot" => Box::pin(s.cmd_screenshot(parse_args(args)?)).await,
74        "batch" => {
75            let steps = args
76                .get("steps")
77                .and_then(|v| v.as_array())
78                .ok_or_else(|| Fail::invalid("batch needs a JSON array of steps"))?;
79            Box::pin(s.run_steps(steps, &Map::new())).await
80        }
81        // `iph script` and `iph run`: whoever asks sends the code along.
82        "script" => Box::pin(s.serve_script(args)).await,
83        "doctor" => Box::pin(doctor::run(s, parse_args(args)?)).await,
84        "dnd" => Box::pin(s.cmd_dnd(parse_args(args)?)).await,
85        "status" => Ok(fields! {
86            "udid": s.udid.clone(),
87            "connection": s.connection(),
88            "tunnel": s.tunnel.is_some(),
89            "accessibility": s.ax.as_ref().is_some_and(|a| !a.is_closed()),
90            "input_session": s.input.is_some(),
91            "connects": s.connects,
92            "ax_restarts": s.ax_restarts,
93            "pid": std::process::id(),
94            "build": build_stamp(),
95        }),
96        // For testing recovery: close the tunnel under the open connections,
97        // as a pulled cable or a Wi-Fi drop would.
98        "debug_drop_tunnel" if std::env::var("IPH_DEBUG").is_ok_and(|v| v == "1") => {
99            let closed = match s.tunnel.as_mut() {
100                Some(t) => t.adapter.close().await.is_ok(),
101                None => false,
102            };
103            Ok(fields! { "closed": closed })
104        }
105        other => Err(Fail::invalid(format!("unknown command `{other}`"))),
106    }
107}
108
109/// How long one request may run before the daemon gives up on it.
110pub fn budget(cmd: &str) -> Duration {
111    match cmd {
112        // A script stops itself first, at [script] timeout_secs.
113        "script" => Duration::from_secs(script::MAX_TIMEOUT_SECS + 60),
114        "batch" => Duration::from_secs(600),
115        "doctor" => Duration::from_secs(120),
116        _ => Duration::from_secs(90),
117    }
118}
119
120struct Shared {
121    session: Mutex<Session>,
122    last_request: StdMutex<Instant>,
123    build: String,
124    udid: String,
125}
126
127async fn handle(stream: ipc::Stream, shared: Arc<Shared>) -> Result<()> {
128    let (read, mut write) = tokio::io::split(stream);
129    let mut line = String::new();
130    BufReader::new(read).read_line(&mut line).await?;
131    if line.trim().is_empty() {
132        return Ok(());
133    }
134    let started = Instant::now();
135    let req: Request = match serde_json::from_str(&line) {
136        Ok(r) => r,
137        Err(e) => {
138            let out = envelope(Err(Fail::invalid(format!("bad request: {e}"))), started);
139            write.write_all(format!("{out}\n").as_bytes()).await?;
140            return Ok(());
141        }
142    };
143    *shared.last_request.lock().unwrap() = Instant::now();
144
145    let reply = match req.cmd.as_str() {
146        "ping" => json!({ "ok": true, "build": shared.build, "pid": std::process::id(), "udid": shared.udid }),
147        "shutdown" => {
148            log("shutdown requested");
149            let mut session = shared.session.lock().await;
150            let reply = json!({ "ok": true });
151            write.write_all(format!("{reply}\n").as_bytes()).await?;
152            write.shutdown().await.ok();
153            session.shutdown().await;
154            ipc::cleanup(&shared.udid);
155            let _ = std::fs::remove_file(paths::daemon_pid(&shared.udid));
156            std::process::exit(0);
157        }
158        _ if req.build != shared.build => envelope(
159            Err(Fail::not_sent("daemon_outdated", "the daemon runs an older build")),
160            started,
161        ),
162        cmd => {
163            events::record("daemon.command", "started", 0, json!({ "udid": shared.udid, "command": cmd }));
164            let mut session = shared.session.lock().await;
165            let work = Box::pin(dispatch(&mut session, cmd, &req.args));
166            let result = match tokio::time::timeout(budget(cmd), work).await {
167                Ok(r) => r,
168                Err(_) => {
169                    // Whatever was in flight is abandoned with its connections.
170                    session.reset();
171                    Err(Fail::unknown(
172                        "timeout",
173                        format!("`{cmd}` did not finish within {} s", budget(cmd).as_secs()),
174                    )
175                    .hint(crate::i18n::t(
176                        "입력이 일부 나갔을 수 있습니다. `iph read`로 화면을 확인하세요.",
177                        "Some input may have gone out. Check the screen with `iph read`.",
178                    )))
179                }
180            };
181            if let Err(f) = &result {
182                log(&format!("{cmd} -> {} {}", f.outcome.as_str(), f.code));
183            }
184            events::record("daemon.command", if result.is_ok() { "ok" } else { "error" }, started.elapsed().as_millis(),
185                json!({ "udid": shared.udid, "command": cmd, "error": result.as_ref().err().map(|f| f.error_json()) }));
186            let reply = envelope(result, started);
187            session.close_input_if_unheld().await;
188            session.sweep().await;
189            reply
190        }
191    };
192    *shared.last_request.lock().unwrap() = Instant::now();
193    write.write_all(format!("{reply}\n").as_bytes()).await?;
194    write.shutdown().await.ok();
195    Ok(())
196}
197
198/// The tunnel's TCP stack and the device library say why a connection went
199/// away ("timed out after 5 retransmissions", "RST on hp=…") as `tracing`
200/// warnings. Without a subscriber they are lost and all iph sees later is
201/// "not connected". They carry ports and byte counts, never screen contents.
202/// `IPH_LOG` takes a filter such as `iphone_cli::tcp=debug` for more.
203fn keep_library_warnings() {
204    events::init_tracing();
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}