1use std::{
5 process::Stdio,
6 time::{Duration, Instant},
7};
8
9use serde_json::{Value, json};
10use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
11
12use crate::{
13 config::Config,
14 daemon::{Request, build_stamp},
15 device::conn,
16 i18n::t,
17 events, ipc, paths,
18 reply::{Fail, envelope},
19};
20
21pub async fn resolve_udid(flag: Option<String>) -> Result<String, Fail> {
24 if let Some(u) = flag.filter(|u| !u.is_empty()) {
25 return Ok(u);
26 }
27 if let Ok(u) = std::env::var("IPH_UDID")
28 && !u.is_empty() {
29 return Ok(u);
30 }
31 let config = Config::load().map_err(|e| Fail::not_sent("config_invalid", format!("{e:#}")))?;
32 if let Some(u) = config.udid.filter(|u| !u.is_empty()) {
33 return Ok(u);
34 }
35 let devices = conn::list()
36 .await
37 .map_err(|e| Fail::not_sent("usbmuxd_unreachable", format!("{e:#}")))?;
38 events::record("device_selection", if devices.len() == 1 { "ok" } else { "error" }, 0,
39 json!({ "devices": devices, "count": devices.len() }));
40 match devices.len() {
41 1 => Ok(devices[0].udid.clone()),
42 0 => Err(Fail::not_sent("no_device", "no iPhone is connected").hint(t(
43 "폰을 USB로 연결하거나 컴퓨터와 같은 Wi-Fi에 두고 화면을 켜 주세요. 처음이라면 `iph setup`을 실행하세요.",
44 "Plug the phone in, or put it on the computer's Wi-Fi and wake it. First time? Run `iph setup`.",
45 ))),
46 n => Err(Fail::not_sent(
47 "multiple_devices",
48 format!("{n} iPhones are connected"),
49 )
50 .hint(t(
51 "`--udid <UDID>`로 하나를 고르거나 ~/.config/iph/config.toml에 `udid = \"…\"`를 적으세요.",
52 "Pick one with `--udid <UDID>` or put `udid = \"…\"` in ~/.config/iph/config.toml.",
53 ))
54 .with("devices", json!(devices))),
55 }
56}
57
58fn spawn_daemon(udid: &str) -> std::io::Result<()> {
59 paths::ensure_private_dir(&paths::state_dir())?;
60 let log = paths::private_file()
61 .create(true)
62 .append(true)
63 .open(paths::daemon_log(udid))?;
64 let mut cmd = std::process::Command::new(std::env::current_exe()?);
65 cmd.arg("daemon")
66 .arg("--udid")
67 .arg(udid)
68 .stdin(Stdio::null())
69 .stdout(log.try_clone()?)
70 .stderr(log);
71 detach(&mut cmd);
72 cmd.spawn().map(|_| ())
73}
74
75#[cfg(unix)]
77fn detach(cmd: &mut std::process::Command) {
78 use std::os::unix::process::CommandExt;
79 unsafe {
81 cmd.pre_exec(|| {
82 libc::setsid();
83 Ok(())
84 });
85 }
86}
87
88#[cfg(windows)]
93fn detach(cmd: &mut std::process::Command) {
94 use std::os::windows::process::CommandExt;
95 use windows_sys::Win32::{
96 Foundation::{HANDLE_FLAG_INHERIT, SetHandleInformation},
97 System::Console::{GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE},
98 };
99 for which in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
100 unsafe {
102 let handle = GetStdHandle(which);
103 if !handle.is_null() {
104 SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
105 }
106 }
107 }
108 const DETACHED_PROCESS: u32 = 0x0000_0008;
109 const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
110 const CREATE_NO_WINDOW: u32 = 0x0800_0000;
111 cmd.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
112}
113
114async fn connect(udid: &str) -> Result<ipc::Stream, String> {
115 if let Ok(s) = ipc::connect(udid).await {
116 return Ok(s);
117 }
118 spawn_daemon(udid).map_err(|e| format!("cannot start the daemon: {e}"))?;
119 let started = Instant::now();
120 while started.elapsed() < Duration::from_secs(8) {
121 if let Ok(s) = ipc::connect(udid).await {
122 return Ok(s);
123 }
124 tokio::time::sleep(Duration::from_millis(40)).await;
125 }
126 Err(format!(
127 "the daemon did not come up; see {}",
128 paths::daemon_log(udid).display()
129 ))
130}
131
132async fn stop(udid: &str) -> Option<Value> {
135 let mut s = ipc::connect(udid).await.ok()?;
136 let req = Request { build: build_stamp(), cmd: "shutdown".into(), args: Value::Null };
137 let _ = s.write_all(format!("{}\n", serde_json::to_string(&req).unwrap()).as_bytes()).await;
138 let mut line = String::new();
139 let patience = crate::daemon::budget("shutdown");
141 if tokio::time::timeout(patience, BufReader::new(&mut s).read_line(&mut line)).await.is_err() {
142 kill_daemon(udid);
143 return Some(json!({ "ok": true, "killed": true }));
144 }
145 let started = Instant::now();
146 while started.elapsed() < Duration::from_secs(5) {
147 if ipc::connect(udid).await.is_err() {
148 break;
149 }
150 tokio::time::sleep(Duration::from_millis(40)).await;
151 }
152 Some(serde_json::from_str(&line).unwrap_or_else(|_| json!({ "ok": true })))
153}
154
155fn kill_daemon(udid: &str) {
157 if let Some(pid) = std::fs::read_to_string(paths::daemon_pid(udid))
158 .ok()
159 .and_then(|s| s.trim().parse::<i32>().ok())
160 .filter(|pid| *pid > 1)
161 {
162 kill_pid(pid);
163 }
164 ipc::cleanup(udid);
165 let _ = std::fs::remove_file(paths::daemon_pid(udid));
166}
167
168pub async fn stop_daemon(udid: &str) -> Option<Value> {
170 stop(udid).await
171}
172
173pub async fn request(udid: &str, cmd: &str, args: Value) -> Value {
175 let started = Instant::now();
176 events::record("request", "started", 0, json!({ "udid": udid, "command": cmd }));
177 let req = Request { build: build_stamp(), cmd: cmd.to_string(), args };
178 let line = format!("{}\n", serde_json::to_string(&req).unwrap());
179 for _ in 0..3 {
180 let mut stream = match connect(udid).await {
181 Ok(s) => s,
182 Err(e) => return envelope(Err(Fail::not_sent("daemon_unreachable", e)), started),
183 };
184 if let Err(e) = stream.write_all(line.as_bytes()).await {
185 return envelope(
186 Err(Fail::not_sent("daemon_unreachable", format!("write: {e}"))),
187 started,
188 );
189 }
190 let mut reply = String::new();
191 let patience = crate::daemon::budget(cmd) + Duration::from_secs(100);
195 let read = tokio::time::timeout(patience, BufReader::new(&mut stream).read_line(&mut reply)).await;
196 let Ok(read) = read else {
197 kill_daemon(udid);
198 return envelope(
199 Err(Fail::unknown(
200 "daemon_timeout",
201 format!("the daemon did not answer within {} s and was stopped", patience.as_secs()),
202 )
203 .hint(t(
204 "입력이 나갔을 수 있습니다. 다시 보내지 말고 `iph read`로 화면을 확인하세요.",
205 "The input may have gone out. Do not resend; check the screen with `iph read`.",
206 ))),
207 started,
208 );
209 };
210 let parsed: Option<Value> = match read {
211 Ok(n) if n > 0 => serde_json::from_str(&reply).ok(),
212 _ => None,
213 };
214 let Some(value) = parsed else {
215 return envelope(
217 Err(Fail::unknown(
218 "daemon_connection_lost",
219 "the daemon closed the connection before answering",
220 )
221 .hint(t(
222 "입력이 나갔을 수 있습니다. 다시 보내지 말고 `iph read`로 화면을 확인하세요.",
223 "The input may have gone out. Do not resend; check the screen with `iph read`.",
224 ))),
225 started,
226 );
227 };
228 if value["error"]["code"] == "daemon_outdated" {
229 stop(udid).await;
231 continue;
232 }
233 events::record("request", if value["ok"] == true { "ok" } else { "error" }, started.elapsed().as_millis(),
234 json!({ "udid": udid, "command": cmd, "outcome": value["outcome"], "error": value["error"] }));
235 return value;
236 }
237 envelope(
238 Err(Fail::not_sent("daemon_unreachable", "the daemon keeps reporting an older build")),
239 started,
240 )
241}
242
243#[cfg(unix)]
244fn kill_pid(pid: i32) {
245 unsafe {
247 libc::kill(pid, libc::SIGKILL);
248 }
249}
250
251#[cfg(windows)]
252fn kill_pid(pid: i32) {
253 let _ = std::process::Command::new("taskkill")
254 .args(["/F", "/PID", &pid.to_string()])
255 .stdout(Stdio::null())
256 .stderr(Stdio::null())
257 .status();
258}