From 7d51e93928a768001ddce40c19b2ba47c2d91666 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:20:37 +0800 Subject: [PATCH 1/3] fix: protocol parser edges (review P1-4) - ax: the passcode field fallback needs words between the numbers ("6:00" isn't one); assemble looks attributes up by (pid, id); DTX fragments are counted and compared in u32, conversations wrap - webinspector: a session is closed and forgotten on every path; a write that stops half-way marks the connection broken (the daemon reopens it); the final piece counts toward the size limit; a refused Target wrapper ends the wait - WDA HTTP: chunk sizes can't overflow and must end in CRLF; trailers are read through; a head that doesn't end in 64 KB is refused - FLV: a header length past 1 KB is refused - vt.rs (macOS): CFData lengths checked, avcC field limits, at most 8 H.264 frames ahead of the caller Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + CHANGELOG.zh-CN.md | 5 + apps/iphone-control/src/video/flv.rs | 20 +++- apps/iphone-control/src/video/vt.rs | 64 ++++++++++-- crates/ictl-ax/src/dtx.rs | 31 +++++- crates/ictl-ax/src/tree.rs | 30 +++++- crates/ictl-ax/src/xml.rs | 33 +++++- crates/ictl-daemon/src/web.rs | 7 +- crates/ictl-wda/src/http.rs | 57 +++++++++- crates/ictl-webinspector/src/lib.rs | 151 +++++++++++++++++++++++---- docs/dev/regression-cases.md | 7 ++ 11 files changed, 362 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc2bf215..9455d95a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 0f9e8390..f1c8d479 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -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)。 diff --git a/apps/iphone-control/src/video/flv.rs b/apps/iphone-control/src/video/flv.rs index cd13ed01..2559e868 100644 --- a/apps/iphone-control/src/video/flv.rs +++ b/apps/iphone-control/src/video/flv.rs @@ -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); @@ -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); } @@ -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}"); + } } } diff --git a/apps/iphone-control/src/video/vt.rs b/apps/iphone-control/src/video/vt.rs index ec612cdc..9f4ba183 100644 --- a/apps/iphone-control/src/video/vt.rs +++ b/apps/iphone-control/src/video/vt.rs @@ -317,8 +317,15 @@ struct Sink { /// H.264: the `avcC` sent last, so a new one goes out before the frame that needs it. JPEG: unused avcc: Mutex>, h264: bool, + /// 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: Option>, } +/// 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 { @@ -349,7 +356,11 @@ 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 })); + if sink.tx.send(Ok(Packet::Frame { key, data })).is_ok() + && let Some(q) = &sink.queued + { + q.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } } unsafe fn sample_bytes(sample: *mut c_void) -> Option> { @@ -385,7 +396,8 @@ unsafe fn avcc_of(desc: *mut c_void) -> Option> { 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()); @@ -417,7 +429,14 @@ fn build_avcc(sets: &[Vec], nal_len: i32) -> Option> { let sps: Vec<&Vec> = sets.iter().filter(|s| s.first().is_some_and(|b| b & 0x1f == 7)).collect(); let pps: Vec<&Vec> = 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]; @@ -750,6 +769,8 @@ struct State { pub struct Session { shared: Arc, out: mpsc::UnboundedReceiver>, + /// [`Sink::queued`] + queued: Arc, } impl Drop for Session { @@ -773,9 +794,10 @@ impl Session { pub fn start(w: u32, h: u32, qp: u8, kicks: usize, info: Option>) -> Self { let shared = Arc::new(Shared { state: Mutex::default(), wake: Condvar::new() }); let (tx, out) = mpsc::unbounded_channel(); - let sh = shared.clone(); + let queued = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (sh, q) = (shared.clone(), queued.clone()); let spawned = std::thread::Builder::new().name("ictl-videotoolbox".into()).spawn(move || { - if let Err(e) = run(&sh, w, h, qp, kicks, tx.clone(), info) { + if let Err(e) = run(&sh, w, h, qp, kicks, tx.clone(), q, info) { note(&sh, &e); let _ = tx.send(Err(e)); } @@ -783,7 +805,7 @@ impl Session { if let Err(e) = spawned { note(&shared, &e.to_string()); } - Self { shared, out } + Self { shared, out, queued } } pub fn push(&self, jpeg: Arc>) { @@ -793,7 +815,18 @@ impl Session { /// The next packet; `None` once the thread has ended. Cancel-safe pub async fn next(&mut self) -> Option> { - self.out.recv().await + let p = self.out.recv().await; + if let Some(Ok(Packet::Frame { .. })) = &p { + let _ = self.queued.fetch_update( + std::sync::atomic::Ordering::SeqCst, + std::sync::atomic::Ordering::SeqCst, + |n| n.checked_sub(1), + ); + // 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 { @@ -825,10 +858,12 @@ fn run( qp: u8, kicks: usize, tx: mpsc::UnboundedSender>, + queued: Arc, info: Option>, ) -> 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(queued.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 }); @@ -840,7 +875,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 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()); @@ -867,7 +905,8 @@ pub fn sample_jpeg(w: u32, h: u32, n: u32) -> Result, 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() { @@ -963,6 +1002,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> = std::iter::repeat_n(sps, 32).chain([vec![0x68, 1]]).collect(); + assert!(build_avcc(&many, 4).is_none(), "32 SPS"); } #[test] diff --git a/crates/ictl-ax/src/dtx.rs b/crates/ictl-ax/src/dtx.rs index 11be47cd..e24d3869 100644 --- a/crates/ictl-ax/src/dtx.rs +++ b/crates/ictl-ax/src/dtx.rs @@ -52,9 +52,19 @@ pub async fn read_frame(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(reader: &mut R, limit: usize) -> std::io::Result { 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]]); @@ -77,7 +87,8 @@ async fn read_frame_within(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)); } } @@ -125,7 +136,7 @@ pub fn invocation(identifier: u32, selector: &str, args: Vec>, expects_r pub fn reply(to: &Frame, value: Option) -> Vec { 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, @@ -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 = + (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(); diff --git a/crates/ictl-ax/src/tree.rs b/crates/ictl-ax/src/tree.rs index d5233276..86e7f8f2 100644 --- a/crates/ictl-ax/src/tree.rs +++ b/crates/ictl-ax/src/tree.rs @@ -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) -> Vec { + // 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() { @@ -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| { + 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, _) = diff --git a/crates/ictl-ax/src/xml.rs b/crates/ictl-ax/src/xml.rs index 57c46e63..1abeff69 100644 --- a/crates/ictl-ax/src/xml.rs +++ b/crates/ictl-ax/src/xml.rs @@ -142,10 +142,11 @@ fn typed_kind(e: &Element) -> &'static str { /// The lock screen's passcode field. Its value holds two numbers, how many digits were entered and how many there are, /// in either order: 「共6位数,已输入2位」, "0 of 6 values entered", "0 valeur saisie sur 6", "0 von 6 Werten eingegeben". /// Known words in the label or the value say so; with none (a language not listed), a 4- or 6-digit total still does +/// when words stand between the numbers: a field showing a time, a fraction or a decimal ("6:00", "2/4", "1.6") is +/// no passcode field, and taking it for one made the screen read as locked fn is_passcode_field(e: &Element) -> bool { - let numbers: Vec = - e.value.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).filter_map(|n| n.parse().ok()).collect(); - let [a, b] = numbers[..] else { return false }; + let runs = digit_runs(&e.value); + let [(a, _), (b, sep)] = runs[..] else { return false }; let total = a.max(b); if total == 0 { return false; @@ -154,7 +155,27 @@ fn is_passcode_field(e: &Element) -> bool { let value = e.value.to_lowercase(); PASSCODE_LABEL_WORDS.iter().any(|w| label.contains(w)) || PASSCODE_VALUE_WORDS.iter().any(|w| value.contains(w)) - || matches!(total, 4 | 6) + || (matches!(total, 4 | 6) && sep.chars().any(char::is_alphabetic)) +} + +/// The numbers in `s`, each with the text before it (since the previous number) +fn digit_runs(s: &str) -> Vec<(u32, &str)> { + let mut out = Vec::new(); + let (mut after, mut i) = (0, 0); + let b = s.as_bytes(); + while i < b.len() { + if b[i].is_ascii_digit() { + let start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + out.push((s[start..i].parse().unwrap_or(u32::MAX), &s[after..start])); + after = i; + } else { + i += 1; + } + } + out } /// Words in the passcode field's label (lowercase): 「密码栏」, "Passcode field", "Champ de code" @@ -519,6 +540,10 @@ mod tests { assert_eq!(kind(&field("0 0")), "TextField"); assert_eq!(kind(&field("1 2 3")), "TextField"); assert_eq!(kind(&field("hello")), "TextField"); + // a time, a fraction, a decimal: punctuation between the numbers, no words + for v in ["6:00", "2/4", "1.6", "4-6", "06:04"] { + assert_eq!(kind(&field(v)), "TextField", "{v}"); + } // untyped, a text field by its traits let untyped = Element { traits: trait_bit::TEXT_FIELD, value: "共6位数,已输入1位".into(), ..Default::default() }; diff --git a/crates/ictl-daemon/src/web.rs b/crates/ictl-daemon/src/web.rs index 59a0a3bc..85989181 100644 --- a/crates/ictl-daemon/src/web.rs +++ b/crates/ictl-daemon/src/web.rs @@ -108,9 +108,14 @@ impl Daemon { conn.used = Instant::now(); // not retried on a new connection: the script may already have run let r = match conn.w.evaluate(page, expression, timeout).await { + // the value came, but closing the session couldn't be written: the next request gets a new connection + Ok(r) if conn.w.is_broken() => { + *slot = None; + r + } Ok(r) => r, Err(e) => { - if breaks_connection(&e) { + if breaks_connection(&e) || conn.w.is_broken() { *slot = None; } return Err(page_error(&e).into()); diff --git a/crates/ictl-wda/src/http.rs b/crates/ictl-wda/src/http.rs index 783c0485..60f0e44f 100644 --- a/crates/ictl-wda/src/http.rs +++ b/crates/ictl-wda/src/http.rs @@ -156,6 +156,14 @@ pub(crate) async fn read_response( loop { if head.is_none() { head = parse_head(&buf); + // no end of the head in its first 64 KB: it isn't coming (and looking again after every read would scan + // those 64 KB over and over up to the limit) + if head.is_none() && buf.len() > MAX_HEAD { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + ictl_l10n::tr!("WDA 的响应头超过 64 KB", "WDA's response head is over 64 KB"), + )); + } if let Some((split, Framing::Length(n))) = head { if split.saturating_add(n) > limit { return Err(too_large()); @@ -206,16 +214,19 @@ impl Framing { fn complete(self, body: &[u8]) -> bool { match self { Self::Length(n) => body.len() >= n, - // 先看结尾是不是结束块,是了才完整解一遍(避免每读 64KB 就把整个正文解一遍) - Self::Chunked => body.ends_with(b"0\r\n\r\n") && dechunk(body).is_some(), + // 先看结尾是不是空行(结束块或 trailer 之后),是了才完整解一遍(避免每读 64KB 就把整个正文解一遍) + Self::Chunked => body.ends_with(b"\r\n\r\n") && dechunk(body).is_some(), Self::UntilEof => false, } } } +/// 响应头最长这么多(WDA 的头不到 1 KB) +const MAX_HEAD: usize = 64 * 1024; + /// 头部收齐了就返回 (正文起点, 定长方式)。头部很短,只在前 64KB 里找结束标记 fn parse_head(raw: &[u8]) -> Option<(usize, Framing)> { - let window = &raw[..raw.len().min(64 * 1024)]; + let window = &raw[..raw.len().min(MAX_HEAD)]; let split = window.windows(4).position(|w| w == b"\r\n\r\n")?; let head = String::from_utf8_lossy(&raw[..split]).to_ascii_lowercase(); let mut framing = Framing::UntilEof; @@ -277,18 +288,31 @@ pub(crate) fn parse_response(raw: impl Into>) -> std::io::Result<(u16, V } } +/// The chunked body's data; `None` until it is whole: each chunk followed by its CRLF, the last one (size 0) by any +/// trailers and the empty line that ends them. A size too large for memory (`size + 2` overflowed) isn't one fn dechunk(mut body: &[u8]) -> Option> { let mut out = Vec::new(); loop { let line_end = body.windows(2).position(|w| w == b"\r\n")?; let size_str = std::str::from_utf8(&body[..line_end]).ok()?; + // `size;extension=value` let size = usize::from_str_radix(size_str.split(';').next()?.trim(), 16).ok()?; body = &body[line_end + 2..]; if size == 0 { - return Some(out); + // trailers, each a line, until an empty one + loop { + let end = body.windows(2).position(|w| w == b"\r\n")?; + if end == 0 { + return Some(out); + } + body = &body[end + 2..]; + } } out.extend_from_slice(body.get(..size)?); - body = body.get(size + 2..)?; + if body.get(size..size.checked_add(2)?)? != b"\r\n" { + return None; + } + body = &body[size + 2..]; } } @@ -350,6 +374,29 @@ mod tests { assert_eq!(parse_response(raw).unwrap(), (200, b"hello".to_vec())); } + /// Chunk extensions and trailers are read through; a size that would overflow, or a chunk not followed by its + /// CRLF, isn't a body; the end is only taken once the trailers' empty line came + #[test] + fn chunked_edges() { + assert_eq!(dechunk(b"4;ext=1\r\nWiki\r\n0\r\nX-Checksum: 1\r\n\r\n").unwrap(), b"Wiki"); + assert_eq!(dechunk(b"0\r\n\r\n").unwrap(), b""); + assert!(dechunk(b"0\r\nX-Checksum: 1\r\n").is_none(), "the trailers' end not there yet"); + assert!(dechunk(b"ffffffffffffffff\r\nabc").is_none(), "no overflow, no panic"); + assert!(dechunk(b"4\r\nWikiXX0\r\n\r\n").is_none(), "a chunk runs on past its size"); + let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nok\r\n0\r\nX-T: 1\r\n\r\n"; + assert!(response_complete(raw), "complete with a trailer"); + assert_eq!(parse_response(raw.to_vec()).unwrap(), (200, b"ok".to_vec())); + } + + /// A head that doesn't end within 64 KB is refused at once instead of scanned again after every read + #[tokio::test] + async fn an_endless_head_is_refused() { + let mut endless = b"HTTP/1.1 200 OK\r\n".to_vec(); + endless.extend(std::iter::repeat_n(b'x', 200 * 1024)); + let e = read_response(&mut &endless[..], MAX_RESPONSE_BYTES).await.unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } + #[test] fn parses_chunked_body() { let raw = b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n"; diff --git a/crates/ictl-webinspector/src/lib.rs b/crates/ictl-webinspector/src/lib.rs index 788380ff..ed40a865 100644 --- a/crates/ictl-webinspector/src/lib.rs +++ b/crates/ictl-webinspector/src/lib.rs @@ -98,16 +98,13 @@ pub struct WebInspector { /// Pieces of a message the phone split up (`WIRPartialMessageKey`) partial: Vec, reported: bool, + /// A write stopped half-way (timed out or failed): the stream is out of step, nothing more is sent on it + broken: bool, } -impl IdeviceService for WebInspector { - fn service_name() -> std::borrow::Cow<'static, str> { - "com.apple.webinspector".into() - } - - async fn from_stream(idevice: Idevice) -> std::result::Result { - let socket = idevice.get_socket().ok_or(IdeviceError::NoEstablishedConnection)?; - Ok(Self { +impl WebInspector { + fn with_socket(socket: Box) -> Self { + Self { socket, connection: uuid::Uuid::new_v4().to_string().to_uppercase(), apps: BTreeMap::new(), @@ -117,7 +114,19 @@ impl IdeviceService for WebInspector { rbuf: Vec::new(), partial: Vec::new(), reported: false, - }) + broken: false, + } + } +} + +impl IdeviceService for WebInspector { + fn service_name() -> std::borrow::Cow<'static, str> { + "com.apple.webinspector".into() + } + + async fn from_stream(idevice: Idevice) -> std::result::Result { + let socket = idevice.get_socket().ok_or(IdeviceError::NoEstablishedConnection)?; + Ok(Self::with_socket(socket)) } fn get_socket(&mut self) -> Option<&mut Box> { @@ -168,18 +177,36 @@ impl WebInspector { Ok((self.apps.values().cloned().collect(), pages)) } + /// Whether a write stopped half-way: the stream is out of step, and the connection should be opened again (a + /// value may still have come back from the call that found it so) + pub fn is_broken(&self) -> bool { + self.broken + } + /// Evaluates `expression` in a page and returns its value. A promise is awaited pub async fn evaluate(&mut self, page: &Page, expression: &str, timeout: Duration) -> Result { let deadline = Instant::now() + timeout; let sender = uuid::Uuid::new_v4().to_string().to_uppercase(); self.open_sessions.insert(sender.clone()); + let result = self.evaluate_in(page, &sender, expression, deadline).await; + // closed and forgotten whichever way it went (a setup that failed left both behind, the session's messages + // kept piling up); a close that can't be written marks the connection broken ([`Self::is_broken`]) + let mut close = self.page_args(page); + close.insert("WIRSenderKey".into(), sender.clone().into()); + let _ = self.send("_rpc_forwardDidClose:", close).await; + self.data.remove(&sender); + self.open_sessions.remove(&sender); + result + } + + async fn evaluate_in(&mut self, page: &Page, sender: &str, expression: &str, deadline: Instant) -> Result { let mut setup = self.page_args(page); - setup.insert("WIRSenderKey".into(), sender.clone().into()); + setup.insert("WIRSenderKey".into(), sender.to_owned().into()); setup.insert("WIRMessageDataTypeChunkSupportedKey".into(), 0.into()); setup.insert("WIRAutomaticallyPause".into(), false.into()); self.send("_rpc_forwardSocketSetup:", setup).await?; - let mut session = Session { sender, target: None, next_id: 1 }; + let mut session = Session { sender: sender.to_owned(), target: None, next_id: 1 }; // current WebKit announces the page target first; older versions take commands directly let probe = (Instant::now() + Duration::from_millis(1500)).min(deadline); while session.target.is_none() { @@ -194,13 +221,7 @@ impl WebInspector { } } - let result = self.run_eval(page, &mut session, expression, deadline).await; - let mut close = self.page_args(page); - close.insert("WIRSenderKey".into(), session.sender.clone().into()); - let _ = self.send("_rpc_forwardDidClose:", close).await; - self.data.remove(&session.sender); - self.open_sessions.remove(&session.sender); - result + self.run_eval(page, &mut session, expression, deadline).await } async fn run_eval(&mut self, page: &Page, s: &mut Session, expression: &str, deadline: Instant) -> Result { @@ -248,9 +269,10 @@ impl WebInspector { a.insert("WIRSenderKey".into(), s.sender.clone().into()); a.insert("WIRSocketDataKey".into(), Value::Data(msg.to_string().into_bytes())); self.send("_rpc_forwardSocketData:", a).await?; + let outer = s.target.as_ref().map(|_| id + 1_000_000); loop { for m in self.take_data(&s.sender) { - if let Some(r) = response_for(&m, id) { + if let Some(r) = answer_to(&m, id, outer) { return r; } } @@ -272,6 +294,13 @@ impl WebInspector { } async fn send(&mut self, selector: &str, mut args: Dictionary) -> Result<()> { + if self.broken { + return Err(std::io::Error::new( + std::io::ErrorKind::BrokenPipe, + "the Web Inspector connection is out of step", + ) + .into()); + } args.insert("WIRConnectionIdentifierKey".into(), self.connection.clone().into()); let mut msg = Dictionary::new(); msg.insert("__selector".into(), selector.into()); @@ -284,10 +313,15 @@ impl WebInspector { self.socket.write_all(&framed).await?; self.socket.flush().await }; - // a write cut off half-way leaves the stream out of step: report it as a broken connection (Io) - tokio::time::timeout(SEND_TIMEOUT, write).await.map_err(|_| { + // a write cut off half-way leaves the stream out of step: report it as a broken connection (Io), and send + // nothing more on it + let r = tokio::time::timeout(SEND_TIMEOUT, write).await.map_err(|_| { std::io::Error::new(std::io::ErrorKind::TimedOut, "the phone stopped reading Web Inspector messages") - })??; + }); + if !matches!(r, Ok(Ok(()))) { + self.broken = true; + } + r??; Ok(()) } @@ -398,6 +432,11 @@ fn unchunk_into(partial: &mut Vec, msg: Dictionary) -> Result MAX_MESSAGE { + partial.clear(); + return Err(Error::Protocol(format!("split message over {MAX_MESSAGE} bytes"))); + } partial.extend_from_slice(last); let whole = std::mem::take(partial); return Ok(Some(plist::from_bytes(&whole)?)); @@ -452,6 +491,19 @@ fn parse_listing(app_id: &str, arg: &Dictionary) -> Vec { } /// The result of command `id` in an inspector message, unwrapping `Target.dispatchMessageFromTarget` +/// The answer to command `id` in `m`, if it is one; or the error of `outer`, the `Target.sendMessageToTarget` that +/// carried it: when that is refused (the target went away), no answer to the command comes, and waiting for one ran +/// to the timeout +fn answer_to(m: &serde_json::Value, id: u64, outer: Option) -> Option> { + if let Some(r) = response_for(m, id) { + return Some(r); + } + match outer.and_then(|o| response_for(m, o)) { + Some(Err(e)) => Some(Err(e)), + _ => None, + } +} + fn response_for(m: &serde_json::Value, id: u64) -> Option> { let inner; let m = if m["method"] == "Target.dispatchMessageFromTarget" { @@ -520,6 +572,61 @@ mod tests { assert!(unchunk_into(&mut partial, part(20)).unwrap().is_none(), "a new message can start"); } + /// The last piece counts toward the limit too + #[test] + fn a_huge_last_piece_is_refused() { + let last = |n: usize| { + let mut a = Dictionary::new(); + a.insert("WIRFinalMessageKey".into(), Value::Data(vec![0u8; n])); + let mut d = Dictionary::new(); + d.insert("__argument".into(), Value::Dictionary(a)); + d + }; + let mut partial = vec![0u8; MAX_MESSAGE - 10]; + assert!(unchunk_into(&mut partial, last(20)).is_err()); + assert!(partial.is_empty()); + } + + /// A refused wrapper ends the wait at once; its plain acknowledgement doesn't; the command's own answer is taken + #[test] + fn a_refused_wrapper_ends_the_wait() { + let inner = |id: u64| { + json!({"method": "Target.dispatchMessageFromTarget", + "params": {"message": json!({"id": id, "result": {"v": 1}}).to_string()}}) + }; + assert!(matches!(answer_to(&inner(3), 3, Some(1_000_003)), Some(Ok(_)))); + let refused = json!({"id": 1_000_003, "error": {"message": "Missing target"}}); + assert!( + matches!(answer_to(&refused, 3, Some(1_000_003)), Some(Err(Error::Command(m))) if m == "Missing target") + ); + let acked = json!({"id": 1_000_003, "result": {}}); + assert!(answer_to(&acked, 3, Some(1_000_003)).is_none(), "the wrapper went through: wait for the answer"); + assert!(answer_to(&refused, 3, None).is_none(), "no wrapper: not ours"); + } + + /// A failed write ends the evaluation, leaves no session behind and marks the connection broken: nothing more is + /// written on it + #[tokio::test] + async fn a_failed_write_leaves_nothing_behind() { + let (ours, theirs) = tokio::io::duplex(64); + drop(theirs); + let mut w = WebInspector::with_socket(Box::new(ours)); + let page = Page { + app_id: "PID:1".into(), + id: 1, + kind: "WebPage".into(), + title: String::new(), + url: String::new(), + in_use: false, + }; + assert!(w.evaluate(&page, "1", Duration::from_secs(1)).await.is_err()); + assert!(w.is_broken()); + assert!(w.open_sessions.is_empty() && w.data.is_empty()); + let t0 = Instant::now(); + assert!(w.evaluate(&page, "1", Duration::from_secs(1)).await.is_err()); + assert!(t0.elapsed() < Duration::from_millis(100), "refused at once"); + } + trait TapPart { fn tap_part(self, n: usize) -> Dictionary; } diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index c4a0a871..58800966 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -227,3 +227,10 @@ | 221 | 装服务:路径里的空格让 systemd 的 `ExecStart` 失败,`$`、反引号、`%` 会被 systemd 或 launchd 的 shell 当成自己的语法;升级暂停 viewer 服务后用 `enable --now` 恢复,用户关掉的开机自启又被打开;自动更新任务配置失败时写了一半的 unit、launcher 留着 | 允许空格(`ExecStart` 加引号),拒绝 `$`、反引号、`%`、引号、反斜杠、控制字符;恢复用 `start_managed`(只 start);配置失败后按 Manual 再走一遍,删掉自己的那些文件:卸载任务(`systemctl disable --now`、`launchctl bootout`)失败也照样删,最后再报错 | 单测 `service_program_paths`、`a_failed_job_setup_leaves_nothing_behind`(假的 systemctl/launchctl 启用和卸载都失败;改回旧代码会失败)、原有的 `the_viewer_service_runs_the_viewer_with_this_path` | | 222 | 设置文件里有 `IPHONE_CONTROL_URL` 时,控制台给 agent 起的 `mcp --task-token-file` 读进这个变量,和参数冲突,MCP 服务起不来;`tokens/` 里上次留下的令牌文件可能和新文件撞名 | `mcp` 子命令带 `--task-token-file`(或 `--task-token-file=`)时,载入设置文件跳过 `IPHONE_CONTROL_URL`、`IPHONE_CONTROL_CA`(从原始参数里认,跳过根选项,不要求 UTF-8,别的命令里的同名文字不算);控制台启动时清掉 `tokens/` 里残留的令牌文件,只清进程号是自己或已不存在的(同一用户别的 viewer 正在用的留着) | 单测 `the_token_file_option_is_found_only_for_mcp`、`only_tokens_of_viewers_that_are_gone_are_cleared` + 真机(设置文件写了 URL,控制台的任务照常完成) | | 223 | 只读登录:画面上按下照样发 `/api/touch`(服务端拒绝,每次弹错误),悬停圆点照常显示,滚轮也会去滑手机 | 只读时手指、预热、滚轮都不发,提示「只读登录」(3 秒内不重复),不显示悬停圆点 | 页面测试 `a read-only page sends no finger and says so once in a while` | +| 224 | 原生控制(ax `xml.rs`):没有已知词的输入框只看两个数字里大的是不是 4 或 6,「6:00」「2/4」「1.6」都被当成锁屏密码栏,再被 `cover_sheet` 当成锁屏 | 兜底时要求两个数字之间有文字(各语言的密码栏都是一句话,时间、分数、小数只有标点) | 单测 `the_lock_screen_passcode_field_reads_as_secure`(加了 6:00、2/4、1.6、4-6、06:04) | +| 225 | `tree::assemble` 按整个 `ObjectRef`(含 `is_app`)查属性:子元素的引用和存属性时的 `is_app` 不一致就查不到,连同子树一起悄悄丢掉 | 按 (pid, id) 查,用存属性时的那个引用 | 单测 `a_child_is_found_whatever_its_reference_says_about_being_an_app` | +| 226 | DTX:`fragment + 1` 是 u16 加法(最后一片是 65535 时溢出),只有头的分片可以无穷无尽,`conversation + 1` 也会溢出 | 比较用 u32;一条消息最多 4096 个分片头;`wrapping_add` | 单测 `odd_fragment_counts_end_and_counters_dont_overflow` | +| 227 | Web Inspector:关会话的写超时被 `let _ =` 吞掉,错位的连接接着用;建会话失败提前返回,`open_sessions`、`data` 留着;`WIRFinalMessageKey` 不算进 64 MB 上限;外层 `Target.sendMessageToTarget` 报错被忽略,等到超时 | 不管哪条路都关会话、清掉;写不完标记 `broken`,之后不再写,守护进程看到就换连接(取到值也换);最后一块也算上限;外层报错立即返回 | 单测 `a_failed_write_leaves_nothing_behind`、`a_refused_wrapper_ends_the_wait`、`a_huge_last_piece_is_refused` + 真机(Safari 页面 `web_eval` 照常) | +| 228 | WDA HTTP:chunked 的 `size + 2` 会溢出,块后的 CRLF 不查;结束块后有 trailer 就永远不算完整(WDA 不关连接,等到超时);64 KB 内找不到头结束就每读一次重扫一遍 | `checked_add`、校验 CRLF;读到 trailer 后的空行才算完;头超过 64 KB 直接报错 | 单测 `chunked_edges`、`an_endless_head_is_refused` + 真机(iPad WDA run.py) | +| 229 | FLV 头长度 4 字节照单全收:一个畸形头会让解析器攒到 4 GB 等它 | 只收 9~1024 | 单测 `other_input_is_an_error`(加了头长度) | +| 230 | macOS VideoToolbox:`CFDataGetLength` 负数转成巨大长度去 `from_raw_parts`;`build_avcc` 的个数、长度截断写进字段;编码线程到调用方是无界通道,页面取得慢就一直攒 | 长度用 `usize::try_from`;超过字段能装的就不造 `avcC`;已发出未取走的 H.264 帧到 8 个,编码线程就等(按实际发出的计,编码器丢的帧不算,不会永远等) | 单测 `avcc_from_parameter_sets`(加了超限);CI 的 macOS 编译和测试(本机没有 macOS) | From 523e08c31430541bfb5e4e85245245f82845d36c Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:35:31 +0800 Subject: [PATCH 2/3] fix(vt): keep the frame count in Shared; no fetch_update (deprecated in 1.99, try_update not in 1.89) Co-Authored-By: Claude Opus 5.5 --- apps/iphone-control/src/video/vt.rs | 47 +++++++++++++++-------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/apps/iphone-control/src/video/vt.rs b/apps/iphone-control/src/video/vt.rs index 9f4ba183..6cfdc421 100644 --- a/apps/iphone-control/src/video/vt.rs +++ b/apps/iphone-control/src/video/vt.rs @@ -317,9 +317,8 @@ struct Sink { /// H.264: the `avcC` sent last, so a new one goes out before the frame that needs it. JPEG: unused avcc: Mutex>, h264: bool, - /// 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: Option>, + /// The session counting H.264 frames sent and not yet taken ([`Shared::queued`]); none for a JPEG + queued: Option>, } /// H.264 frames the encoding thread may have sent ahead of the caller: a caller that falls behind (a slow page) no @@ -356,10 +355,14 @@ extern "C" fn on_encoded(refcon: *mut c_void, _frame: *mut c_void, status: OSSta let _ = sink.tx.send(Ok(Packet::Config(avcc))); } } - if sink.tx.send(Ok(Packet::Frame { key, data })).is_ok() - && let Some(q) = &sink.queued + // 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 { - q.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + s.queued.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); } } @@ -751,6 +754,9 @@ impl Drop for Decoder { struct Shared { state: Mutex, 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)] @@ -769,8 +775,6 @@ struct State { pub struct Session { shared: Arc, out: mpsc::UnboundedReceiver>, - /// [`Sink::queued`] - queued: Arc, } impl Drop for Session { @@ -792,12 +796,15 @@ 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>) -> 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 queued = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let (sh, q) = (shared.clone(), queued.clone()); + let sh = shared.clone(); let spawned = std::thread::Builder::new().name("ictl-videotoolbox".into()).spawn(move || { - if let Err(e) = run(&sh, w, h, qp, kicks, tx.clone(), q, info) { + if let Err(e) = run(&sh, w, h, qp, kicks, tx.clone(), info) { note(&sh, &e); let _ = tx.send(Err(e)); } @@ -805,7 +812,7 @@ impl Session { if let Err(e) = spawned { note(&shared, &e.to_string()); } - Self { shared, out, queued } + Self { shared, out } } pub fn push(&self, jpeg: Arc>) { @@ -817,11 +824,8 @@ impl Session { pub async fn next(&mut self) -> Option> { let p = self.out.recv().await; if let Some(Ok(Packet::Frame { .. })) = &p { - let _ = self.queued.fetch_update( - std::sync::atomic::Ordering::SeqCst, - std::sync::atomic::Ordering::SeqCst, - |n| n.checked_sub(1), - ); + // 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(); @@ -852,17 +856,16 @@ fn note(sh: &Shared, e: &str) { } fn run( - sh: &Shared, + sh: &Arc, w: u32, h: u32, qp: u8, kicks: usize, tx: mpsc::UnboundedSender>, - queued: Arc, info: Option>, ) -> Result<(), String> { let (ew, eh) = even((w, h)); - let sink = Sink { tx, avcc: Mutex::default(), h264: true, queued: Some(queued.clone()) }; + 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 { @@ -876,7 +879,7 @@ fn run( return Ok(()); } // the caller is behind: wait for it (the frame waiting meanwhile is replaced by newer ones) - if queued.load(std::sync::atomic::Ordering::SeqCst) < MAX_AHEAD + if sh.queued.load(std::sync::atomic::Ordering::SeqCst) < MAX_AHEAD && let Some(j) = s.next.take() { break j; From 5d065edeb771e123a20933c2d285c79a3037ce57 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:21:18 +0800 Subject: [PATCH 3/3] fix: review nits of P1-4 (WDA head limit at 64 KB, a stray doc line) - A head not ended within 64 KB is refused once 64 KB are read: parse_head looks no further, so more bytes can't complete it. - The doc line of `response_for` had ended up above `answer_to`'s. Co-Authored-By: Claude Opus 5.5 --- crates/ictl-wda/src/http.rs | 4 ++-- crates/ictl-webinspector/src/lib.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ictl-wda/src/http.rs b/crates/ictl-wda/src/http.rs index 60f0e44f..282730c4 100644 --- a/crates/ictl-wda/src/http.rs +++ b/crates/ictl-wda/src/http.rs @@ -157,8 +157,8 @@ pub(crate) async fn read_response( if head.is_none() { head = parse_head(&buf); // no end of the head in its first 64 KB: it isn't coming (and looking again after every read would scan - // those 64 KB over and over up to the limit) - if head.is_none() && buf.len() > MAX_HEAD { + // those 64 KB over and over up to the limit). [`parse_head`] looks no further, so 64 KB read is enough + if head.is_none() && buf.len() >= MAX_HEAD { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, ictl_l10n::tr!("WDA 的响应头超过 64 KB", "WDA's response head is over 64 KB"), diff --git a/crates/ictl-webinspector/src/lib.rs b/crates/ictl-webinspector/src/lib.rs index ed40a865..548edcb8 100644 --- a/crates/ictl-webinspector/src/lib.rs +++ b/crates/ictl-webinspector/src/lib.rs @@ -490,7 +490,6 @@ fn parse_listing(app_id: &str, arg: &Dictionary) -> Vec { pages } -/// The result of command `id` in an inspector message, unwrapping `Target.dispatchMessageFromTarget` /// The answer to command `id` in `m`, if it is one; or the error of `outer`, the `Target.sendMessageToTarget` that /// carried it: when that is refused (the target went away), no answer to the command comes, and waiting for one ran /// to the timeout @@ -504,6 +503,7 @@ fn answer_to(m: &serde_json::Value, id: u64, outer: Option) -> Option Option> { let inner; let m = if m["method"] == "Target.dispatchMessageFromTarget" {