diff --git a/CHANGELOG.md b/CHANGELOG.md index 9171523..f99eb2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index f18b6a1..61198b4 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -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)。 diff --git a/apps/iphone-control/src/video/vt.rs b/apps/iphone-control/src/video/vt.rs index d6c347c..ec612cd 100644 --- a/apps/iphone-control/src/video/vt.rs +++ b/apps/iphone-control/src/video/vt.rs @@ -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 { @@ -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()) } } diff --git a/crates/ictl-ax/src/archive.rs b/crates/ictl-ax/src/archive.rs index f6d5845..e96d2c0 100644 --- a/crates/ictl-ax/src/archive.rs +++ b/crates/ictl-ax/src/archive.rs @@ -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 { + 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 = @@ -106,11 +117,29 @@ pub fn decode(bytes: &[u8]) -> Result { .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>, + /// Values still to be decoded ([`BUDGET_PER_BYTE`]); at 0 everything reads as [`Obj::Null`] and the archive is + /// refused + budget: std::cell::Cell, + /// A value was left out for want of [`Self::budget`] (one that used the last of it exactly is fine) + exhausted: std::cell::Cell, } impl Reader<'_> { @@ -118,10 +147,23 @@ impl Reader<'_> { 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), @@ -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) -> Vec { + 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 = (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 = (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)); diff --git a/crates/ictl-daemon/src/tools/input.rs b/crates/ictl-daemon/src/tools/input.rs index 82e56e9..7291738 100644 --- a/crates/ictl-daemon/src/tools/input.rs +++ b/crates/ictl-daemon/src/tools/input.rs @@ -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(()) } diff --git a/crates/ictl-daemon/src/tools/native.rs b/crates/ictl-daemon/src/tools/native.rs index 9dfc4c8..92b1a48 100644 --- a/crates/ictl-daemon/src/tools/native.rs +++ b/crates/ictl-daemon/src/tools/native.rs @@ -146,7 +146,7 @@ impl Daemon { overlays: bool, ) -> crate::error::Result { 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) @@ -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 @@ -266,7 +272,7 @@ 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 { 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; @@ -274,6 +280,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 @@ -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(r: &ictl_device::Result) -> 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 { diff --git a/crates/ictl-device/src/ax.rs b/crates/ictl-device/src/ax.rs index b3ed87c..d8cfc3f 100644 --- a/crates/ictl-device/src/ax.rs +++ b/crates/ictl-device/src/ax.rs @@ -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 = 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 = 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?) diff --git a/crates/ictl-device/src/hid.rs b/crates/ictl-device/src/hid.rs index f3fc43a..00f2928 100644 --- a/crates/ictl-device/src/hid.rs +++ b/crates/ictl-device/src/hid.rs @@ -50,6 +50,41 @@ impl Button { } } +/// 手势时长的上限:再长的按住、拖动都是给错了数 +const MAX_GESTURE: f64 = 60.0; + +/// 手势的一段时长:负数当 0,超过 [`MAX_GESTURE`] 截到上限;不是有限数(`NaN`、无穷)的不做, +/// `Duration::from_secs_f64` 遇到它会 panic +fn gesture_time(seconds: f64) -> Result { + if !seconds.is_finite() { + return Err(DeviceError::InvalidInput(ictl_l10n::trf!( + "手势时长不是有效的数:{seconds}", + "The gesture's duration isn't a valid number: {seconds}" + ))); + } + Ok(Duration::from_secs_f64(seconds.clamp(0.0, MAX_GESTURE))) +} + +/// 界面上的点 → HID 归一化坐标。不是有限数的坐标、量不出的屏幕尺寸不换算:`NaN` 会悄悄变成 (0,0),点到左上角 +fn map_point(p: (f64, f64), screen: ScreenSize, rotation: Rotation) -> Result<(u16, u16)> { + if !(p.0.is_finite() && p.1.is_finite()) { + return Err(DeviceError::InvalidInput(ictl_l10n::trf!( + "坐标不是有效的数:({}, {})", + "The point isn't a valid number: ({}, {})", + p.0, + p.1 + ))); + } + if !(screen.width.is_finite() && screen.height.is_finite() && screen.width > 0.0 && screen.height > 0.0) { + return Err(DeviceError::InvalidInput( + ictl_l10n::tr!("屏幕尺寸未知,没法换算坐标", "The screen size is unknown, so the point can't be mapped") + .into(), + )); + } + let (x, y) = rotation.to_portrait(p, screen); + Ok(to_hid(x, y, screen)) +} + /// 点 → HID 归一化坐标 pub fn to_hid(x: f64, y: f64, screen: ScreenSize) -> (u16, u16) { let n = |v: f64, max: f64| (v / max * HID_MAX).round().clamp(0.0, HID_MAX) as u16; @@ -157,14 +192,13 @@ impl HidSession { } } - /// 界面上的点 → HID 归一化坐标(先按 [`Self::rotation`] 换算回竖放) - fn hid_point(&self, p: (f64, f64)) -> (u16, u16) { - let (x, y) = self.rotation.to_portrait(p, self.screen); - to_hid(x, y, self.screen) + /// 界面上的点 → HID 归一化坐标(先按 [`Self::rotation`] 换算回竖放),见 [`map_point`] + fn hid_point(&self, p: (f64, f64)) -> Result<(u16, u16)> { + map_point(p, self.screen, self.rotation) } pub async fn tap(&mut self, x: f64, y: f64) -> Result<()> { - let (hx, hy) = self.hid_point((x, y)); + let (hx, hy) = self.hid_point((x, y))?; limit(ictl_l10n::tr!("HID 点击", "HID tap"), Duration::from_secs(10), async { Ok(self.touch.tap(hx, hy).await?) }) @@ -173,10 +207,11 @@ impl HidSession { /// 拖动:按时长换算采样数(每 20ms 一个点,至少 10 个),太快会被识别成点击 pub async fn drag(&mut self, from: (f64, f64), to: (f64, f64), seconds: f64) -> Result<()> { - let (x1, y1) = self.hid_point(from); - let (x2, y2) = self.hid_point(to); - let steps = ((seconds * 1000.0 / 20.0).round() as u32).max(10); - let d = Duration::from_secs_f64(seconds.max(0.0) + 10.0); + let (x1, y1) = self.hid_point(from)?; + let (x2, y2) = self.hid_point(to)?; + let moving = gesture_time(seconds)?; + let steps = ((moving.as_secs_f64() * 1000.0 / 20.0).round() as u32).max(10); + let d = moving + Duration::from_secs(10); limit(ictl_l10n::tr!("HID 拖动", "HID drag"), d, async { Ok(self.touch.drag(x1, y1, x2, y2, steps, 20).await?) }) @@ -186,11 +221,12 @@ impl HidSession { /// 按住再拖:按下后在起点按住 `hold` 秒(和 [`Self::long_press`] 一样每 100 毫秒重报一次位置),不抬起,接着 /// 像 [`Self::drag`] 一样移到终点抬起。拖动主屏幕图标、列表排序这类要先长按才能拖的 pub async fn held_drag(&mut self, from: (f64, f64), to: (f64, f64), hold: f64, seconds: f64) -> Result<()> { - let (x1, y1) = self.hid_point(from); - let (x2, y2) = self.hid_point(to); - let held = Duration::from_secs_f64(hold.clamp(0.0, 60.0)); - let steps = ((seconds * 1000.0 / 20.0).round() as u32).max(10); - let d = held + Duration::from_secs_f64(seconds.max(0.0) + 10.0); + let (x1, y1) = self.hid_point(from)?; + let (x2, y2) = self.hid_point(to)?; + let held = gesture_time(hold)?; + let moving = gesture_time(seconds)?; + let steps = ((moving.as_secs_f64() * 1000.0 / 20.0).round() as u32).max(10); + let d = held + moving + Duration::from_secs(10); 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?; @@ -212,7 +248,7 @@ impl HidSession { /// point (the first one touches down, later ones move it), false lifts it there. iOS works out taps, long presses /// and the speed of a swipe from these samples and their timing, the same way as from a real finger pub async fn touch(&mut self, contact: bool, x: f64, y: f64) -> Result<()> { - let (hx, hy) = self.hid_point((x, y)); + let (hx, hy) = self.hid_point((x, y))?; let state = if contact { TOUCHSCREEN_STATE_CONTACT } else { TOUCHSCREEN_STATE_RELEASE }; limit(ictl_l10n::tr!("HID 触摸", "HID touch"), Duration::from_secs(5), async { self.touch.send_touchscreen(state, hx, hy, None).await?; @@ -225,8 +261,8 @@ impl HidSession { /// 长按:按下,按住 `seconds` 秒,抬起。按住时每 100 毫秒重报一次位置:只报一次的话,有的 App(微信) /// 会当成轻点(iCTRL 的做法) pub async fn long_press(&mut self, x: f64, y: f64, seconds: f64) -> Result<()> { - let (hx, hy) = self.hid_point((x, y)); - let held = Duration::from_secs_f64(seconds.clamp(0.0, 60.0)); + let (hx, hy) = self.hid_point((x, y))?; + let held = gesture_time(seconds)?; limit(ictl_l10n::tr!("HID 长按", "HID long press"), held + Duration::from_secs(10), async { let end = tokio::time::Instant::now() + held; self.touch.send_touchscreen(TOUCHSCREEN_STATE_CONTACT, hx, hy, None).await?; @@ -366,6 +402,26 @@ mod tests { const SCREEN: ScreenSize = ScreenSize { width: 430.0, height: 932.0 }; + /// `NaN` or an infinity used to panic in `Duration::from_secs_f64`, or tap the top left corner (`NaN as u16` is 0) + #[test] + fn only_finite_points_and_durations_reach_the_phone() { + let p = |x, y| map_point((x, y), SCREEN, Rotation::Portrait); + assert_eq!(p(0.0, 0.0).unwrap(), (0, 0)); + assert_eq!(p(430.0, 932.0).unwrap(), (65535, 65535)); + for (x, y) in [(f64::NAN, 1.0), (1.0, f64::INFINITY), (f64::NEG_INFINITY, 1.0)] { + assert!(matches!(p(x, y), Err(DeviceError::InvalidInput(_))), "({x}, {y})"); + } + for screen in [ScreenSize { width: 0.0, height: 932.0 }, ScreenSize { width: f64::NAN, height: 932.0 }] { + assert!(matches!(map_point((1.0, 1.0), screen, Rotation::Portrait), Err(DeviceError::InvalidInput(_)))); + } + assert_eq!(gesture_time(0.5).unwrap(), Duration::from_millis(500)); + assert_eq!(gesture_time(-3.0).unwrap(), Duration::ZERO); + assert_eq!(gesture_time(1e9).unwrap(), Duration::from_secs(60), "capped"); + for s in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(matches!(gesture_time(s), Err(DeviceError::InvalidInput(_))), "{s}"); + } + } + #[test] fn hid_norm_corners_center_and_clamp() { assert_eq!(to_hid(0.0, 0.0, SCREEN), (0, 0)); diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rs index 243b659..a8887b1 100644 --- a/crates/ictl-device/src/lib.rs +++ b/crates/ictl-device/src/lib.rs @@ -632,9 +632,12 @@ impl Device { /// Asking for debug messages (what idevice's `start_trace` does) makes every process on the phone produce them: /// about 650 lines a second instead of about 80 on an idle iPhone 15 Pro Max (iOS 27.0.1), and gestures got /// slower and some failed while the stream ran. Most info messages go with them, but some processes still send - /// Info entries (MobileTimer on iOS 27.2.1); callers that promise default, Error and Fault only drop those + /// Info entries (MobileTimer on iOS 27.2.1); callers that promise default, Error and Fault only drop those. + /// Only what is logged from now on: the historical entries (what idevice asks for too) came first, and readers + /// took them for new: the WDA runner a past "Enabling Automation Mode" for a passcode prompt now, `app_logs` + /// old lines stamped with the time they arrived pub async fn log_stream(&self) -> Result { - let flags = oslog::flags::IDEVICE_DEFAULT & !oslog::flags::DEBUG; + let flags = oslog::flags::LIVE; let inner = limit(ictl_l10n::tr!("打开日志流", "open the log stream"), QUERY, oslog::start(&*self.provider, flags)) .await?; diff --git a/crates/ictl-device/src/oslog.rs b/crates/ictl-device/src/oslog.rs index a8b4683..f9c5202 100644 --- a/crates/ictl-device/src/oslog.rs +++ b/crates/ictl-device/src/oslog.rs @@ -20,6 +20,8 @@ pub mod flags { pub const DEBUG: u64 = 0x20; /// What idevice and pymobiledevice3 send pub const IDEVICE_DEFAULT: u64 = PAYLOAD | HISTORICAL | CALLSTACK | DEBUG; + /// What [`crate::Device::log_stream`] asks for: what is logged from now on, without debug messages + pub const LIVE: u64 = IDEVICE_DEFAULT & !DEBUG & !HISTORICAL; } /// Fixed part of an entry before the strings @@ -130,6 +132,14 @@ fn take(rest: &[u8], at: &mut usize, n: usize) -> Option { mod tests { use super::*; + /// Neither debug messages (they slow the phone) nor the past (it was read as new) + #[test] + fn the_stream_is_live_only() { + use flags::*; + assert_eq!(LIVE & (DEBUG | HISTORICAL), 0); + assert_eq!(LIVE, PAYLOAD | CALLSTACK); + } + fn entry(level: u8, file: &str, msg: &str, label: Option<(&str, &str)>) -> Vec { let mut p = vec![0u8; HEADER]; p[9..13].copy_from_slice(&42u32.to_le_bytes()); diff --git a/crates/ictl-sign/src/ipa.rs b/crates/ictl-sign/src/ipa.rs index 874f2f7..48796b4 100644 --- a/crates/ictl-sign/src/ipa.rs +++ b/crates/ictl-sign/src/ipa.rs @@ -1,7 +1,7 @@ //! .ipa 解包和打包(就是 zip,里面是 `Payload/X.app`)。保留 Unix 权限位,否则可执行文件会丢掉 x 位。 use std::fs::File; -use std::io::{self, Read, Write}; +use std::io; use std::path::{Path, PathBuf}; use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions}; @@ -26,12 +26,30 @@ pub fn find_app(payload: &Path) -> io::Result { }) } -/// 把 `root` 下的 `Payload/` 打成 ipa +/// 把 `root` 下的 `Payload/` 打成 ipa。写在旁边的临时文件里,写完才换上去:`out` 要么是原来的,要么是完整的新包 pub fn pack(root: &Path, out: &Path) -> io::Result<()> { - let mut zip = ZipWriter::new(File::create(out)?); - add_dir(&mut zip, root, &root.join("Payload"))?; - zip.finish().map_err(io::Error::other)?; - Ok(()) + write_atomically(out, |f| { + let mut zip = ZipWriter::new(f); + add_dir(&mut zip, root, &root.join("Payload"))?; + zip.finish().map_err(io::Error::other)?; + Ok(()) + }) +} + +/// 在 `out` 同一个目录里写一个临时文件,写完 fsync 后改名成 `out`;出错就删掉临时文件,`out` 不动 +fn write_atomically(out: &Path, write: impl FnOnce(File) -> io::Result<()>) -> io::Result<()> { + let name = out.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let tmp = out.with_file_name(format!(".{name}.{}.part", uuid::Uuid::new_v4())); + let r = File::create(&tmp).and_then(|f| { + let sync = f.try_clone()?; + write(f)?; + sync.sync_all() + }); + let r = r.and_then(|()| std::fs::rename(&tmp, out)); + if r.is_err() { + let _ = std::fs::remove_file(&tmp); + } + r } /// 根目录直接是 `X.app/` 的 zip(Appium 发布的 WDA 真机包)改成 ipa:每项加上 `Payload/` 前缀, @@ -45,20 +63,22 @@ pub fn from_app_zip(src: &Path, out: &Path) -> io::Result<()> { ictl_l10n::tr!("zip 根目录下没有 .app", "no .app at the root of the zip"), )); } - let mut w = ZipWriter::new(File::create(out)?); - w.add_directory("Payload/", SimpleFileOptions::default().unix_permissions(0o755)).map_err(io::Error::other)?; - for i in 0..zip.len() { - let f = zip.by_index_raw(i).map_err(io::Error::other)?; - let name = format!("Payload/{}", f.name().map_err(io::Error::other)?); - if f.is_dir() { - let mode = f.unix_mode().map_or(0o755, |m| m & 0o7777); - w.add_directory(name, SimpleFileOptions::default().unix_permissions(mode)).map_err(io::Error::other)?; - } else { - w.raw_copy_file_rename(f, name).map_err(io::Error::other)?; + write_atomically(out, |f| { + let mut w = ZipWriter::new(f); + w.add_directory("Payload/", SimpleFileOptions::default().unix_permissions(0o755)).map_err(io::Error::other)?; + for i in 0..zip.len() { + let f = zip.by_index_raw(i).map_err(io::Error::other)?; + let name = format!("Payload/{}", f.name().map_err(io::Error::other)?); + if f.is_dir() { + let mode = f.unix_mode().map_or(0o755, |m| m & 0o7777); + w.add_directory(name, SimpleFileOptions::default().unix_permissions(mode)).map_err(io::Error::other)?; + } else { + w.raw_copy_file_rename(f, name).map_err(io::Error::other)?; + } } - } - w.finish().map_err(io::Error::other)?; - Ok(()) + w.finish().map_err(io::Error::other)?; + Ok(()) + }) } fn add_dir(zip: &mut ZipWriter, root: &Path, dir: &Path) -> io::Result<()> { @@ -77,9 +97,7 @@ fn add_dir(zip: &mut ZipWriter, root: &Path, dir: &Path) -> io::Result<()> zip.add_symlink(rel, target.to_string_lossy(), opts).map_err(io::Error::other)?; } else { zip.start_file(rel, opts).map_err(io::Error::other)?; - let mut buf = Vec::new(); - File::open(&path)?.read_to_end(&mut buf)?; - zip.write_all(&buf)?; + io::copy(&mut File::open(&path)?, zip)?; } } Ok(()) @@ -88,6 +106,23 @@ fn add_dir(zip: &mut ZipWriter, root: &Path, dir: &Path) -> io::Result<()> #[cfg(test)] mod tests { use super::*; + use std::io::Write; + + /// A package that fails halfway leaves the old one as it was and nothing beside it + #[test] + fn a_failed_pack_leaves_the_old_package() { + let root = std::env::temp_dir().join(format!("ictl-ipa-fail-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&root).unwrap(); + let out = root.join("out.ipa"); + std::fs::write(&out, b"old").unwrap(); + assert!(pack(&root, &out).is_err(), "no Payload/ to pack"); + assert_eq!(std::fs::read(&out).unwrap(), b"old"); + let left: Vec<_> = std::fs::read_dir(&root).unwrap().flatten().map(|e| e.file_name()).collect(); + assert_eq!(left, vec![std::ffi::OsString::from("out.ipa")], "no temporary file left"); + assert!(from_app_zip(&root.join("missing.zip"), &out).is_err()); + assert_eq!(std::fs::read(&out).unwrap(), b"old"); + std::fs::remove_dir_all(root).unwrap(); + } #[test] fn pack_then_unpack_keeps_exec_bit() { diff --git a/crates/ictl-sign/src/lib.rs b/crates/ictl-sign/src/lib.rs index ef44d6e..66fbdbb 100644 --- a/crates/ictl-sign/src/lib.rs +++ b/crates/ictl-sign/src/lib.rs @@ -104,6 +104,8 @@ impl AccountDir { .accounts_add_from_session(email.to_owned(), account) .await .map_err(|e| SignError::Developer(e.to_string()))?; + // the session's tokens were just written with the default umask + restrict_tree(&self.dir)?; Ok(email.to_owned()) } @@ -187,9 +189,11 @@ impl Session { /// 签名 .ipa:Bundle ID 改成 `<原 ID>.<团队 ID>`(免费账号不能用别人的 ID),申请描述文件,深度优先签名所有嵌套 bundle。 /// 签好后自检(每个嵌套 bundle 都有 `_CodeSignature`、描述文件含这台手机且带 get-task-allow)。 pub async fn sign_ipa(&self, input: &Path, output: &Path, udid: &str) -> Result { - let work = std::env::temp_dir().join(format!("ictl-sign-{}", uuid::Uuid::new_v4())); - let result = self.sign_in(&work, input, output, udid).await; - let _ = std::fs::remove_dir_all(&work); + // removed however this ends, also when the caller gives up waiting and drops it + let work = WorkDir(std::env::temp_dir().join(format!("ictl-sign-{}", uuid::Uuid::new_v4()))); + let result = self.sign_in(&work.0, input, output, udid).await; + // a key written on the way is locked down even when signing failed after it + let _ = restrict_tree(&self.dir.dir); result } @@ -225,6 +229,9 @@ impl Session { Some(&mut on_reset), ) .await?; + // a new certificate's private key was just written with the default umask (0644): locked down now, not after + // the whole package is signed + restrict_tree(&self.dir.dir)?; let new_certificate = cert.new; if new_certificate { tracing::warn!( @@ -338,6 +345,15 @@ pub fn verify_signed(app_dir: &Path, udid: &str, signing_cert: Option<&[u8]>) -> Ok(p) } +/// [`AccountDir::sign_ipa`]'s scratch directory, removed when dropped +struct WorkDir(PathBuf); + +impl Drop for WorkDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + fn restrict_dir(dir: &Path) -> std::io::Result<()> { use std::os::unix::fs::PermissionsExt; std::fs::create_dir_all(dir)?; @@ -399,6 +415,15 @@ mod tests { } use std::time::{Duration, SystemTime}; + /// The scratch directory goes with the guard, also when the signing future is dropped (a caller's timeout) + #[test] + fn the_scratch_directory_is_removed_when_dropped() { + let dir = std::env::temp_dir().join(format!("ictl-sign-test-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(dir.join("Payload/X.app")).unwrap(); + drop(WorkDir(dir.clone())); + assert!(!dir.exists()); + } + #[test] fn account_tree_is_locked_down() { use std::os::unix::fs::PermissionsExt; diff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rs index 53728df..6ec5281 100644 --- a/crates/ictl-wda/src/elements.rs +++ b/crates/ictl-wda/src/elements.rs @@ -790,15 +790,46 @@ pub fn delete_key(elements: &[Element], pad: &[(i64, i64); 10]) -> Option<(i64, } /// 有 Touch ID 的机型(iPad mini 5,iPadOS 26.6.1 真机)上滑后先是「触控 ID」提示,只有「使用密码」和「取消」两个按钮, -/// 树里没有数字键和密码栏,点「使用密码」才出键盘。返回它的中心。英文标签没在真机上核对过 +/// 树里没有数字键和密码栏,点「使用密码」才出键盘。返回它的中心。英文标签没在真机上核对过。 +/// 别的语言认不出文字时按结构找:整棵树只有这两个按钮、上下叠在同一条竖线上,没有锁屏本身的标识(「按下主屏幕按钮 +/// 以解锁」也是个按钮)和密码栏,「使用密码」在上(三个真机样本都是)。万一点成了「取消」,只是回到锁屏,不算输错密码 pub fn use_passcode_button(elements: &[Element]) -> Option<(i64, i64)> { - elements + let by_label = elements.iter().find(|e| { + e.kind == "Button" + && (USE_PASSCODE_LABELS.contains(&e.label.as_str()) || USE_PASSCODE_LABELS.contains(&e.name.as_str())) + }); + if let Some(e) = by_label { + return Some(e.center); + } + let buttons: Vec<&Element> = elements.iter().filter(|e| e.kind == "Button").collect(); + let stacked = |a: &Element, b: &Element| (a.center.0 - b.center.0).abs() <= 20 && a.center.1 != b.center.1; + // the lock screen itself (its "press Home to unlock" is a button too, with a notification above it) + let lock_screen = elements .iter() - .find(|e| { - e.kind == "Button" - && (USE_PASSCODE_LABELS.contains(&e.label.as_str()) || USE_PASSCODE_LABELS.contains(&e.name.as_str())) - }) - .map(|e| e.center) + .any(|e| ["call-to-action-label", "proud-lock", "lockscreen-date-view"].contains(&e.name.as_str())); + // the upper one: Use Passcode is above Cancel in every sample, whatever order the tree lists them in + (buttons.len() == 2 && stacked(buttons[0], buttons[1]) && !lock_screen && passcode_field(elements).is_none()) + .then(|| buttons.iter().map(|b| b.center).min_by_key(|c| c.1)) + .flatten() +} + +/// 「触控 ID」提示的结构,和界面语言无关:SpringBoard 的 `SBCoverSheetWindow` 里没有锁屏日期(不是锁屏本身, +/// 也不是通知中心),只有两个按钮。按钮上的字只认得中文和英文([`USE_PASSCODE_LABELS`]),繁中、日、德、法…… +/// 的系统上靠这个认出锁屏:认不出时把锁着的 iPad 当成了解锁的,之后不再查锁屏 +fn touch_id_prompt(xml: &str) -> bool { + let Some(at) = xml.find("name=\"SBCoverSheetWindow\"") else { return false }; + let start = xml[..at].rfind('<').unwrap_or(0); + // the window itself: an element of another kind with that name would be matched to a window's end tag + if !xml[start..].starts_with("').map(|i| at + i) else { return false }; + if xml[..open_end].ends_with('/') { + return false; + } + let Some(len) = xml[open_end..].find("") else { return false }; + let window = &xml[start..open_end + len]; + !window.contains("\"lockscreen-date-view\"") && window.matches(" CoverSheet { static PASSCODE: LazyLock = LazyLock::new(|| regex(r#"]*value="([^"]*)""#)); let passcode_field = PASSCODE.captures_iter(xml).any(|c| parse_passcode_value(&c[1]).is_some()); - if lock_glyph || use_passcode || passcode_field { + if lock_glyph || use_passcode || passcode_field || touch_id_prompt(xml) { CoverSheet::Locked } else if xml.contains("\"lockscreen-date-view\"") { CoverSheet::NotificationCenter @@ -912,6 +943,53 @@ mod tests { assert!(els.iter().any(|e| e.label == "紧急情况")); } + /// The Touch ID prompt in a language whose words aren't known (here German): still a lock screen, and its first + /// button (Use Passcode) is the one to tap. The lock screen itself, with its two buttons in the corners, isn't it + #[test] + fn a_touch_id_prompt_in_any_language() { + let german = |xml: &str| { + xml.replace("使用密码", "Code verwenden") + .replace("取消", "Abbrechen") + .replace("触控 ID", "Touch ID") + .replace("触控ID", "Touch ID") + }; + let portrait = + View { screen: ScreenSize { width: 768.0, height: 1024.0 }, orientation: Some(Orientation::Portrait) }; + let cases = [ + (IPAD_TOUCHID_P, portrait), + (IPAD_TOUCHID, land(Some(Orientation::LandscapeLeft))), + (IPAD_TOUCHID_LEFT, land(Some(Orientation::LandscapeLeft))), + ]; + for (xml, view) in cases { + let de = german(xml); + assert!(!de.contains("使用密码")); + assert_eq!(cover_sheet(&de), CoverSheet::Locked); + assert_eq!( + use_passcode_button(&parse(&de, view)), + use_passcode_button(&parse(xml, view)), + "the same button" + ); + assert!(use_passcode_button(&parse(xml, view)).is_some()); + // listed the other way round: still the upper one + let mut reversed = parse(&de, view); + reversed.reverse(); + assert_eq!(use_passcode_button(&reversed), use_passcode_button(&parse(xml, view))); + } + // the name on something that isn't a window: not the prompt + let other = IPAD_TOUCHID.replace( + "