diff --git a/CHANGELOG.md b/CHANGELOG.md index 7596db05..1de28b9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 19cf2d16..d7663db2 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -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 diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs index ba39b7b0..926e697d 100644 --- a/apps/iphone-control/src/video/mod.rs +++ b/apps/iphone-control/src/video/mod.rs @@ -399,13 +399,15 @@ pub async fn serve_mjpeg( let (tx, rx) = watch::channel::>>>(None); let reader = tokio::spawn(async move { let mut f = mjpeg::Frames::new(src); - let mut last: Option> = None; + let mut last: Option>> = 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; } } diff --git a/apps/iphone-control/src/viewer/auth.rs b/apps/iphone-control/src/viewer/auth.rs index ab096e4f..b638f940 100644 --- a/apps/iphone-control/src/viewer/auth.rs +++ b/apps/iphone-control/src/viewer/auth.rs @@ -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 @@ -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 @@ -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, 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 diff --git a/crates/ictl-ax/src/dtx.rs b/crates/ictl-ax/src/dtx.rs index 2c6d5856..11be47cd 100644 --- a/crates/ictl-ax/src/dtx.rs +++ b/crates/ictl-ax/src/dtx.rs @@ -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(reader: &mut R) -> std::io::Result { + read_frame_within(reader, MAX_MESSAGE_BYTES).await +} + +async fn read_frame_within(reader: &mut R, limit: usize) -> std::io::Result { let mut payload = Vec::new(); loop { let mut h = [0u8; 32]; @@ -61,12 +68,15 @@ pub async fn read_frame(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)); } @@ -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 { + 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(); diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 9dd1b5f9..8530f8ab 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -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 => {} } diff --git a/crates/ictl-daemon/src/devtools.rs b/crates/ictl-daemon/src/devtools.rs index 1fd57e9c..e20762f7 100644 --- a/crates/ictl-daemon/src/devtools.rs +++ b/crates/ictl-daemon/src/devtools.rs @@ -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()); @@ -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; @@ -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; } } @@ -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)); diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs index 6564cb2c..1cd8b56f 100644 --- a/crates/ictl-daemon/src/supervise.rs +++ b/crates/ictl-daemon/src/supervise.rs @@ -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()); } @@ -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); @@ -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() } @@ -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 }); + } +} diff --git a/crates/ictl-daemon/src/tools/mod.rs b/crates/ictl-daemon/src/tools/mod.rs index 6fe7beab..5532c1b8 100644 --- a/crates/ictl-daemon/src/tools/mod.rs +++ b/crates/ictl-daemon/src/tools/mod.rs @@ -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" }, ) } }; diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs index 99eb84d2..b9befe20 100644 --- a/crates/ictl-daemon/src/tools/native.rs +++ b/crates/ictl-daemon/src/tools/native.rs @@ -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.» diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rs index 7a15afc1..f3fc43ac 100644 --- a/crates/ictl-device/src/hid.rs +++ b/crates/ictl-device/src/hid.rs @@ -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 } diff --git a/crates/ictl-device/src/media.rs b/crates/ictl-device/src/media.rs index 0c1e6e3b..657a3492 100644 --- a/crates/ictl-device/src/media.rs +++ b/crates/ictl-device/src/media.rs @@ -125,16 +125,23 @@ fn receive( media_ssrc = p.ssrc; first_seq.get_or_insert(p.sequence_number); last_seq = p.sequence_number; + // 没人订阅时只记参数集,不拼帧(新订阅者会要关键帧,参数集补在它前面) + let watched = frames.receiver_count() > 0; // 新的时间戳开始了新的一帧:上一帧要是还没随 marker 结束,先把它发出去 - if let Some(f) = asm.new_timestamp(p.timestamp) { + if let Some(Some(f)) = asm.new_timestamp(p.timestamp, watched) { let _ = frames.send(f); } depack.push(p.sequence_number, p.timestamp, p.payload); asm.push(&depack.take_output()); - if p.marker && let Some(f) = asm.finish() { + if p.marker && let Some(f) = asm.complete(watched) { received = received.wrapping_add(1); let _ = video.send_to(device_port, build_frame_ack(our_ssrc, p.timestamp)).await; - let _ = frames.send(f); + if let Some(f) = f { + let _ = frames.send(f); + } + } + if asm.take_dropped() { + keyframe_wanted = true; } } r = keyframe.recv() => { @@ -167,6 +174,9 @@ fn receive( }) } +/// 一帧最多这么大。手机的关键帧几十 KB 到一两 MB;超过就是丢了 marker 又一直是同一个时间戳之类的坏数据 +const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024; + /// 把解包器吐出的 Annex-B 攒成一帧:帧以 RTP marker 结束(或下一帧的时间戳开始)。记下最近的参数集,补到没带它们 /// 的关键帧前面 #[derive(Default)] @@ -175,31 +185,63 @@ struct Assembler { timestamp: Option, /// 最近一次见到的 VPS、SPS、PPS(各自带起始码) params: [Option>; 3], + /// 这一帧超过了 [`MAX_FRAME_BYTES`]:丢掉,到下一帧再收 + overflow: bool, + /// 丢过超大的帧,还没告诉调用方(它要请手机补一个关键帧) + dropped: bool, } impl Assembler { - fn new_timestamp(&mut self, ts: u32) -> Option { - let done = if self.timestamp.is_some_and(|t| t != ts) { self.finish() } else { None }; + /// 新的时间戳开始了新的一帧:上一帧要是还没随 marker 结束,就在这里结束(返回值同 [`Self::complete`]) + fn new_timestamp(&mut self, ts: u32, watched: bool) -> Option> { + let done = if self.timestamp.is_some_and(|t| t != ts) { self.complete(watched) } else { None }; self.timestamp = Some(ts); done } fn push(&mut self, annexb: &[u8]) { + if self.overflow { + return; + } + if self.current.len() + annexb.len() > MAX_FRAME_BYTES { + self.current.clear(); + self.overflow = true; + self.dropped = true; + return; + } self.current.extend_from_slice(annexb); } - /// 攒好的一帧;没有画面数据(只有参数集、AUD)时不算一帧,参数集留下 + /// 丢过超大的帧吗(问一次就清掉) + fn take_dropped(&mut self) -> bool { + std::mem::take(&mut self.dropped) + } + + /// 攒好的一帧([`Self::complete`],有人在看) + #[cfg(test)] fn finish(&mut self) -> Option { - let data = std::mem::take(&mut self.current); - let nals = nal_units(&data); + self.complete(true).flatten() + } + + /// 结束攒着的一帧。`None`:没有画面数据(只有参数集、AUD,或超大被丢了),参数集留下;`Some(None)`:是一帧, + /// 但没人看(`watched` 为 false),只记下参数集、不复制不分配(Agent 操作时媒体流开着,常常没人看); + /// `Some(Some(帧))`:要发给订阅者的一帧 + fn complete(&mut self, watched: bool) -> Option> { + if std::mem::take(&mut self.overflow) { + self.current.clear(); + return None; + } let mut key = false; let mut has = [false; 3]; let mut vcl = false; - for n in &nals { + for n in nal_units(&self.current) { match nal_type(n) { Some(t @ 32..=34) => { has[usize::from(t - 32)] = true; - self.params[usize::from(t - 32)] = Some(n.to_vec()); + let slot = &mut self.params[usize::from(t - 32)]; + if slot.as_deref() != Some(n) { + *slot = Some(n.to_vec()); + } } Some(t) if t <= 31 => { vcl = true; @@ -208,17 +250,25 @@ impl Assembler { _ => {} } } - if !vcl { - return None; + if !vcl || !watched { + // 留着缓冲区的容量,下一帧接着用 + self.current.clear(); + return vcl.then_some(None); } + let data = std::mem::take(&mut self.current); let data = if key && has != [true; 3] && self.params.iter().all(Option::is_some) { let mut v: Vec = self.params.iter().flatten().flatten().copied().collect(); - v.extend(nals.iter().filter(|n| !matches!(nal_type(n), Some(32..=34))).flat_map(|n| n.iter().copied())); + v.extend( + nal_units(&data) + .into_iter() + .filter(|n| !matches!(nal_type(n), Some(32..=34))) + .flat_map(|n| n.iter().copied()), + ); v } else { data }; - Some(ScreenFrame { key, data: Arc::new(data) }) + Some(Some(ScreenFrame { key, data: Arc::new(data) })) } } @@ -501,9 +551,42 @@ mod tests { a.push(&[0, 0, 0, 1, 0x46, 1, 0x50]); assert!(a.finish().is_none(), "an access unit delimiter alone isn't a frame"); // a frame without a marker ends when the next timestamp starts - assert!(a.new_timestamp(1).is_none()); + assert!(a.new_timestamp(1, true).is_none()); a.push(&trail); - assert!(a.new_timestamp(2).is_some()); + assert!(a.new_timestamp(2, true).is_some_and(|f| f.is_some())); + } + + /// Nobody watching: frames are counted (and acknowledged) but not copied; the parameter sets are still kept, so + /// the first keyframe a new subscriber gets is decodable + #[test] + fn unwatched_frames_keep_only_the_parameter_sets() { + let (vps, sps, pps) = ([0u8, 0, 0, 1, 0x40, 1, 9], [0u8, 0, 0, 1, 0x42, 1, 8], [0u8, 0, 0, 1, 0x44, 1, 7]); + let idr = [0u8, 0, 0, 1, 0x28, 1, 0xAA]; + let mut a = Assembler::default(); + a.push(&[vps.as_slice(), &sps, &pps, &idr].concat()); + assert!(matches!(a.complete(false), Some(None)), "a frame, not delivered"); + a.push(&[0, 0, 0, 1, 0x46, 1, 0x50]); + assert!(a.complete(false).is_none(), "no picture data: not a frame either way"); + a.push(&idr); + let f = a.complete(true).flatten().unwrap(); + assert_eq!(*f.data, [vps.as_slice(), &sps, &pps, &idr].concat()); + } + + /// A frame over the limit is dropped whole (once), the next one comes through + #[test] + fn oversized_frames_are_dropped() { + let idr = [0u8, 0, 0, 1, 0x28, 1, 0xAA]; + let mut a = Assembler::default(); + let big = vec![0xAB; MAX_FRAME_BYTES / 2 + 1]; + a.push(&idr); + a.push(&big); + a.push(&big); + a.push(&idr); + assert!(a.take_dropped()); + assert!(!a.take_dropped(), "told once"); + assert!(a.finish().is_none()); + a.push(&idr); + assert_eq!(*a.finish().unwrap().data, idr); } /// The SPS the iPhone 18 Pro Max (iOS 27.2.1) sends: Main profile, level 5.0 diff --git a/crates/ictl-wda/src/http.rs b/crates/ictl-wda/src/http.rs index 31f63f59..783c0485 100644 --- a/crates/ictl-wda/src/http.rs +++ b/crates/ictl-wda/src/http.rs @@ -121,29 +121,7 @@ impl DeviceTransport { sock.write_all(&req).await.map_err(write_failed)?; sock.flush().await.map_err(write_failed)?; written = true; - // WDA 收到 `Connection: close` 也不关连接,不能读到 EOF:读够一个完整响应就停。 - // 头部只解析一次;正文按 Content-Length 判断,chunked 只在收到结束块后才完整解一次 - let mut buf = Vec::new(); - let mut chunk = vec![0u8; 64 * 1024]; - let mut head: Option<(usize, Framing)> = None; - loop { - if head.is_none() { - head = parse_head(&buf); - if let Some((split, Framing::Length(n))) = head { - buf.reserve((split + n).saturating_sub(buf.len())); - } - } - if let Some((split, framing)) = head - && framing.complete(&buf[split..]) - { - break; - } - let n = sock.read(&mut chunk).await.map_err(after_sent)?; - if n == 0 { - break; - } - buf.extend_from_slice(&chunk[..n]); - } + let buf = read_response(&mut sock, MAX_RESPONSE_BYTES).await.map_err(after_sent)?; parse_response(buf).map_err(after_sent) }; tokio::time::timeout(timeout, fut).await.map_err(|_| { @@ -155,6 +133,53 @@ impl DeviceTransport { } } +/// 一个 WDA 响应最多这么大(头部加正文)。最大的是 iPad 的截图(base64 的 PNG,十几 MB)和大界面的 `/source`; +/// 超过就当坏了,不跟着对方给的 Content-Length 无限分配 +pub(crate) const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; + +/// 读够一个完整响应就停:WDA 收到 `Connection: close` 也不关连接,不能读到 EOF。 +/// 头部只解析一次;正文按 Content-Length 判断,chunked 只在收到结束块后才完整解一次。 +/// 超过 `limit`(含 Content-Length 声明的长度)返回 `InvalidData` +pub(crate) async fn read_response( + sock: &mut R, + limit: usize, +) -> std::io::Result> { + let too_large = || { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + ictl_l10n::trf!("WDA 的响应超过 {} MB", "WDA's response is over {} MB", limit >> 20), + ) + }; + let mut buf = Vec::new(); + let mut chunk = vec![0u8; 64 * 1024]; + let mut head: Option<(usize, Framing)> = None; + loop { + if head.is_none() { + head = parse_head(&buf); + if let Some((split, Framing::Length(n))) = head { + if split.saturating_add(n) > limit { + return Err(too_large()); + } + buf.reserve((split + n).saturating_sub(buf.len())); + } + } + if let Some((split, framing)) = head + && framing.complete(&buf[split..]) + { + break; + } + let n = sock.read(&mut chunk).await?; + if n == 0 { + break; + } + if buf.len() + n > limit { + return Err(too_large()); + } + buf.extend_from_slice(&chunk[..n]); + } + Ok(buf) +} + pub(crate) fn build_request(method: &str, path: &str, body: Option<&[u8]>) -> Vec { let body = body.unwrap_or_default(); let mut req = @@ -303,6 +328,22 @@ mod tests { assert!(post.contains("Content-Length: 2\r\n") && post.ends_with("\r\n\r\n{}")); } + #[tokio::test] + async fn oversized_responses_are_refused() { + // declared too large: refused before reading the body + let mut declared: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\nabc"; + let e = read_response(&mut declared, 100).await.unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + // no length (read until EOF) and more than the limit arrives + let big = [b"HTTP/1.1 200 OK\r\n\r\n".as_slice(), &[b'x'; 200]].concat(); + let e = read_response(&mut big.as_slice(), 100).await.unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + // within the limit: read whole, the rest of the stream left alone + let mut ok: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"; + let raw = read_response(&mut ok, 100).await.unwrap(); + assert_eq!(parse_response(raw).unwrap(), (200, b"{}".to_vec())); + } + #[test] fn parses_content_length_body() { let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nServer: x\r\n\r\nhelloEXTRA"; diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index 023a4a4c..6190ea24 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -175,3 +175,7 @@ | 169 | 事件日志、「上次重签」、重签完成的到期时间按 UTC 显示又不标明,东八区的用户看到的时间差 8 小时 | 显示本地时间并带时区偏移(`2026-11-24 16:08:52 +08:00`);写给旧版本读的 `last_resign` 整句照旧是 UTC | 单测 `local_time_carries_its_offset`、`resign_result_is_shown_in_the_reader_language`(在 UTC、东八区、`America/St_Johns` 下都要过) | | 170 | 更新器、后台服务、自动更新任务的报错写死英文(约 120 条),中文界面下 `iphone-control update` 和控制台更新面板显示英文 | 全部中英成对(`tr!`/`trf!`),按运行时的语言输出;`outcome.json` 的 `status` 字段不变,控制台仍按它显示状态 | 手动:`IPHONE_CONTROL_LANG=zh` 和 `en` 下各运行一次 `iphone-control update apply`(没有脚本安装记录时),报错分别是中文、英文 | | 171 | iOS 17–18(#185,iPhone XS,iOS 18.7.12):开发者镜像经 cryptexd 挂载卡住,WDA 起不来。这些版本要经典个性化镜像,走 lockdown 的 `mobile_image_mounter` | iOS 17–18 不问 cryptexd:先 `lookup_image("Personalized")`(已挂上就不读文件;锁屏等其他错误照常报出,不当成没挂),没挂才从 `ddi/personalized/` 缓存(上游 `Xcode_iOS_DDI_Personalized`,自动下载)或 `ICTL_DDI_DIR` 取三个文件再挂;iOS 26 及以后、版本读不出(0)照旧走 cryptexd;连续挂载失败只清掉这台手机用的那份缓存 | 单测 `only_ios_17_and_18_take_the_personalized_image_with_its_three_files_next_to_the_cryptex_one` + 真机(iPhone XS,iOS 18.7.12:补丁前一版挂上并起了 WDA;本版待重测) | +| 172 | 原生控制的手机(iOS 27)在别的设备用过 WDA 后(`wda_bundle` 是全局的)仍定时查描述文件、自动重签,每天联网查 Apple ID 会话,还可能弹「会话失效」提醒 | 自动重签、会话检查只为用 WDA 的设备做:在用的设备走原生时都不做,这一轮也不算数(换到 WDA 设备下一轮就做);没装过 WDA 不做;没连手机时会话检查照做 | 单测 `wda_upkeep_is_only_for_devices_that_use_wda` + 真机(iPhone 15 Pro Max iOS 27.2.1 原生、iPad mini 5 iPadOS 26.7.3 WDA:`run.py`、`scenarios.py` 全过) | +| 173 | 协议和媒体数据没有总大小上限:WDA 响应按对方给的 Content-Length 预分配,DTX 只限单片 64 MB、按包头先分配,HEVC 帧丢了 marker 又一直同一时间戳时无限拼接 | WDA 响应 64 MB(先核对 Content-Length 再分配)、DTX 整条消息 64 MB(各片合计,边收边读)、HEVC 帧 8 MB(超了整帧丢掉并请求关键帧) | 单测 `oversized_responses_are_refused`、`the_whole_message_is_limited_not_each_fragment`、`oversized_frames_are_dropped` | +| 174 | `HidSession::held_drag`(`iphone_swipe` 带 `hold`)按下后没记下手指:中途失败或超时,关会话时不补发抬起,手指留在屏幕上 | 按下后记 `contact`,拖完清掉;会话关闭时照常抬起 | 代码审查(无法在单测里构造 HID 会话中途失败) | +| 175 | 重签完成后不忘掉旧的后台 WDA 记录、不唤醒巡检,新 WDA 要等最多 10 秒的下一轮才拉起 | 重签成功后先忘掉这台设备的后台 WDA,再丢会话并唤醒巡检 | 代码审查(真机回归期间这个分支上没有触发重签) |