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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ What changed in each release, one line per change. Versions follow [Semantic Ver

- Times in `status`, `doctor` and the event log are shown in local time with the time zone; they were UTC without saying so.
- Errors from `iphone-control update`, `service` and the update panel on the control page follow the chosen language; they were always in English.
- Phones driven natively (iOS 27+) no longer trigger WebDriverAgent re-signing or the daily Apple ID session check (and its "session expired" warning) when another device once used WebDriverAgent.
- After re-signing, the new WebDriverAgent starts right away instead of at the next check up to 10 seconds later.
- A dragged finger held down (`iphone_swipe` with `hold`) is lifted if the drag fails or times out halfway.
- Responses from WebDriverAgent, accessibility messages and screen video frames have size limits, so a broken stream can't make the program use unbounded memory.
- Screenshots of a phone driven natively say "via CoreDevice" instead of "via HID".
- With nobody watching the control page, the phone's screen video is no longer assembled into frames, which saves CPU while an agent works.

## [0.2.14] - 2026-11-24

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

- `status`、`doctor` 和事件日志里的时间改为本地时间并标明时区,之前显示的是 UTC 却没有说明。
- `iphone-control update`、`service` 和控制台更新面板里的报错跟随界面语言,之前总是英文。
- 原生控制的手机(iOS 27 起)不再因为别的设备用过 WebDriverAgent 而触发 WebDriverAgent 重签和每天一次的 Apple ID 会话检查(以及「会话失效」提醒)。
- 重签完成后马上启动新的 WebDriverAgent,不用再等最多 10 秒的下一轮巡检。
- 按住再拖(`iphone_swipe` 带 `hold`)中途失败或超时时会抬起手指,不再留着按下的状态。
- WebDriverAgent 的响应、无障碍消息和屏幕视频帧都有了大小上限,数据流出错时不会无限占用内存。
- 原生控制时截图说明写「经 CoreDevice」,不再写「经 HID」。
- 控制台没人观看时不再把手机的屏幕视频拼成帧,Agent 操作期间更省 CPU。

## [0.2.14] - 2026-11-24

Expand Down
8 changes: 5 additions & 3 deletions apps/iphone-control/src/video/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,13 +399,15 @@ pub async fn serve_mjpeg(
let (tx, rx) = watch::channel::<Option<Arc<Vec<u8>>>>(None);
let reader = tokio::spawn(async move {
let mut f = mjpeg::Frames::new(src);
let mut last: Option<Vec<u8>> = None;
let mut last: Option<Arc<Vec<u8>>> = None;
while let Ok(Ok(Some(j))) = tokio::time::timeout(idle, f.next()).await {
if last.as_ref() == Some(&j) {
if last.as_deref() == Some(&j) {
continue;
}
// kept and sent as the same allocation, not copied per frame
let j = Arc::new(j);
last = Some(j.clone());
if tx.send(Some(Arc::new(j))).is_err() {
if tx.send(Some(j)).is_err() {
return;
}
}
Expand Down
54 changes: 31 additions & 23 deletions apps/iphone-control/src/viewer/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,19 @@ fn write_private(file: &Path, data: &[u8]) -> io::Result<()> {
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = file.with_extension("tmp");
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(data)?;
f.sync_all()?;
std::fs::rename(&tmp, file)
// a name of its own: two commands changing tokens at once must not write into the same temporary file
let tmp = file.with_extension(format!("{}.{}.tmp", std::process::id(), &new_token()?[..8]));
let written = (|| {
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?;
f.set_permissions(std::fs::Permissions::from_mode(0o600))?;
f.write_all(data)?;
f.sync_all()?;
std::fs::rename(&tmp, file)
})();
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written
}

/// Who a request is logged in as
Expand Down Expand Up @@ -351,26 +358,18 @@ impl Auth {
}
}

/// Too many wrong tokens just now
pub fn limited(&self) -> bool {
let mut f = self.failures.lock().unwrap_or_else(|p| p.into_inner());
let now = Instant::now();
while f.front().is_some_and(|t| now.duration_since(*t) > WINDOW) {
f.pop_front();
}
f.len() >= MAX_FAILURES
}

/// A wrong token (or task token, see `viewer::login_gate`) was sent: [`Verdict::Wrong`], or
/// [`Verdict::Limited`] once there were too many
/// [`Verdict::Limited`] once there were too many. Checked and counted under one lock: two wrong tokens at the
/// same moment can't both slip under the limit
pub fn failed(&self) -> Verdict {
let limited = self.limited();
let mut f = self.failures.lock().unwrap_or_else(|p| p.into_inner());
// counted up to the limit only: a flood doesn't keep it going after the minute
if !limited {
f.push_back(Instant::now());
let now = Instant::now();
if recent_failures(&mut f, now) >= MAX_FAILURES {
return Verdict::Limited;
}
if limited { Verdict::Limited } else { Verdict::Wrong }
// counted up to the limit only: a flood doesn't keep it going after the minute
f.push_back(now);
Verdict::Wrong
}

/// `Set-Cookie` for a browser that logged in with the token named `name`; `secure` over HTTPS (the browser then
Expand All @@ -388,7 +387,16 @@ impl Auth {
}
}

/// Equal, in a time that doesn't depend on where they differ
/// Drops the failures older than [`WINDOW`] and counts the rest
fn recent_failures(f: &mut std::collections::VecDeque<Instant>, now: Instant) -> usize {
while f.front().is_some_and(|t| now.duration_since(*t) > WINDOW) {
f.pop_front();
}
f.len()
}

/// Equal, in a time that doesn't depend on where they differ (ring's `verify_slices_are_equal` is deprecated in
/// 0.17 and promises nothing about side channels)
fn same(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
Expand Down
45 changes: 41 additions & 4 deletions crates/ictl-ax/src/dtx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,15 @@ impl Frame {
}
}

/// The largest message accepted, its fragments joined (a big accessibility reply is a few MB)
pub const MAX_MESSAGE_BYTES: usize = 64 << 20;

/// Reads the next whole message
pub async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> std::io::Result<Frame> {
read_frame_within(reader, MAX_MESSAGE_BYTES).await
}

async fn read_frame_within<R: AsyncRead + Unpin>(reader: &mut R, limit: usize) -> std::io::Result<Frame> {
let mut payload = Vec::new();
loop {
let mut h = [0u8; 32];
Expand All @@ -61,12 +68,15 @@ pub async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> std::io::Result
continue;
}
let len = word(12) as usize;
if len > 64 << 20 {
// the whole message, all its fragments together, not each one: a header can claim anything
if payload.len().saturating_add(len) > limit {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "DTX message too large"));
}
let mut part = vec![0u8; len];
reader.read_exact(&mut part).await?;
payload.extend(part);
// read as it comes instead of allocating what the header claims up front
let read = (&mut *reader).take(len as u64).read_to_end(&mut payload).await?;
if read < len {
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "DTX message cut short"));
}
if fragment + 1 >= fragments {
return Ok(parse(word(16), word(20), word(24) as i32, word(28) == 1, &payload));
}
Expand Down Expand Up @@ -143,6 +153,33 @@ mod tests {
assert_eq!(f.first_arg(), Some(Obj::Bool(true)));
}

/// A fragment's 32-byte header and its bytes
fn fragment(index: u16, count: u16, data: &[u8]) -> Vec<u8> {
let mut h = Vec::new();
h.extend(0x1F3D_5B79u32.to_le_bytes());
h.extend(32u32.to_le_bytes());
h.extend(index.to_le_bytes());
h.extend(count.to_le_bytes());
h.extend((data.len() as u32).to_le_bytes());
h.extend([5u32, 0, 0, 0].iter().flat_map(|w| w.to_le_bytes()));
h.extend(data);
h
}

#[tokio::test]
async fn the_whole_message_is_limited_not_each_fragment() {
// the first of several fragments is the header alone
let parts = |n: usize| [fragment(0, 3, &[]), fragment(1, 3, &vec![1; n]), fragment(2, 3, &vec![2; n])].concat();
assert!(read_frame_within(&mut &parts(40)[..], 100).await.is_ok());
let e = read_frame_within(&mut &parts(60)[..], 100).await.unwrap_err();
assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
// a header claiming more than arrives is an error, not a huge allocation
let mut cut = fragment(0, 1, &[0; 10]);
cut[12..16].copy_from_slice(&50u32.to_le_bytes());
let e = read_frame_within(&mut &cut[..], 100).await.unwrap_err();
assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
}

#[tokio::test]
async fn replies_answer_the_conversation() {
let asked = read_frame(&mut &invocation(4, "hostAPIVersion", vec![], true)[..]).await.unwrap();
Expand Down
7 changes: 2 additions & 5 deletions crates/ictl-daemon/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1129,11 +1129,8 @@ impl Daemon {
return Response::error(ictl_l10n::tr!("手机未连接", "Phone not connected"));
};
let Request::InstallApp { path } = req else { unreachable!("lane") };
let r = self.install_app(&device, &path).await;
if r.is_ok() {
self.inner.lock().await.dev.apps.clear();
}
return text(r);
// install_app clears the app lists itself once installed
return text(self.install_app(&device, &path).await);
}
Lane::Device => {}
}
Expand Down
17 changes: 11 additions & 6 deletions crates/ictl-daemon/src/devtools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ impl Daemon {
// an app's name or bundle ID → the process it runs as; anything else is taken as a process name
let wanted = if process.is_empty() { None } else { Some(self.process_name(g, process).await) };
let c = g.dev.log_capture.as_ref().expect("set above");
let filter = LogFilter { process: wanted.as_deref(), grep, errors_only };
let filter = LogFilter::new(wanted.as_deref(), grep, errors_only);
let from = Instant::now().checked_sub(since);
let (lines, oldest) = {
let b = c.buf.lock().unwrap_or_else(|p| p.into_inner());
Expand Down Expand Up @@ -325,11 +325,16 @@ fn is_wda_runner(bid: &str, signed: Option<&str>) -> bool {
struct LogFilter<'a> {
/// executable name, matched against the last path component, ignoring case
process: Option<&'a str>,
grep: &'a str,
/// already lowercased ([`LogFilter::new`]): it is matched against up to 20,000 entries
grep: String,
errors_only: bool,
}

impl LogFilter<'_> {
impl<'a> LogFilter<'a> {
fn new(process: Option<&'a str>, grep: &str, errors_only: bool) -> Self {
Self { process, grep: grep.to_lowercase(), errors_only }
}

fn matches(&self, e: &LogEntry) -> bool {
if self.errors_only && !matches!(e.level, LogLevel::Error | LogLevel::Fault) {
return false;
Expand All @@ -341,9 +346,9 @@ impl LogFilter<'_> {
}
}
if !self.grep.is_empty() {
let g = self.grep.to_lowercase();
let g = &self.grep;
let sub = e.subsystem.as_deref().unwrap_or_default();
if !e.message.to_lowercase().contains(&g) && !sub.to_lowercase().contains(&g) {
if !e.message.to_lowercase().contains(g) && !sub.to_lowercase().contains(g) {
return false;
}
}
Expand Down Expand Up @@ -454,7 +459,7 @@ mod tests {
fn log_filter() {
let app = "/private/var/containers/Bundle/Application/X/My App.app/MyApp";
let e = entry(app, LogLevel::Error, "Request failed: timeout");
let f = |process, grep, errors_only| LogFilter { process, grep, errors_only };
let f = |process, grep, errors_only| LogFilter::new(process, grep, errors_only);
assert!(f(Some("myapp"), "", false).matches(&e));
assert!(!f(Some("App"), "", false).matches(&e));
assert!(f(None, "TIMEOUT", true).matches(&e));
Expand Down
57 changes: 46 additions & 11 deletions crates/ictl-daemon/src/supervise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,19 +166,19 @@ impl Daemon {
}

let now = Instant::now();
if now >= g.next_resign {
let upkeep = wda_upkeep(g.device.is_some(), self.native(g), g.persisted.wda_bundle.is_some());
// 不该做的这一轮不算数:换到用 WDA 的设备后下一轮就做,不用再等一个周期
if now >= g.next_resign && upkeep.resign {
g.next_resign = now + self.cfg.resign_check;
if g.device.is_some() && g.persisted.wda_bundle.is_some() {
let d = self.clone();
tokio::task::spawn_local(async move {
if let Err(e) = d.resign_now(false).await {
let mut g = d.inner.lock().await;
d.notify(&mut g, Event::ResignFailed(e.to_string()));
}
});
}
let d = self.clone();
tokio::task::spawn_local(async move {
if let Err(e) = d.resign_now(false).await {
let mut g = d.inner.lock().await;
d.notify(&mut g, Event::ResignFailed(e.to_string()));
}
});
}
if now >= g.next_session_check {
if now >= g.next_session_check && upkeep.session {
g.next_session_check = now + self.cfg.session_check;
tokio::task::spawn_local(self.clone().check_session());
}
Expand Down Expand Up @@ -1034,9 +1034,12 @@ impl Daemon {
g.persisted.save(&self.cfg.state_file());
// 新包装上后旧的 runner 会失效,下一轮巡检重新拉起。签名期间切到了别的设备就不动它的会话
if g.device.as_ref().is_some_and(|d| d.udid == signed_udid) {
// 装新包时旧的后台 WDA 已被结束:忘掉它(进程号可能被别的进程用上),巡检马上重新拉起
self.forget_detached_here(g);
self.drop_session(g).await;
self.refresh_device_profile(g).await;
g.backoff.reset();
self.wake.notify_one();
}
g.dedup.clear("resign");
let expires = crate::eventlog::format_local(exp);
Expand All @@ -1062,6 +1065,20 @@ impl Daemon {
}
}

/// 定时的 WDA 维护(自动重签、Apple ID 会话检查)这一轮该不该做
#[derive(Debug, PartialEq, Eq)]
struct Upkeep {
resign: bool,
session: bool,
}

/// 只为用 WDA 的设备做:在用的设备走原生控制时都不做(iOS 27 原生不要 Apple ID,见 docs/dev/ios27-native.md)。
/// 没装过 WDA(`has_bundle` 为 false)也不做。会话检查在没连手机时照做,提早发现会话失效
fn wda_upkeep(device: bool, native: bool, has_bundle: bool) -> Upkeep {
let wda = has_bundle && !(device && native);
Upkeep { resign: wda && device, session: wda }
}

fn now_secs() -> u64 {
std::time::SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
}
Expand Down Expand Up @@ -1170,3 +1187,21 @@ mod display_tests {
std::fs::remove_dir_all(dir).unwrap();
}
}

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

#[test]
fn wda_upkeep_is_only_for_devices_that_use_wda() {
// a WDA device with WDA installed: both
assert_eq!(wda_upkeep(true, false, true), Upkeep { resign: true, session: true });
// the device in use is driven natively: neither, even with a WDA bundle left from another device
assert_eq!(wda_upkeep(true, true, true), Upkeep { resign: false, session: false });
// no phone: nothing to re-sign for, the Apple ID session is still checked
assert_eq!(wda_upkeep(false, false, true), Upkeep { resign: false, session: true });
// never installed WDA (native only): no Apple ID upkeep at all
assert_eq!(wda_upkeep(true, false, false), Upkeep { resign: false, session: false });
assert_eq!(wda_upkeep(false, false, false), Upkeep { resign: false, session: false });
}
}
4 changes: 3 additions & 1 deletion crates/ictl-daemon/src/tools/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,11 +360,13 @@ impl Daemon {
if !hid_supported(g.info.as_ref()) {
return Err(wda_down(&g.state, g.info.as_ref()).into());
}
// the picture comes from CoreDevice's screencaptureservice either way; driven natively that is the
// normal path, without it WDA is down and «HID» tells the agent so (taps say «via HID» too)
(
self.hid_screenshot(g)
.await
.map_err(|e| ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}"))?,
"HID",
if self.native(g) { "CoreDevice" } else { "HID" },
)
}
};
Expand Down
2 changes: 2 additions & 0 deletions crates/ictl-daemon/src/tools/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,8 @@ impl Daemon {
.collect();
for pid in &pids {
self.ensure_tunnel(g, &device).await?.signal(*pid, 9).await?;
// the frontmost-app cache must not name a pid that may be reused
g.dev.bundles.remove(&(*pid as i64));
}
// gone before this says so: a launch right after one killed failed with «The process identifier of the
// launched application could not be determined. It may have already terminated.»
Expand Down
6 changes: 5 additions & 1 deletion crates/ictl-device/src/hid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,16 @@ impl HidSession {
limit(ictl_l10n::tr!("HID 按住拖动", "HID held drag"), d, async {
let end = tokio::time::Instant::now() + held;
self.touch.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, x1, y1, None).await?;
// the finger is down: if this fails or times out from here on, closing the session lifts it
self.contact = Some((x1, y1));
while tokio::time::Instant::now() < end {
tokio::time::sleep(Duration::from_millis(100).min(end - tokio::time::Instant::now())).await;
self.touch.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, x1, y1, None).await?;
}
// drag() starts with a contact at (x1, y1): the finger stays down from the hold into the move
Ok(self.touch.drag(x1, y1, x2, y2, steps, 20).await?)
self.touch.drag(x1, y1, x2, y2, steps, 20).await?;
self.contact = None;
Ok(())
})
.await
}
Expand Down
Loading
Loading