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