From 3cd72d70e1abde2e48be7ffc6dbce2ab1600eaac Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Sat, 28 Nov 2026 16:08:07 +0800 Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E6=94=AF=E6=8C=81=E7=B2=98?= =?UTF-8?q?=E8=B4=B4=E9=85=8D=E5=AF=B9=E5=B9=B6=E4=BF=AE=E5=A4=8D=E4=B8=B2?= =?UTF-8?q?=E6=B5=81=E4=B8=8E=E8=AE=BE=E5=A4=87=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 支持 Ctrl+V 粘贴配对文本和二维码图片,预览确认后识别校验 - 修复控制发送阻塞、TLS 读写争锁、设备切换沿用旧连接及串流误关窗 - 优化媒体加密上下文、UDP 接收缓冲和异步诊断日志 - 安装器按路径停止主控与信令进程,统一递增版本、打包和清理旧产物 - 发布 0.1.3+4,通过三端编译、20 项 Flutter 测试和 58 项 Rust 单元测试 --- AGENTS.md | 3 + README.md | 2 +- android_receiver/app/build.gradle.kts | 4 +- .../receiver/MediaProtocolInstrumentation.kt | 7 + .../lancast/receiver/session/MediaPackets.kt | 22 ++- docs/streaming-troubleshooting.md | 68 +++++++ flutter_sender/lib/core/diagnostic_log.dart | 39 ++-- flutter_sender/lib/core/pairing_input.dart | 120 ++++++++++++ .../discovery/pairing_paste_dialog.dart | 136 ++++++++++++++ flutter_sender/lib/main.dart | 174 +++++++----------- .../flutter/generated_plugin_registrant.cc | 4 + .../linux/flutter/generated_plugins.cmake | 1 + .../Flutter/GeneratedPluginRegistrant.swift | 2 + flutter_sender/pubspec.lock | 81 +++++++- flutter_sender/pubspec.yaml | 5 +- .../test/core/diagnostic_log_test.dart | 54 ++++++ .../test/core/pairing_input_test.dart | 37 ++++ flutter_sender/test/fixtures/pairing_qr.dart | 30 +++ .../test/pairing_paste_dialog_test.dart | 93 ++++++++++ flutter_sender/test/widget_test.dart | 95 ++++++++-- .../flutter/generated_plugin_registrant.cc | 3 + .../windows/flutter/generated_plugins.cmake | 1 + .../windows/runner/video_texture.cpp | 26 ++- flutter_sender/windows/runner/video_window.h | 2 +- installer/README.md | 10 + installer/prune-artifacts.ps1 | 47 +++++ installer/release.ps1 | 50 +++++ installer/windows/setup.iss | 18 ++ installer/windows/setup.ps1 | 4 +- .../windows/stop-installed-processes.ps1 | 18 ++ rust_core/Cargo.lock | 3 +- rust_core/Cargo.toml | 3 +- rust_core/src/demo_server.rs | 135 +++++++++++--- rust_core/src/ffi.rs | 1 + rust_core/src/lib.rs | 2 +- rust_core/src/media/packet.rs | 32 +++- rust_core/src/media/receiver.rs | 28 ++- rust_core/src/session/tls.rs | 9 + 38 files changed, 1173 insertions(+), 196 deletions(-) create mode 100644 docs/streaming-troubleshooting.md create mode 100644 flutter_sender/lib/core/pairing_input.dart create mode 100644 flutter_sender/lib/features/discovery/pairing_paste_dialog.dart create mode 100644 flutter_sender/test/core/diagnostic_log_test.dart create mode 100644 flutter_sender/test/core/pairing_input_test.dart create mode 100644 flutter_sender/test/fixtures/pairing_qr.dart create mode 100644 flutter_sender/test/pairing_paste_dialog_test.dart create mode 100644 installer/prune-artifacts.ps1 create mode 100644 installer/release.ps1 create mode 100644 installer/windows/stop-installed-processes.ps1 diff --git a/AGENTS.md b/AGENTS.md index 86eb8aa..4b671a5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,9 @@ 2. 提交信息用**中文** Conventional Commits(`feat(scope): ...` / `fix(scope): ...`),正文用 `- ` 列要点。 3. 提交时排除构建产物:`android_receiver/.remotecompile/`、`android_receiver/app/build/`、`flutter_sender/build/`、`rust_core/target/`、`dist/`。 4. 改协议(控制帧 msgType / payload 布局)必须**三端同步**:`rust_core`、`android_receiver`、`flutter_sender`,并更新 `README.md` 里的协议表。 +5. **每轮代码修改交付时递增版本并重新生成安装包**:同步 Flutter `version`、Android `versionName/versionCode` 与 Rust crate 版本,补丁至少加一,不能用旧版本号覆盖新代码。编译和测试通过后打 Android 三种签名 APK 与 Windows 安装器。 +6. 新安装包验证成功后清理 `dist/` 内旧版本安装包、归档和暂存 bundle,只保留最新交付版本;保留用户提供的日志、测试记录和诊断文件,不删除源码、签名密钥、SDK 或依赖缓存。清理前校验绝对路径位于仓库 `dist/` 内。 + 默认执行 `installer/release.ps1 -VCRedist <路径> [-Iscc <路径>]`,自动递增补丁版本和构建号、同步三端版本、编译测试打包并清理旧产物;本轮已手动递增时才用 `-UseCurrentVersion`。 ## 编译验证命令 diff --git a/README.md b/README.md index 39c09dd..0925a62 100644 --- a/README.md +++ b/README.md @@ -501,7 +501,7 @@ POST /mirror/request?token= 触发一次投屏确认(便 | 层 | 机制 | | --- | --- | | 发现 | mDNS TXT 带应用签名 `fp`;仅公布指纹本身不等于证明连接身份 | -| 配对 | 被控端生成二维码,主控端支持粘贴配对链接;相机扫码、TOTP PIN 尚未实现 | +| 配对 | 被控端生成二维码;桌面端“扫码配对”窗口支持 Ctrl+V 粘贴配对文本、二维码截图或图片文件,预览后点击确认才识别与校验;无相机扫描,TOTP PIN 尚未实现 | | 传输 | 控制通道 TLS 1.3 + 自签证书 pinning(`tls=` 指纹),无指纹时明文;控制帧 AES-256-GCM | | 会话 | ECDH P-256 → AES-256-GCM | | 媒体 | v2 AES-256-GCM、认证包头、滑动防重放窗口、完整分片重组;拒绝旧明文包 | diff --git a/android_receiver/app/build.gradle.kts b/android_receiver/app/build.gradle.kts index 8257cca..7f4b669 100644 --- a/android_receiver/app/build.gradle.kts +++ b/android_receiver/app/build.gradle.kts @@ -16,8 +16,8 @@ android { applicationId = "com.ttstd.lancast.receiver" minSdk = 26 targetSdk = 35 - versionCode = 1 - versionName = "0.1.0" + versionCode = 4 + versionName = "0.1.3" testInstrumentationRunner = "com.ttstd.lancast.receiver.MediaProtocolInstrumentation" } diff --git a/android_receiver/app/src/androidTest/java/com/ttstd/lancast/receiver/MediaProtocolInstrumentation.kt b/android_receiver/app/src/androidTest/java/com/ttstd/lancast/receiver/MediaProtocolInstrumentation.kt index 5aaea51..d4253c0 100644 --- a/android_receiver/app/src/androidTest/java/com/ttstd/lancast/receiver/MediaProtocolInstrumentation.kt +++ b/android_receiver/app/src/androidTest/java/com/ttstd/lancast/receiver/MediaProtocolInstrumentation.kt @@ -27,6 +27,13 @@ class MediaProtocolInstrumentation : Instrumentation() { check(packet.size == payload.size + MediaPackets.OVERHEAD) check(decrypt(packet, key).contentEquals(payload)) check(!MediaPackets.encode(payload, 42, 1, key).contentEquals(packet)) + // Exercise cached Cipher reinitialization and alternating audio/video keys. + val otherKey = ByteArray(32) { (it + 1).toByte() } + repeat(200) { index -> + val activeKey = if (index % 2 == 0) key else otherKey + val encoded = MediaPackets.encode(payload, index.toLong(), 1, activeKey) + check(decrypt(encoded, activeKey).contentEquals(payload)) + } val tampered = packet.clone().apply { this[lastIndex] = (this[lastIndex].toInt() xor 1).toByte() } check(runCatching { decrypt(tampered,key) }.isFailure) check(runCatching { decrypt(packet,ByteArray(32)) }.isFailure) diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt index b2d9fa3..fd5a326 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/session/MediaPackets.kt @@ -28,6 +28,15 @@ object MediaPackets { const val FRAGMENT_PAYLOAD_SIZE = 1152 private const val HEADER_SIZE = 37 + // 视频与音频各在线程内复用密码上下文;每个包仍使用全局唯一 nonce。 + // 避免每个 1152 字节分片都执行 HKDF 和 JCA provider 查找。 + private class Encoder { + var sessionKey: ByteArray? = null + var packetKey: SecretKeySpec? = null + val cipher: Cipher = Cipher.getInstance("AES/GCM/NoPadding") + } + private val encoders = ThreadLocal.withInitial { Encoder() } + fun encode(payload: ByteArray, pts: Long, flags: Int, sessionKey: ByteArray, frameId: Long = nextFrameId(), fragmentIndex: Int = 0, fragmentCount: Int = 1): ByteArray { require(payload.size <= FRAGMENT_PAYLOAD_SIZE && fragmentCount in 1..8192 && fragmentIndex in 0 until fragmentCount && frameId > 0) @@ -47,10 +56,15 @@ object MediaPackets { put("and2".toByteArray(Charsets.US_ASCII)); putLong(sequence) }.array() // Domain separation from the outer relay-media AES-GCM key. - val prk = hmac("ttstdconnect-v1".toByteArray(Charsets.UTF_8), sessionKey) - val key = hmac(prk, "lancast/media/packet/v2".toByteArray(Charsets.UTF_8) + byteArrayOf(1)) - val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { - init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce)) + val encoder = encoders.get()!! + if (encoder.sessionKey?.contentEquals(sessionKey) != true) { + val prk = hmac("ttstdconnect-v1".toByteArray(Charsets.UTF_8), sessionKey) + val key = hmac(prk, "lancast/media/packet/v2".toByteArray(Charsets.UTF_8) + byteArrayOf(1)) + encoder.packetKey = SecretKeySpec(key, "AES") + encoder.sessionKey = sessionKey.copyOf() + } + val cipher = encoder.cipher.apply { + init(Cipher.ENCRYPT_MODE, encoder.packetKey, GCMParameterSpec(128, nonce)) updateAAD(header) } return header + nonce + cipher.doFinal(payload) diff --git a/docs/streaming-troubleshooting.md b/docs/streaming-troubleshooting.md new file mode 100644 index 0000000..e743ec6 --- /dev/null +++ b/docs/streaming-troubleshooting.md @@ -0,0 +1,68 @@ +# 2026-11-28 串流停顿与关窗排查 + +输入证据:用户提供的 `dist/ttstd_connect.log`,12:47:26 至 12:49:55。 + +## 已确认 + +- 12:49:33 至 12:49:38,`received=decoded=645`、`pending=0`、解码错误为空; + 随后增至 663。说明观察到的停顿期间没有新访问单元到达解码队列,不能据此归因于解码积压。 +- 12:49:38 后窗口关闭,但主控持续记录到 12:49:55;这次关窗不是主控进程退出。 +- 原主控连续 5 秒未解码新帧便发送 stopMirror 并关闭窗口,网络抖动或静止画面会触发误停。 + +## 修复 + +- 收帧暂停时保留最后画面、窗口和会话,恢复后继续;明确停止/断连和首次确认/首帧超时仍会结束投屏。 +- Android 在线程内复用 AES-GCM Cipher,按会话密钥缓存派生密钥;Rust 接收端缓存 HKDF 和 AES 密钥调度。 + 包格式、AAD、唯一 nonce、防重放和认证后切换会话的约束保持一致。 +- UDP 接收缓冲申请 4 MiB,缓解关键帧密集分片时的本机缓冲溢出;系统可能限制实际大小。 +- Windows 只在解码线程操作解码器与 Rust 接口,将诊断字符串安全发布到界面线程; + 窗口句柄使用原子访问,销毁窗口前先停止并等待解码线程退出。 +- 周期诊断日志改为有界异步顺序写盘,移除界面线程上的逐条强制刷新。 + +## 验证与边界 + +- Windows Rust:`cargo check --offline`、56 项单元测试、6 项集成测试通过;Release 核心库构建成功。 +- WSL Ubuntu-24.04:Rust 离线编译检查和 56 项单元测试通过。 +- Flutter:`dart analyze lib`、14 项测试、Windows Debug/Release 构建通过。 +- Android:neutral/aosp Kotlin 编译、三种 Release APK 构建通过;仅在 emulator-5554 + 运行 JCA 加密测试,覆盖 200 次交替密钥加密、解密、篡改拒绝和 nonce 唯一性。 +- 本轮没有真实网络下的流畅度提升测量,没有普通签名真机音频验收,不宣称实际进程闪退已复现或根治。 + 如主控整个退出,需对应时间的 Windows Application Error/WER 或 dump;如 Android 退出,需该设备的 logcat 崩溃堆栈。 +- 用户此前暂缓的真机与跨网段验收仍按 `AGENTS.md` 保留待办。 + +复测时同时更新两端,使用与原 Android 安装相同签名的 APK。先观察连续画面,再保持静止超过 5 秒、 +恢复操作,确认窗口不误关;重复停止、关窗与重连。保留对应版本和时间段日志。 + +## 0.1.1:点击后界面阻塞 + +用户补充停顿由点击串流窗口触发。代码路径为 Win32 输入回调 → Dart → 同步 FFI → +`demo_server::send_control` → TCP/TLS 写入或中继 HTTP。原来发送调用在界面线程等待网络, +且 TLS 接收线程持有读写共用的 mutex 阻塞读取,可能导致写线程持续等锁。 + +- 控制事件进入每连接独立、容量 128 的 FIFO,后台加密并写入;FFI 成功表示已入队。 + 入队不等待网络,满队列/写线程退出明确返回错误,异步写入失败进入诊断事件;输入回调处理入队失败提示。 +- TLS 先读取已解密缓冲,再通过克隆 socket 在 mutex 外 `peek` 等待;有网络数据才持锁读取 TLS。 + TCP 开启 `TCP_NODELAY` 并设置写入超时。网络半包仍可能延迟后台线程,但不再同步阻塞输入回调。 +- 新增阻塞写端下入队不阻塞、有界容量、FIFO 和唯一 nonce 回归测试。 +- Windows 与 WSL Ubuntu-24.04 均通过 58 项 Rust 单元测试;Windows 另通过 6 项集成测试。 + 真实 TLS 回环连接完成证书 pinning 和 ECDH 后,在对端不发数据时连续发送 50 个加密控制事件: + FFI 入队最大 0.063 ms、平均 0.029 ms;对端收到事件最大 0.376 ms、平均 0.205 ms。 + 该数据仅代表本机回环,不代表真实网络或 Android 输入执行耗时;原始结果位于 `dist/validation/tls-idle-input/result.json`。 +- Android/Flutter/Rust 同步升为 0.1.1,Android versionCode 与 Flutter build 为 2; + `installer/release.ps1` 负责后续默认递增、验证、打包和清理。 +- 安装器更新前按完整路径停止目标目录的主控与信令进程。停止脚本已用两个临时同名信令进程实测, + 目标实例被停止,其他目录实例保留;包含空格、单引号的路径通过测试。 + +仍需用户在原设备上重复点击、拖拽和长按,确认实际操作延迟;上述回归测试不替代真实设备性能测量。 + +## 0.1.2:选择 .141 后请求投屏失败 + +用户新日志(13:46:00 至 13:48:06)仅在 13:46:34 记录向 `192.168.100.50` 发起连接; +后续界面 `target` 已变为 `192.168.100.141`,但 `demoStatus.peerIp` 始终为 `.50`、 +`peerConnected/keyEstablished` 为 true,没有向 `.141` 发起连接的记录。 +因此本次请求发往旧设备,旧设备返回确认超时;日志不能证明 `.141` 自身不可达。 + +修复设备切换流程:先禁用控制与投屏、结束旧窗口和会话,成功后才更新所选设备;用户再点击连接。 +发现列表刷新不替换仍在连接中的设备;配对导入也复用该流程;切换设备后放弃旧设备迟到的指纹确认/中继连接操作。 +新增 Widget 回归测试模拟活动设备消失、选择第二台设备、断开异步等待,验证不会把旧连接标成新设备已连接。 +版本同步递增并重新生成安装器;真实 `.141` 连接仍需用户在其网络中复测。 diff --git a/flutter_sender/lib/core/diagnostic_log.dart b/flutter_sender/lib/core/diagnostic_log.dart index c7ff122..90a0781 100644 --- a/flutter_sender/lib/core/diagnostic_log.dart +++ b/flutter_sender/lib/core/diagnostic_log.dart @@ -5,6 +5,8 @@ class DiagnosticLog { final String fileName; File? _file; + Future _writes = Future.value(); + int _pendingCharacters = 0; String get path => _file?.path ?? ''; @@ -32,25 +34,36 @@ class DiagnosticLog { } void write(String message) { - message = message.replaceAll(RegExp(r'#token=[^\s;)]*'), '#token=[redacted]'); + message = + message.replaceAll(RegExp(r'#token=[^\s;)]*'), '#token=[redacted]'); final file = _file; if (file == null) return; - try { - if (file.lengthSync() > 2 * 1024 * 1024) { - file.writeAsStringSync( - '=== log rotated: ${DateTime.now().toIso8601String()} ===\n', - mode: FileMode.write, - flush: true, + final line = '${DateTime.now().toIso8601String()} $message\n'; + // Slow disks must not block input/painting or create an unbounded log queue. + if (_pendingCharacters + line.length > 256 * 1024) return; + _pendingCharacters += line.length; + _writes = _writes.then((_) async { + try { + if (await file.length() > 2 * 1024 * 1024) { + await file.writeAsString( + '=== log rotated: ${DateTime.now().toIso8601String()} ===\n', + mode: FileMode.write, + ); + } + await file.writeAsString( + line, + mode: FileMode.append, ); + } on Object catch (_) { + // Logging failure must not interrupt the stream or poison later writes. + } finally { + _pendingCharacters -= line.length; } - file.writeAsStringSync( - '${DateTime.now().toIso8601String()} $message\n', - mode: FileMode.append, - flush: true, - ); - } on Object catch (_) {} + }); } + Future flush() => _writes; + void dispose() { write('=== stopped ==='); _file = null; diff --git a/flutter_sender/lib/core/pairing_input.dart b/flutter_sender/lib/core/pairing_input.dart new file mode 100644 index 0000000..5fe1852 --- /dev/null +++ b/flutter_sender/lib/core/pairing_input.dart @@ -0,0 +1,120 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/services.dart'; +import 'package:image/image.dart' as img; +import 'package:pasteboard/pasteboard.dart'; +import 'package:zxing2/qrcode.dart'; + +import 'pairing.dart'; + +const maxPairingImageBytes = 16 * 1024 * 1024; + +class PairingClipboardContent { + const PairingClipboardContent({this.text, this.image}); + final String? text; + final Uint8List? image; +} + +Future readPairingClipboard() async { + final image = await Pasteboard.image; + if (image != null && image.isNotEmpty) { + if (image.length > maxPairingImageBytes) + throw const FormatException('图片过大,请复制较小的二维码截图(不超过 16 MB)'); + return PairingClipboardContent(image: image); + } + final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text; + if (text != null && text.trim().isNotEmpty) { + if (text.length > 32768) throw const FormatException('配对文本过长,请只复制配对链接'); + return PairingClipboardContent(text: text); + } + for (final path in await Pasteboard.files()) { + if (!RegExp(r'\.(png|jpe?g|bmp|webp|gif)$', caseSensitive: false) + .hasMatch(path)) continue; + final file = File(path); + if (await file.length() > maxPairingImageBytes) + throw const FormatException('图片过大,请使用不超过 16 MB 的图片'); + final bytes = await file.readAsBytes(); + if (bytes.length > maxPairingImageBytes) + throw const FormatException('图片过大'); + return PairingClipboardContent(image: bytes); + } + throw const FormatException('剪贴板中没有配对文本或图片,请复制后重试'); +} + +PairingUri parsePairingText(String text) { + try { + final links = + RegExp(r'''lancast://pair\?[^\s<>"']+''', caseSensitive: false) + .allMatches(text) + .toList(); + if (links.length > 1) throw const FormatException('检测到多个配对链接,请只粘贴一个设备的信息'); + final pairing = + PairingUri.parse(links.isEmpty ? text : links.single.group(0)!); + if (pairing == null || InternetAddress.tryParse(pairing.ip) == null) { + throw const FormatException('配对链接无效,请检查 IP 地址和端口'); + } + bool validDigest(String value) => + RegExp(r'^(sha256:)?[0-9a-f]{64}$', caseSensitive: false) + .hasMatch(value); + if (!validDigest(pairing.fingerprint)) + throw const FormatException('配对链接缺少有效的设备指纹,请重新复制被控端的配对信息'); + if (pairing.tlsFingerprint.isNotEmpty && + !validDigest(pairing.tlsFingerprint)) { + throw const FormatException('配对链接中的 TLS 指纹无效'); + } + return pairing; + } on FormatException { + rethrow; + } on Object { + throw const FormatException('无法解析配对链接,请重新复制'); + } +} + +// Called in a background isolate only after the user confirms the preview. +PairingUri parsePairingImage(Uint8List bytes) { + if (bytes.isEmpty || bytes.length > maxPairingImageBytes) + throw const FormatException('图片大小无效'); + final decoder = img.findDecoderForData(bytes); + final info = decoder?.startDecode(bytes); + if (info == null) throw const FormatException('无法读取图片,请粘贴 PNG、JPEG 或二维码截图'); + if (info.width <= 0 || + info.height <= 0 || + info.width * info.height > 16000000) { + throw const FormatException('图片分辨率过大,请裁剪到二维码区域后重试'); + } + var image = decoder!.decodeFrame(0); + if (image == null) throw const FormatException('图片已损坏或不受支持'); + image = img.bakeOrientation(image); + if (image.width > 2048 || image.height > 2048) { + image = img.copyResize(image, + width: image.width >= image.height ? 2048 : null, + height: image.height > image.width ? 2048 : null); + } + // White background also handles transparent QR images correctly. + final flattened = + img.Image(width: image.width, height: image.height, numChannels: 4); + img.fill(flattened, color: img.ColorRgba8(255, 255, 255, 255)); + img.compositeImage(flattened, image); + var oriented = flattened; + for (var rotation = 0; rotation < 4; rotation++) { + final pixels = oriented.getBytes(order: img.ChannelOrder.bgra); + final source = RGBLuminanceSource( + oriented.width, + oriented.height, + Int32List.view( + pixels.buffer, pixels.offsetInBytes, pixels.length ~/ 4)); + String? text; + for (final candidate in [source, source.invert()]) { + try { + text = QRCodeReader() + .decode(BinaryBitmap(HybridBinarizer(candidate))) + .text; + break; + } on ReaderException {/* Try the other orientation/polarity. */} + } + if (text != null) return parsePairingText(text); + oriented = img.copyRotate(oriented, angle: 90); + } + throw const FormatException('未识别到二维码,请使用清晰、完整的单个配对二维码图片'); +} diff --git a/flutter_sender/lib/features/discovery/pairing_paste_dialog.dart b/flutter_sender/lib/features/discovery/pairing_paste_dialog.dart new file mode 100644 index 0000000..328e4e4 --- /dev/null +++ b/flutter_sender/lib/features/discovery/pairing_paste_dialog.dart @@ -0,0 +1,136 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../core/pairing.dart'; +import '../../core/pairing_input.dart'; + +class PairingPasteDialog extends StatefulWidget { + const PairingPasteDialog( + {super.key, this.readClipboard = readPairingClipboard, this.decodeImage}); + final Future Function() readClipboard; + final Future Function(Uint8List)? decodeImage; + + @override + State createState() => _PairingPasteDialogState(); +} + +class _PairingPasteDialogState extends State { + PairingClipboardContent? _content; + bool _busy = false; + String? _error; + + Future _paste() async { + if (_busy) return; + setState(() { + _busy = true; + _error = null; + }); + try { + final content = await widget.readClipboard(); + if (mounted) setState(() => _content = content); + } on Object catch (error) { + if (mounted) + setState(() { + _content = null; + _error = _message(error); + }); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + String _message(Object error) => + error is FormatException ? error.message : '读取或识别失败,请重新复制后重试'; + + Future _confirm() async { + final content = _content; + if (_busy || content == null) return; + setState(() { + _busy = true; + _error = null; + }); + try { + final image = content.image; + final PairingUri pairing; + if (image != null) { + pairing = await (widget.decodeImage?.call(image) ?? + compute(parsePairingImage, image)); + } else { + pairing = parsePairingText(content.text ?? ''); + } + if (mounted) Navigator.of(context).pop(pairing); + } on Object catch (error) { + if (mounted) setState(() => _error = _message(error)); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) { + final image = _content?.image; + return CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.keyV, control: true): _paste, + const SingleActivator(LogicalKeyboardKey.keyV, meta: true): _paste, + }, + child: Focus( + autofocus: true, + child: AlertDialog( + title: const Text('扫码配对'), + content: SizedBox( + width: 480, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('按 Ctrl+V 粘贴配对文本或二维码图片。核对预览后,点击确认配对进行识别和校验。'), + const SizedBox(height: 16), + Container( + constraints: + const BoxConstraints(minHeight: 140, maxHeight: 260), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: image == null ? null : Colors.white, + border: Border.all( + color: Theme.of(context).colorScheme.outline), + borderRadius: BorderRadius.circular(8)), + child: image != null + ? Image.memory(image, + fit: BoxFit.contain, + cacheWidth: 640, + errorBuilder: (_, __, ___) => + const Text('图片预览不可用,可点击确认尝试识别或重新粘贴')) + : SingleChildScrollView( + child: Text(_content?.text ?? '等待粘贴…')), + ), + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: 12), + child: Text(_error!, + style: TextStyle( + color: Theme.of(context).colorScheme.error))), + if (_busy) + const Padding( + padding: EdgeInsets.only(top: 12), + child: LinearProgressIndicator()), + ]), + ), + ), + actions: [ + TextButton( + onPressed: _busy ? null : () => Navigator.of(context).pop(), + child: const Text('取消')), + TextButton( + onPressed: _busy ? null : _paste, child: const Text('粘贴')), + FilledButton( + onPressed: _busy || _content == null ? null : _confirm, + child: const Text('确认配对')), + ], + ), + ), + ); + } +} diff --git a/flutter_sender/lib/main.dart b/flutter_sender/lib/main.dart index 3839772..60b56b9 100644 --- a/flutter_sender/lib/main.dart +++ b/flutter_sender/lib/main.dart @@ -17,6 +17,7 @@ import 'core/pin_store.dart'; import 'core/watch_client.dart'; import 'features/control/control_toolbar.dart'; import 'features/discovery/device_list.dart'; +import 'features/discovery/pairing_paste_dialog.dart'; import 'features/file/file_browser_page.dart'; import 'features/session/connect_bar.dart'; import 'features/session/mirror_bar.dart'; @@ -76,6 +77,8 @@ class _HomePageState extends State { List _devices = const []; DeviceInfo? _selected; + bool _switchingDevice = false; + bool _pairingDialogOpen = false; ConnectionPhase _phase = ConnectionPhase.idle; AppSettings _settings = AppSettings.defaults; String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl; @@ -92,6 +95,7 @@ class _HomePageState extends State { bool _videoStreaming = false; int _lastWindowFrames = 0; DateTime? _lastVideoFrameAt; + DateTime? _lastControlErrorAt; DateTime? _mirrorRequestedAt; DateTime? _mirrorGrantedAt; int _videoWindowGeneration = 0; @@ -131,7 +135,7 @@ class _HomePageState extends State { } _bridge.watchPhase().listen((phase) { _diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})'); - if (mounted) setState(() => _phase = phase); + if (mounted && !_switchingDevice) setState(() => _phase = phase); }); _applySignalingSettings(); _refreshDevices(); @@ -189,7 +193,7 @@ class _HomePageState extends State { } void _refreshDemoStatus() { - if (_nativeCore == null || !mounted) return; + if (_nativeCore == null || !mounted || _switchingDevice) return; try { final wasConnected = _phase.isConnected; final status = _bridge.demoStatus(); @@ -344,7 +348,7 @@ class _HomePageState extends State { /// 被控端上行的剪贴板内容 → 写入本机剪贴板。 Future _applyRemoteClipboard(String text) async { - if (text.isEmpty || !_settings.clipboardSync) return; + if (_pairingDialogOpen || text.isEmpty || !_settings.clipboardSync) return; // 先记住这条内容,否则本机剪贴板轮询会把它当成「本机新复制」再发回去。 _lastClipboardText = text; await Clipboard.setData(ClipboardData(text: text)); @@ -356,7 +360,7 @@ class _HomePageState extends State { /// Windows 没有可订阅的剪贴板变更事件,只能定时读一次再和上次内容比较; /// 内容与 [_lastClipboardText] 相同说明是刚同步过来的,不再回送。 Future _syncLocalClipboard() async { - if (!mounted || _nativeCore == null) return; + if (!mounted || _nativeCore == null || _pairingDialogOpen) return; if (!_phase.isConnected || !_settings.clipboardSync) return; if (!_grantedAccess.allowsControl) return; final ClipboardData? data; @@ -366,6 +370,7 @@ class _HomePageState extends State { // 剪贴板被别的程序占用(Office 等的延迟渲染)时读会抛错,下一轮再试。 return; } + if (_pairingDialogOpen) return; final text = data?.text; if (text == null || text.isEmpty || text == _lastClipboardText) return; _lastClipboardText = text; @@ -454,9 +459,9 @@ class _HomePageState extends State { final lastFrame = _lastVideoFrameAt; final granted = _mirrorGrantedAt; final requested = _mirrorRequestedAt; - if (lastFrame != null && now.difference(lastFrame) > const Duration(seconds: 5)) { - await _abortMirror('被控端已停止发送画面,请重新请求投屏'); - } else if (lastFrame == null && granted != null && now.difference(granted) > const Duration(seconds: 15)) { + // 静止画面、网络抖动都可能暂时不产出新帧。保留窗口和会话, + // 恢复收帧后自动继续;只有明确停止/断连或首次授权超时才结束投屏。 + if (lastFrame == null && granted != null && now.difference(granted) > const Duration(seconds: 15)) { await _abortMirror('投屏已允许,但等待首帧超时'); } else if (lastFrame == null && granted == null && requested != null && now.difference(requested) > const Duration(minutes: 1)) { await _abortMirror('等待投屏确认超时'); @@ -468,7 +473,7 @@ class _HomePageState extends State { /// /// 被控端会弹窗确认,确认后才开始推流;这段时间窗口显示「等待画面」。 Future _requestMirror() async { - if (_videoWindowOpen || _mirrorRequesting) return; + if (_videoWindowOpen || _mirrorRequesting || _switchingDevice) return; if (!_mediaProtocolAgreed) { _snack('媒体加密协议尚未协商或版本不兼容,请升级两端后重新连接'); return; @@ -802,7 +807,8 @@ class _HomePageState extends State { setState(() { _devices = devices; if (_selected == null || - !devices.any((device) => PairedDeviceStore.sameDevice(device, _selected!))) { + (!_phase.isConnected && _phase != ConnectionPhase.probing && + !_switchingDevice && !devices.any((device) => PairedDeviceStore.sameDevice(device, _selected!)))) { _selected = devices.isEmpty ? null : devices.first; } _refreshing = false; @@ -829,52 +835,22 @@ class _HomePageState extends State { /// 导入 `lancast://pair?...`(扫码内容或手工粘贴)。 Future _showPairingDialog() async { - final controller = TextEditingController(); - final text = await showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('导入配对信息'), - content: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Text( - '用手机扫描被控端界面上的二维码,把得到的链接粘贴到这里;' - '也可以让被控端把链接文本发给你。', - style: TextStyle(fontSize: 13), - ), - const SizedBox(height: 12), - TextField( - controller: controller, - autofocus: true, - minLines: 1, - maxLines: 3, - decoration: const InputDecoration( - labelText: 'lancast://pair?...', - hintText: 'lancast://pair?ip=192.168.1.10&port=41001&fp=...', - ), - ), - ], - ), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('取消'), - ), - FilledButton( - onPressed: () => Navigator.of(context).pop(controller.text), - child: const Text('导入'), - ), - ], - ), - ); - controller.dispose(); - if (text == null || text.trim().isEmpty) return; - final pairing = PairingUri.parse(text); - if (pairing == null) { - _snack('配对信息无法识别,请确认粘贴的是 lancast://pair?... 链接'); - return; + if (_pairingDialogOpen) return; + _pairingDialogOpen = true; + PairingUri? pairing; + try { + pairing = await showDialog( + context: context, + builder: (_) => const PairingPasteDialog(), + ); + } finally { + // Do not forward pairing secrets to an already connected remote device. + try { + _lastClipboardText = (await Clipboard.getData(Clipboard.kTextPlain))?.text; + } on Object { /* Clipboard may be temporarily unavailable. */ } + _pairingDialogOpen = false; } + if (!mounted || pairing == null) return; final device = pairing.toDevice(); // 配对链接本身就是带外渠道,导入即可信:直接写 pin,后续连接走一致性校验。 if (device.fingerprint.isNotEmpty) { @@ -887,21 +863,47 @@ class _HomePageState extends State { ); setState(() { _devices = _mergePaired(_devices); - _selected = device; }); + await _selectDevice(device); _snack('已导入 ${device.name}'); } static String _pinKeyOf(DeviceInfo device) => device.id.trim().isNotEmpty ? device.id.trim() : '${device.ip}:${device.controlPort}'; + Future _selectDevice(DeviceInfo device) async { + if (_switchingDevice || (_selected != null && PairedDeviceStore.sameDevice(_selected!, device))) return; + _switchingDevice = true; + try { + final needsDisconnect = _phase != ConnectionPhase.idle || _demoRunning || _relayActive || _videoWindowOpen; + if (needsDisconnect) { + _diagnosticLog.write('device switch: ${_selected?.ip} -> ${device.ip}; disconnect old session'); + // Disable controls before the first await; selection must not relabel a live socket. + setState(() { + _phase = ConnectionPhase.idle; + _mediaProtocolAgreed = false; + _grantedAccess = AccessLevel.view; + }); + await _disconnect(); + } + if (mounted) setState(() => _selected = device); + } on Object catch (error) { + _diagnosticLog.write('device switch failed: $error'); + if (mounted) _snack('旧设备断开失败,请重试切换设备'); + } finally { + _switchingDevice = false; + } + } + Future _connect() async { + if (_switchingDevice) return; final device = _selected; if (device == null) return; _diagnosticLog.write( 'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}', ); if (!await _confirmFingerprint(device)) return; + if (!mounted || _selected == null || !PairedDeviceStore.sameDevice(_selected!, device)) return; if (_settings.relayEnabled) { await _connectViaRelay(device); return; @@ -941,7 +943,7 @@ class _HomePageState extends State { if (mounted) _snack('信令连接失败:$error'); return; } - if (!mounted) return; + if (!mounted || _selected == null || !PairedDeviceStore.sameDevice(_selected!, device)) return; final error = _bridge.startRelay(device, signalingUrl); if (!mounted) return; if (error != null) { @@ -1052,52 +1054,7 @@ class _HomePageState extends State { _applySessionConfig(); } - Future _showPairing() async { - final uri = await _bridge.pairingUri(); - if (!mounted) return; - if (uri == null) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('当前平台不支持扫码配对')), - ); - return; - } - showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('扫码配对'), - content: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - width: 180, - height: 180, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(12), - ), - child: const Icon(Icons.qr_code_2, size: 140, color: Colors.black87), - ), - const SizedBox(height: 16), - SelectableText(uri, textAlign: TextAlign.center), - const SizedBox(height: 12), - Text( - '首次连接需在被控端确认指纹;配对时可选择“仅查看 / 查看+控制 / 全权限”。', - style: Theme.of(context).textTheme.bodySmall, - textAlign: TextAlign.center, - ), - ], - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('关闭'), - ), - ], - ), - ); - } + Future _showPairing() => _showPairingDialog(); void _sendControl(String type, Map payload) { // 控制栏的「发送剪贴板」:payload 不带文本时读本机剪贴板实时内容。 @@ -1105,7 +1062,14 @@ class _HomePageState extends State { unawaited(_sendLocalClipboard()); return; } - _bridge.sendControl(type, payload); + unawaited(_bridge.sendControl(type, payload).catchError((Object error) { + final now = DateTime.now(); + final previous = _lastControlErrorAt; + if (previous != null && now.difference(previous) < const Duration(seconds: 3)) return; + _lastControlErrorAt = now; + _diagnosticLog.write('control enqueue failed ($type): $error'); + if (mounted) _snack('控制发送队列不可用,请重新连接被控端'); + })); // 只有一次性动作才弹提示:触摸/鼠标/按键/滚轮是连续事件(拖拽时每秒几十条), // 每条都弹 SnackBar 会把 Flutter UI 线程压满,串流反而更卡。 const labels = { @@ -1160,7 +1124,7 @@ class _HomePageState extends State { child: DeviceList( devices: _devices, selectedId: _selected?.id, - onSelected: (device) => setState(() => _selected = device), + onSelected: _selectDevice, onRefresh: _refreshDevices, onPair: _showPairingDialog, refreshing: _refreshing, @@ -1184,7 +1148,7 @@ class _HomePageState extends State { child: DeviceList( devices: _devices, selectedId: _selected?.id, - onSelected: (device) => setState(() => _selected = device), + onSelected: _selectDevice, onRefresh: _refreshDevices, onPair: _showPairingDialog, refreshing: _refreshing, diff --git a/flutter_sender/linux/flutter/generated_plugin_registrant.cc b/flutter_sender/linux/flutter/generated_plugin_registrant.cc index e71a16d..d21238c 100644 --- a/flutter_sender/linux/flutter/generated_plugin_registrant.cc +++ b/flutter_sender/linux/flutter/generated_plugin_registrant.cc @@ -6,6 +6,10 @@ #include "generated_plugin_registrant.h" +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) pasteboard_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "PasteboardPlugin"); + pasteboard_plugin_register_with_registrar(pasteboard_registrar); } diff --git a/flutter_sender/linux/flutter/generated_plugins.cmake b/flutter_sender/linux/flutter/generated_plugins.cmake index 2e1de87..c242e0a 100644 --- a/flutter_sender/linux/flutter/generated_plugins.cmake +++ b/flutter_sender/linux/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + pasteboard ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/flutter_sender/macos/Flutter/GeneratedPluginRegistrant.swift b/flutter_sender/macos/Flutter/GeneratedPluginRegistrant.swift index cccf817..01b3d91 100644 --- a/flutter_sender/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/flutter_sender/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,6 +5,8 @@ import FlutterMacOS import Foundation +import pasteboard func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + PasteboardPlugin.register(with: registry.registrar(forPlugin: "PasteboardPlugin")) } diff --git a/flutter_sender/pubspec.lock b/flutter_sender/pubspec.lock index 4c8af15..7dd5017 100644 --- a/flutter_sender/pubspec.lock +++ b/flutter_sender/pubspec.lock @@ -1,6 +1,14 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + archive: + dependency: transitive + description: + name: archive + sha256: "2fda90592c0afd219c5e285618a98da835cd10df38372666093d25dfe457a2d0" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.7.1" async: dependency: transitive description: @@ -25,6 +33,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.4.1" + charcode: + dependency: transitive + description: + name: charcode + sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.0" clock: dependency: transitive description: @@ -65,6 +81,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "2.2.0" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.1" flutter: dependency: "direct main" description: flutter @@ -75,6 +99,19 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + image: + dependency: "direct main" + description: + name: image + sha256: bc13f61f0f5cb77936e78ae5dae3800f442718dac5d2bc4654f03c239230ed0c + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.13.1" leak_tracker: dependency: transitive description: @@ -131,6 +168,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.19.0" + pasteboard: + dependency: "direct main" + description: + name: pasteboard + sha256: "7b1c7ed83b4ff27acced26e96b87c16ac37fb6c57d7886eb3130faccb28b2cc2" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.6.2" path: dependency: transitive description: @@ -139,6 +184,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.9.1" + posix: + dependency: transitive + description: + name: posix + sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63" + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.5.4" sky_engine: dependency: transitive description: flutter @@ -192,6 +245,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "0.7.14" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.6.0" vector_math: dependency: transitive description: @@ -208,6 +269,22 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "15.4.0" + web: + dependency: transitive + description: + name: web + sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.2" + zxing2: + dependency: "direct main" + description: + name: zxing2 + sha256: "2677c49a3b9ca9457cb1d294fd4bd5041cac6aab8cdb07b216ba4e98945c684f" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.2.4" sdks: - dart: ">=3.13.0-0 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + dart: ">=3.13.0 <4.0.0" + flutter: ">=3.44.0" diff --git a/flutter_sender/pubspec.yaml b/flutter_sender/pubspec.yaml index d4d9f62..7413acc 100644 --- a/flutter_sender/pubspec.yaml +++ b/flutter_sender/pubspec.yaml @@ -1,7 +1,7 @@ name: ttstd_sender description: TTSTDConnect 跨平台主控端(Flutter UI + Rust Core 桥接) publish_to: none -version: 0.1.0+1 +version: 0.1.3+4 environment: sdk: '>=3.4.0 <4.0.0' @@ -11,6 +11,9 @@ dependencies: sdk: flutter ffi: ^2.1.0 crypto: ^3.0.6 + pasteboard: ^0.6.2 + zxing2: ^0.2.4 + image: ^4.13.1 dev_dependencies: flutter_test: diff --git a/flutter_sender/test/core/diagnostic_log_test.dart b/flutter_sender/test/core/diagnostic_log_test.dart new file mode 100644 index 0000000..1fb09d9 --- /dev/null +++ b/flutter_sender/test/core/diagnostic_log_test.dart @@ -0,0 +1,54 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:ttstd_sender/core/diagnostic_log.dart'; + +void main() { + test( + 'asynchronous logs preserve order, redact tokens and finish after dispose', + () async { + final log = DiagnosticLog( + 'ttstd_log_test_${DateTime.now().microsecondsSinceEpoch}.log'); + log.start(); + final file = File(log.path); + addTearDown(() async { + await log.flush(); + if (await file.exists()) await file.delete(); + }); + log.write('first #token=secret'); + log.write('second'); + log.dispose(); + await log.flush(); + final text = await file.readAsString(); + expect(text, contains('first #token=[redacted]')); + expect(text, isNot(contains('secret'))); + expect(text.indexOf('first'), lessThan(text.indexOf('second'))); + expect(text.indexOf('second'), lessThan(text.indexOf('=== stopped ==='))); + }); + + test('log rotation and failed writes do not prevent later writes', () async { + final log = DiagnosticLog( + 'ttstd_log_test_${DateTime.now().microsecondsSinceEpoch}.log'); + log.start(); + final file = File(log.path); + addTearDown(() async { + log.dispose(); + await log.flush(); + if (await file.exists()) await file.delete(); + }); + await file.writeAsString('x' * (2 * 1024 * 1024 + 1)); + log.write('after rotation'); + await log.flush(); + expect( + await file.readAsString(), + allOf(contains('log rotated:'), contains('after rotation'), + isNot(startsWith('xxx')))); + await file.delete(); + log.write('unavailable file'); + await log.flush(); + await file.writeAsString('recovered\n'); + log.write('after recovery'); + await log.flush(); + expect(await file.readAsString(), contains('after recovery')); + }); +} diff --git a/flutter_sender/test/core/pairing_input_test.dart b/flutter_sender/test/core/pairing_input_test.dart new file mode 100644 index 0000000..0c0000d --- /dev/null +++ b/flutter_sender/test/core/pairing_input_test.dart @@ -0,0 +1,37 @@ +import 'dart:typed_data'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ttstd_sender/core/pairing_input.dart'; +import '../fixtures/pairing_qr.dart'; + +void main() { + test('parses pairing links in copied text and validates identity fields', () { + expect(parsePairingText('配对信息:\n$pairingText\n').ip, '192.168.100.141'); + for (final invalid in [ + 'hello', + '$pairingText\n$pairingText', + pairingText.replaceFirst('41001', '70000'), + pairingText.replaceFirst('192.168.100.141', 'invalid'), + 'lancast://pair?ip=127.0.0.1&port=41001', + '$pairingText&tls=invalid' + ]) { + expect(() => parsePairingText(invalid), throwsFormatException); + } + }); + test('decodes color, grayscale and rotated QR images', () { + for (final bytes in [ + pairingQr(), + pairingQr(grayscale: true), + pairingQr(rotate: true) + ]) { + final result = parsePairingImage(bytes); + expect(result.deviceId, 'test-qr'); + expect(result.ip, '192.168.100.141'); + } + }); + test('rejects malformed or oversized image data', () { + expect(() => parsePairingImage(Uint8List.fromList([1, 2, 3])), + throwsFormatException); + expect(() => parsePairingImage(Uint8List(maxPairingImageBytes + 1)), + throwsFormatException); + }); +} diff --git a/flutter_sender/test/fixtures/pairing_qr.dart b/flutter_sender/test/fixtures/pairing_qr.dart new file mode 100644 index 0000000..0670f61 --- /dev/null +++ b/flutter_sender/test/fixtures/pairing_qr.dart @@ -0,0 +1,30 @@ +import 'dart:typed_data'; +import 'package:image/image.dart' as img; +import 'package:zxing2/qrcode.dart'; + +final pairingText = + 'lancast://pair?ip=192.168.100.141&port=41001&fp=${'ab' * 32}&id=test-qr&name=Receiver'; + +Uint8List pairingQr({bool rotate = false, bool grayscale = false}) { + final matrix = Encoder.encode(pairingText, ErrorCorrectionLevel.m).matrix!; + const scale = 5, margin = 4; + var image = img.Image( + width: (matrix.width + margin * 2) * scale, + height: (matrix.height + margin * 2) * scale, + numChannels: grayscale ? 1 : 4); + img.fill(image, color: img.ColorRgba8(255, 255, 255, 255)); + for (var y = 0; y < matrix.height; y++) { + for (var x = 0; x < matrix.width; x++) { + if (matrix.get(x, y) == 1) { + img.fillRect(image, + x1: (x + margin) * scale, + y1: (y + margin) * scale, + x2: (x + margin + 1) * scale - 1, + y2: (y + margin + 1) * scale - 1, + color: img.ColorRgba8(0, 0, 0, 255)); + } + } + } + if (rotate) image = img.copyRotate(image, angle: 90); + return img.encodePng(image); +} diff --git a/flutter_sender/test/pairing_paste_dialog_test.dart b/flutter_sender/test/pairing_paste_dialog_test.dart new file mode 100644 index 0000000..2fcae49 --- /dev/null +++ b/flutter_sender/test/pairing_paste_dialog_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ttstd_sender/core/pairing.dart'; +import 'package:ttstd_sender/core/pairing_input.dart'; +import 'package:ttstd_sender/features/discovery/pairing_paste_dialog.dart'; +import 'fixtures/pairing_qr.dart'; + +void main() { + Future open(WidgetTester tester, PairingPasteDialog dialog, + void Function(PairingUri?) result) async { + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () async => result(await showDialog( + context: context, builder: (_) => dialog)), + child: const Text('open'), + )))); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + } + + testWidgets('Ctrl+V previews text; only confirmation returns a pairing', + (tester) async { + PairingUri? result; + await open( + tester, + PairingPasteDialog( + readClipboard: () async => + PairingClipboardContent(text: pairingText)), + (value) => result = value); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyV); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + expect(find.text(pairingText), findsOneWidget); + expect(result, isNull); + await tester.tap(find.text('确认配对')); + await tester.pumpAndSettle(); + expect(result?.ip, '192.168.100.141'); + }); + + testWidgets('pasting image does not decode until confirmation', + (tester) async { + var decodes = 0; + PairingUri? result; + await open( + tester, + PairingPasteDialog( + readClipboard: () async => + PairingClipboardContent(image: pairingQr()), + decodeImage: (_) async { + decodes++; + return parsePairingText(pairingText); + }, + ), + (value) => result = value); + await tester.tap(find.text('粘贴')); + await tester.pumpAndSettle(); + expect(find.byType(Image), findsOneWidget); + expect(decodes, 0); + expect(result, isNull); + await tester.tap(find.text('确认配对')); + await tester.pumpAndSettle(); + expect(decodes, 1); + expect(result?.deviceId, 'test-qr'); + }); + + testWidgets('invalid text remains in dialog and can be replaced or cancelled', + (tester) async { + var text = 'invalid text'; + PairingUri? result; + await open( + tester, + PairingPasteDialog( + readClipboard: () async => PairingClipboardContent(text: text)), + (value) => result = value); + await tester.tap(find.text('粘贴')); + await tester.pumpAndSettle(); + expect(find.textContaining('配对链接无效'), findsNothing); + await tester.tap(find.text('确认配对')); + await tester.pumpAndSettle(); + expect(find.textContaining('配对链接无效'), findsOneWidget); + expect(find.byType(PairingPasteDialog), findsOneWidget); + text = pairingText; + await tester.tap(find.text('粘贴')); + await tester.pumpAndSettle(); + expect(find.textContaining('配对链接无效'), findsNothing); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(result, isNull); + }); +} diff --git a/flutter_sender/test/widget_test.dart b/flutter_sender/test/widget_test.dart index 0116335..3633e8e 100644 --- a/flutter_sender/test/widget_test.dart +++ b/flutter_sender/test/widget_test.dart @@ -1,8 +1,12 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ttstd_sender/core/models.dart'; import 'package:ttstd_sender/main.dart'; +import 'package:ttstd_sender/features/session/connect_bar.dart'; +import 'package:ttstd_sender/features/session/mirror_bar.dart'; const MethodChannel _methodChannel = MethodChannel('ttstd/sender'); const EventChannel _eventChannel = EventChannel('ttstd/sender/events'); @@ -22,7 +26,8 @@ DeviceInfo _testDevice() => const DeviceInfo( ); void _mockChannels({List devices = const [], String? pairingUri}) { - final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler(_methodChannel, (call) async { switch (call.method) { case 'discover': @@ -41,11 +46,69 @@ void _mockChannels({List devices = const [], String? pairingUri}) { void main() { tearDown(() { - final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler(_methodChannel, null); messenger.setMockStreamHandler(_eventChannel, null); }); + testWidgets('切换设备先断开旧连接,发现刷新不替换活动设备', (tester) async { + final first = _testDevice(); + const second = DeviceInfo( + id: 'second-device', + name: '另一设备', + ip: '192.168.100.141', + mediaPort: 41000, + controlPort: 41001, + fingerprint: 'second-fingerprint', + ); + final devices = [first, second]; + final disconnected = Completer(); + var disconnectCalls = 0; + late void Function(Object?) emitPhase; + _mockChannels(devices: devices); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(_methodChannel, (call) async { + if (call.method == 'discover') + return devices.map((device) => device.toJson()).toList(); + if (call.method == 'disconnect') { + disconnectCalls++; + await disconnected.future; + } + return null; + }); + messenger.setMockStreamHandler(_eventChannel, MockStreamHandler.inline( + onListen: (arguments, events) { + emitPhase = events.success; + }, + )); + await tester.pumpWidget(const TTSTDConnectApp()); + await tester.pumpAndSettle(_settleTimeout); + emitPhase('direct'); + await tester.pumpAndSettle(_settleTimeout); + expect(tester.widget(find.byType(MirrorBar)).connected, isTrue); + devices.remove(first); + await tester.tap(find.byIcon(Icons.refresh)); + await tester.pumpAndSettle(_settleTimeout); + expect(tester.widget(find.byType(ConnectBar)).device?.id, + first.id); + + await tester.tap(find.text('另一设备')); + await tester.pump(); + expect(disconnectCalls, 1); + expect(tester.widget(find.byType(MirrorBar)).connected, isFalse); + expect(tester.widget(find.byType(ConnectBar)).device?.id, + first.id); + disconnected.complete(); + await tester.pumpAndSettle(_settleTimeout); + final bar = tester.widget(find.byType(ConnectBar)); + expect(bar.device?.ip, '192.168.100.141'); + expect(bar.phase, ConnectionPhase.idle); + expect(tester.widget(find.byType(MirrorBar)).connected, isFalse); + await tester.pumpWidget(const SizedBox()); + }); + testWidgets('首页无设备时显示空态', (tester) async { _mockChannels(); await tester.pumpWidget(const TTSTDConnectApp()); @@ -69,28 +132,22 @@ void main() { expect(find.text('可连接设备'), findsOneWidget); }); - testWidgets('扫码配对对话框展示原生返回的 pairing URI', (tester) async { - const uri = 'lancast://pair?ip=10.0.0.2&port=41001&fp=test-fingerprint'; - _mockChannels(pairingUri: uri); - await tester.pumpWidget(const TTSTDConnectApp()); - await tester.pumpAndSettle(_settleTimeout); - - await tester.tap(find.byTooltip('扫码配对').first); - await tester.pumpAndSettle(_settleTimeout); - - expect(find.text('扫码配对'), findsOneWidget); - expect(find.text(uri), findsOneWidget); - }); - - testWidgets('配对码不可用时提示而不展示假 URI', (tester) async { + testWidgets('扫码配对入口打开粘贴窗口,不依赖原生扫码', (tester) async { _mockChannels(); await tester.pumpWidget(const TTSTDConnectApp()); await tester.pumpAndSettle(_settleTimeout); - await tester.tap(find.byTooltip('扫码配对').first); await tester.pumpAndSettle(_settleTimeout); - - expect(find.text('当前平台不支持扫码配对'), findsOneWidget); + expect(find.text('确认配对'), findsOneWidget); + expect(find.textContaining('Ctrl+V'), findsOneWidget); + expect(find.text('等待粘贴…'), findsOneWidget); + expect( + tester + .widget(find.widgetWithText(FilledButton, '确认配对')) + .onPressed, + isNull); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(_settleTimeout); }); testWidgets('设置页可切换本机信令与外部信令', (tester) async { diff --git a/flutter_sender/windows/flutter/generated_plugin_registrant.cc b/flutter_sender/windows/flutter/generated_plugin_registrant.cc index 8b6d468..7c2f20e 100644 --- a/flutter_sender/windows/flutter/generated_plugin_registrant.cc +++ b/flutter_sender/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,9 @@ #include "generated_plugin_registrant.h" +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + PasteboardPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PasteboardPlugin")); } diff --git a/flutter_sender/windows/flutter/generated_plugins.cmake b/flutter_sender/windows/flutter/generated_plugins.cmake index b93c4c3..6414160 100644 --- a/flutter_sender/windows/flutter/generated_plugins.cmake +++ b/flutter_sender/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + pasteboard ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/flutter_sender/windows/runner/video_texture.cpp b/flutter_sender/windows/runner/video_texture.cpp index 8b5e648..0ec7046 100644 --- a/flutter_sender/windows/runner/video_texture.cpp +++ b/flutter_sender/windows/runner/video_texture.cpp @@ -907,6 +907,10 @@ class VideoTexturePlugin : public flutter::Plugin { } ~VideoTexturePlugin() override { + stop_.store(true); + if (worker_.joinable()) { + worker_.join(); + } // 先摘掉回调,避免析构期间 DestroyWindow 触发 InvokeMethod。 video_window_.SetCloseHandler(nullptr); video_window_.SetInputHandler(nullptr); @@ -914,10 +918,6 @@ class VideoTexturePlugin : public flutter::Plugin { video_window_.SetWheelHandler(nullptr); video_window_.SetKeyboardHandler(nullptr); video_window_.Close(); - stop_.store(true); - if (worker_.joinable()) { - worker_.join(); - } if (texture_registrar_ != nullptr && texture_id_ != 0) { texture_registrar_->UnregisterTexture(texture_id_, std::function()); @@ -1028,7 +1028,7 @@ class VideoTexturePlugin : public flutter::Plugin { ? decoded - window_start_frame_ : 0)); map[flutter::EncodableValue("pending")] = - flutter::EncodableValue(static_cast(api_.Pending())); + flutter::EncodableValue(pending_count_.load()); map[flutter::EncodableValue("received")] = flutter::EncodableValue(static_cast(received_)); map[flutter::EncodableValue("width")] = @@ -1037,7 +1037,11 @@ class VideoTexturePlugin : public flutter::Plugin { flutter::EncodableValue(static_cast(height)); map[flutter::EncodableValue("pts")] = flutter::EncodableValue(static_cast(frames_->pts())); - std::string error = api_.error() + decoder_.error(); + std::string error; + { + std::lock_guard lock(diagnostic_mutex_); + error = diagnostic_error_; + } if (error.empty() && !saw_codec_config_.load() && keyframes_.load() > 0 && frames_->frames() == 0) { // 关键帧都收到了却始终没有 SPS/PPS,解码器会一直「吃数据不出图」且不报错, @@ -1071,6 +1075,13 @@ class VideoTexturePlugin : public flutter::Plugin { bool has_pending = false; while (!stop_.load()) { + // API function pointers and decoder strings belong to the worker thread. + // Publish a protected snapshot instead of reading them from the UI thread. + { + std::lock_guard lock(diagnostic_mutex_); + diagnostic_error_ = api_.error() + decoder_.error(); + } + pending_count_.store(static_cast(api_.Pending())); if (!has_pending) { if (!api_.EnsureLoaded()) { Sleep(kRetrySleepMs); @@ -1162,6 +1173,9 @@ class VideoTexturePlugin : public flutter::Plugin { bool closing_from_channel_ = false; RustVideoApi api_; VideoDecoder decoder_; + std::mutex diagnostic_mutex_; + std::string diagnostic_error_; + std::atomic pending_count_{0}; std::atomic stop_{false}; std::thread worker_; int64_t texture_id_ = 0; diff --git a/flutter_sender/windows/runner/video_window.h b/flutter_sender/windows/runner/video_window.h index 4d131ec..7f11ab3 100644 --- a/flutter_sender/windows/runner/video_window.h +++ b/flutter_sender/windows/runner/video_window.h @@ -88,7 +88,7 @@ class VideoWindow { void EnsureBackBuffer(HDC reference, int width, int height); void ReleaseBackBuffer(); - HWND hwnd_ = nullptr; + std::atomic hwnd_{nullptr}; std::atomic open_{false}; std::atomic repaint_pending_{false}; FrameProvider provider_; diff --git a/installer/README.md b/installer/README.md index 8255387..f5af320 100644 --- a/installer/README.md +++ b/installer/README.md @@ -6,6 +6,16 @@ ## Windows x64 +日常交付使用统一入口(默认递增补丁版本和构建号、同步 Android/Flutter/Rust,编译测试后生成三种 Android APK 与 Windows 安装器): + +```powershell +./installer/release.ps1 -VCRedist 'C:/path/to/vc_redist.x64.exe' -Iscc 'C:/path/to/ISCC.exe' +``` + +已在本轮手动递增版本时增加 `-UseCurrentVersion`,避免重复递增。产物位于 `dist/releases/v<版本>/`, +含 SHA256SUMS。新版成功生成后清理旧安装包和暂存目录;用户日志和本地设备配置保留在 `dist/validation/retained-artifact-data/`。 +安装器在覆盖文件前按完整路径停止目标安装目录中的主控与信令进程;停止失败时中止安装并提示重试。 + 需要 Windows Flutter/Visual Studio C++、Rust MSVC、Go、Inno Setup 6。 从 Microsoft/Visual Studio 获取官方 `vc_redist.x64.exe`,安装器会运行它安装运行库 (运行库安装可能请求管理员权限)。安装程序默认按当前用户安装,含开始菜单、可选桌面快捷方式、卸载入口。 diff --git a/installer/prune-artifacts.ps1 b/installer/prune-artifacts.ps1 new file mode 100644 index 0000000..c62c813 --- /dev/null +++ b/installer/prune-artifacts.ps1 @@ -0,0 +1,47 @@ +param([Parameter(Mandatory = $true)][string]$KeepVersion) +$ErrorActionPreference = 'Stop' +if ($KeepVersion -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid version' } +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$dist = [IO.Path]::GetFullPath((Join-Path $root 'dist')) +$keep = [IO.Path]::GetFullPath((Join-Path $dist "releases/v$KeepVersion")) +foreach ($name in @("TTSTDConnect-$KeepVersion-windows-x64-setup.exe", "TTSTDConnect-Receiver-$KeepVersion-neutral.apk", "TTSTDConnect-Receiver-$KeepVersion-aosp.apk", "TTSTDConnect-Receiver-$KeepVersion-zhanxun.apk", 'SHA256SUMS')) { + if (-not (Test-Path -LiteralPath (Join-Path $keep $name))) { throw "Latest release is incomplete: $name" } +} +function Remove-OwnedArtifact([string]$Path) { + if (-not (Test-Path -LiteralPath $Path)) { return } + $resolved = (Resolve-Path -LiteralPath $Path).Path + if (-not $resolved.StartsWith($dist + '\', [StringComparison]::OrdinalIgnoreCase) -or + $resolved -eq $keep -or $resolved.StartsWith($keep + '\', [StringComparison]::OrdinalIgnoreCase)) { + throw "Unsafe cleanup target: $resolved" + } + $item = Get-Item -LiteralPath $resolved + if ($item.PSIsContainer) { + $contents = @(Get-ChildItem -LiteralPath $resolved -Recurse -Force) + if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { + throw "Refusing a linked cleanup root: $resolved" + } + foreach ($link in ($contents | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint })) { + $linkPath = [IO.Path]::GetFullPath($link.FullName) + if (-not $linkPath.StartsWith($resolved + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Unsafe link: $linkPath" } + # Unlink the entry itself without recursion; never traverse its target. + Remove-Item -LiteralPath $linkPath -Force + } + # Preserve diagnostics and local app settings that accidentally landed in a bundle. + foreach ($file in ($contents | Where-Object { -not $_.PSIsContainer -and -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and ($_.Extension -eq '.log' -or $_.Name -like 'ttstd_*.json') })) { + $relative = $file.FullName.Substring($dist.Length + 1) + $saved = Join-Path $dist "validation/retained-artifact-data/$relative" + New-Item -ItemType Directory -Force -Path (Split-Path $saved) | Out-Null + Copy-Item -LiteralPath $file.FullName -Destination $saved -Force + } + } + Write-Output "Removing old artifact: $resolved" + Remove-Item -LiteralPath $resolved -Recurse -Force +} +Get-ChildItem -LiteralPath (Join-Path $dist 'releases') -Directory | Where-Object { $_.FullName -ne $keep } | ForEach-Object { Remove-OwnedArtifact $_.FullName } +$windows = Join-Path $dist 'windows' +if (Test-Path -LiteralPath $windows) { + Get-ChildItem -LiteralPath $windows -Directory -Filter 'stage-*' | ForEach-Object { Remove-OwnedArtifact $_.FullName } + Get-ChildItem -LiteralPath $windows -File -Filter 'TTSTDConnect-*-setup.exe' | Where-Object { $_.Name -ne "TTSTDConnect-$KeepVersion-windows-x64-setup.exe" } | ForEach-Object { Remove-OwnedArtifact $_.FullName } +} +foreach ($name in @('TTSTDConnect-Windows', 'TTSTDConnect-Android', 'linux', 'linux-signaling')) { Remove-OwnedArtifact (Join-Path $dist $name) } +Get-ChildItem -LiteralPath $dist -File | Where-Object { $_.Name -match '^(ttstdconnect[-_].*\.(deb|rpm)|TTSTDConnect-.*\.(AppImage|apk|exe|zip)|SHA256SUMS)$' } | ForEach-Object { Remove-OwnedArtifact $_.FullName } diff --git a/installer/release.ps1 b/installer/release.ps1 new file mode 100644 index 0000000..4692089 --- /dev/null +++ b/installer/release.ps1 @@ -0,0 +1,50 @@ +param( + [Parameter(Mandatory = $true)][string]$VCRedist, + [string]$Iscc, + [switch]$UseCurrentVersion +) +$ErrorActionPreference = 'Stop' +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$pubspec = Join-Path $root 'flutter_sender/pubspec.yaml' +$versionText = Get-Content -LiteralPath $pubspec -Raw +$match = [regex]::Match($versionText, '(?m)^version:\s*(\d+)\.(\d+)\.(\d+)\+(\d+)') +if (-not $match.Success) { throw 'Flutter version must be major.minor.patch+build' } +$version = "$($match.Groups[1]).$($match.Groups[2]).$($match.Groups[3])" +$build = [int]$match.Groups[4].Value +if (-not $UseCurrentVersion) { + $version = "$($match.Groups[1]).$($match.Groups[2]).$([int]$match.Groups[3].Value + 1)" + $build++ + $utf8 = [Text.UTF8Encoding]::new($false) + [IO.File]::WriteAllText($pubspec, [regex]::Replace($versionText, '(?m)^version:.*$', "version: $version+$build"), $utf8) + $android = Join-Path $root 'android_receiver/app/build.gradle.kts' + $text = Get-Content -LiteralPath $android -Raw + $text = [regex]::Replace($text, 'versionCode = \d+', "versionCode = $build") + $text = [regex]::Replace($text, 'versionName = "[^"]+"', "versionName = `"$version`"") + [IO.File]::WriteAllText($android, $text, $utf8) + $cargo = Join-Path $root 'rust_core/Cargo.toml' + $text = Get-Content -LiteralPath $cargo -Raw + [IO.File]::WriteAllText($cargo, [regex]::Replace($text, '(?m)^version = "[^"]+"', "version = `"$version`""), $utf8) +} +function Invoke-Checked([string]$Directory, [string]$Command, [string[]]$Arguments) { + Push-Location $Directory + try { & $Command @Arguments; if ($LASTEXITCODE -ne 0) { throw "$Command failed ($LASTEXITCODE)" } } + finally { Pop-Location } +} +$android = Join-Path $root 'android_receiver' +Invoke-Checked $android './gradlew.bat' @(':app:compileNeutralDebugKotlin', ':app:compileAospDebugKotlin', ':app:assembleNeutralRelease', ':app:assembleAospRelease', ':app:assembleZhanxunRelease', '--offline') +Invoke-Checked "$root/flutter_sender" flutter @('pub', 'get', '--offline') +Invoke-Checked "$root/flutter_sender" flutter @('test') +& "$PSScriptRoot/windows/setup.ps1" -VCRedist $VCRedist -Iscc $Iscc -Version $version +# setup.ps1 throws on a failed build; do not remove previous packages until all outputs exist. +$release = Join-Path $root "dist/releases/v$version" +New-Item -ItemType Directory -Force -Path $release | Out-Null +Copy-Item -LiteralPath "$root/dist/windows/TTSTDConnect-$version-windows-x64-setup.exe" -Destination $release +foreach ($flavor in @('neutral', 'aosp', 'zhanxun')) { + Copy-Item -LiteralPath "$android/app/build/outputs/apk/$flavor/release/app-$flavor-release.apk" -Destination "$release/TTSTDConnect-Receiver-$version-$flavor.apk" +} +Get-ChildItem -LiteralPath $release -File | Where-Object { $_.Extension -in '.apk', '.exe' } | ForEach-Object { + '{0} {1}' -f (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant(), $_.Name +} | Set-Content -LiteralPath "$release/SHA256SUMS" -Encoding ascii +@{ version = $version; build = $build; baseCommit = (git -C $root rev-parse HEAD); workingTreeModified = [bool](git -C $root status --porcelain); builtAt = [DateTimeOffset]::Now.ToString('o') } | ConvertTo-Json | Set-Content -LiteralPath "$release/BUILD-INFO.json" -Encoding utf8 +& "$PSScriptRoot/prune-artifacts.ps1" -KeepVersion $version +Write-Output "Release ready: $release" diff --git a/installer/windows/setup.iss b/installer/windows/setup.iss index a8a2d59..e4d7ce6 100644 --- a/installer/windows/setup.iss +++ b/installer/windows/setup.iss @@ -20,9 +20,11 @@ Compression=lzma2 SolidCompression=yes WizardStyle=modern CloseApplications=yes +RestartApplications=no [Tasks] Name: desktopicon; Description: "Create a desktop shortcut"; Flags: unchecked [Files] +Source: "stop-installed-processes.ps1"; Flags: dontcopy Source: "{#VCRedist}"; DestDir: "{tmp}"; DestName: "vc_redist.x64.exe"; Flags: deleteafterinstall Source: "{#BundleDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs [Icons] @@ -31,3 +33,19 @@ Name: "{autodesktop}\TTSTDConnect"; Filename: "{app}\ttstd_sender.exe"; Tasks: d [Run] Filename: "{tmp}\vc_redist.x64.exe"; Parameters: "/install /passive /norestart"; StatusMsg: "Installing Microsoft Visual C++ Runtime"; Flags: waituntilterminated Filename: "{app}\ttstd_sender.exe"; Description: "Launch TTSTDConnect"; Flags: nowait postinstall skipifsilent + +[Code] +function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ExitCode: Integer; +begin + Result := ''; + ExtractTemporaryFile('stop-installed-processes.ps1'); + if not Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), + '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' + + ExpandConstant('{tmp}\stop-installed-processes.ps1') + '" -InstallDir "' + + ExpandConstant('{app}') + '"', '', SW_HIDE, ewWaitUntilTerminated, ExitCode) then + Result := 'Unable to stop the installed application and signaling server.'; + if (Result = '') and (ExitCode <> 0) then + Result := 'The installed application or signaling server could not be stopped. Close it and retry.'; +end; diff --git a/installer/windows/setup.ps1 b/installer/windows/setup.ps1 index 9b4cf0d..defd0a3 100644 --- a/installer/windows/setup.ps1 +++ b/installer/windows/setup.ps1 @@ -40,7 +40,9 @@ if (-not $Bundle) { Invoke-Step "$root/flutter_sender" flutter @('build', 'windows', '--release') $Bundle = Join-Path $output ('stage-' + [guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Path $Bundle | Out-Null - Copy-Item "$root/flutter_sender/build/windows/x64/runner/Release/*" $Bundle -Recurse + Get-ChildItem "$root/flutter_sender/build/windows/x64/runner/Release" -File | + Where-Object { $_.Extension -in '.exe', '.dll' } | Copy-Item -Destination $Bundle + Copy-Item "$root/flutter_sender/build/windows/x64/runner/Release/data" $Bundle -Recurse Copy-Item "$root/rust_core/target/x86_64-pc-windows-msvc/release/ttstdconnect_core.dll" $Bundle Invoke-Step "$root/signaling_server" go @('build', '-o', "$Bundle/signaling_server.exe", '.') } diff --git a/installer/windows/stop-installed-processes.ps1 b/installer/windows/stop-installed-processes.ps1 new file mode 100644 index 0000000..97efd84 --- /dev/null +++ b/installer/windows/stop-installed-processes.ps1 @@ -0,0 +1,18 @@ +param([Parameter(Mandatory = $true)][string]$InstallDir) +$ErrorActionPreference = 'Stop' +$installPath = [IO.Path]::GetFullPath($InstallDir) +$ownedPaths = @('ttstd_sender.exe', 'signaling_server.exe') | ForEach-Object { Join-Path $installPath $_ } +# Match full executable paths, never terminate another installation by name alone. +Get-CimInstance Win32_Process -Filter "Name = 'ttstd_sender.exe' OR Name = 'signaling_server.exe'" | ForEach-Object { + if ($_.ExecutablePath -and $ownedPaths -contains $_.ExecutablePath) { + $process = Get-Process -Id $_.ProcessId -ErrorAction SilentlyContinue + if ($process) { + Write-Output "Stopping installed process: $($_.ExecutablePath) ($($_.ProcessId))" + if ($process.CloseMainWindow()) { $null = $process.WaitForExit(3000) } + if (-not $process.HasExited) { + $process.Kill() + if (-not $process.WaitForExit(5000)) { throw "Process did not stop: $($_.ProcessId)" } + } + } + } +} diff --git a/rust_core/Cargo.lock b/rust_core/Cargo.lock index 4b7e576..e3445fd 100644 --- a/rust_core/Cargo.lock +++ b/rust_core/Cargo.lock @@ -298,12 +298,13 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "ttstdconnect_core" -version = "0.1.0" +version = "0.1.3" dependencies = [ "mdns-sd", "ring", "rustls", "rustls-native-certs", + "socket2", ] [[package]] diff --git a/rust_core/Cargo.toml b/rust_core/Cargo.toml index 2246222..f66678f 100644 --- a/rust_core/Cargo.toml +++ b/rust_core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ttstdconnect_core" -version = "0.1.0" +version = "0.1.3" edition = "2021" description = "TTSTDConnect 核心协议层:控制帧、发现、会话、媒体、文件与连接状态机" @@ -11,6 +11,7 @@ crate-type = ["rlib", "cdylib"] [dependencies] ring = "0.17" +socket2 = "0.6" rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } mdns-sd = "0.22" rustls-native-certs = "0.8" diff --git a/rust_core/src/demo_server.rs b/rust_core/src/demo_server.rs index 787dcb5..a25c4d7 100644 --- a/rust_core/src/demo_server.rs +++ b/rust_core/src/demo_server.rs @@ -9,6 +9,7 @@ use std::collections::VecDeque; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream, UdpSocket}; +use std::sync::mpsc::{sync_channel, SyncSender}; use std::sync::atomic::{AtomicBool, AtomicU16, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::thread::{self, JoinHandle}; @@ -134,8 +135,34 @@ impl ControlSink { struct ControlSender { sink: ControlSink, - /// 与读循环共用同一个实例,避免两条编码路径各自从 counter=1 起算造成 nonce 复用。 - channel: Arc, + outbound: SyncSender, +} + +impl ControlSender { + fn new(sink: ControlSink, channel: Arc, shared: &Arc) -> Self { + let (outbound, pending) = sync_channel::(128); + let writer = sink.clone(); + let shared = Arc::downgrade(shared); + thread::spawn(move || { + while let Ok(event) = pending.recv() { + // Same channel as the reader/keepalive: never reset its nonce counter. + let result = channel.encode(&event) + .map_err(|error| error.to_string()) + .and_then(|frame| writer.send(&frame)); + if let Some(shared) = shared.upgrade() { + match &result { + Ok(()) => shared.push_event(format!("sent:seq={}:type={}", event.sequence(), event.msg_type())), + Err(error) => shared.push_event(format!("error:control-send:{}", error)), + } + } + if result.is_err() { + writer.shutdown(); + break; + } + } + }); + Self { sink, outbound } + } } /// 被控端上行的控制事件(mirror 应答 / 剪贴板),供 UI 侧轮询消费。 @@ -424,6 +451,13 @@ pub fn start(control_port: u16, video_port: u16, audio_port: u16) -> Result<(), .map_err(|error| format!("监听 UDP {} 失败:{}", video_port, error))?; let audio = retry_bind(|| UdpSocket::bind(("0.0.0.0", audio_port))) .map_err(|error| format!("监听 UDP {} 失败:{}", audio_port, error))?; + // 一个关键帧可连续发送数百个小分片;默认接收缓冲过小会在解密前丢包。 + // 系统可能钳制大小,设置失败只记录,不阻止会话建立。 + for socket in [&video, &audio] { + if let Err(error) = socket2::SockRef::from(socket).set_recv_buffer_size(4 * 1024 * 1024) { + handle.shared.push_event(format!("warning:udp:receive-buffer:{}", error)); + } + } listener .set_nonblocking(true) .map_err(|error| format!("设置 TCP 非阻塞失败:{}", error))?; @@ -665,10 +699,7 @@ fn run_relay(shared: Arc, base_url: String, peer_id: String) { let sink = ControlSink::Relay(Arc::new(channel.clone())); let control_channel = Arc::new(SecureControlChannel::new(control)); if let Ok(mut guard) = shared.sender.lock() { - *guard = Some(ControlSender { - sink: sink.clone(), - channel: Arc::clone(&control_channel), - }); + *guard = Some(ControlSender::new(sink.clone(), Arc::clone(&control_channel), &shared)); } let mut buffer: Vec = Vec::new(); @@ -830,7 +861,7 @@ pub fn request_file(json: String, timeout: Duration) -> Result { } /// 把控制事件编码为 AES-GCM 帧并下发给当前被控端。 -/// 返回 Ok(()) 表示已写入 TCP,Err 表示未连接或写入失败。 +/// Ok 表示进入有界发送队列;实际网络写入在后台顺序执行,错误记录到状态事件。 pub fn send_control(event: ControlEvent) -> Result<(), String> { let handle = server_handle(); let sender = handle @@ -839,17 +870,7 @@ pub fn send_control(event: ControlEvent) -> Result<(), String> { .lock() .map_err(|_| "控制通道锁不可用".to_string())?; let sender = sender.as_ref().ok_or_else(|| "没有已连接的被控端".to_string())?; - let frame = sender - .channel - .encode(&event) - .map_err(|error| format!("控制帧加密失败:{}", error))?; - sender.sink.send(&frame)?; - handle.shared.push_event(format!( - "sent:seq={}:type={}", - event.sequence(), - event.msg_type() - )); - Ok(()) + sender.outbound.try_send(event).map_err(|error| format!("控制发送队列不可用:{}", error)) } /// 构造触摸控制事件。 @@ -929,6 +950,8 @@ fn run_tcp(listener: TcpListener, shared: Arc) { } // listener 是非阻塞的,accept 出的连接会继承该标志;改回阻塞以便 read_exact。 let _ = stream.set_nonblocking(false); + let _ = stream.set_nodelay(true); + let _ = stream.set_write_timeout(Some(Duration::from_secs(2))); if let Ok(mut ip) = shared.peer_ip.lock() { *ip = address.ip().to_string(); } @@ -1030,10 +1053,7 @@ fn handle_peer_plain(stream: &mut std::net::TcpStream, shared: &Arc) { }; let sink = ControlSink::Tcp(Arc::new(Mutex::new(write_stream))); if let Ok(mut guard) = shared.sender.lock() { - *guard = Some(ControlSender { - sink: sink.clone(), - channel: Arc::clone(&channel), - }); + *guard = Some(ControlSender::new(sink.clone(), Arc::clone(&channel), shared)); } let mut buffer = Vec::new(); let mut chunk = [0u8; 4096]; @@ -1183,12 +1203,13 @@ fn handle_peer_tls(tls: Arc>, shared: &Arc) { let channel = Arc::new(SecureControlChannel::new(control)); let sink = ControlSink::Tls(Arc::clone(&tls)); if let Ok(mut guard) = shared.sender.lock() { - *guard = Some(ControlSender { - sink: sink.clone(), - channel: Arc::clone(&channel), - }); + *guard = Some(ControlSender::new(sink.clone(), Arc::clone(&channel), shared)); } + let socket = match tls.lock().ok().and_then(|stream| stream.socket_clone().ok()) { + Some(socket) => socket, + None => return, + }; let mut buffer = Vec::new(); let mut chunk = [0u8; 4096]; let mut keepalive_sequence = 0u16; @@ -1198,7 +1219,22 @@ fn handle_peer_tls(tls: Arc>, shared: &Arc) { let Ok(mut guard) = tls.lock() else { break; }; - guard.read(&mut chunk) + guard.read_buffered(&mut chunk) + }; + // Wait for network readiness outside the TLS mutex, so a quiet peer + // cannot starve the input writer by immediately reacquiring the lock. + let read = match read { + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + match socket.peek(&mut [0u8; 1]) { + Ok(0) => Ok(0), + Ok(_) => match tls.lock() { + Ok(mut guard) => guard.read(&mut chunk), + Err(_) => break, + }, + Err(error) => Err(error), + } + } + result => result, }; match read { Ok(0) => { @@ -1413,3 +1449,48 @@ fn decrypt_relay_media(key: &[u8; 32], data: &[u8]) -> Option> { ) .ok() } + +#[cfg(test)] +mod outbound_tests { + use super::*; + + #[test] + fn blocked_network_writer_does_not_block_enqueue_and_queue_is_bounded() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let _peer = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let stream = Arc::new(Mutex::new(stream)); + let blocked = stream.lock().unwrap(); + let shared = Arc::new(Shared::new()); + let sender = ControlSender::new(ControlSink::Tcp(stream.clone()), Arc::new(SecureControlChannel::new([3; 32])), &shared); + let start = Instant::now(); + let mut accepted = 0; + for sequence in 0..1000 { + if sender.outbound.try_send(ControlEvent::new(sequence, ControlEventKind::Ping(1))).is_err() { break; } + accepted += 1; + } + assert!((128..=129).contains(&accepted)); + assert!(start.elapsed() < Duration::from_millis(200), "enqueue waited for network IO"); + drop(blocked); + } + + #[test] + fn queued_control_preserves_order_and_uses_distinct_nonces() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let mut peer = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + peer.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let shared = Arc::new(Shared::new()); + let channel = Arc::new(SecureControlChannel::new([4; 32])); + let sender = ControlSender::new(ControlSink::Tcp(Arc::new(Mutex::new(stream))), channel.clone(), &shared); + for sequence in 1..=2 { + sender.outbound.try_send(ControlEvent::new(sequence, ControlEventKind::Ping(sequence as u64))).unwrap(); + } + let mut bytes = [0u8; 88]; // two encrypted Ping frames (8+12+8+16) + peer.read_exact(&mut bytes).unwrap(); + let (first, consumed) = channel.decode(&bytes).unwrap().unwrap(); + let (second, _) = channel.decode(&bytes[consumed..]).unwrap().unwrap(); + assert_eq!((first.sequence(), second.sequence()), (1, 2)); + assert_ne!(&bytes[8..20], &bytes[consumed+8..consumed+20]); + } +} diff --git a/rust_core/src/ffi.rs b/rust_core/src/ffi.rs index b2c5721..961d738 100644 --- a/rust_core/src/ffi.rs +++ b/rust_core/src/ffi.rs @@ -317,6 +317,7 @@ pub unsafe extern "C" fn ttstd_control_decode( } /// 向当前被控端下发控制帧。payload 为各事件类型的二进制负载。 +/// OK 表示已入队,不等待网络;异步写入失败通过 demo status 的错误事件报告。 /// msg_type: 0=touch 1=mouse 2=key 3=wheel 4=clipboard(UTF-8) 5=ping(u64 LE) /// 8=mirror([action:u8]+文本) 9=sessionConfig(UTF-8 JSON) 10=access(UTF-8 JSON) #[no_mangle] diff --git a/rust_core/src/lib.rs b/rust_core/src/lib.rs index 797c6a9..89116ec 100644 --- a/rust_core/src/lib.rs +++ b/rust_core/src/lib.rs @@ -17,7 +17,7 @@ pub use file::{FileMeta, PrepareRequest, TransferSession}; pub use media::{MediaPacket, VideoRenderer}; pub use session::{PairingUri, SessionContext, SessionState}; -pub const VERSION: &str = "0.1.0"; +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub fn version() -> &'static str { VERSION diff --git a/rust_core/src/media/packet.rs b/rust_core/src/media/packet.rs index c2521fe..cc37104 100644 --- a/rust_core/src/media/packet.rs +++ b/rust_core/src/media/packet.rs @@ -1,5 +1,6 @@ //! Media v2: authenticated header + nonce + AES-256-GCM payload/tag. -use crate::crypto::{decrypt, derive_subkey, encrypt}; +use crate::crypto::{derive_subkey, encrypt}; +use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM}; use std::fmt; use std::sync::atomic::{AtomicU64, Ordering}; @@ -102,6 +103,20 @@ pub fn encode_media_fragment( pub(crate) fn decode_fragment( buffer: &[u8], key: &[u8; 32], +) -> Result, MediaError> { + let key = packet_decryption_key(key)?; + decode_fragment_with_key(buffer, &key) +} + +pub(crate) fn packet_decryption_key(key: &[u8; 32]) -> Result { + let derived = derive_subkey(key, PACKET_KEY_LABEL).map_err(|_| MediaError::InvalidMac)?; + let key = UnboundKey::new(&AES_256_GCM, &derived).map_err(|_| MediaError::InvalidMac)?; + Ok(LessSafeKey::new(key)) +} + +pub(crate) fn decode_fragment_with_key( + buffer: &[u8], + key: &LessSafeKey, ) -> Result, MediaError> { if buffer.len() < 4 { return Ok(None); @@ -134,14 +149,13 @@ pub(crate) fn decode_fragment( if nonce[4..] != sequence.to_le_bytes() { return Err(MediaError::InvalidMac); } - let packet_key = derive_subkey(key, PACKET_KEY_LABEL).map_err(|_| MediaError::InvalidMac)?; - let payload = decrypt( - &packet_key, - nonce, - &buffer[HEADER_LEN + NONCE_LEN..total], - &buffer[..HEADER_LEN], - ) - .map_err(|_| MediaError::InvalidMac)?; + let mut payload = buffer[HEADER_LEN + NONCE_LEN..total].to_vec(); + let length = key.open_in_place( + Nonce::assume_unique_for_key(*nonce), + Aad::from(&buffer[..HEADER_LEN]), + &mut payload, + ).map_err(|_| MediaError::InvalidMac)?.len(); + payload.truncate(length); Ok(Some(( Fragment { packet: MediaPacket { diff --git a/rust_core/src/media/receiver.rs b/rust_core/src/media/receiver.rs index b041ba0..7a6195b 100644 --- a/rust_core/src/media/receiver.rs +++ b/rust_core/src/media/receiver.rs @@ -1,4 +1,5 @@ -use super::packet::{decode_fragment, MediaError, MediaPacket, MAX_FRAME_SIZE}; +use super::packet::{decode_fragment_with_key, packet_decryption_key, MediaError, MediaPacket, MAX_FRAME_SIZE}; +use ring::aead::LessSafeKey; use std::collections::{BTreeMap, BTreeSet}; use std::time::{Duration, Instant}; const REPLAY_WINDOW: u64 = 16384; @@ -17,6 +18,7 @@ struct Assembly { #[derive(Default)] pub struct MediaReceiver { key: Option<[u8; 32]>, + packet_key: Option, highest: u64, seen: BTreeSet, frames: BTreeMap, @@ -32,13 +34,21 @@ impl MediaReceiver { return Err(MediaError::LengthMismatch); } // Never update replay/session state from unauthenticated metadata. - let (fragment, size) = decode_fragment(data, key)?.ok_or(MediaError::LengthMismatch)?; + // Cache HKDF and the AES key schedule for the active session only. + // Authenticate a candidate key before replacing replay/reassembly state. + let candidate = if self.key.as_ref() != Some(key) { + Some(packet_decryption_key(key)?) + } else { None }; + let decrypt_key = candidate.as_ref().or(self.packet_key.as_ref()) + .ok_or(MediaError::InvalidMac)?; + let (fragment, size) = decode_fragment_with_key(data, decrypt_key)?.ok_or(MediaError::LengthMismatch)?; if size != data.len() { return Err(MediaError::LengthMismatch); } if self.key.as_ref() != Some(key) { *self = Self::default(); self.key = Some(*key); + self.packet_key = candidate; } let seq = fragment.sequence; if self.seen.contains(&seq) @@ -167,6 +177,20 @@ mod tests { ); } #[test] + fn rejected_candidate_key_preserves_cached_session_and_partial_frame() { + let key = [2; 32]; + let other = [8; 32]; + let mut receiver = MediaReceiver::default(); + let first = encode_media_fragment(&packet(b"first"), &key, 10, 0, 2).unwrap(); + let last = encode_media_fragment(&packet(b"last"), &key, 10, 1, 2).unwrap(); + assert!(receiver.receive(&key, &first).unwrap().is_none()); + assert!(receiver.receive(&other, &last).is_err()); + assert_eq!(receiver.receive(&key, &last).unwrap().unwrap().payload, b"firstlast"); + let new = encode_media_fragment(&packet(b"rekey"), &other, 1, 0, 1).unwrap(); + assert_eq!(receiver.receive(&other, &new).unwrap().unwrap().payload, b"rekey"); + assert_eq!(receiver.receive(&other, &new), Err(MediaError::Replay)); + } + #[test] fn pcm_fragments_are_not_played_until_complete() { let key = [9; 32]; let mut receiver = MediaReceiver::default(); diff --git a/rust_core/src/session/tls.rs b/rust_core/src/session/tls.rs index 4ffcdd4..bce9170 100644 --- a/rust_core/src/session/tls.rs +++ b/rust_core/src/session/tls.rs @@ -150,6 +150,15 @@ impl PinnedTlsStream { self.socket.set_read_timeout(timeout) } + pub fn socket_clone(&self) -> std::io::Result { + self.socket.try_clone() + } + + /// Read only already decrypted bytes; never wait on the socket with the TLS lock held. + pub fn read_buffered(&mut self, buffer: &mut [u8]) -> std::io::Result { + self.connection.reader().read(buffer) + } + /// 关闭底层 TCP(用于 stop 时打断阻塞中的读)。 pub fn shutdown(&self) { let _ = self.socket.shutdown(std::net::Shutdown::Both);