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        "syslog" => Box::pin(s.cmd_syslog(args)).await,
86        "status" => Ok(fields! {
87            "udid": s.udid.clone(),
88            "connection": s.connection(),
89            "tunnel": s.tunnel.is_some(),
90            "accessibility": s.ax.as_ref().is_some_and(|a| !a.is_closed()),
91            "input_session": s.input.is_some(),
92            "connects": s.connects,
93            "ax_restarts": s.ax_restarts,
94            "capture": s.capture_state(),
95            "pid": std::process::id(),
96            "build": build_stamp(),
97        }),
98        // For testing recovery: close the tunnel under the open connections,
99        // as a pulled cable or a Wi-Fi drop would.
100        "debug_drop_tunnel" if std::env::var("IPH_DEBUG").is_ok_and(|v| v == "1") => {
101            let closed = match s.tunnel.as_mut() {
102                Some(t) => t.adapter.close().await.is_ok(),
103                None => false,
104            };
105            Ok(fields! { "closed": closed })
106        }
107        other => Err(Fail::invalid(format!("unknown command `{other}`"))),
108    }
109}
110
111/// How long one request may run before the daemon gives up on it.
112pub fn budget(cmd: &str) -> Duration {
113    match cmd {
114        // A script stops itself first, at [script] timeout_secs.
115        "script" => Duration::from_secs(script::MAX_TIMEOUT_SECS + 60),
116        "batch" => Duration::from_secs(600),
117        "doctor" => Duration::from_secs(120),
118        _ => Duration::from_secs(90),
119    }
120}
121
122struct Shared {
123    session: Mutex<Session>,
124    last_request: StdMutex<Instant>,
125    build: String,
126    udid: String,
127}
128
129async fn handle(stream: ipc::Stream, shared: Arc<Shared>) -> Result<()> {
130    let (read, mut write) = tokio::io::split(stream);
131    let mut line = String::new();
132    BufReader::new(read).read_line(&mut line).await?;
133    if line.trim().is_empty() {
134        return Ok(());
135    }
136    let started = Instant::now();
137    let req: Request = match serde_json::from_str(&line) {
138        Ok(r) => r,
139        Err(e) => {
140            let out = envelope(Err(Fail::invalid(format!("bad request: {e}"))), started);
141            write.write_all(format!("{out}\n").as_bytes()).await?;
142            return Ok(());
143        }
144    };
145    *shared.last_request.lock().unwrap() = Instant::now();
146
147    let reply = match req.cmd.as_str() {
148        "ping" => json!({ "ok": true, "build": shared.build, "pid": std::process::id(), "udid": shared.udid }),
149        "shutdown" => {
150            log("shutdown requested");
151            let mut session = shared.session.lock().await;
152            session.end_capture_before_exit("the daemon was stopped (iph stop, or replaced by a newer build)").await;
153            let reply = json!({ "ok": true });
154            write.write_all(format!("{reply}\n").as_bytes()).await?;
155            write.shutdown().await.ok();
156            session.shutdown().await;
157            ipc::cleanup(&shared.udid);
158            let _ = std::fs::remove_file(paths::daemon_pid(&shared.udid));
159            std::process::exit(0);
160        }
161        _ if req.build != shared.build => envelope(
162            Err(Fail::not_sent("daemon_outdated", "the daemon runs an older build")),
163            started,
164        ),
165        cmd => {
166            events::record("daemon.command", "started", 0, json!({ "udid": shared.udid, "command": cmd }));
167            let mut session = shared.session.lock().await;
168            let work = Box::pin(dispatch(&mut session, cmd, &req.args));
169            let result = match tokio::time::timeout(budget(cmd), work).await {
170                Ok(r) => r,
171                Err(_) => {
172                    // Whatever was in flight is abandoned with its connections.
173                    session.reset();
174                    Err(Fail::unknown(
175                        "timeout",
176                        format!("`{cmd}` did not finish within {} s", budget(cmd).as_secs()),
177                    )
178                    .hint(crate::i18n::t(
179                        "입력이 일부 나갔을 수 있습니다. `iph read`로 화면을 확인하세요.",
180                        "Some input may have gone out. Check the screen with `iph read`.",
181                    )))
182                }
183            };
184            if let Err(f) = &result {
185                log(&format!("{cmd} -> {} {}", f.outcome.as_str(), f.code));
186            }
187            events::record("daemon.command", if result.is_ok() { "ok" } else { "error" }, started.elapsed().as_millis(),
188                json!({ "udid": shared.udid, "command": cmd, "error": result.as_ref().err().map(|f| f.error_json()) }));
189            let reply = envelope(result, started);
190            session.close_input_if_unheld().await;
191            session.sweep().await;
192            reply
193        }
194    };
195    *shared.last_request.lock().unwrap() = Instant::now();
196    write.write_all(format!("{reply}\n").as_bytes()).await?;
197    write.shutdown().await.ok();
198    Ok(())
199}
200
201/// The tunnel's TCP stack and the device library say why a connection went
202/// away ("timed out after 5 retransmissions", "RST on hp=…") as `tracing`
203/// warnings. Without a subscriber they are lost and all iph sees later is
204/// "not connected". They carry ports and byte counts, never screen contents.
205/// `IPH_LOG` takes a filter such as `iphone_cli::tcp=debug` for more.
206fn keep_library_warnings() {
207    events::init_tracing();
208}
209
210pub async fn run(udid: String) -> Result<()> {
211    keep_library_warnings();
212    paths::ensure_private_dir(&paths::state_dir())?;
213    if ipc::connect(&udid).await.is_ok() {
214        bail!("a daemon for {udid} is already running");
215    }
216    let mut listener = ipc::Listener::bind(&udid)?;
217    // So a client can put down a daemon that stopped answering.
218    std::fs::write(paths::daemon_pid(&udid), std::process::id().to_string())?;
219
220    let config = Config::load()?;
221    let idle_exit = Duration::from_secs(config.daemon.idle_exit_secs.max(30));
222    let shared = Arc::new(Shared {
223        session: Mutex::new(Session::new(udid.clone(), config)),
224        last_request: StdMutex::new(Instant::now()),
225        build: build_stamp(),
226        udid: udid.clone(),
227    });
228    log(&format!("daemon for {udid} listening, build {}", shared.build));
229
230    // Requests run one at a time, so everything stays on this thread: the
231    // device futures need not be `Send`.
232    let local = tokio::task::LocalSet::new();
233    local
234        .run_until(async move {
235            // Housekeeping: close an idle input session, exit when unused.
236            let keeper = shared.clone();
237            tokio::task::spawn_local(async move {
238                loop {
239                    tokio::time::sleep(Duration::from_secs(5)).await;
240                    let idle = keeper.last_request.lock().unwrap().elapsed();
241                    if let Ok(mut session) = keeper.session.try_lock() {
242                        session.sweep().await;
243                        session.close_idle_input().await;
244                        if idle > idle_exit {
245                            log("idle, exiting");
246                            session.end_capture_before_exit("the daemon exited after its idle time").await;
247                            session.shutdown().await;
248                            ipc::cleanup(&keeper.udid);
249                            let _ = std::fs::remove_file(paths::daemon_pid(&keeper.udid));
250                            std::process::exit(0);
251                        }
252                    }
253                }
254            });
255
256            loop {
257                let stream = listener.accept().await?;
258                let shared = shared.clone();
259                tokio::task::spawn_local(async move {
260                    if let Err(e) = handle(stream, shared).await {
261                        log(&format!("connection error: {e:#}"));
262                    }
263                });
264            }
265        })
266        .await
267}