Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ What changed in each release, one line per change. Versions follow [Semantic Ver

## [Unreleased]

### Fixes

- WebDriverAgent on the phone now listens on the phone itself only: other devices on the same Wi-Fi can no longer reach its port 8100 (the unauthenticated control API) or 9100 (the picture). After upgrading, a WDA an older version launched in the background is launched again once.

## [0.2.13] - 2026-11-24

### Fixes
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

## [Unreleased]

### 修复

- 手机上的 WebDriverAgent 只在手机本机监听,同一 Wi-Fi 里的其他设备不能再访问它的 8100(没有认证的操作接口)和 9100(画面)端口。升级后,旧版本在后台启动的 WDA 会被重新启动一次。

## [0.2.13] - 2026-11-24

### 修复
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

48 changes: 47 additions & 1 deletion crates/ictl-daemon/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ pub struct Persisted {
/// 占着 8100 端口,新 runner 的 HTTP 服务起不来)。见 [`crate::detached`]
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub detached_wdas: std::collections::BTreeMap<String, u64>,
/// The background WDAs launched listening on the phone's loopback only (`USE_IP`, see
/// `ictl_wda::runner::WDA_BIND_IP`), by UDID. One in [`Self::detached_wdas`] but not here was launched by an older
/// version, listening on every interface (on Wi-Fi anyone on the network could drive the phone): it isn't attached
/// to again but launched anew ([`Self::adoptable_for`]). Older versions don't know this field; a WDA they launch
/// gets a new pid, so it doesn't match here either
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub loopback_wdas: std::collections::BTreeMap<String, u64>,
/// Which way Home and locking work on each device, by UDID ([`Self::ways_for`]). Kept here, not only in memory:
/// after a restart or switching devices the first Home on an iPad mini 5 tried the way that doesn't work there,
/// waited 2 s for the home screen, then pressed again (4.4 s instead of 0.8)
Expand Down Expand Up @@ -168,6 +175,13 @@ impl Persisted {
.or_else(|| self.detached_wda.as_ref().filter(|d| d.udid.eq_ignore_ascii_case(udid)).map(|d| d.pid))
}

/// The background WDA on `udid` that may be attached to again: one this version launched, listening on the
/// phone's loopback only. Any other is launched anew, which ends it
pub fn adoptable_for(&self, udid: &str) -> Option<u64> {
let pid = self.detached_for(udid)?;
self.loopback_wdas.iter().any(|(k, p)| k.eq_ignore_ascii_case(udid) && *p == pid).then_some(pid)
}

/// Every recorded background WDA: (UDID, pid)
pub fn detached_all(&self) -> Vec<(String, u64)> {
let mut all: Vec<_> = self.detached_wdas.iter().map(|(u, p)| (u.clone(), *p)).collect();
Expand Down Expand Up @@ -195,7 +209,12 @@ impl Persisted {
.cloned()
.unwrap_or_else(|| udid.to_owned());
let last = Some(DetachedWda { udid: key.clone(), pid });
let changed = self.detached_wdas.get(&key) != Some(&pid) || self.detached_wda != last;
// this version launches and attaches to loopback-only WDAs alone: whatever is recorded now is one
let others = self.loopback_wdas.len();
self.loopback_wdas.retain(|k, _| !k.eq_ignore_ascii_case(udid) || *k == key);
let loopback_changed =
self.loopback_wdas.len() != others || self.loopback_wdas.insert(key.clone(), pid) != Some(pid);
let changed = loopback_changed || self.detached_wdas.get(&key) != Some(&pid) || self.detached_wda != last;
self.detached_wdas.insert(key, pid);
self.detached_wda = last;
changed
Expand All @@ -206,6 +225,7 @@ impl Persisted {
pub fn forget_detached(&mut self, udid: &str, pid: Option<u64>) -> bool {
let before = (self.detached_wdas.len(), self.detached_wda.is_some());
self.detached_wdas.retain(|k, p| !(k.eq_ignore_ascii_case(udid) && pid.is_none_or(|x| x == *p)));
self.loopback_wdas.retain(|k, p| !(k.eq_ignore_ascii_case(udid) && pid.is_none_or(|x| x == *p)));
if self
.detached_wda
.as_ref()
Expand Down Expand Up @@ -1646,6 +1666,32 @@ pub(crate) mod tests {
assert_eq!((p.detached_all(), p.detached_wda), (vec![], None));
}

/// A background WDA launched before WDA was confined to the phone's loopback listens on every interface: it isn't
/// attached to again (launching anew ends it). Once this version records it, it is
#[test]
fn only_a_loopback_only_background_wda_is_attached_to_again() {
let mut p: Persisted =
serde_json::from_str(r#"{"detached_wdas":{"IPHONE":7},"detached_wda":{"udid":"IPHONE","pid":7}}"#).unwrap();
assert_eq!(p.detached_for("IPHONE"), Some(7), "still known: ended when the phone goes native");
assert_eq!(p.adoptable_for("IPHONE"), None, "an older version's, listening on every interface");

assert!(p.record_detached("iphone", 9), "launched anew");
assert_eq!(p.adoptable_for("IPHONE"), Some(9));
assert!(!p.record_detached("IPHONE", 9), "attached to again: nothing changed");
let json = serde_json::to_value(&p).unwrap();
assert_eq!(json["loopback_wdas"], serde_json::json!({"IPHONE": 9}));
assert_eq!(json["detached_wdas"], serde_json::json!({"IPHONE": 9}), "older versions still find it");

// an older version launched another (it doesn't know loopback_wdas): not attached to by this one
p.detached_wdas.insert("IPHONE".into(), 12);
assert_eq!(p.adoptable_for("IPHONE"), None);

assert!(p.forget_detached("IPHONE", None));
assert!(p.loopback_wdas.is_empty());
let empty = serde_json::to_value(&p).unwrap();
assert!(empty.get("loopback_wdas").is_none(), "not written when empty");
}

/// A state.json from an older version has only the one record: it is still found, attached to and forgotten
#[test]
fn an_older_versions_background_wda_is_still_known() {
Expand Down
12 changes: 10 additions & 2 deletions crates/ictl-daemon/src/supervise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,15 @@ impl Daemon {
"Starting WDA (launched in the background, no XCTest session)"
));
}
let known = g.persisted.detached_for(&device.udid);
let known = g.persisted.adoptable_for(&device.udid);
if known.is_none()
&& let Some(pid) = g.persisted.detached_for(&device.udid)
{
self.log.log(&ictl_l10n::log_trf!(
"手机上的后台 WDA(进程 {pid})是旧版本启动的,对手机的所有网卡开放:重新启动,只听手机本机",
"The background WDA on the phone (pid {pid}) was launched by an older version and listens on every interface of the phone: launching it again, listening on the phone's loopback only"
));
}
let (cache, url, user_dir) = (self.cfg.ddi_cache(), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());
let Ok(lease) = crate::maintenance::shared() else { return };
let wake = self.wake.clone();
Expand Down Expand Up @@ -1070,7 +1078,7 @@ async fn ensure_ddi(
async fn prepare_detached(t: &mut Tunnel, known: Option<u64>, bundle: &str) -> Result<Detached, DeviceError> {
match known {
Some(pid) if detached::is_wda(&t.processes().await?, pid) => Ok(Detached::Adopted(pid)),
_ => Ok(Detached::Launched(t.launch_in_background(bundle).await?)),
_ => Ok(Detached::Launched(t.launch_in_background(bundle, &ictl_wda::runner::launch_env()).await?)),
}
}

Expand Down
22 changes: 18 additions & 4 deletions crates/ictl-device/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -837,10 +837,11 @@ impl Tunnel {

/// 在后台启动一个 App(DVT processcontrol,选项 `ActivateSuspended`),先结束已在运行的实例,返回进程号。
///
/// 不带任何环境变量和参数。前台启动(CoreDevice appservice,或 processcontrol 不带 `ActivateSuspended`)
/// 不带启动参数。前台启动(CoreDevice appservice,或 processcontrol 不带 `ActivateSuspended`)
/// 锁屏时会被 SpringBoard 拒绝(`RequestDenied … Locked`),后台启动不会(iPhone16,2 / iOS 27.0.1 真机)。
/// 用来启动 WDA 时,runner 自己合成测试配置,不需要主机持有 XCTest 会话(见 `docs/dev/wda-dependency-research.md`)
pub async fn launch_in_background(&mut self, bundle_id: &str) -> Result<u64> {
/// 用来启动 WDA 时,runner 自己合成测试配置,不需要主机持有 XCTest 会话(见 `docs/dev/wda-dependency-research.md`)。
/// `env` 是这个进程的环境变量(WDA 的 `USE_IP` 就靠它)
pub async fn launch_in_background(&mut self, bundle_id: &str, env: &[(&str, &str)]) -> Result<u64> {
use idevice::dvt::{message::AuxValue, remote_server::RemoteServerClient};
limit(ictl_l10n::tr!("后台启动 App", "launch an app in the background"), Duration::from_secs(60), async {
let mut dvt: RemoteServerClient<Box<dyn idevice::ReadWrite>> =
Expand All @@ -857,7 +858,7 @@ impl Tunnel {
Some(vec![
AuxValue::archived_value(""),
AuxValue::archived_value(bundle_id.to_owned()),
AuxValue::archived_value(plist::Dictionary::new()),
AuxValue::archived_value(environment(env)),
AuxValue::archived_value(plist::Value::Array(vec![])),
AuxValue::archived_value(opts),
]),
Expand Down Expand Up @@ -898,10 +899,23 @@ impl Tunnel {
}
}

/// A launch's environment as processcontrol takes it
fn environment(env: &[(&str, &str)]) -> plist::Dictionary {
env.iter().map(|(k, v)| ((*k).to_owned(), plist::Value::String((*v).to_owned()))).collect()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn the_launch_environment_is_a_dictionary_of_strings() {
let env = environment(&[("USE_IP", "127.0.0.1")]);
assert_eq!(env.len(), 1);
assert_eq!(env.get("USE_IP").and_then(plist::Value::as_string), Some("127.0.0.1"));
assert!(environment(&[]).is_empty());
}

#[test]
fn springboard_interface_orientation_preserves_all_four_directions() {
use InterfaceOrientation::*;
Expand Down
1 change: 1 addition & 0 deletions crates/ictl-wda/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ description = "WDA:启动 XCTest runner、HTTP 客户端、元素树解析"
ictl-l10n.workspace = true
ictl-device.workspace = true
idevice.workspace = true
plist.workspace = true
tokio.workspace = true
quick-xml.workspace = true
serde_json.workspace = true
Expand Down
17 changes: 16 additions & 1 deletion crates/ictl-wda/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ use crate::{Result, WdaClient, WdaError, is_automation_pin_error};

pub const WDA_PORT: u16 = 8100;

/// The address WDA listens on, given to it as `USE_IP`. Without it WDA listens on every interface of the phone: with
/// the phone on Wi-Fi anyone on the network reaches its HTTP server (8100, no authentication) and its MJPEG stream
/// (9100). usbmuxd's connections arrive on the phone's loopback, so the host still reaches it. WDA 16.15.3 gives it
/// to both servers (`FBWebServer`: the HTTP server's interface and the MJPEG socket's local endpoint)
pub const WDA_BIND_IP: &str = "127.0.0.1";

/// Environment WDA is launched with, in the background (`Tunnel::launch_in_background`) or by XCTest
pub fn launch_env() -> Vec<(&'static str, &'static str)> {
vec![("USE_IP", WDA_BIND_IP)]
}

/// runner 等「Enable UI Automation」密码的时长是 60 秒(runner 自己的超时),多留 5 秒收它的报错
const AUTOMATION_WAIT: Duration = Duration::from_secs(65);
/// 连接 installation_proxy、查 runner 的安装信息的时限(idevice 读应答没有超时)
Expand Down Expand Up @@ -220,13 +231,17 @@ impl WdaRunner {
other => WdaError::StartFailed(other.to_string()),
})
};
let cfg = tokio::time::timeout(LOOKUP_TIMEOUT, lookup).await.map_err(|_| {
let mut cfg = tokio::time::timeout(LOOKUP_TIMEOUT, lookup).await.map_err(|_| {
WdaError::StartFailed(ictl_l10n::trf!(
"查 WDA 安装信息超时({} 秒)",
"querying the WDA install info timed out ({} s)",
LOOKUP_TIMEOUT.as_secs()
))
})??;
let env = cfg.runner_env.get_or_insert_with(plist::Dictionary::new);
for (k, v) in launch_env() {
env.insert(k.into(), v.into());
}

let progress = Arc::new(Mutex::new(Progress::default()));
let task = {
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
**控制接口**:Unix socket(root 默认 `/run/iphone-control/ctl.sock`,普通用户默认 `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`,没有这个变量时(macOS)在数据目录下,权限 0600),JSON 行协议。请求/响应类型和客户端 `call(socket, req, timeout)` 在 `ictl-protocol`,MCP 和 CLI 共用。理由:

- MCP 进程由 AI 客户端直接调用二进制拉起,短命且可能同时有多个;设备连接(尤其是 HID 需要的显示媒体流、WDA 的 XCTest 会话)只能有一个持有者。
- 不开 TCP 端口,避免重蹈 `ios forward` 监听所有网卡的覆辙。WDA 本身也通过 idevice 的 provider 直连设备端口,**本机不再监听 8100**。如需给外部工具用,`iphone-control wda-bridge` 显式开启,只绑 127.0.0.1,且只转发 Host 头是 `localhost`/`127.0.0.1`/`[::1]` 的请求(挡住 DNS rebinding)。注意**本机的任何用户都能连上 bridge**,而 WDA 没有认证,用完就停。
- 不开 TCP 端口,避免重蹈 `ios forward` 监听所有网卡的覆辙。WDA 本身也通过 idevice 的 provider 直连设备端口,**本机不再监听 8100**;手机一侧的 WDA 启动时带 `USE_IP=127.0.0.1`,8100、9100 只听手机的回环地址,手机连着 Wi-Fi 时局域网也访问不到(usbmuxd 的连接在手机上本来就到回环地址)。如需给外部工具用,`iphone-control wda-bridge` 显式开启,只绑 127.0.0.1,且只转发 Host 头是 `localhost`/`127.0.0.1`/`[::1]` 的请求(挡住 DNS rebinding)。注意**本机的任何用户都能连上 bridge**,而 WDA 没有认证,用完就停。
- `iphone-control viewer` 同样显式开启、默认只绑 127.0.0.1、检查 Host 头;每个 HTTP 请求都要登录令牌(本机也一样),`--lan` 时也对局域网开放、走 HTTPS,同一个端口上还有 `/mcp`(MCP over HTTP)和给外部平台开任务的接口(见 [task-control.md](task-control.md) 第 7 节、[D3](decisions.md)):页面看 WDA 的 MJPEG 流(手机上的 9100 端口,经 usbmuxd,只读);点击、滑动、输入、按键是 POST,还要检查 `Origin` 是页面本身、内容类型是 JSON,然后作为普通请求发给守护进程,和 agent 的调用排队、自动解锁。它跟着守护进程控制的设备:在本页、别的页面、`iphone-control select`、MCP 工具里切换,或拔掉后自动换了一台,`/api/info` 的 `udid` 都会变,页面最迟在下一次 10 秒轮询时发现,把画面(`/stream?udid=`)和各面板换过去。每个操作带上页面显示的那台的 UDID(`X-Ictl-Device`),守护进程控制的不是这台就拒绝,不会发到用户没在看的手机上。还没装 WDA 的设备,登录了 Apple ID 时页面上可以直接签名安装(`/api/sign`,即 `Request::Resign { force: true }`,时限 16 分钟)。AI 任务执行中不能切换设备,设了 `IPHONE_UDID` 时也不能。
- viewer 的画面像触摸屏:iOS 27 起按下、移动、松开各发一个 `Request::Touch`(`prepare`/`down`/`move`/`up`),守护进程在已开的 HID 会话上发一个 touchscreen 报告(约 2 毫秒);解锁、核对方向只在 `down` 时做一次。页面一次只发一个请求,没发出去的移动只留最新的一个,按住不动时每 100 毫秒再报一次位置。滚轮、触控板换成同样的手指拖动。iOS 27 以下松开后发整段手势(WDA)。画面的 MJPEG 流在 `WdaClient::fast_stream` 下最多每秒 60 帧、原尺寸、不转正:缩放或转正时 WDA 要逐帧解码、处理、重新编码,CPU 超过 iOS 的上限(60 秒内平均 80%)会被杀掉;这样设置时它直接转发 testmanagerd 用硬件编好的 JPEG。iPhone 横屏时这些帧仍是竖的:JPEG 带 EXIF 方向,浏览器显示 MJPEG 的 img 时自己转正;本机编码的 H.264 不带方向,页面按界面方向(`/api/info` 的 `display.rotation`)在 canvas 上转正,和手机自己的视频一样。页面的文字中英两套,请求带 `X-Ictl-Lang`,viewer 在这种语言下处理,AI 任务记下开始时的语言。
- viewer 的画面编码(`video/`):macOS 上和装了 ffmpeg 时页面拉 `/video`,是 H.264。每个连接读手机的 MJPEG,丢掉和上一帧相同的(静止时 WDA 每秒重复约 25 次),交给一个 ffmpeg 子进程(`mpjpeg` 进,FLV 出;FLV 每帧带长度,收完最后一个字节就能发,裸 H.264 要等下一帧开头才知道这一帧结束),再按「1 字节类型 + 4 字节长度 + 内容」发给页面,页面用 WebCodecs 解码画到 canvas。发出去的解码配置先改写 SPS,写明不重排帧(`video/sps.rs`):没写的话 Chrome 的硬件解码器按级别的最坏情况扣着几帧不出(990×2151 时 4 帧),画面滞后,静止后停在动作中间。macOS 上先用本程序直接调的 VideoToolbox(`video/vt.rs`,每个连接一个线程:VideoToolbox 的 JPEG 解码器把 JPEG 解成 NV12,奇数尺寸顺带拉成偶数,直接交给 H.264 编码器;不重排、不扣帧,每帧编完才取下一帧,不用补帧;输出本来就是 avcC 格式,avcC 取自格式描述;qp 用 `MinAllowedFrameQP`/`MaxAllowedFrameQP` 定住,macOS 12 以前的系统按 `Quality` 近似;macOS 11 以后才有的键运行时用 `dlsym` 找,免得在旧系统上起不来),不需要 ffmpeg。其余编码器在 `viewer` 启动时按顺序试(NVENC、各渲染节点上的 VAAPI(先显卡解 JPEG,再 CPU 解)、QSV、V4L2 M2M、ffmpeg 的 VideoToolbox(原生的备用)、x264),处理真实画面失败就换下一个。ffmpeg 会扣住最新的一帧等下一帧来(AMD 780M 的 VAAPI 是 1 帧),画面静止时最后一次变化就出不来,所以每帧后面紧跟着把它再写 K 遍,K 在探测时测出(写入的帧数减去出来的帧数),这几份副本各编成约 100 字节。流量控制:系统和 SSH 隧道的缓冲能吞下几 MB,光看队列满不满判断不了页面跟不跟得上(每秒读 30 KB 的客户端曾落后 40 秒),所以页面每 100 毫秒 `POST /api/video/ack` 报告收到多少字节;最早一个没确认的消息比平常的往返时间晚 300 毫秒以上,或者在路上的字节超过「链路速度 ×(往返时间 + 300 毫秒)」时,新画面先不交给编码器,追上后只交最新一张。编好的帧一个不丢,帧链完整,不需要关键帧。没有 ffmpeg 或浏览器不支持 WebCodecs 时用 `/stream`:同样丢掉重复帧、只发最新一张,每帧后面紧跟下一部分的分隔线和头部(Chrome 要看到这些才显示上一帧)。
Expand Down
Loading
Loading