1use 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 pub build: String,
32 pub cmd: String,
33 #[serde(default)]
34 pub args: Value,
35}
36
37pub 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 "scroll" => Box::pin(s.cmd_scroll(parse_args(args)?)).await,
67 "type" => Box::pin(s.cmd_type(parse_args(args)?)).await,
68 "key" => Box::pin(s.cmd_key(parse_args(args)?)).await,
69 "button" => Box::pin(s.cmd_button(parse_args(args)?)).await,
70 "launch" => Box::pin(s.cmd_launch(parse_args(args)?)).await,
71 "apps" => s.cmd_apps().await,
72 "screenshot" => Box::pin(s.cmd_screenshot(parse_args(args)?)).await,
73 "batch" => {
74 let steps = args
75 .get("steps")
76 .and_then(|v| v.as_array())
77 .ok_or_else(|| Fail::invalid("batch needs a JSON array of steps"))?;
78 Box::pin(s.run_steps(steps, &Map::new())).await
79 }
80 "script" => Box::pin(s.serve_script(args)).await,
82 "doctor" => Box::pin(doctor::run(s, parse_args(args)?)).await,
83 "dnd" => Box::pin(s.cmd_dnd(parse_args(args)?)).await,
84 "status" => Ok(fields! {
85 "udid": s.udid.clone(),
86 "connection": s.connection(),
87 "tunnel": s.tunnel.is_some(),
88 "accessibility": s.ax.as_ref().is_some_and(|a| !a.is_closed()),
89 "input_session": s.input.is_some(),
90 "connects": s.connects,
91 "ax_restarts": s.ax_restarts,
92 "pid": std::process::id(),
93 "build": build_stamp(),
94 }),
95 "debug_drop_tunnel" if std::env::var("IPH_DEBUG").is_ok_and(|v| v == "1") => {
98 let closed = match s.tunnel.as_mut() {
99 Some(t) => t.adapter.close().await.is_ok(),
100 None => false,
101 };
102 Ok(fields! { "closed": closed })
103 }
104 other => Err(Fail::invalid(format!("unknown command `{other}`"))),
105 }
106}
107
108pub fn budget(cmd: &str) -> Duration {
110 match cmd {
111 "script" => Duration::from_secs(script::MAX_TIMEOUT_SECS + 60),
113 "batch" => Duration::from_secs(600),
114 "doctor" => Duration::from_secs(120),
115 _ => Duration::from_secs(90),
116 }
117}
118
119struct Shared {
120 session: Mutex<Session>,
121 last_request: StdMutex<Instant>,
122 build: String,
123 udid: String,
124}
125
126async fn handle(stream: ipc::Stream, shared: Arc<Shared>) -> Result<()> {
127 let (read, mut write) = tokio::io::split(stream);
128 let mut line = String::new();
129 BufReader::new(read).read_line(&mut line).await?;
130 if line.trim().is_empty() {
131 return Ok(());
132 }
133 let started = Instant::now();
134 let req: Request = match serde_json::from_str(&line) {
135 Ok(r) => r,
136 Err(e) => {
137 let out = envelope(Err(Fail::invalid(format!("bad request: {e}"))), started);
138 write.write_all(format!("{out}\n").as_bytes()).await?;
139 return Ok(());
140 }
141 };
142 *shared.last_request.lock().unwrap() = Instant::now();
143
144 let reply = match req.cmd.as_str() {
145 "ping" => json!({ "ok": true, "build": shared.build, "pid": std::process::id(), "udid": shared.udid }),
146 "shutdown" => {
147 log("shutdown requested");
148 let mut session = shared.session.lock().await;
149 let reply = json!({ "ok": true });
150 write.write_all(format!("{reply}\n").as_bytes()).await?;
151 write.shutdown().await.ok();
152 session.shutdown().await;
153 ipc::cleanup(&shared.udid);
154 let _ = std::fs::remove_file(paths::daemon_pid(&shared.udid));
155 std::process::exit(0);
156 }
157 _ if req.build != shared.build => envelope(
158 Err(Fail::not_sent("daemon_outdated", "the daemon runs an older build")),
159 started,
160 ),
161 cmd => {
162 events::record("daemon.command", "started", 0, json!({ "udid": shared.udid, "command": cmd }));
163 let mut session = shared.session.lock().await;
164 let work = Box::pin(dispatch(&mut session, cmd, &req.args));
165 let result = match tokio::time::timeout(budget(cmd), work).await {
166 Ok(r) => r,
167 Err(_) => {
168 session.reset();
170 Err(Fail::unknown(
171 "timeout",
172 format!("`{cmd}` did not finish within {} s", budget(cmd).as_secs()),
173 )
174 .hint(crate::i18n::t(
175 "입력이 일부 나갔을 수 있습니다. `iph read`로 화면을 확인하세요.",
176 "Some input may have gone out. Check the screen with `iph read`.",
177 )))
178 }
179 };
180 if let Err(f) = &result {
181 log(&format!("{cmd} -> {} {}", f.outcome.as_str(), f.code));
182 }
183 events::record("daemon.command", if result.is_ok() { "ok" } else { "error" }, started.elapsed().as_millis(),
184 json!({ "udid": shared.udid, "command": cmd, "error": result.as_ref().err().map(|f| f.error_json()) }));
185 let reply = envelope(result, started);
186 session.close_input_if_unheld().await;
187 session.sweep().await;
188 reply
189 }
190 };
191 *shared.last_request.lock().unwrap() = Instant::now();
192 write.write_all(format!("{reply}\n").as_bytes()).await?;
193 write.shutdown().await.ok();
194 Ok(())
195}
196
197fn keep_library_warnings() {
203 events::init_tracing();
204}
205
206pub async fn run(udid: String) -> Result<()> {
207 keep_library_warnings();
208 paths::ensure_private_dir(&paths::state_dir())?;
209 if ipc::connect(&udid).await.is_ok() {
210 bail!("a daemon for {udid} is already running");
211 }
212 let mut listener = ipc::Listener::bind(&udid)?;
213 std::fs::write(paths::daemon_pid(&udid), std::process::id().to_string())?;
215
216 let config = Config::load()?;
217 let idle_exit = Duration::from_secs(config.daemon.idle_exit_secs.max(30));
218 let shared = Arc::new(Shared {
219 session: Mutex::new(Session::new(udid.clone(), config)),
220 last_request: StdMutex::new(Instant::now()),
221 build: build_stamp(),
222 udid: udid.clone(),
223 });
224 log(&format!("daemon for {udid} listening, build {}", shared.build));
225
226 let local = tokio::task::LocalSet::new();
229 local
230 .run_until(async move {
231 let keeper = shared.clone();
233 tokio::task::spawn_local(async move {
234 loop {
235 tokio::time::sleep(Duration::from_secs(5)).await;
236 let idle = keeper.last_request.lock().unwrap().elapsed();
237 if let Ok(mut session) = keeper.session.try_lock() {
238 session.sweep().await;
239 session.close_idle_input().await;
240 if idle > idle_exit {
241 log("idle, exiting");
242 session.shutdown().await;
243 ipc::cleanup(&keeper.udid);
244 let _ = std::fs::remove_file(paths::daemon_pid(&keeper.udid));
245 std::process::exit(0);
246 }
247 }
248 }
249 });
250
251 loop {
252 let stream = listener.accept().await?;
253 let shared = shared.clone();
254 tokio::task::spawn_local(async move {
255 if let Err(e) = handle(stream, shared).await {
256 log(&format!("connection error: {e:#}"));
257 }
258 });
259 }
260 })
261 .await
262}