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    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            events::record("daemon.command", "started", 0, json!({ "udid": shared.udid, "command": cmd }));
162            let mut session = shared.session.lock().await;
163            let work = Box::pin(dispatch(&mut session, cmd, &req.args));
164            let result = match tokio::time::timeout(budget(cmd), work).await {
165                Ok(r) => r,
166                Err(_) => {
167                    // Whatever was in flight is abandoned with its connections.
168                    session.reset();
169                    Err(Fail::unknown(
170                        "timeout",
171                        format!("`{cmd}` did not finish within {} s", budget(cmd).as_secs()),
172                    )
173                    .hint(crate::i18n::t(
174                        "입력이 일부 나갔을 수 있습니다. `iph read`로 화면을 확인하세요.",
175                        "Some input may have gone out. Check the screen with `iph read`.",
176                    )))
177                }
178            };
179            if let Err(f) = &result {
180                log(&format!("{cmd} -> {} {}", f.outcome.as_str(), f.code));
181            }
182            events::record("daemon.command", if result.is_ok() { "ok" } else { "error" }, started.elapsed().as_millis(),
183                json!({ "udid": shared.udid, "command": cmd, "error": result.as_ref().err().map(|f| f.error_json()) }));
184            let reply = envelope(result, started);
185            session.close_input_if_unheld().await;
186            session.sweep().await;
187            reply
188        }
189    };
190    *shared.last_request.lock().unwrap() = Instant::now();
191    write.write_all(format!("{reply}\n").as_bytes()).await?;
192    write.shutdown().await.ok();
193    Ok(())
194}
195
196/// The tunnel's TCP stack and the device library say why a connection went
197/// away ("timed out after 5 retransmissions", "RST on hp=…") as `tracing`
198/// warnings. Without a subscriber they are lost and all iph sees later is
199/// "not connected". They carry ports and byte counts, never screen contents.
200/// `IPH_LOG` takes a filter such as `iphone_cli::tcp=debug` for more.
201fn keep_library_warnings() {
202    events::init_tracing();
203}
204
205pub async fn run(udid: String) -> Result<()> {
206    keep_library_warnings();
207    paths::ensure_private_dir(&paths::state_dir())?;
208    if ipc::connect(&udid).await.is_ok() {
209        bail!("a daemon for {udid} is already running");
210    }
211    let mut listener = ipc::Listener::bind(&udid)?;
212    // So a client can put down a daemon that stopped answering.
213    std::fs::write(paths::daemon_pid(&udid), std::process::id().to_string())?;
214
215    let config = Config::load()?;
216    let idle_exit = Duration::from_secs(config.daemon.idle_exit_secs.max(30));
217    let shared = Arc::new(Shared {
218        session: Mutex::new(Session::new(udid.clone(), config)),
219        last_request: StdMutex::new(Instant::now()),
220        build: build_stamp(),
221        udid: udid.clone(),
222    });
223    log(&format!("daemon for {udid} listening, build {}", shared.build));
224
225    // Requests run one at a time, so everything stays on this thread: the
226    // device futures need not be `Send`.
227    let local = tokio::task::LocalSet::new();
228    local
229        .run_until(async move {
230            // Housekeeping: close an idle input session, exit when unused.
231            let keeper = shared.clone();
232            tokio::task::spawn_local(async move {
233                loop {
234                    tokio::time::sleep(Duration::from_secs(5)).await;
235                    let idle = keeper.last_request.lock().unwrap().elapsed();
236                    if let Ok(mut session) = keeper.session.try_lock() {
237                        session.sweep().await;
238                        session.close_idle_input().await;
239                        if idle > idle_exit {
240                            log("idle, exiting");
241                            session.shutdown().await;
242                            ipc::cleanup(&keeper.udid);
243                            let _ = std::fs::remove_file(paths::daemon_pid(&keeper.udid));
244                            std::process::exit(0);
245                        }
246                    }
247                }
248            });
249
250            loop {
251                let stream = listener.accept().await?;
252                let shared = shared.clone();
253                tokio::task::spawn_local(async move {
254                    if let Err(e) = handle(stream, shared).await {
255                        log(&format!("connection error: {e:#}"));
256                    }
257                });
258            }
259        })
260        .await
261}