Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

设备层:HID 会话归隧道所有、所有调用加时限;spike 并入 iphone-control debug

Derrors3686b34f115a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 146add2..824cdf2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -19,7 +19,7 @@ jobs:
- uses: Swatinem/rust-cache@v2
# vendor/ 是上游代码,不格式化;只检查本仓库的包
- name: fmt
- run: for p in ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp iphone-control ictl-spike; do cargo fmt -p $p -- --check; done
+ run: for p in ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp iphone-control; do cargo fmt -p $p -- --check; done
- run: cargo clippy --workspace --all-targets --locked -- -D warnings
- run: cargo test --workspace --locked
diff --git a/Cargo.lock b/Cargo.lock
index cbd11f8..276f858 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2041,18 +2041,6 @@ dependencies = [
"zip 8.6.0",
]
-[[package]]
-name = "ictl-spike"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "clap",
- "ictl-device",
- "ictl-wda",
- "tokio",
- "tracing-subscriber",
-]
-
[[package]]
name = "ictl-unlock"
version = "0.1.0"
@@ -2286,6 +2274,7 @@ dependencies = [
"ictl-device",
"ictl-mcp",
"ictl-sign",
+ "ictl-wda",
"rustls",
"serde_json",
"tokio",
diff --git a/Cargo.toml b/Cargo.toml
index dd1e199..0a82b4d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,7 +8,6 @@ members = [
"crates/ictl-daemon",
"crates/ictl-mcp",
"apps/iphone-control",
- "spike",
]
# vendor/ 下是 Impactor 的组件(MPL-2.0 / MIT),作为路径依赖使用,但不算本 workspace 成员:
# 不对它们跑 clippy/test,也不把它们的 lint 当成本项目的问题。
diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.toml
index 7c294a8..8a2c7b9 100644
--- a/apps/iphone-control/Cargo.toml
+++ b/apps/iphone-control/Cargo.toml
@@ -12,6 +12,7 @@ ictl-daemon.workspace = true
ictl-device.workspace = true
ictl-mcp.workspace = true
ictl-sign.workspace = true
+ictl-wda.workspace = true
clap.workspace = true
tokio.workspace = true
anyhow.workspace = true
diff --git a/spike/src/main.rs b/apps/iphone-control/src/debug.rs
similarity index 79%
rename from spike/src/main.rs
rename to apps/iphone-control/src/debug.rs
index 14ffc46..b593681 100644
--- a/spike/src/main.rs
+++ b/apps/iphone-control/src/debug.rs
@@ -1,16 +1,15 @@
-//! 第 0 步真机验证(docs/spike-plan.md)。每个子命令验证一项,可独立重跑,结果记到 spike/RESULTS.md。
-//! 运行前须停掉 toolkit 容器;`wda` 会中断 toolkit 的 WDA,`ddi --force-uninstall` 会卸载手机上的开发者镜像,都须先征得用户同意。
+//! `iphone-control debug …`:真机诊断(原第 0 步 spike,结果见 docs/spike-results.md)。直接调用设备层和 WDA 客户端,
+//! 不经守护进程。`wda`、`e2e` 会启动 XCTest、`hid` 会开屏幕媒体流,和守护进程同时跑会互相干扰:
+//! 先停掉守护进程(例如在另一个只跑 usbmuxd 的容器里运行)。
use std::path::PathBuf;
use std::time::{Duration, Instant};
-use clap::{Parser, Subcommand};
+use clap::{Args, Subcommand};
use ictl_device::{Button, Device, ScreenSize};
-#[derive(Parser)]
-struct Cli {
- #[arg(long, env = "IPHONE_UDID")]
- udid: Option<String>,
+#[derive(Args)]
+pub struct DebugArgs {
/// 屏幕点尺寸(HID 坐标换算用)
#[arg(long, default_value_t = 430.0)]
width: f64,
@@ -28,10 +27,6 @@ enum Check {
#[arg(long, default_value = ictl_device::ddi::DEFAULT_BASE_URL)]
url: String,
},
- /// 诊断:逐个调用 cryptexd 只读例程(不改设备状态)
- CryptexdProbe,
- /// 诊断:分步挂载开发者镜像(不依赖 copy-installed),挂完用截图服务确认
- DdiSteps { restore_dir: PathBuf },
/// 2. HID:媒体流 + universalhidservice tap,再按 Home(以截图对比为准,调用成功不代表生效)
Hid { x: f64, y: f64 },
/// 3. 截图:screencaptureservice PNG
@@ -143,7 +138,7 @@ async fn e2e_with_wda(
// HID 路线:同样的点击和 Home,以 WDA 的前台 App 判断是否生效
let screen = wda.screen_size().await?;
let t = Instant::now();
- let mut hid = tunnel.hid(screen).await?;
+ let hid = tunnel.hid(screen).await?;
check("打开 HID 会话", t, true, String::new())?;
let r = async {
let t = Instant::now();
@@ -156,21 +151,17 @@ async fn e2e_with_wda(
check("HID Home", t, now == SPRINGBOARD, format!("前台 {now}"))
}
.await;
- hid.close().await;
+ // 停掉屏幕媒体流,否则手机端一直挂着
+ tunnel.close_hid().await;
r
}
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- tracing_subscriber::fmt()
- .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
- .init();
- let cli = Cli::parse();
- let device = Device::find(cli.udid.as_deref()).await?;
+pub async fn run(udid: Option<&str>, args: DebugArgs) -> anyhow::Result<()> {
+ let device = Device::find(udid).await?;
let info = device.info().await?;
println!("手机 {} iOS {}", info.product_type, info.product_version);
- let screen = ScreenSize { width: cli.width, height: cli.height };
- match cli.check {
+ let screen = ScreenSize { width: args.width, height: args.height };
+ match args.check {
Check::Ddi { restore_dir, url } => {
let mut t = device.open_tunnel().await?;
match t.ddi_mounted().await? {
@@ -185,34 +176,19 @@ async fn main() -> anyhow::Result<()> {
let t = device.open_tunnel().await?;
println!("universalhidservice: {}", t.has_service("com.apple.coredevice.hid.universalhidservice"));
}
- Check::CryptexdProbe => {
- let mut t = device.open_tunnel().await?;
- for (routine, r) in t.probe_cryptexd(Duration::from_secs(20)).await {
- println!("{routine}: {r}");
- }
- }
- Check::DdiSteps { restore_dir } => {
- let mut t = device.open_tunnel().await?;
- let t0 = Instant::now();
- t.mount_ddi_steps(&restore_dir, Duration::from_secs(120)).await?;
- println!("挂载流程结束,总耗时 {:.1}s;用截图服务确认镜像是否生效", t0.elapsed().as_secs_f64());
- let mut t = device.open_tunnel().await?;
- println!(
- "screenshot: {}",
- match t.screenshot_png().await {
- Ok(p) => format!("成功 {} 字节", p.len()),
- Err(e) => format!("失败 {e}"),
- }
- );
- }
Check::Hid { x, y } => {
let mut t = device.open_tunnel().await?;
- let mut hid = t.hid(screen).await?;
- hid.tap(x, y).await?;
- println!("已点 ({x},{y}),3 秒后按 Home");
- tokio::time::sleep(Duration::from_secs(3)).await;
- hid.press(Button::Home).await?;
- hid.close().await;
+ let r = async {
+ let hid = t.hid(screen).await?;
+ hid.tap(x, y).await?;
+ println!("已点 ({x},{y}),3 秒后按 Home");
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ hid.press(Button::Home).await
+ }
+ .await;
+ // 停掉屏幕媒体流,否则手机端一直挂着
+ t.close().await;
+ r?;
println!("完成:请以截图/肉眼确认是否真的生效");
}
Check::Screenshot { out } => {
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index 3775044..9003198 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -11,6 +11,8 @@ use anyhow::{Context, bail};
use clap::{Parser, Subcommand};
use ictl_daemon::protocol::{self, Request, Response};
+mod debug;
+
#[derive(Parser)]
#[command(name = "iphone-control", version, about = "在 Linux 上控制 iPhone,并提供 MCP 工具")]
struct Cli {
@@ -65,6 +67,9 @@ enum Command {
#[arg(long, default_value_t = 8100)]
port: u16,
},
+ /// 真机诊断(原第 0 步 spike)。`wda`/`e2e`/`hid` 会和守护进程抢 XCTest、HID,先停掉守护进程
+ #[command(hide = true)]
+ Debug(debug::DebugArgs),
/// 按已配置的渠道发测试通知:每类事件各一条(标题带「[测试]」),或只发指定的一类
NotifyTest {
/// resign / session / pin / pin-recovered / unlock / offline / online;不给就全发
@@ -111,6 +116,7 @@ async fn main() -> anyhow::Result<()> {
Command::Passcode { action } => passcode(&cli.data_dir, action),
Command::UnlockReset => print_text(&cli.socket, Request::UnlockReset).await,
Command::WdaBridge { port } => wda_bridge(port).await,
+ Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,
Command::NotifyTest { event } => notify_test(&cli.data_dir, event.as_deref()).await,
}
}
@@ -148,6 +154,11 @@ async fn notify_test(data_dir: &Path, only: Option<&str>) -> anyhow::Result<()>
Ok(())
}
+/// 读环境变量,去掉首尾空白,空值当作没设(.env 里常留着 `KEY=`)
+fn env_nonempty(key: &str) -> Option<String> {
+ std::env::var(key).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())
+}
+
async fn ask(socket: &Path, req: Request) -> anyhow::Result<Response> {
protocol::call(socket, &req).await.with_context(|| {
format!("连不上守护进程({}):先启动 iphone-control daemon(容器里是入口进程)", socket.display())
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index c7fddab..ce0dfa6 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -83,7 +83,6 @@ struct Inner {
device: Option<Device>,
info: Option<DeviceInfo>,
tunnel: Option<Tunnel>,
- hid: Option<HidSession>,
runner: Option<WdaRunner>,
wda: Option<WdaClient<DeviceTransport>>,
wda_misses: Misses,
@@ -107,11 +106,18 @@ pub struct Daemon {
inner: Mutex<Inner>,
}
-/// 先停 HID 会话的屏幕媒体流再丢掉(要在隧道断开之前)。直接丢的话手机一直以为「配对的电脑」在看屏幕:
-/// 灵动岛常驻图标、不会自动锁屏,本进程退出后也不消失(iOS 27 真机,要拔插数据线才清掉)
+/// 停掉 HID 会话(屏幕媒体流),隧道保留。媒体流不停的话手机一直以为「配对的电脑」在看屏幕:
+/// 灵动岛常驻图标、不会自动锁屏,本进程退出、拔插数据线都清不掉(iOS 27 真机)
async fn close_hid(g: &mut Inner) {
- if let Some(h) = g.hid.take() {
- let _ = tokio::time::timeout(Duration::from_secs(3), h.close()).await;
+ if let Some(t) = g.tunnel.as_mut() {
+ t.close_hid().await;
+ }
+}
+
+/// 丢掉隧道。一律走这里:先停 HID 媒体流再断(见 [`close_hid`])
+async fn drop_tunnel(g: &mut Inner) {
+ if let Some(t) = g.tunnel.take() {
+ t.close().await;
}
}
@@ -130,7 +136,6 @@ impl Daemon {
device: None,
info: None,
tunnel: None,
- hid: None,
runner: None,
wda: None,
wda_misses: Misses::default(),
@@ -211,8 +216,7 @@ impl Daemon {
r.stop();
}
g.wda = None;
- close_hid(g).await;
- g.tunnel = None;
+ drop_tunnel(g).await;
g.wda_misses.reset();
}
@@ -228,7 +232,7 @@ impl Daemon {
let g = &mut *g;
self.ensure_usbmuxd(g, false).await;
- if g.hid.is_some() && g.hid_used.is_none_or(|t| t.elapsed() >= HID_IDLE) {
+ if g.tunnel.as_ref().is_some_and(Tunnel::hid_open) && g.hid_used.is_none_or(|t| t.elapsed() >= HID_IDLE) {
close_hid(g).await;
tracing::info!("HID 会话空闲,已关闭(停止屏幕媒体流)");
}
@@ -385,11 +389,11 @@ impl Daemon {
Ok(Some(v)) => self.log.log(&format!("开发者镜像已挂载 {v}")),
Ok(None) => {}
Err(DeviceError::PasswordProtected) => {
- g.tunnel = None;
+ drop_tunnel(g).await;
return self.set_state(g, DeviceState::NeedsUnlock);
}
Err(e) => {
- g.tunnel = None;
+ drop_tunnel(g).await;
g.backoff.failed(Instant::now());
return self.set_state(g, DeviceState::WdaStarting { last_error: Some(format!("开发者镜像:{e}")) });
}
@@ -579,19 +583,15 @@ impl Daemon {
/// HID 会话(WDA 不可用时的后备路线)。出错时丢掉会话和隧道,下次重建
async fn hid<'a>(&self, g: &'a mut Inner) -> Result<&'a mut HidSession, String> {
- if g.hid.is_none() {
- let screen = self.screen(g).await?;
- let device = g.device.clone().ok_or("手机未连接")?;
- let t = self.ensure_tunnel(g, &device).await.map_err(|e| format!("HID 后备路线不可用:{e}"))?;
- match t.hid(screen).await {
- Ok(h) => g.hid = Some(h),
- Err(e) => {
- g.tunnel = None;
- return Err(format!("HID 后备路线不可用:{e}"));
- }
- }
+ let screen = self.screen(g).await?;
+ let device = g.device.clone().ok_or("手机未连接")?;
+ let t = self.ensure_tunnel(g, &device).await.map_err(|e| format!("HID 后备路线不可用:{e}"))?;
+ if let Err(e) = t.hid(screen).await {
+ drop_tunnel(g).await;
+ return Err(format!("HID 后备路线不可用:{e}"));
}
- Ok(g.hid.as_mut().expect("刚建好"))
+ // 第二次调用直接返回已开好的会话(这样写是为了绕开借用检查对条件返回的限制)
+ g.tunnel.as_mut().expect("刚建好").hid(screen).await.map_err(|e| e.to_string())
}
async fn hid_do<F>(&self, g: &mut Inner, f: F) -> Result<(), String>
@@ -603,10 +603,14 @@ impl Daemon {
{
let r = f(self.hid(g).await?).await;
g.hid_used = Some(Instant::now());
- if let Err(e) = r {
- close_hid(g).await;
- g.tunnel = None;
- return Err(format!("HID 命令失败: {e}"));
+ match r {
+ // 参数问题(例如不能输入的字符),连接没坏,不用重建
+ Err(e @ DeviceError::InvalidInput(_)) => return Err(e.to_string()),
+ Err(e) => {
+ drop_tunnel(g).await;
+ return Err(format!("HID 命令失败: {e}"));
+ }
+ Ok(()) => {}
}
Ok(())
}
@@ -665,8 +669,7 @@ impl Daemon {
match t.screenshot_png().await {
Ok(p) => (p, "HID"),
Err(e) => {
- close_hid(g).await;
- g.tunnel = None;
+ drop_tunnel(g).await;
return Err(format!("HID 命令失败: {e}"));
}
}
diff --git a/crates/ictl-device/src/ddi.rs b/crates/ictl-device/src/ddi.rs
index 451b7f0..02a31cb 100644
--- a/crates/ictl-device/src/ddi.rs
+++ b/crates/ictl-device/src/ddi.rs
@@ -15,15 +15,34 @@ pub const DEFAULT_BASE_URL: &str =
pub const FILES: [&str; 5] =
["BuildManifest.plist", "Image.dmg", "Image.dmg.trustcache", "Image.dmg.cryptex_info", "Image.dmg.root_hash"];
+/// 记录缓存来自哪个下载地址:换了地址就整套重新下载,免得新旧文件混在一起
+const SOURCE_STAMP: &str = ".source";
+
/// 缓存是否完整
pub fn cache_complete(dir: &Path) -> bool {
FILES.iter().all(|f| dir.join(f).is_file())
}
+/// 删掉缓存(挂载反复失败时调用,下次重新下载)
+pub fn invalidate(dir: &Path) {
+ for f in FILES.iter().chain([&SOURCE_STAMP]) {
+ let _ = std::fs::remove_file(dir.join(f));
+ }
+}
+
/// 确保 `dir` 里有完整的 DDI,缺的从 `base_url` 下载;返回该目录。
/// 下载先写临时文件再改名,中途失败不会留下半个文件。
pub async fn ensure_cache(dir: &Path, base_url: &str) -> Result<PathBuf> {
+ let stamp = std::fs::read_to_string(dir.join(SOURCE_STAMP)).ok();
+ if stamp.as_deref().is_some_and(|s| s.trim() != base_url) {
+ tracing::info!("开发者镜像下载地址变了,重新下载");
+ invalidate(dir);
+ }
if cache_complete(dir) {
+ if stamp.is_none() {
+ // 早期版本下载的缓存没有记录来源:认作当前地址
+ let _ = std::fs::write(dir.join(SOURCE_STAMP), base_url);
+ }
return Ok(dir.to_owned());
}
tokio::fs::create_dir_all(dir).await?;
@@ -49,6 +68,7 @@ pub async fn ensure_cache(dir: &Path, base_url: &str) -> Result<PathBuf> {
tokio::fs::write(&tmp, &bytes).await?;
tokio::fs::rename(&tmp, &dest).await?;
}
+ tokio::fs::write(dir.join(SOURCE_STAMP), base_url).await?;
Ok(dir.to_owned())
}
@@ -66,6 +86,8 @@ mod tests {
assert!(!cache_complete(&dir));
std::fs::write(dir.join(FILES[4]), b"x").unwrap();
assert!(cache_complete(&dir));
+ invalidate(&dir);
+ assert!(!cache_complete(&dir));
std::fs::remove_dir_all(&dir).unwrap();
}
}
diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rs
index 728c9d0..5f56fa8 100644
--- a/crates/ictl-device/src/hid.rs
+++ b/crates/ictl-device/src/hid.rs
@@ -13,7 +13,7 @@ use idevice::{
tcp::handle::AdapterHandle,
};
-use crate::{DeviceError, Result, ScreenSize, media::ScreenMediaStream};
+use crate::{DeviceError, Result, ScreenSize, limit, media::ScreenMediaStream};
pub const HID_MAX: f64 = 65535.0;
@@ -116,16 +116,27 @@ impl HidSession {
screen: ScreenSize,
) -> Result<Self> {
let stream = crate::media::start(adapter, handshake, 1).await?;
- // backboardd 要一点时间把 HID 设备和刚授权的媒体流对上
- tokio::time::sleep(Duration::from_millis(300)).await;
- let touch = UniversalHidServiceClient::connect_rsd(adapter, handshake).await?;
- let indigo = IndigoHidClient::connect_rsd(adapter, handshake).await?;
- Ok(Self { screen, stream: Some(stream), touch, indigo })
+ let clients = async {
+ // backboardd 要一点时间把 HID 设备和刚授权的媒体流对上
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let touch = UniversalHidServiceClient::connect_rsd(adapter, handshake).await?;
+ let indigo = IndigoHidClient::connect_rsd(adapter, handshake).await?;
+ Ok::<_, DeviceError>((touch, indigo))
+ }
+ .await;
+ match clients {
+ Ok((touch, indigo)) => Ok(Self { screen, stream: Some(stream), touch, indigo }),
+ Err(e) => {
+ // 媒体流已经起来了:不停掉的话手机端会一直挂着它
+ stream.stop().await;
+ Err(e)
+ }
+ }
}
pub async fn tap(&mut self, x: f64, y: f64) -> Result<()> {
let (hx, hy) = to_hid(x, y, self.screen);
- Ok(self.touch.tap(hx, hy).await?)
+ limit("HID 点击", Duration::from_secs(10), async { Ok(self.touch.tap(hx, hy).await?) }).await
}
/// 拖动:按时长换算采样数(每 20ms 一个点,至少 10 个),太快会被识别成点击
@@ -133,22 +144,31 @@ impl HidSession {
let (x1, y1) = to_hid(from.0, from.1, self.screen);
let (x2, y2) = to_hid(to.0, to.1, self.screen);
let steps = ((seconds * 1000.0 / 20.0).round() as u32).max(10);
- Ok(self.touch.drag(x1, y1, x2, y2, steps, 20).await?)
+ let d = Duration::from_secs_f64(seconds.max(0.0) + 10.0);
+ limit("HID 拖动", d, async { Ok(self.touch.drag(x1, y1, x2, y2, steps, 20).await?) }).await
}
pub async fn press(&mut self, button: Button) -> Result<()> {
let (page, code, hold) = button.usage();
- self.indigo.send_button(page, code, ButtonState::Down).await?;
- tokio::time::sleep(Duration::from_millis(hold)).await;
- Ok(self.indigo.send_button(page, code, ButtonState::Up).await?)
+ limit("HID 按键", Duration::from_secs(10), async {
+ self.indigo.send_button(page, code, ButtonState::Down).await?;
+ tokio::time::sleep(Duration::from_millis(hold)).await;
+ Ok(self.indigo.send_button(page, code, ButtonState::Up).await?)
+ })
+ .await
}
/// 只能输入美式键盘直接按得出的 ASCII;有不支持的字符时一个都不输
pub async fn type_ascii(&mut self, text: &str) -> Result<()> {
let keys: Vec<_> = text
.chars()
- .map(|c| ascii_to_usage(c).ok_or_else(|| DeviceError::Idevice(format!("HID 不能输入字符 {c:?}"))))
+ .map(|c| ascii_to_usage(c).ok_or_else(|| DeviceError::InvalidInput(format!("HID 不能输入字符 {c:?}"))))
.collect::<Result<_>>()?;
+ let d = Duration::from_secs(10) + Duration::from_millis(50 * keys.len() as u64);
+ limit("HID 输入", d, self.send_keys(keys)).await
+ }
+
+ async fn send_keys(&mut self, keys: Vec<(u64, bool)>) -> Result<()> {
for (usage, shift) in keys {
if shift {
self.indigo.send_keyboard(KEY_LEFT_SHIFT, ButtonState::Down).await?;
@@ -163,7 +183,7 @@ impl HidSession {
Ok(())
}
- /// 停止媒体流。不调用也行,但设备那边的流要等超时才结束
+ /// 停止屏幕媒体流。必须调用:直接丢掉的话手机端一直挂着这个会话(见 [`crate::Tunnel`])
pub async fn close(mut self) {
if let Some(s) = self.stream.take() {
s.stop().await;
@@ -171,6 +191,16 @@ impl HidSession {
}
}
+impl Drop for HidSession {
+ fn drop(&mut self) {
+ if self.stream.is_some() {
+ tracing::warn!(
+ "HID 会话没有 close() 就被丢掉,手机端的屏幕媒体流会一直挂着(不自动锁屏),需拔插或重开一次 HID 清掉"
+ );
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rs
index f2b38ed..1f8c468 100644
--- a/crates/ictl-device/src/lib.rs
+++ b/crates/ictl-device/src/lib.rs
@@ -15,8 +15,10 @@ pub mod ddi;
pub mod hid;
mod media;
+use std::future::Future;
use std::path::Path;
use std::sync::Arc;
+use std::time::Duration;
use idevice::{
IdeviceError, IdeviceService, RsdService,
@@ -53,14 +55,23 @@ pub enum DeviceError {
/// 锁屏且自开机以来从未解锁(BFU),或锁屏时建隧道,都会报这个
#[error("手机锁屏(PasswordProtected),需要解锁")]
PasswordProtected,
- #[error("App 未安装:{0}")]
- AppNotInstalled(String),
#[error("下载开发者镜像失败:{0}")]
Download(String),
#[error("{0}")]
Io(#[from] std::io::Error),
#[error("idevice:{0}")]
Idevice(String),
+ /// 手机上的服务没在限定时间内应答。调用方应丢掉隧道重建
+ #[error("超时:{0}")]
+ Timeout(String),
+ /// 调用方给的参数不合法(例如 HID 不能输入的字符)。与连接无关,不需要重建会话
+ #[error("{0}")]
+ InvalidInput(String),
+}
+
+/// 给对手机的一次调用加时限:卡住的服务不能把调用方(守护进程持锁时)一起卡死
+pub(crate) async fn limit<T>(what: &str, d: Duration, f: impl Future<Output = Result<T>>) -> Result<T> {
+ tokio::time::timeout(d, f).await.map_err(|_| DeviceError::Timeout(format!("{what}({} 秒)", d.as_secs())))?
}
impl From<IdeviceError> for DeviceError {
@@ -166,10 +177,16 @@ impl Device {
self.provider.clone()
}
- /// usbmuxd 里有没有这台手机的配对记录
+ /// usbmuxd 里有没有这台手机的配对记录。只有「没有记录」算 false;连不上 usbmuxd 等错误照常返回,
+ /// 免得 usbmuxd 抖一下就让状态变成「请在手机上点信任」
pub async fn paired(&self) -> Result<bool> {
let mut mux = self.provider.addr.connect(0).await?;
- Ok(mux.get_pair_record(&self.udid).await.is_ok())
+ match mux.get_pair_record(&self.udid).await {
+ Ok(_) => Ok(true),
+ // 没有记录时 usbmuxd 的应答里没有 PairRecordData;记录损坏同样需要重新配对
+ Err(IdeviceError::UnexpectedResponse(_)) => Ok(false),
+ Err(e) => Err(e.into()),
+ }
}
/// 发起配对:手机上弹「信任此电脑」。用户还没点时返回 [`DeviceError::PairingPending`],调用方应轮询重试。
@@ -189,12 +206,13 @@ impl Device {
pub async fn info(&self) -> Result<DeviceInfo> {
let mut lockdown = LockdownClient::connect(&*self.provider).await?;
let mut get = async |key: &str| -> String {
- lockdown
- .get_value(Some(key), None)
- .await
- .ok()
- .and_then(|v| v.as_string().map(str::to_owned))
- .unwrap_or_default()
+ match lockdown.get_value(Some(key), None).await {
+ Ok(v) => v.as_string().map(str::to_owned).unwrap_or_default(),
+ Err(e) => {
+ tracing::warn!("读设备信息 {key} 失败:{e}");
+ String::new()
+ }
+ }
};
Ok(DeviceInfo {
udid: self.udid.clone(),
@@ -215,12 +233,15 @@ impl Device {
/// 建立 CoreDeviceProxy 用户态隧道并完成 RSD 握手。锁屏时报 [`DeviceError::PasswordProtected`]。
pub async fn open_tunnel(&self) -> Result<Tunnel> {
- let proxy = CoreDeviceProxy::connect(&*self.provider).await?;
- let rsd_port = proxy.tunnel_info().server_rsd_port;
- let mut adapter = proxy.create_software_tunnel()?.to_async_handle();
- let stream = adapter.connect(rsd_port).await?;
- let handshake = RsdHandshake::new(stream).await?;
- Ok(Tunnel { adapter, handshake })
+ limit("建隧道", Duration::from_secs(30), async {
+ let proxy = CoreDeviceProxy::connect(&*self.provider).await?;
+ let rsd_port = proxy.tunnel_info().server_rsd_port;
+ let mut adapter = proxy.create_software_tunnel()?.to_async_handle();
+ let stream = adapter.connect(rsd_port).await?;
+ let handshake = RsdHandshake::new(stream).await?;
+ Ok(Tunnel { adapter, handshake, hid: None })
+ })
+ .await
}
/// 已安装的 App。`include_system` 为 false 只列用户 App,为 true 只列系统 App(与 toolkit 一致)。
@@ -230,7 +251,7 @@ impl Device {
Ok(apps::parse_apps(proxy.get_apps(Some(kind), None).await?))
}
- /// 经 usbmuxd 直连手机上的 TCP 端口(WDA bridge 用)
+ /// 经 usbmuxd 直连手机上的 TCP 端口(`iphone-control wda-bridge` 用)
pub async fn connect_port(&self, port: u16) -> Result<Box<dyn idevice::ReadWrite>> {
let dev = self.provider.connect(port).await?;
dev.get_socket().ok_or_else(|| DeviceError::Idevice("连接没有套接字".into()))
@@ -244,9 +265,14 @@ impl Device {
}
/// 一条活着的隧道。HID、截图、cryptexd 都经它访问 RSD 服务;丢掉它隧道就断了。
+///
+/// HID 会话归隧道所有:它持有屏幕媒体流,必须在隧道断开之前停掉,否则手机端一直挂着这个会话
+/// (灵动岛「配对的电脑」图标常驻、不会自动锁屏,进程退出和拔插数据线都清不掉)。
+/// 所以不要直接丢掉 `Tunnel`,用 [`Tunnel::close`]。
pub struct Tunnel {
adapter: AdapterHandle,
handshake: RsdHandshake,
+ hid: Option<HidSession>,
}
impl Tunnel {
@@ -257,110 +283,55 @@ impl Tunnel {
/// 已挂载的开发者镜像版本,未挂载返回 None
pub async fn ddi_mounted(&mut self) -> Result<Option<String>> {
- Ok(installed_ddi(&mut self.adapter, &mut self.handshake).await?.map(|c| c.version))
+ limit("查询开发者镜像", Duration::from_secs(20), async {
+ Ok(installed_ddi(&mut self.adapter, &mut self.handshake).await?.map(|c| c.version))
+ })
+ .await
}
- /// 诊断用:逐个调用 cryptexd 的只读例程,每个限时,返回 (例程, 结果) 列表
- pub async fn probe_cryptexd(&mut self, timeout: std::time::Duration) -> Vec<(&'static str, String)> {
- use idevice::{RsdService as _, cryptexd::CryptexdClient};
- let mut out = Vec::new();
- for routine in ["read-personalization-id", "copy-installed"] {
- let fut = async {
- let c: CryptexdClient<Box<dyn idevice::ReadWrite>> =
- CryptexdClient::connect_rsd(&mut self.adapter, &mut self.handshake).await?;
- c.invoke(routine, Default::default()).await
- };
- let r = match tokio::time::timeout(timeout, fut).await {
- Err(_) => "超时".to_owned(),
- Ok(Err(e)) => format!("错误:{e}"),
- Ok(Ok(v)) => format!("成功:{}", format!("{v:?}").chars().take(160).collect::<String>()),
- };
- out.push((routine, r));
- }
- out
+ /// 个性化并安装开发者镜像。`restore_dir` 见 [`ddi::ensure_cache`]
+ pub async fn mount_ddi(&mut self, restore_dir: &Path) -> Result<String> {
+ let assets = Cryptex1Assets::load(restore_dir).await?;
+ // 含 TSS 联网签票
+ limit("挂载开发者镜像", Duration::from_secs(180), async {
+ Ok(install_ddi(&mut self.adapter, &mut self.handshake, &assets).await?.version)
+ })
+ .await
}
- /// 诊断用:分步挂载开发者镜像(读标识 → 取 nonce → TSS 签票 → install),每步限时并打印耗时。
- /// 不调用 copy-installed,用于排查它挂住的情况(idevice 补丁前在 iOS 27.0.1 上出现过,见 spike/RESULTS.md)
- pub async fn mount_ddi_steps(&mut self, restore_dir: &Path, step_timeout: std::time::Duration) -> Result<()> {
- use idevice::{
- RsdService as _,
- cryptexd::{CryptexInstallRequest, CryptexdClient},
- tss::TSSRequest,
- };
- macro_rules! step {
- ($name:expr, $fut:expr) => {{
- let t0 = std::time::Instant::now();
- let r = tokio::time::timeout(step_timeout, $fut).await;
- let el = t0.elapsed().as_secs_f64();
- match r {
- Err(_) => {
- println!(" {}:超时({el:.1}s)", $name);
- return Err(DeviceError::Io(std::io::Error::other(format!("{} 超时", $name))));
- }
- Ok(Err(e)) => {
- println!(" {}:失败({el:.1}s){e}", $name);
- return Err(e.into());
- }
- Ok(Ok(v)) => {
- println!(" {}:成功({el:.1}s)", $name);
- v
- }
- }
- }};
+ pub async fn screenshot_png(&mut self) -> Result<Vec<u8>> {
+ limit("截图", Duration::from_secs(30), async {
+ let mut client = ScreenCaptureServiceClient::connect_rsd(&mut self.adapter, &mut self.handshake).await?;
+ Ok(client.take_screenshot(None, ImageFormat::Png).await?)
+ })
+ .await
+ }
+
+ /// HID 会话;没有就开一个:先启动显示媒体流(HID 的授权闸门),再连 universalhidservice 和 indigo
+ pub async fn hid(&mut self, screen: ScreenSize) -> Result<&mut HidSession> {
+ if self.hid.is_none() {
+ let h = limit("开启 HID 会话", Duration::from_secs(20), async {
+ HidSession::open(&mut self.adapter, &mut self.handshake, screen).await
+ })
+ .await?;
+ self.hid = Some(h);
}
- let assets = Cryptex1Assets::load(restore_dir).await?;
- let (a, h) = (&mut self.adapter, &mut self.handshake);
- let chip = step!("读个性化标识", async {
- let c: CryptexdClient<Box<dyn idevice::ReadWrite>> = CryptexdClient::connect_rsd(a, h).await?;
- c.read_personalization_identifiers().await
- });
- let domain = assets.nonce_domain()?;
- let (a, h) = (&mut self.adapter, &mut self.handshake);
- let nonce = step!("取 cryptex nonce", async {
- let c: CryptexdClient<Box<dyn idevice::ReadWrite>> = CryptexdClient::connect_rsd(a, h).await?;
- c.cryptex_nonce(domain).await
- });
- let mut req = TSSRequest::new();
- req.add_cryptex1_tags(&assets.build_identity, &chip, &nonce)?;
- let resp = step!("TSS 签票", req.send());
- let resp = resp.into_dictionary().ok_or_else(|| DeviceError::Io(std::io::Error::other("TSS 响应不是字典")))?;
- let key = if resp.contains_key("Cryptex1,Ticket") { "Cryptex1,Ticket" } else { "ApImg4Ticket" };
- println!(" 票据字段:{key}");
- let im4m = resp
- .get(key)
- .and_then(|v| v.as_data())
- .ok_or_else(|| DeviceError::Io(std::io::Error::other("TSS 响应里没有票据")))?
- .to_vec();
- let request = CryptexInstallRequest::new(
- assets.image.clone(),
- assets.trustcache.clone(),
- im4m,
- assets.info.clone(),
- assets.volumehash.clone(),
- assets.cryptex1_properties()?,
- );
- let (a, h) = (&mut self.adapter, &mut self.handshake);
- step!("install", async {
- let c: CryptexdClient<Box<dyn idevice::ReadWrite>> = CryptexdClient::connect_rsd(a, h).await?;
- c.install(request).await
- });
- Ok(())
+ Ok(self.hid.as_mut().expect("刚建好"))
}
- /// 个性化并安装开发者镜像。`restore_dir` 见 [`ddi::ensure_cache`]
- pub async fn mount_ddi(&mut self, restore_dir: &Path) -> Result<String> {
- let assets = Cryptex1Assets::load(restore_dir).await?;
- Ok(install_ddi(&mut self.adapter, &mut self.handshake, &assets).await?.version)
+ pub fn hid_open(&self) -> bool {
+ self.hid.is_some()
}
- pub async fn screenshot_png(&mut self) -> Result<Vec<u8>> {
- let mut client = ScreenCaptureServiceClient::connect_rsd(&mut self.adapter, &mut self.handshake).await?;
- Ok(client.take_screenshot(None, ImageFormat::Png).await?)
+ /// 停掉 HID 会话(含屏幕媒体流),隧道保留
+ pub async fn close_hid(&mut self) {
+ if let Some(h) = self.hid.take() {
+ let _ = tokio::time::timeout(Duration::from_secs(3), h.close()).await;
+ }
}
- /// 开启 HID 会话:先启动显示媒体流(HID 的授权闸门),再连 universalhidservice 和 indigo
- pub async fn hid(&mut self, screen: ScreenSize) -> Result<HidSession> {
- HidSession::open(&mut self.adapter, &mut self.handshake, screen).await
+ /// 关掉隧道:先停 HID 的屏幕媒体流
+ pub async fn close(mut self) {
+ self.close_hid().await;
}
}
diff --git a/crates/ictl-device/src/media.rs b/crates/ictl-device/src/media.rs
index 3cdd2f5..1659c79 100644
--- a/crates/ictl-device/src/media.rs
+++ b/crates/ictl-device/src/media.rs
@@ -22,7 +22,7 @@ const CLIENT_SUPPORTED_FEATURES: u64 = 140;
/// 活着的媒体流。两个 UDP 套接字必须一直绑定,丢掉就会解绑端口。
pub(crate) struct ScreenMediaStream {
- pub client: DisplayServiceClient<Box<dyn ReadWrite>>,
+ client: DisplayServiceClient<Box<dyn ReadWrite>>,
_audio_udp: UdpSocketHandle,
_video_udp: UdpSocketHandle,
}
@@ -88,7 +88,11 @@ pub(crate) async fn start(
display_id,
session,
);
- client.start_media_stream(params).await.map_err(|e| fail("启动视频流", &e))?;
+ if let Err(e) = client.start_media_stream(params).await {
+ // 音频流已经起来了,要停掉:stopAll 连同会话一起结束,否则手机端一直挂着
+ let _ = client.stop_media_stream().await;
+ return Err(fail("启动视频流", &e));
+ }
Ok(ScreenMediaStream { client, _audio_udp: audio_udp, _video_udp: video_udp })
}
diff --git a/spike/RESULTS.md b/docs/spike-results.md
similarity index 100%
rename from spike/RESULTS.md
rename to docs/spike-results.md
diff --git a/spike/Cargo.toml b/spike/Cargo.toml
deleted file mode 100644
index 9b2aeb0..0000000
--- a/spike/Cargo.toml
+++ /dev/null
@@ -1,16 +0,0 @@
-[package]
-name = "ictl-spike"
-version.workspace = true
-edition.workspace = true
-rust-version.workspace = true
-license.workspace = true
-publish.workspace = true
-description = "第 0 步真机验证程序(直接调用 ictl-device / ictl-wda,与守护进程同一套代码)"
-
-[dependencies]
-ictl-device.workspace = true
-ictl-wda.workspace = true
-clap.workspace = true
-tokio.workspace = true
-anyhow.workspace = true
-tracing-subscriber.workspace = true