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 @@ -16,6 +16,12 @@ What changed in each release, one line per change. Versions follow [Semantic Ver

### Fixes

- iPads with Touch ID in a language other than Chinese or English: the "Touch ID" prompt after swiping up is known as the lock screen, and auto-unlock taps "Use Passcode" on it; the iPad was taken for unlocked and never checked again (#198).
- A malformed accessibility answer from the phone (iOS 27+) can no longer keep the daemon busy for ever; a malformed touch (a coordinate or duration that isn't a number) is refused instead of crashing or tapping the top-left corner (#198).
- The phone's log is read from now on only: the daemon took old lines for new, such as a past "Enable UI Automation" prompt, and `iphone_app_logs` showed them as just logged (#198).
- Re-signing locks down the Apple ID session and a new signing key as soon as they are written, leaves no scratch directory behind when it times out, and never leaves a half-written package (#198).
- macOS: a memory-safety bug in the built-in video encoder's JPEG decoding is fixed (#198).

- iOS 27+: an action that comes while the control page checks the phone in the background no longer leaves the accessibility connection half-read, and those checks no longer restart the phone's accessibility daemon; only actions decide that (#197).
- A task paused for a long time no longer keeps the control page's background checks from running (#197).
- Switching back to a phone made ready in the background takes effect at once even when the daemon was busy at that moment; it could wait 10 seconds. The daemon serves at most 256 clients at once; more wait their turn (#197).
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@

### 修复

- 界面语言不是中文或英文的 Touch ID iPad:上滑后的「触控 ID」提示也认作锁屏,自动解锁会点上面的「使用密码」;之前会把锁着的 iPad 当成已解锁,之后再也不查(#198)。
- 手机(iOS 27 起)发来格式异常的无障碍应答,不会再让守护进程一直忙下去;坐标或时长不是有效数字的触摸会被拒绝,不再崩溃或点到左上角(#198)。
- 手机日志只读从现在起产生的:之前守护进程会把旧日志当成新的(比如以前出现过的「Enable UI Automation」密码框),`iphone_app_logs` 也会把它们当成刚记下的(#198)。
- 重签时,Apple ID 会话和新的签名私钥一写出就收紧权限;超时也不留下临时目录;不会留下写了一半的安装包(#198)。
- macOS:内置视频编码器解 JPEG 时的一个内存安全问题已修复(#198)。

- iOS 27 起:控制台在后台检查手机时来了操作,检查中途让路后无障碍连接不再停在半条消息上;这类检查也不再重启手机的无障碍服务,要不要重启只由操作决定(#197)。
- 任务暂停很久时,控制台的后台检查不再一直跑不了(#197)。
- 切回一台在后台准备好的手机时,即使守护进程当时正忙也马上生效,之前可能要等 10 秒;守护进程同时最多服务 256 个客户端,更多的排队等候(#197)。
Expand Down
13 changes: 9 additions & 4 deletions apps/iphone-control/src/video/vt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,8 +696,11 @@ impl Decoder {
"CMSampleBufferCreateReady",
)?;
let sample = Cf(sample);
let slot = unsafe { &mut *self.out };
*slot = DecodedSlot::default();
// the callback ([`on_decoded`]) writes the slot through its own pointer while the calls below run: no
// reference to it is held across them (two live `&mut` to one place are undefined behaviour), only short
// accesses through the raw pointer before and after
// SAFETY: `self.out` is the Box made in `new`, alive until `drop`; nothing else touches it meanwhile
unsafe { *self.out = DecodedSlot::default() };
let s = self.session.ptr();
check(
unsafe {
Expand All @@ -706,8 +709,10 @@ impl Decoder {
"VTDecompressionSessionDecodeFrame",
)?;
unsafe { VTDecompressionSessionWaitForAsynchronousFrames(s) };
check(slot.status, "decoder")?;
slot.image.take().ok_or_else(|| "decoder: no picture".to_owned())
// SAFETY: as above; the callback has run (the wait returns once every frame is out)
let (status, image) = unsafe { ((*self.out).status, (*self.out).image.take()) };
check(status, "decoder")?;
image.ok_or_else(|| "decoder: no picture".to_owned())
}
}

Expand Down
114 changes: 110 additions & 4 deletions crates/ictl-ax/src/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,22 @@ impl Obj {
}
}

/// Deeper than this is a cycle or garbage: such a value reads as [`Obj::Null`]
/// Deeper than this is garbage: such a value reads as [`Obj::Null`]
const MAX_DEPTH: usize = 200;

/// Values an archive may decode to, per byte of it (plus a floor). Each reference in an archive takes at least a
/// byte, so a real one stays well below this; one whose objects share children over and over (a DAG built to blow
/// up, `2^depth` values from a few hundred bytes) is refused instead of decoded for ever
const BUDGET_PER_BYTE: usize = 8;
const BUDGET_FLOOR: usize = 10_000;

/// Decodes one archive
pub fn decode(bytes: &[u8]) -> Result<Obj> {
decode_within(bytes, bytes.len().saturating_mul(BUDGET_PER_BYTE).saturating_add(BUDGET_FLOOR)).map(|(o, _)| o)
}

/// [`decode`] with at most `budget` values; also how many it took
fn decode_within(bytes: &[u8], budget: usize) -> Result<(Obj, usize)> {
let top = Value::from_reader(Cursor::new(bytes)).map_err(|e| AxError::Archive(e.to_string()))?;
let dict = top.as_dictionary().ok_or_else(|| AxError::Archive("not a dictionary".into()))?;
let objects =
Expand All @@ -106,22 +117,53 @@ pub fn decode(bytes: &[u8]) -> Result<Obj> {
.and_then(Value::as_dictionary)
.and_then(|t| t.get("root").or_else(|| t.values().next()))
.ok_or_else(|| AxError::Archive("no $top root".into()))?;
Ok(Reader { objects }.resolve(root, 0))
let reader = Reader {
objects,
visiting: Default::default(),
exhausted: std::cell::Cell::new(false),
budget: std::cell::Cell::new(budget),
};
let obj = reader.resolve(root, 0);
if reader.exhausted.get() {
return Err(AxError::Archive("too many values for its size".into()));
}
Ok((obj, budget - reader.budget.get()))
}

struct Reader<'a> {
objects: &'a [Value],
/// The objects being decoded on the way down: one that refers back to one of them is a cycle, read as
/// [`Obj::Null`]
visiting: std::cell::RefCell<std::collections::HashSet<u64>>,
/// Values still to be decoded ([`BUDGET_PER_BYTE`]); at 0 everything reads as [`Obj::Null`] and the archive is
/// refused
budget: std::cell::Cell<usize>,
/// A value was left out for want of [`Self::budget`] (one that used the last of it exactly is fine)
exhausted: std::cell::Cell<bool>,
}

impl Reader<'_> {
fn resolve(&self, v: &Value, depth: usize) -> Obj {
if depth > MAX_DEPTH {
return Obj::Null;
}
if self.budget.get() == 0 {
self.exhausted.set(true);
return Obj::Null;
}
self.budget.set(self.budget.get() - 1);
match v {
Value::Uid(u) => match self.objects.get(u.get() as usize) {
// (on a 32-bit target a UID past usize isn't truncated to another object)
Value::Uid(u) => match usize::try_from(u.get()).ok().and_then(|i| self.objects.get(i)) {
Some(Value::String(s)) if s == "$null" => Obj::Null,
Some(o) => self.resolve(o, depth + 1),
Some(o) => {
if !self.visiting.borrow_mut().insert(u.get()) {
return Obj::Null;
}
let r = self.resolve(o, depth + 1);
self.visiting.borrow_mut().remove(&u.get());
r
}
None => Obj::Null,
},
Value::Boolean(b) => Obj::Bool(*b),
Expand Down Expand Up @@ -360,6 +402,70 @@ pub fn encode_request(
mod tests {
use super::*;

/// An archive of `objects` (object 0 is `$null`, the root is object 1), as the phone would send one
fn archive(objects: Vec<Value>) -> Vec<u8> {
let mut all = vec![Value::String("$null".into())];
all.extend(objects);
let mut top = Dictionary::new();
top.insert("root".into(), Value::Uid(plist::Uid::new(1)));
let mut d = Dictionary::new();
d.insert("$archiver".into(), Value::String("NSKeyedArchiver".into()));
d.insert("$objects".into(), Value::Array(all));
d.insert("$top".into(), Value::Dictionary(top));
let mut out = Vec::new();
Value::Dictionary(d).to_writer_binary(&mut out).unwrap();
out
}

/// An `NSArray` instance of the given objects, its class at `class`
fn ns_array(items: &[u64], class: u64) -> Value {
let mut d = Dictionary::new();
d.insert("$class".into(), Value::Uid(plist::Uid::new(class)));
d.insert("NS.objects".into(), Value::Array(items.iter().map(|&u| Value::Uid(plist::Uid::new(u))).collect()));
Value::Dictionary(d)
}

fn class(name: &str) -> Value {
let mut d = Dictionary::new();
d.insert("$classname".into(), Value::String(name.into()));
Value::Dictionary(d)
}

/// An object that holds itself is a cycle: it reads as null there, not as a recursion 200 deep
#[test]
fn a_cycle_reads_as_null() {
// 1: an array holding itself and a string; 2: its class; 3: the string
let bytes = archive(vec![ns_array(&[1, 3], 2), class("NSArray"), Value::String("x".into())]);
let Obj::Array(items) = decode(&bytes).unwrap() else { panic!("not an array") };
assert!(matches!(items[0], Obj::Null), "{items:?}");
assert_eq!(items[1].as_str(), Some("x"));
}

/// Objects that each hold the next one twice: 2^60 values from a few hundred bytes. Refused at once
#[test]
fn an_archive_built_to_blow_up_is_refused() {
const LEVELS: u64 = 60;
let class_at = LEVELS + 2;
let mut objects: Vec<Value> = (1..=LEVELS).map(|i| ns_array(&[i + 1, i + 1], class_at)).collect();
objects.push(Value::String("leaf".into()));
objects.push(class("NSArray"));
let bytes = archive(objects);
let t0 = std::time::Instant::now();
assert!(matches!(decode(&bytes), Err(AxError::Archive(_))));
assert!(t0.elapsed() < std::time::Duration::from_secs(2), "{:?}", t0.elapsed());
// shared, but small: decoded
let mut objects: Vec<Value> = (1..=4).map(|i| ns_array(&[i + 1, i + 1], 6)).collect();
objects.push(Value::String("leaf".into()));
objects.push(class("NSArray"));
let bytes = archive(objects);
let Obj::Array(top) = decode(&bytes).unwrap() else { panic!("not an array") };
assert_eq!(top.len(), 2);
// a budget used up exactly is enough; one value short isn't
let (_, took) = decode_within(&bytes, usize::MAX).unwrap();
assert!(decode_within(&bytes, took).is_ok());
assert!(decode_within(&bytes, took - 1).is_err());
}

#[test]
fn scalars_round_trip() {
assert_eq!(decode(&encode_scalar(Value::Boolean(true))).unwrap(), Obj::Bool(true));
Expand Down
21 changes: 16 additions & 5 deletions crates/ictl-daemon/src/tools/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,22 @@ impl Daemon {
h.rotation = rot;
let result = Box::pin(h.touch(contact, x, y)).await;
g.hid_used = Some(Instant::now());
if let Err(e) = result {
// A failed write may still have reached the phone.
g.dev.touch_rotation = None;
drop_tunnel(g).await;
return Err(Response::error(ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}")));
match result {
Ok(()) => {}
// refused before anything was sent (a point that isn't a number, an unknown screen size): the tunnel and
// its sessions are fine; a finger that is down stays where it was
Err(e @ ictl_device::DeviceError::InvalidInput(_)) => {
if phase == TouchPhase::Down {
g.dev.touch_rotation = None;
}
return Err(Response::error(e.to_string()).with_failure(Delivery::NotSent, FailureStage::Preflight));
}
Err(e) => {
// A failed write may still have reached the phone.
g.dev.touch_rotation = None;
drop_tunnel(g).await;
return Err(Response::error(ictl_l10n::trf!("HID 命令失败: {e}", "HID command failed: {e}")));
}
}
Ok(())
}
Expand Down
33 changes: 31 additions & 2 deletions crates/ictl-daemon/src/tools/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl Daemon {
overlays: bool,
) -> crate::error::Result<ictl_device::ax::AxScreen> {
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
let mut restarted = false;
let (mut restarted, mut rebuilt) = (false, false);
loop {
let t = self
.ensure_tunnel(g, &device)
Expand All @@ -157,6 +157,12 @@ impl Daemon {
t.close_ax().await;
}
g.ax_used = Some(Instant::now());
if tunnel_timed_out(&r) {
drop_tunnel(g).await;
if !std::mem::replace(&mut rebuilt, true) {
continue;
}
}
if let Err(ictl_device::DeviceError::AxUnanswered(e)) = &r
&& !restarted
&& Box::pin(self.restart_stuck_ax(g, &device, e)).await
Expand Down Expand Up @@ -266,14 +272,20 @@ impl Daemon {
/// The frontmost app's bundle ID (one request, no walk)
pub(crate) async fn native_foreground(&self, g: &mut Inner) -> crate::error::Result<String> {
let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
let mut restarted = false;
let (mut restarted, mut rebuilt) = (false, false);
let r = loop {
let t = self.ensure_tunnel(g, &device).await?;
let r = t.ax_frontmost_pid(AX_WAIT).await;
if r.is_err() {
t.close_ax().await;
}
g.ax_used = Some(Instant::now());
if tunnel_timed_out(&r) {
drop_tunnel(g).await;
if !std::mem::replace(&mut rebuilt, true) {
continue;
}
}
if let Err(ictl_device::DeviceError::AxUnanswered(e)) = &r
&& !restarted
&& Box::pin(self.restart_stuck_ax(g, &device, e)).await
Expand Down Expand Up @@ -1123,10 +1135,27 @@ impl Screen for NativeScreen<'_> {
}
}

/// A read that timed out in the tunnel itself (connecting to the service's port, a query through it): the tunnel
/// is stuck, and keeping it would time out every read after it. It is dropped (and the read tried once more on a new
/// one). Not [`ictl_device::DeviceError::AxUnanswered`]: that is the accessibility daemon, restarted instead
fn tunnel_timed_out<T>(r: &ictl_device::Result<T>) -> bool {
matches!(r, Err(ictl_device::DeviceError::Timeout(_)))
}

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

/// Only a time-out in the tunnel itself drops it; the accessibility daemon's is restarted instead
#[test]
fn a_stuck_tunnel_is_dropped_not_the_accessibility_daemon() {
use ictl_device::DeviceError;
assert!(tunnel_timed_out::<()>(&Err(DeviceError::Timeout("connect".into()))));
assert!(!tunnel_timed_out::<()>(&Err(DeviceError::AxUnanswered("request".into()))));
assert!(!tunnel_timed_out::<()>(&Err(DeviceError::InvalidInput("x".into()))));
assert!(!tunnel_timed_out(&Ok(())));
}

#[test]
fn only_a_recognisable_unlocked_springboard_can_confirm_absence() {
let screen = |springboard_front| ictl_device::ax::AxScreen {
Expand Down
12 changes: 11 additions & 1 deletion crates/ictl-device/src/ax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,17 @@ impl Tunnel {
.get(ictl_ax::SERVICE)
.map(|s| s.port)
.ok_or_else(|| DeviceError::Idevice(format!("the phone offers no {}", ictl_ax::SERVICE)))?;
let stream: Box<dyn ReadWrite> = Box::new(self.adapter.connect(port).await?);
// the tunnel's own connect has no time limit: one that doesn't come is the tunnel's fault (a timeout, the
// tunnel is rebuilt), not the accessibility daemon's
let adapter = &mut self.adapter;
let stream: Box<dyn ReadWrite> = Box::new(
limit(
ictl_l10n::tr!("连接无障碍服务的端口", "connect to the accessibility service's port"),
CONNECT_WAIT,
async { Ok(adapter.connect(port).await?) },
)
.await?,
);
let s =
limit(ictl_l10n::tr!("连接无障碍服务", "connect to the accessibility service"), CONNECT_WAIT, async {
Ok(AxSession::connect(stream, CONNECT_WAIT).await?)
Expand Down
Loading
Loading