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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
- Services install from a program path with spaces, and refuse one with characters systemd or the shell would read as their own; an update that paused the viewer's service starts it again without turning on its start at login; setting up the automatic update job and failing leaves none of its files behind, even when the service manager can't be reached (#202).
- An AI task from the control page works when `IPHONE_CONTROL_URL` is set in the settings file (#202).
- A read-only login no longer sends touches from the picture (each answered with an error) and shows no pointer on it (#202).
- iOS 27+: an ordinary text field showing a time or a fraction ("6:00", "2/4") is no longer taken for the lock screen's passcode field, which made the phone read as locked (#203).
- iOS 27+: an element the phone lists under another flag than its own is no longer left out of the screen with everything under it (#203).
- Malformed answers from the phone (endless or oversized message fragments from the accessibility service, a Web Inspector message split past its limit, a WebDriverAgent answer with an endless head or odd chunks) are refused instead of read for ever or crashing; a WebDriverAgent answer with trailers no longer waits for the timeout (#203).
- `iphone_web_eval`: a page that went away is reported at once instead of after the timeout, and a connection left out of step is opened again for the next call (#203).
- macOS: the built-in video encoder no longer piles up frames for a page that is slow to take them (#203).
- When pressing Home finds a system alert in the way, the daemon's answer now also marks it in its structured result (`alert_reported`), as launching an app or opening a link does; programs reading the result rather than its text missed it (#200).
- A long press falls back to HID like a tap when WebDriverAgent can't be reached (#200).
- Requests that can't run (a tap count of 0, an empty tap sequence, an unknown button, a point that isn't a number) are refused at once, before waiting for the phone and without dropping the cached screen (#200).
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@
- 程序路径里有空格也能装服务;带有 systemd 或 shell 会特殊处理的字符时拒绝安装;升级时暂停过的控制台服务恢复时,不再把它的开机自启打开;配置自动更新任务失败时,连不上服务管理器也不会留下它的文件(#202)。
- 设置文件里写了 `IPHONE_CONTROL_URL` 时,控制台上的 AI 任务也能正常工作(#202)。
- 只读登录时,在画面上按下不再把触摸发给手机(之前每次都会弹一个错误),也不显示指针(#202)。
- iOS 27 起:显示时间或分数(如「6:00」「2/4」)的普通输入框,不再被当成锁屏的密码栏(之前会因此把手机判成锁着)(#203)。
- iOS 27 起:手机列出的某个元素标记和它自己的不一致时,不再把它连同下面的所有内容一起漏掉(#203)。
- 手机发来格式异常的应答时直接拒绝,不再一直读下去或崩溃。包括:无障碍服务的消息分片没完没了或过大、Web Inspector 的拆分消息超过上限、WebDriverAgent 的应答头没有结尾或分块异常。WebDriverAgent 的应答带 trailer 时也不再等到超时(#203)。
- `iphone_web_eval`:页面已经不在时立刻报错,不用等到超时;连接错位后,下一次调用会重新打开连接(#203)。
- macOS:页面取画面慢时,内置视频编码器不再越积越多(#203)。
- 按 Home 时发现有系统弹窗挡着,守护进程的应答现在也会在结构化结果里标出(`alert_reported`),和启动 App、打开链接一样;之前只读结果字段、不看文字的程序会漏掉(#200)。
- 长按和点击一样,连不上 WebDriverAgent 时改用 HID(#200)。
- 执行不了的请求(点击次数为 0、空的点击序列、不认识的按键、坐标不是有效数字)立刻拒绝,不再先排队等手机,也不会清掉缓存的界面(#200)。
Expand Down
20 changes: 18 additions & 2 deletions apps/iphone-control/src/video/flv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ pub struct Parser {
started: bool,
}

/// The longest FLV file header taken (FLV 1's is 9 bytes)
const MAX_HEADER: usize = 1024;

impl Parser {
pub fn push(&mut self, data: &[u8]) {
self.buf.extend_from_slice(data);
Expand All @@ -36,8 +39,13 @@ impl Parser {
if &self.buf[..3] != b"FLV" {
return Err("ffmpeg's output isn't FLV".into());
}
// the header's own length, then the first "previous tag size" (0)
let skip = u32::from_be_bytes([self.buf[5], self.buf[6], self.buf[7], self.buf[8]]) as usize + 4;
// the header's own length (9 in FLV 1), then the first "previous tag size" (0). A length past any real
// header means the stream isn't FLV: waited for, it would have grown the buffer up to 4 GB
let len = u32::from_be_bytes([self.buf[5], self.buf[6], self.buf[7], self.buf[8]]) as usize;
if !(9..=MAX_HEADER).contains(&len) {
return Err(format!("FLV header of {len} bytes, not FLV"));
}
let skip = len + 4;
if self.buf.len() < skip {
return Ok(None);
}
Expand Down Expand Up @@ -137,5 +145,13 @@ pub(crate) mod tests {
p.push(&header());
p.push(&tag(9, &[0x1C, 1, 0, 0, 0]));
assert!(p.next().is_err(), "HEVC isn't expected");
// a header length no FLV has: refused at once, not waited for
for len in [0u32, 8, 1025, u32::MAX] {
let mut p = Parser::default();
let mut h = b"FLV\x01\x01".to_vec();
h.extend(len.to_be_bytes());
p.push(&h);
assert!(p.next().is_err(), "{len}");
}
}
}
65 changes: 56 additions & 9 deletions apps/iphone-control/src/video/vt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,14 @@ struct Sink {
/// H.264: the `avcC` sent last, so a new one goes out before the frame that needs it. JPEG: unused
avcc: Mutex<Vec<u8>>,
h264: bool,
/// The session counting H.264 frames sent and not yet taken ([`Shared::queued`]); none for a JPEG
queued: Option<Arc<Shared>>,
}

/// H.264 frames the encoding thread may have sent ahead of the caller: a caller that falls behind (a slow page) no
/// longer makes the channel grow without end; meanwhile the newest JPEG replaces the one waiting ([`Session::push`])
const MAX_AHEAD: usize = 8;

extern "C" fn on_encoded(refcon: *mut c_void, _frame: *mut c_void, status: OSStatus, _flags: u32, sample: *mut c_void) {
let sink = unsafe { &*(refcon as *const Sink) };
if status != 0 {
Expand Down Expand Up @@ -349,7 +355,15 @@ extern "C" fn on_encoded(refcon: *mut c_void, _frame: *mut c_void, status: OSSta
let _ = sink.tx.send(Ok(Packet::Config(avcc)));
}
}
let _ = sink.tx.send(Ok(Packet::Frame { key, data }));
// counted before it is sent: the caller may take it at once, and its count must not go below zero
if let Some(s) = &sink.queued {
s.queued.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
if sink.tx.send(Ok(Packet::Frame { key, data })).is_err()
&& let Some(s) = &sink.queued
{
s.queued.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}
}

unsafe fn sample_bytes(sample: *mut c_void) -> Option<Vec<u8>> {
Expand Down Expand Up @@ -385,7 +399,8 @@ unsafe fn avcc_of(desc: *mut c_void) -> Option<Vec<u8>> {
let name = cfstr(c"avcC");
let d = unsafe { CFDictionaryGetValue(atoms, name.ptr()) };
if !d.is_null() {
let n = unsafe { CFDataGetLength(d) } as usize;
// a CFIndex: negative would make a huge length
let n = usize::try_from(unsafe { CFDataGetLength(d) }).unwrap_or(0);
let p = unsafe { CFDataGetBytePtr(d) };
if n > 6 && !p.is_null() {
return Some(unsafe { std::slice::from_raw_parts(p, n) }.to_vec());
Expand Down Expand Up @@ -417,7 +432,14 @@ fn build_avcc(sets: &[Vec<u8>], nal_len: i32) -> Option<Vec<u8>> {
let sps: Vec<&Vec<u8>> = sets.iter().filter(|s| s.first().is_some_and(|b| b & 0x1f == 7)).collect();
let pps: Vec<&Vec<u8>> = sets.iter().filter(|s| s.first().is_some_and(|b| b & 0x1f == 8)).collect();
let first = sps.first().filter(|s| s.len() >= 4)?;
if pps.is_empty() || !(1..=4).contains(&nal_len) {
// what the avcC's fields hold: 5 bits of SPS count, a byte of PPS count, 16-bit lengths (cut short, the
// record would describe other bytes than follow)
if pps.is_empty()
|| !(1..=4).contains(&nal_len)
|| sps.len() > 31
|| pps.len() > 255
|| sets.iter().any(|s| s.len() > usize::from(u16::MAX))
{
return None;
}
let mut v = vec![1, first[1], first[2], first[3], 0xFC | (nal_len as u8 - 1), 0xE0 | sps.len() as u8];
Expand Down Expand Up @@ -732,6 +754,9 @@ impl Drop for Decoder {
struct Shared {
state: Mutex<State>,
wake: Condvar,
/// H.264 frames sent and not yet taken ([`Session::next`]); the encoding thread waits while there are
/// [`MAX_AHEAD`]. Counted as sent, not as given to the encoder: a frame the encoder drops sends nothing
queued: std::sync::atomic::AtomicUsize,
}

#[derive(Default)]
Expand Down Expand Up @@ -771,7 +796,11 @@ impl Session {
/// Starts the thread; `kicks`: copies after each frame (0 unless measured otherwise). `info` is told once the
/// encoder is set up
pub fn start(w: u32, h: u32, qp: u8, kicks: usize, info: Option<tokio::sync::oneshot::Sender<Info>>) -> Self {
let shared = Arc::new(Shared { state: Mutex::default(), wake: Condvar::new() });
let shared = Arc::new(Shared {
state: Mutex::default(),
wake: Condvar::new(),
queued: std::sync::atomic::AtomicUsize::new(0),
});
let (tx, out) = mpsc::unbounded_channel();
let sh = shared.clone();
let spawned = std::thread::Builder::new().name("ictl-videotoolbox".into()).spawn(move || {
Expand All @@ -793,7 +822,15 @@ impl Session {

/// The next packet; `None` once the thread has ended. Cancel-safe
pub async fn next(&mut self) -> Option<Result<Packet, String>> {
self.out.recv().await
let p = self.out.recv().await;
if let Some(Ok(Packet::Frame { .. })) = &p {
// counted before it was sent ([`on_encoded`]): at least one
self.shared.queued.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
// under the lock: the thread checks the count with it held, so this wake-up can't come in between
let _held = self.shared.state.lock().unwrap_or_else(|p| p.into_inner());
self.shared.wake.notify_all();
}
p
}

pub fn written(&self) -> usize {
Expand All @@ -819,7 +856,7 @@ fn note(sh: &Shared, e: &str) {
}

fn run(
sh: &Shared,
sh: &Arc<Shared>,
w: u32,
h: u32,
qp: u8,
Expand All @@ -828,7 +865,8 @@ fn run(
info: Option<tokio::sync::oneshot::Sender<Info>>,
) -> Result<(), String> {
let (ew, eh) = even((w, h));
let (mut enc, pinned_qp) = h264(ew, eh, qp, Sink { tx, avcc: Mutex::default(), h264: true })?;
let sink = Sink { tx, avcc: Mutex::default(), h264: true, queued: Some(sh.clone()) };
let (mut enc, pinned_qp) = h264(ew, eh, qp, sink)?;
let mut dec = Decoder::new(w, h)?;
if let Some(i) = info {
let _ = i.send(Info { hardware: enc.hardware, pinned_qp });
Expand All @@ -840,7 +878,10 @@ fn run(
if s.stop {
return Ok(());
}
if let Some(j) = s.next.take() {
// the caller is behind: wait for it (the frame waiting meanwhile is replaced by newer ones)
if sh.queued.load(std::sync::atomic::Ordering::SeqCst) < MAX_AHEAD
&& let Some(j) = s.next.take()
{
break j;
}
s = sh.wake.wait(s).unwrap_or_else(|p| p.into_inner());
Expand All @@ -867,7 +908,8 @@ pub fn sample_jpeg(w: u32, h: u32, n: u32) -> Result<Vec<u8>, String> {
let (tx, mut rx) = mpsc::unbounded_channel();
let image = pattern(w, h, n)?;
let tune = |s: *mut c_void| set(s, unsafe { kVTCompressionPropertyKey_Quality }, number_f64(0.8).ptr(), "Quality");
let mut e = Encoder::new(w, h, kCMVideoCodecType_JPEG, tune, Sink { tx, avcc: Mutex::default(), h264: false })?;
let sink = Sink { tx, avcc: Mutex::default(), h264: false, queued: None };
let mut e = Encoder::new(w, h, kCMVideoCodecType_JPEG, tune, sink)?;
e.encode(image.ptr())?;
drop(e);
match rx.try_recv() {
Expand Down Expand Up @@ -963,6 +1005,11 @@ mod tests {
let a = build_avcc(&[sps, pps], 4).unwrap();
assert_eq!(a, [1, 0x64, 0x00, 0x28, 0xFF, 0xE1, 0, 5, 0x67, 0x64, 0x00, 0x28, 0xAC, 1, 0, 3, 0x68, 0xEE, 0x3C]);
assert!(build_avcc(&[vec![0x68, 1]], 4).is_none(), "no SPS");
// more than the record's fields hold
let sps = vec![0x67, 0x64, 0x00, 0x28];
assert!(build_avcc(&[[sps.clone(), vec![0; 70_000]].concat(), vec![0x68, 1]], 4).is_none(), "a set over 64 KB");
let many: Vec<Vec<u8>> = std::iter::repeat_n(sps, 32).chain([vec![0x68, 1]]).collect();
assert!(build_avcc(&many, 4).is_none(), "32 SPS");
}

#[test]
Expand Down
31 changes: 29 additions & 2 deletions crates/ictl-ax/src/dtx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,19 @@ pub async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> std::io::Result
read_frame_within(reader, MAX_MESSAGE_BYTES).await
}

/// Fragments one message may come in, at most: the phone's take a handful
const MAX_FRAGMENTS: usize = 4096;

async fn read_frame_within<R: AsyncRead + Unpin>(reader: &mut R, limit: usize) -> std::io::Result<Frame> {
let mut payload = Vec::new();
// headers read for this message: ones that carry nothing (a first fragment, an empty one) don't grow `payload`,
// so the size limit alone never ends a stream of them
let mut headers = 0usize;
loop {
headers += 1;
if headers > MAX_FRAGMENTS {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "DTX message in too many fragments"));
}
let mut h = [0u8; 32];
reader.read_exact(&mut h).await?;
let word = |i: usize| u32::from_le_bytes([h[i], h[i + 1], h[i + 2], h[i + 3]]);
Expand All @@ -77,7 +87,8 @@ async fn read_frame_within<R: AsyncRead + Unpin>(reader: &mut R, limit: usize) -
if read < len {
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "DTX message cut short"));
}
if fragment + 1 >= fragments {
// in u32: the last fragment of 65535 would overflow a u16
if u32::from(fragment) + 1 >= u32::from(fragments) {
return Ok(parse(word(16), word(20), word(24) as i32, word(28) == 1, &payload));
}
}
Expand Down Expand Up @@ -125,7 +136,7 @@ pub fn invocation(identifier: u32, selector: &str, args: Vec<Vec<u8>>, expects_r
pub fn reply(to: &Frame, value: Option<Value>) -> Vec<u8> {
let with_value = value.is_some();
let mut b = Message::new(
MessageHeader::new(0, 1, to.identifier, to.conversation + 1, to.channel, false),
MessageHeader::new(0, 1, to.identifier, to.conversation.wrapping_add(1), to.channel, false),
PayloadHeader::new(),
None,
value,
Expand Down Expand Up @@ -180,6 +191,22 @@ mod tests {
assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
}

/// Fragments that carry nothing, without end, are refused instead of read for ever; the last of 65535 fragments
/// ends its message (its index plus one overflowed a u16); a conversation at u32::MAX is answered
#[tokio::test]
async fn odd_fragment_counts_end_and_counters_dont_overflow() {
let empty: Vec<u8> =
(0..MAX_FRAGMENTS + 1).flat_map(|i| fragment((i % 100) as u16 + 1, u16::MAX, &[])).collect();
let e = read_frame_within(&mut &empty[..], 1 << 20).await.unwrap_err();
assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
let last = fragment(u16::MAX, u16::MAX, &[]);
assert!(read_frame_within(&mut &last[..], 100).await.is_ok(), "the last one ends it");
let mut asked = read_frame(&mut &invocation(4, "x", vec![], true)[..]).await.unwrap();
asked.conversation = u32::MAX;
let ack = read_frame(&mut &reply(&asked, None)[..]).await.unwrap();
assert_eq!(ack.conversation, 0, "wraps");
}

#[tokio::test]
async fn replies_answer_the_conversation() {
let asked = read_frame(&mut &invocation(4, "hostAPIVersion", vec![], true)[..]).await.unwrap();
Expand Down
30 changes: 28 additions & 2 deletions crates/ictl-ax/src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,17 +188,20 @@ const MAX_DEPTH: usize = 60;
/// Elements in reading order from `root`, depth first, each with the attributes `attrs` holds for it. Elements
/// without attributes are left out with their descendants
pub fn assemble(root: ObjectRef, attrs: &HashMap<ObjectRef, Obj>) -> Vec<Element> {
// an element is its process and ID: a reference to it may carry another `is_app` than the one its attributes came
// under (looked up as it was, its whole subtree was left out without a word); it keeps the attributes' own
let by_id: HashMap<(i64, u64), (&ObjectRef, &Obj)> = attrs.iter().map(|(k, v)| ((k.pid, k.id), (k, v))).collect();
let mut out = Vec::new();
let mut seen = HashSet::new();
let mut stack = vec![(root, None, 0usize)];
while let Some((o, parent, depth)) = stack.pop() {
// the same element can be listed under two parents
let key = (o.pid, o.id);
let Some(a) = attrs.get(&o) else { continue };
let Some(&(o, a)) = by_id.get(&key) else { continue };
if depth > MAX_DEPTH || !seen.insert(key) {
continue;
}
let (e, kids) = element(Some(o), a, parent, depth);
let (e, kids) = element(Some(*o), a, parent, depth);
out.push(e);
let idx = out.len() - 1;
for k in kids.into_iter().rev() {
Expand Down Expand Up @@ -310,6 +313,29 @@ mod tests {
assert_eq!(p.elements[2].identifier, "com.apple.settings.general");
}

/// A child referenced with another `is_app` than its attributes were stored under is still found, with its
/// subtree, and keeps the attributes' own reference
#[test]
fn a_child_is_found_whatever_its_reference_says_about_being_an_app() {
let r = |id, is_app| ObjectRef { pid: 10, id, is_app };
let mut stored = HashMap::new();
stored.insert(r(1, true), attrs(vec![(attr::LABEL, Obj::Str("app".into()))]));
stored.insert(r(2, true), attrs(vec![(attr::LABEL, Obj::Str("listed as an app".into()))]));
stored.insert(r(3, false), attrs(vec![(attr::LABEL, Obj::Str("its child".into()))]));
// the children as the parents name them: 2 without the app flag
let mut with_kids = |of: ObjectRef, kids: Vec<Obj>| {
if let Some(Obj::Dict(d)) = stored.get_mut(&of) {
d.push((Obj::Int(attr::CHILDREN), Obj::Array(kids)));
}
};
with_kids(r(1, true), vec![obj(10, 2)]);
with_kids(r(2, true), vec![obj(10, 3)]);
let els = assemble(r(1, true), &stored);
let labels: Vec<_> = els.iter().map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["app", "listed as an app", "its child"]);
assert_eq!(els[1].object, Some(r(2, true)), "the stored reference");
}

#[test]
fn a_value_kept_in_the_identifier_is_split_off() {
let (e, _) =
Expand Down
Loading
Loading