feat(security): 完善信令认证与媒体加密
- 增加信令访问令牌、HTTPS 校验、限流及跨网段中继连接修复 - 同步三端媒体 v2 协议,实现 AES-GCM、防重放和乱序分片重组,升级 Rust ABI 6 - 修复文件鉴权、权限协商及剪贴板越权,完善上传校验和串流超时处理 - 增加跨端回归测试及部署文档,在 AGENTS.md 记录真机与真实跨网段待验收项目
This commit is contained in:
1 parent
4c9d006d11
commit
f6b7730684
58 files changed
+2167
-218
No files matched your search
@@ -77,3 +77,58 @@ flutter build windows --debug
|
||||
屏幕用 `DisplayManager` + `CAPTURE_VIDEO_OUTPUT` 直采(无授权弹窗、无音频),输入用
|
||||
`INJECT_EVENTS`(`SystemInputExecutor`);普通应用仍走 MediaProjection + 无障碍
|
||||
(`AccessibilityInputExecutor`)。
|
||||
|
||||
## 待完成的真机与跨网段验收(2026-11-28)
|
||||
|
||||
用户暂时没有完整测试条件,要求记录后自行测试。以下两项均为**待实测**,不要把已有的
|
||||
编译、模拟器、WSL 或回环测试当作真机/真实跨网段验收通过;用户要求恢复前,不继续安装真机应用或调整网络。
|
||||
|
||||
### 1. 普通签名 Android 真机:MediaProjection 与实际音频
|
||||
|
||||
- [ ] 完成普通签名录屏、系统音频采集、主控播放及停止/重连验收。
|
||||
- 本轮只读检测到 USB 真机 G12NL,序列号 `0123456789ABCDEF`,Android 13 / API 33,
|
||||
`arm64-v8a`;检测时尚未安装接收端,**本轮未向该真机安装应用、未验证录屏或音频**。
|
||||
恢复测试时先重新运行 `adb devices -l`,不要假定设备和状态仍然相同。
|
||||
- 使用 `neutral` 普通签名包,不能用 `aosp` / 系统 UID / 特权直采替代。
|
||||
在 `android_receiver/` 执行 `./gradlew :app:assembleNeutralDebug --offline`,
|
||||
APK 位于 `app/build/outputs/apk/neutral/debug/app-neutral-debug.apk`。
|
||||
如设备已有不同签名版本,不自动卸载主应用或清除数据。
|
||||
- 正常授予通知、`RECORD_AUDIO` 和系统 MediaProjection 授权,确认走非特权路径;
|
||||
检查拒绝授权时不采集,允许后才开流。重复请求投屏、停止、断开、重连后再授权也要检查。
|
||||
- 用明确允许系统音频回采的媒体/游戏音源测试,最好播放已知测试音。
|
||||
`AudioCapturer` 仅匹配 `USAGE_MEDIA` / `USAGE_GAME`;通话、受保护内容或禁止回采的播放器
|
||||
不能作为音频失败的唯一依据,也不能只看到静音 PCM 数据就宣称有声音。
|
||||
- 通过标准:实际画面可解码;主控实际收到非静音 PCM16(48 kHz 双声道)且能正常播放;
|
||||
停止后画面和声音都停止,系统录屏状态释放;重连可恢复。
|
||||
额外检查拒绝录音权限/关闭音频时视频仍正常且不崩溃,记录无声音提示是否充分。
|
||||
- `rust_core/tests/device_media_smoke.py` 只覆盖视频、旧协议拒绝与停止,**不能单独证明音频验收通过**。
|
||||
模拟器平台签名直采本来没有音频,不得用它代替本项。
|
||||
|
||||
### 2. 两个真实网段:HTTPS 认证、中继投屏和文件传输
|
||||
|
||||
- [ ] 完成真实跨网段 HTTPS 信令、认证失败路径、中继投屏/音频及文件传输验收。
|
||||
- 尚缺可用 HTTPS 信令地址和访问令牌,本轮没有真实部署/跨网段结果。
|
||||
检测时主控电脑地址为 `192.168.1.6/24`,G12NL Wi-Fi 为 `192.168.3.78/24`,
|
||||
仅说明地址属于不同网段,**不证明路由、互联网或防火墙可达**;测试时重新确认网络。
|
||||
- 先按 `docs/signaling-deployment.md` 部署可被两端访问、证书链和主机名验证正常的 HTTPS 服务,
|
||||
设置至少 32 字符的随机 `SIGNALING_TOKEN`。不要关闭证书校验,不把令牌写进仓库或公开日志。
|
||||
共享令牌仅适用于互信设备组,不代表每设备独立认证。
|
||||
- 两端填写同一外部信令地址及令牌;主控关闭「使用本机信令服务器」,开启「连接走信令中继」。
|
||||
Android 保存后停止再启动待命服务。用 `/list` / `/watch` 的证据确认发现来自信令,
|
||||
用状态/日志中的中继标记确认控制与媒体实际走 `/relay`,不能用直连成功替代中继验收。
|
||||
- 检查无令牌和错误令牌被拒绝(401),正确令牌才能注册/发现/轮询;不可信或主机名不匹配的
|
||||
HTTPS 证书必须失败,不能退回明文。检查投屏前 `mediaProtocol=aes-gcm/2` 已协商。
|
||||
- 实测允许/拒绝投屏、连续画面、实际声音、停止、断网及信令重启后的表现,记录是否能重新连接。
|
||||
- 文件仅使用专门创建的测试文件与目录:验证 `msgType=7` 的目录浏览、上传、空文件、分片、
|
||||
上传完成后的 SHA-256 一致性,以及中断/取消时未完成 `.part` 文件的清理。
|
||||
`view` / `control` 应拒绝文件操作,`full` 才能执行;超过 64 MiB 的文件/会话应明确拒绝。
|
||||
- 当前控制通道文件操作为 `prepare/chunk/progress/cancel/list`;如需验证下载,必须记录它实际
|
||||
走哪条链路。不能把同网段 HTTP 文件服务下载当成跨 NAT 的中继下载已实现或已通过。
|
||||
|
||||
### 结果记录与交付
|
||||
|
||||
- 已有验证范围与复现命令见 `docs/media-v2-testing.md`;跨网段配置见 `docs/signaling-deployment.md`。
|
||||
- 实测后记录提交号、设备/API、签名与授权路径、两端网络、信令部署方式、每项通过/失败和相关日志。
|
||||
凭据、剪贴板、个人文件内容应脱敏,测试产物放 `dist/`,不要提交构建产物。
|
||||
- 只有取得对应真实证据后才勾选上面的待办;失败项保留并附复现步骤。验证通过后再重新生成
|
||||
Android APK、Windows 安装器与 Linux 包;已有旧安装包不能代表本轮媒体 v2 / ABI 6 改动。
|
||||
@@ -156,6 +156,9 @@ sig=<信令服务器URL,可选>
|
||||
信封自定义 `ttstd:"relay/1"`,`kind` 取 `hs`(发起方 65 字节 ECDH 公钥)、`hsAck`(被控端公钥)、
|
||||
`frame`(一整帧已加密控制帧的 base64)、`media`(一批加密媒体分片,`video`/`audio` 各一个 base64 数组)、
|
||||
`bye`。`pub` 长度不是 65 字节或版本号不符直接丢弃。
|
||||
- `/relay/poll` 返回 `{"messages":[{"from":"...","to":"...","payload":{...},"createdAt":"..."}]}`;
|
||||
Rust 和 Android 先检查目标及内外层 `from` 一致,再解析 `payload` 中的 `relay/1` 信封。
|
||||
外部部署使用 Bearer 访问令牌,配置步骤与受信任设备组边界见 [跨网段部署说明](docs/signaling-deployment.md)。
|
||||
|
||||
发现结果合并:主控端同时开 UDP 信标(41003)与 mDNS 常驻浏览,按 `ip + 控制端口` 去重,
|
||||
信标优先(字段更全,带 `audioPort`);mDNS 命中可覆盖跨 VLAN 但信标被拦的场景。
|
||||
@@ -168,7 +171,7 @@ sig=<信令服务器URL,可选>
|
||||
3. 主控端按信标/配对二维码里的 `tls` 校验证书 SHA-256,不符直接断;`tls` 为空则退回明文控制通道
|
||||
(被控端用 `PushbackInputStream` 窥探首字节 `0x16` 自动区分,旧版本互操作不受影响)
|
||||
4. ECDH P-256 派生会话密钥 → AES-256-GCM 加密后续控制帧
|
||||
5. 视频/音频通道用会话密钥派生子密钥,每包带 4 字节 MAC;中继时媒体分片再套一层 AES-GCM
|
||||
5. 视频/音频使用 `aes-gcm/2` 派生包密钥,每分片 AES-GCM、认证头和防重放;中继再套独立外层 AES-GCM
|
||||
6. 音频负载是 PCM16(48 kHz 双声道,`FLAG_PCM=0x80`),主控端不解码直接交给 `waveOut`
|
||||
(仓库没有打包 libopus,见 §8.4)
|
||||
|
||||
@@ -187,7 +190,7 @@ struct ControlFrameHeader {
|
||||
u8 msg_type; // 0=touch 1=mouse 2=key 3=wheel 4=clipboard 5=ping 6=pong
|
||||
// 7=file(JSON 子协议) 8=mirror(投屏请求/应答) 9=sessionConfig(会话配置)
|
||||
// 10=access(权限等级应答)
|
||||
u16 sequence; // 递增序号,用于去重/重传
|
||||
u16 sequence; // 递增序号;当前未实现应用层去重、ACK 或重传
|
||||
u32 payload_len; // 负载长度(不包括头部)
|
||||
};
|
||||
|
||||
@@ -227,8 +230,9 @@ struct MirrorEvent {
|
||||
u8 message[]; // 可选,UTF-8 原因说明(denied/error 时)
|
||||
};
|
||||
|
||||
// 会话配置(msg_type = 9):主控端在请求投屏之前下发,payload 为 UTF-8 JSON,字段全部可选
|
||||
// {"preferH265":false,"bitrateMbps":8,"audioEnabled":true,"clipboardSync":true}
|
||||
// 会话配置(msg_type = 9):主控端在请求投屏之前下发,payload 为 UTF-8 JSON
|
||||
// {"mediaProtocol":"aes-gcm/2","preferH265":false,"bitrateMbps":8,"audioEnabled":true,"clipboardSync":true}
|
||||
// mediaProtocol 为投屏必选项,不一致或缺失时拒绝采集/发送媒体,禁止明文降级。
|
||||
// 被控端缺省字段沿用当前值;投屏中改编码格式/码率会重建采集链路,
|
||||
// audioEnabled=false 时不建音频采集,clipboardSync=false 时双向丢弃剪贴板内容。
|
||||
```
|
||||
@@ -318,6 +322,41 @@ impl ControlFrameCodec for BinaryCodec {
|
||||
|
||||
---
|
||||
|
||||
### 4.5 媒体 v2:直连与中继统一加密
|
||||
|
||||
视频和音频使用相同的 AES-256-GCM 媒体包;所有整数小端,包头整体作为 AAD。
|
||||
|
||||
| 偏移 | 字段 | 长度 |
|
||||
| --- | --- | --- |
|
||||
| 0 | magic,ASCII `TTM2` | 4 |
|
||||
| 4 | flags(原编码/音频标记不变) | 1 |
|
||||
| 5 | pts,微秒 | 8 |
|
||||
| 13 | packetSequence,非零、进程内单调计数 | 8 |
|
||||
| 21 | frameId,同一帧所有分片相同,单流单调递增 | 8 |
|
||||
| 29 | fragmentIndex,从 0 开始 | 2 |
|
||||
| 31 | fragmentCount,1~8192 | 2 |
|
||||
| 33 | 明文负载长度 N | 4 |
|
||||
| 37 | nonce:发送域 4B + packetSequence 8B | 12 |
|
||||
| 49 | AES-GCM 密文 | N |
|
||||
| 49+N | 认证 tag | 16 |
|
||||
|
||||
总开销 65B;Android 分片负载最多 1152B,包含 IPv6/UDP 头仍低于 1280B。
|
||||
基础视频/音频密钥沿用 ECDH + HKDF 标签 `lancast/video/v1` / `lancast/audio/v1`;
|
||||
包加密密钥再对基础密钥做 HKDF-SHA256,salt=`ttstdconnect-v1`,info=`lancast/media/packet/v2`。
|
||||
它与中继外层使用的基础密钥隔离,避免内外层 GCM 共用 nonce 空间。
|
||||
nonce 发送域 Android=`and2`、Rust=`rus2`,进程内计数器不随投屏或重连重置,溢出即拒绝发送;
|
||||
会话密钥必须来自新 ECDH,不能持久化复用。音视频基础密钥不同。
|
||||
|
||||
接收端认证成功后才更新 16384 包滑动防重放窗口,重复/过旧包拒绝;包头、密文或 tag
|
||||
篡改不改变窗口状态。分片允许窗口内乱序,按 frameId/index/count 重组,完整帧才入播放队列。
|
||||
每流最多保留 8 个未完成帧、16 MiB 负载,单帧上限 8 MiB,分片 2 秒超时并在后续收包时回收。
|
||||
已播放的新帧之前才完成的旧帧会丢弃,避免把过时参考帧送入解码器。
|
||||
|
||||
主控在 `msgType=9` 指定 `mediaProtocol:"aes-gcm/2"`,被控在 `msgType=10` 回送同名协商结果和
|
||||
`supportedMediaProtocols`。缺失/不匹配时 `msgType=8 request` 返回 error 且不采集/发流;
|
||||
旧 HMAC 明文媒体包直接拒绝,无兼容降级。Flutter 要求 Rust ABI 6,两端须一起升级。
|
||||
中继信封仍为 `relay/1`,新版媒体包外继续保留 nonce+AES-GCM 密文+tag,AAD=`relay-media`。
|
||||
|
||||
## 5. 跨网段问题(重点章节)
|
||||
|
||||
### 5.1 现象根因
|
||||
@@ -383,8 +422,9 @@ mDNS 用组播地址 `224.0.0.251:5353`,**TTL=1,RFC 6762 明确禁止路由
|
||||
|
||||
即使路由可达,企业防火墙常 deny UDP 5353/1900 或限制非标端口。对策:
|
||||
|
||||
- 信令服务器**统一走 HTTPS 443**(复用现有放行规则)
|
||||
- 媒体 UDP 端口若被拦,自动降级到 **TCP 443 上的 WebSocket 媒体通道**(牺牲 ~10ms 换连通性)
|
||||
- 外部信令建议使用 HTTPS;Go 支持证书配置或由反向代理终止 TLS,Rust/Android/Flutter 均校验证书。
|
||||
- 当前通过设置页显式启用 HTTP(S) `/relay` 批量轮询中继;尚未实现自动 UDP→WebSocket 媒体降级。
|
||||
- 访问令牌、客户端配置和实际安全边界见 [跨网段部署说明](docs/signaling-deployment.md)。
|
||||
|
||||
---
|
||||
|
||||
@@ -460,13 +500,13 @@ POST /mirror/request?token= 触发一次投屏确认(便
|
||||
|
||||
| 层 | 机制 |
|
||||
| --- | --- |
|
||||
| 发现 | mDNS TXT 带 `fp` 指纹,防冒充 |
|
||||
| 配对 | 二维码扫码 或 6 位 TOTP PIN(30s 过期) |
|
||||
| 发现 | mDNS TXT 带应用签名 `fp`;仅公布指纹本身不等于证明连接身份 |
|
||||
| 配对 | 被控端生成二维码,主控端支持粘贴配对链接;相机扫码、TOTP PIN 尚未实现 |
|
||||
| 传输 | 控制通道 TLS 1.3 + 自签证书 pinning(`tls=` 指纹),无指纹时明文;控制帧 AES-256-GCM |
|
||||
| 会话 | ECDH P-256 → AES-256-GCM |
|
||||
| 媒体 | 派生子密钥,每包 4 字节 MAC 防篡改 |
|
||||
| 媒体 | v2 AES-256-GCM、认证包头、滑动防重放窗口、完整分片重组;拒绝旧明文包 |
|
||||
| 权限 | 被控端设上限,主控端请求,有效等级取较小值(`msgType=9` 请求 / `msgType=10` 应答) |
|
||||
| 信令 | 客户端 pin 信令服务器公钥,防中间人 |
|
||||
| 信令 | 共享 Bearer 访问令牌 + HTTPS 系统证书链/主机名验证;非信令公钥 pinning |
|
||||
| 中继 | 信封 `relay/1`,`hs/hsAck` 只交换 ECDH 公钥;控制帧与媒体分片都是 AEAD 密文,服务器无法解密 |
|
||||
|
||||
**指纹的真实含义**:`fp` 和 `tls` 是两件不同的事,别混用。
|
||||
@@ -565,7 +605,7 @@ POST /mirror/request?token= 触发一次投屏确认(便
|
||||
### 8.4 音频链路
|
||||
|
||||
被控端 `AudioPlaybackCapture`(48 kHz / 双声道 / PCM16)→ `MediaPackets` 打包(`FLAG_AUDIO|FLAG_PCM`)
|
||||
→ UDP 41002(中继时走 `kind=media`)→ Rust Core 校验 MAC 后写入 `media/audio.rs` 队列
|
||||
→ UDP 41002(中继时走 `kind=media`)→ Rust Core AES-GCM 认证解密、防重放、重组后写入 `media/audio.rs` 队列
|
||||
→ Windows runner 的 `audio_player.cpp` 轮询 `ttstd_audio_next`,用 `waveOut` 输出。
|
||||
|
||||
- **为什么不用 Opus**:仓库没有打包 libopus(`app/src/main/cpp/CMakeLists.txt` 里的
|
||||
@@ -602,7 +642,7 @@ POST /mirror/request?token= 触发一次投屏确认(便
|
||||
- **ADR-003** 跨网段用自部署信令而非依赖网络设备 mDNS 网关 —— 用户不可控网络设备,家庭场景无运维
|
||||
- **ADR-004** 文件传输抄 LocalSend v2 协议但自研实现 —— 复用 TLS 会话 + 加断点续传,不引入 LocalSend 进程
|
||||
- **ADR-005** 被控反连主控(scrcpy 模式) —— 避免服务启动竞态
|
||||
- **ADR-006** 媒体 UDP 优先,被 ACL 拦时降级 TCP/WS over 443 —— 连通性 > 10ms 延迟
|
||||
- **ADR-006(目标)** 媒体 UDP 优先,未来补齐自动降级;当前需显式开启 HTTP(S) 轮询中继
|
||||
- **ADR-007** 控制通道帧采用自定义二进制 + 抽象接口 —— 初期轻量高效,后期可平滑切换 Protobuf
|
||||
|
||||
---
|
||||
|
||||
@@ -18,6 +18,7 @@ android {
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "0.1.0"
|
||||
testInstrumentationRunner = "com.ttstd.lancast.receiver.MediaProtocolInstrumentation"
|
||||
}
|
||||
|
||||
// 按签名划分变体:aosp/zhanxun 为系统签名,neutral 为普通(中性)签名。
|
||||
@@ -52,6 +53,11 @@ android {
|
||||
abortOnError = false
|
||||
}
|
||||
|
||||
packaging {
|
||||
// OSGi metadata from the three Bouncy Castle jars is unused on Android.
|
||||
resources.excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.ttstd.lancast.receiver
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Instrumentation
|
||||
import android.os.Bundle
|
||||
import com.ttstd.lancast.receiver.session.MediaPackets
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetAddress
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/** Real Android JCA provider interoperability test; no extra test dependencies. */
|
||||
class MediaProtocolInstrumentation : Instrumentation() {
|
||||
private var args = Bundle()
|
||||
override fun onCreate(arguments: Bundle?) { super.onCreate(arguments); args = arguments ?: Bundle(); start() }
|
||||
override fun onStart() {
|
||||
val result = Bundle()
|
||||
try {
|
||||
val key = ByteArray(32) { it.toByte() }
|
||||
val payload = "android-media-v2".toByteArray()
|
||||
val packet = MediaPackets.encode(payload, 42, 1, key)
|
||||
check(packet.size == payload.size + MediaPackets.OVERHEAD)
|
||||
check(decrypt(packet, key).contentEquals(payload))
|
||||
check(!MediaPackets.encode(payload, 42, 1, key).contentEquals(packet))
|
||||
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)
|
||||
check(runCatching { MediaPackets.encode(ByteArray(1153),42,1,key) }.isFailure)
|
||||
val audio = MediaPackets.encode(byteArrayOf(0,1,2,3),42,0x82,key)
|
||||
check(decrypt(audio,key).contentEquals(byteArrayOf(0,1,2,3)))
|
||||
val rust = args.getString("rustPacket")
|
||||
if (!rust.isNullOrEmpty()) check(decrypt(unhex(rust),key).contentEquals("rust-media-v2".toByteArray()))
|
||||
result.putString("androidPacket", packet.joinToString("") { "%02x".format(it) })
|
||||
args.getString("targetHost")?.let { host ->
|
||||
val frame = MediaPackets.nextFrameId()
|
||||
val parts = listOf("android-", "wsl-", "media").mapIndexed { index, value ->
|
||||
MediaPackets.encode(value.toByteArray(),42,1,key,frame,index,3)
|
||||
}
|
||||
val damaged = parts[1].clone().apply { this[lastIndex] = (this[lastIndex].toInt() xor 1).toByte() }
|
||||
DatagramSocket().use { socket ->
|
||||
val address = InetAddress.getByName(host)
|
||||
for (bytes in listOf(parts[2],parts[0],parts[0],damaged,parts[1],parts[2],ByteArray(40))) {
|
||||
socket.send(DatagramPacket(bytes,bytes.size,address,args.getString("targetPort","42004").toInt()))
|
||||
Thread.sleep(30)
|
||||
}
|
||||
}
|
||||
}
|
||||
result.putString("result", "PASS: Android AES-GCM, tamper, key, nonce and Rust interoperability")
|
||||
finish(Activity.RESULT_OK,result)
|
||||
} catch (error: Throwable) {
|
||||
result.putString("error",error.stackTraceToString())
|
||||
finish(Activity.RESULT_CANCELED,result)
|
||||
}
|
||||
}
|
||||
private fun unhex(value:String):ByteArray = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
private fun decrypt(packet:ByteArray,key:ByteArray):ByteArray {
|
||||
check(packet.copyOfRange(0,4).contentEquals("TTM2".toByteArray()))
|
||||
val header = packet.copyOfRange(0,37)
|
||||
check(ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN).getInt(33) == packet.size-65)
|
||||
val prk = hmac("ttstdconnect-v1".toByteArray(),key)
|
||||
val derived = hmac(prk,"lancast/media/packet/v2".toByteArray()+byteArrayOf(1))
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
|
||||
init(Cipher.DECRYPT_MODE,SecretKeySpec(derived,"AES"),GCMParameterSpec(128,packet.copyOfRange(37,49)))
|
||||
updateAAD(header)
|
||||
}
|
||||
return cipher.doFinal(packet.copyOfRange(49,packet.size))
|
||||
}
|
||||
private fun hmac(key:ByteArray,bytes:ByteArray):ByteArray = Mac.getInstance("HmacSHA256").apply {
|
||||
init(SecretKeySpec(key,"HmacSHA256"))
|
||||
}.doFinal(bytes)
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.View
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import android.text.InputType
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.RadioButton
|
||||
@@ -156,6 +158,31 @@ class MainActivity : Activity() {
|
||||
}
|
||||
}
|
||||
|
||||
val signalUrl = EditText(this).apply {
|
||||
hint = "外部信令地址(https://signal.example.com)"
|
||||
setSingleLine(true)
|
||||
setText(Prefs.signalingUrl(this@MainActivity))
|
||||
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
|
||||
}
|
||||
val signalToken = EditText(this).apply {
|
||||
hint = "信令访问令牌"
|
||||
setSingleLine(true)
|
||||
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
|
||||
setText(Prefs.signalingToken(this@MainActivity))
|
||||
}
|
||||
val saveSignaling = Button(this).apply {
|
||||
text = "保存跨网段设置"
|
||||
setOnClickListener {
|
||||
val url = signalUrl.text.toString().trim()
|
||||
val uri = android.net.Uri.parse(url)
|
||||
if (url.isNotEmpty() && (uri.scheme !in listOf("http", "https") || uri.host.isNullOrBlank() || uri.fragment != null || uri.userInfo != null)) {
|
||||
Toast.makeText(this@MainActivity, "信令地址格式无效", Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
Prefs.setSignaling(this@MainActivity, url, signalToken.text.toString().trim())
|
||||
Toast.makeText(this@MainActivity, "已保存,请停止后重新启动待命服务", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
val content = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(48, 64, 48, 64)
|
||||
@@ -169,6 +196,9 @@ class MainActivity : Activity() {
|
||||
addView(accessGroup)
|
||||
addView(authorize)
|
||||
addView(startButton)
|
||||
addView(signalUrl)
|
||||
addView(signalToken)
|
||||
addView(saveSignaling)
|
||||
addView(storageInfo)
|
||||
addView(storageButton)
|
||||
addView(fileInfo)
|
||||
@@ -202,7 +232,7 @@ class MainActivity : Activity() {
|
||||
// ------------------------------------------------------------------ 动作
|
||||
|
||||
private fun startStandby() {
|
||||
MediaProjectionService.start(this, hostOverride, "")
|
||||
MediaProjectionService.start(this, hostOverride)
|
||||
status.text = "状态:正在进入待命…"
|
||||
handler.postDelayed({ refreshStatus }, 300)
|
||||
}
|
||||
|
||||
+1
-1
@@ -132,7 +132,7 @@ class MediaProjectionService : Service() {
|
||||
get() = com.ttstd.lancast.receiver.discovery.HostBeacon.lastHost
|
||||
|
||||
/** 启动待命服务(不需要屏幕录制授权)。 */
|
||||
fun start(context: Context, host: String = "", signalingUrl: String = "") {
|
||||
fun start(context: Context, host: String = "", signalingUrl: String = Prefs.signalingEndpoint(context)) {
|
||||
val intent = Intent(context, MediaProjectionService::class.java).apply {
|
||||
action = ACTION_START
|
||||
putExtra(EXTRA_HOST, host)
|
||||
|
||||
@@ -13,6 +13,18 @@ import java.security.SecureRandom
|
||||
* - [fileToken]:文件服务访问令牌,首次使用时生成,显示在主界面供主控端填写。
|
||||
*/
|
||||
object Prefs {
|
||||
fun signalingUrl(context: Context): String = prefs(context).getString("signaling_url", "").orEmpty()
|
||||
fun signalingToken(context: Context): String = prefs(context).getString("signaling_token", "").orEmpty()
|
||||
fun setSignaling(context: Context, url: String, token: String) {
|
||||
prefs(context).edit().putString("signaling_url", url).putString("signaling_token", token).apply()
|
||||
}
|
||||
fun signalingEndpoint(context: Context): String {
|
||||
val base = signalingUrl(context)
|
||||
if (base.isBlank()) return ""
|
||||
val token = signalingToken(context)
|
||||
return android.net.Uri.parse(base).buildUpon()
|
||||
.encodedFragment(if (token.isEmpty()) null else "token=" + android.net.Uri.encode(token)).build().toString()
|
||||
}
|
||||
private const val NAME = "lancast_receiver_prefs"
|
||||
private const val KEY_AUTO_GRANT = "auto_grant"
|
||||
private const val KEY_FILE_SERVICE = "file_service_enabled"
|
||||
|
||||
@@ -26,6 +26,7 @@ import com.ttstd.lancast.receiver.input.InputInjector
|
||||
import com.ttstd.lancast.receiver.protocol.AccessLevel
|
||||
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.session.ReceiverTransport
|
||||
import com.ttstd.lancast.receiver.session.MediaPackets
|
||||
import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.TlsIdentity
|
||||
@@ -169,7 +170,7 @@ class ReceiverSession(
|
||||
* @return 是否成功建立采集链路。
|
||||
*/
|
||||
fun beginMirroring(projection: MediaProjection?): Boolean {
|
||||
if (!running) return false
|
||||
if (!running || transport?.mediaProtocolReady != true) return false
|
||||
synchronized(captureLock) {
|
||||
if (mirroring) return true
|
||||
this.projection = projection
|
||||
@@ -299,7 +300,7 @@ class ReceiverSession(
|
||||
controlPort = 41001,
|
||||
fingerprint = this@ReceiverSession.fingerprint,
|
||||
capabilities = listOf(
|
||||
"h264", "opus", "uibc", "clipboard", "file", "mirror-request", "file-browse",
|
||||
"h264", "pcm16", "uibc", "clipboard", "file", "mirror-request", "file-browse", MediaPackets.PROTOCOL,
|
||||
),
|
||||
model = Build.MODEL,
|
||||
resolution = "${size[0]}x${size[1]}",
|
||||
@@ -326,7 +327,7 @@ class ReceiverSession(
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (target.isNotEmpty() && transport == null) {
|
||||
if ((target.isNotEmpty() || signalingUrl.isNotBlank()) && transport == null) {
|
||||
val created = ReceiverTransport(
|
||||
target,
|
||||
41001,
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
package com.ttstd.lancast.receiver.discovery
|
||||
|
||||
import android.util.Log
|
||||
import com.ttstd.lancast.receiver.session.SignalingEndpoint
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
@@ -62,7 +63,7 @@ class ReceiverAnnouncer(
|
||||
private fun post(path: String, body: String): Boolean {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
val http = URL(signalingUrl.trimEnd('/') + path).openConnection() as HttpURLConnection
|
||||
val http = SignalingEndpoint.connection(signalingUrl, path)
|
||||
connection = http
|
||||
http.requestMethod = "POST"
|
||||
http.doOutput = true
|
||||
|
||||
+30
-9
@@ -15,7 +15,10 @@ import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.net.URLDecoder
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.security.MessageDigest
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.Semaphore
|
||||
|
||||
/**
|
||||
* LocalSend 风格的文件服务(默认 53317,被占用时顺延)。
|
||||
@@ -42,7 +45,8 @@ class FileHttpServer(
|
||||
}
|
||||
|
||||
private val browser = FileBrowser(context)
|
||||
private val workers = Executors.newCachedThreadPool()
|
||||
private val workers = Executors.newFixedThreadPool(4)
|
||||
private val clients = Semaphore(4)
|
||||
private var serverSocket: ServerSocket? = null
|
||||
private var acceptThread: Thread? = null
|
||||
|
||||
@@ -101,7 +105,13 @@ class FileHttpServer(
|
||||
if (!running) return
|
||||
continue
|
||||
}
|
||||
workers.execute { handle(client) }
|
||||
if (!clients.tryAcquire()) { client.close(); continue }
|
||||
try {
|
||||
workers.execute { try { handle(client) } finally { clients.release() } }
|
||||
} catch (_: java.util.concurrent.RejectedExecutionException) {
|
||||
clients.release()
|
||||
client.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,9 +137,15 @@ class FileHttpServer(
|
||||
}
|
||||
}
|
||||
|
||||
val body = readBody(input, headers)
|
||||
val path = target.substringBefore('?')
|
||||
val query = parseQuery(target.substringAfter('?', ""))
|
||||
val publicInfo = method == "GET" && path in setOf("/api/localsend/v1/info", "/api/localsend/v2/info")
|
||||
val publicRegister = method == "POST" && path in setOf("/api/localsend/v1/register", "/api/localsend/v2/register")
|
||||
if (!publicInfo && !publicRegister && !authorized(query, headers)) {
|
||||
writeResponse(output, jsonResponse(403, "令牌无效"))
|
||||
return
|
||||
}
|
||||
val body = if (publicInfo || publicRegister) byteArrayOf() else readBody(input, headers)
|
||||
|
||||
val response = try {
|
||||
route(method, path, query, headers, body)
|
||||
@@ -153,10 +169,10 @@ class FileHttpServer(
|
||||
body: ByteArray,
|
||||
): Response {
|
||||
// LocalSend 发现/注册接口不需要令牌,方便桌面端识别设备。
|
||||
if (path == "/api/localsend/v1/info" || path == "/api/localsend/v2/info") {
|
||||
if (method == "GET" && (path == "/api/localsend/v1/info" || path == "/api/localsend/v2/info")) {
|
||||
return jsonResponse(200, infoJson())
|
||||
}
|
||||
if (path.endsWith("/register")) {
|
||||
if (method == "POST" && path in setOf("/api/localsend/v1/register", "/api/localsend/v2/register")) {
|
||||
return Response(204, "application/json")
|
||||
}
|
||||
|
||||
@@ -164,6 +180,9 @@ class FileHttpServer(
|
||||
return jsonResponse(403, "令牌无效,请填写主界面显示的文件服务令牌")
|
||||
}
|
||||
|
||||
val expectedMethod = if (path == "/mirror/request" || path.endsWith("/upload")) "POST" else "GET"
|
||||
if (method != expectedMethod) return jsonResponse(405, "请求方法不支持")
|
||||
|
||||
return when (path) {
|
||||
"/", "/index.html" -> htmlResponse(indexHtml())
|
||||
"/browse" -> jsonResponse(200, browser.list(query["path"] ?: "").toString())
|
||||
@@ -209,9 +228,11 @@ class FileHttpServer(
|
||||
|
||||
private fun authorized(query: Map<String, String>, headers: Map<String, String>): Boolean {
|
||||
val expected = tokenProvider()
|
||||
if (expected.isEmpty()) return true
|
||||
if (expected.isBlank()) return false
|
||||
val provided = query["token"] ?: headers["x-lancast-token"]
|
||||
return provided == expected
|
||||
return provided != null && MessageDigest.isEqual(
|
||||
provided.toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8),
|
||||
)
|
||||
}
|
||||
|
||||
private fun infoJson(): String = JSONObject().apply {
|
||||
@@ -219,7 +240,7 @@ class FileHttpServer(
|
||||
put("version", "2.1")
|
||||
put("deviceModel", Build.MODEL ?: "Android")
|
||||
put("deviceType", "mobile")
|
||||
put("fingerprint", tokenProvider())
|
||||
put("fingerprint", Fingerprint.of(context))
|
||||
put("port", boundPort)
|
||||
put("protocol", "http")
|
||||
put("download", false)
|
||||
@@ -288,7 +309,7 @@ class FileHttpServer(
|
||||
var read = 0
|
||||
while (read < buffer.size) {
|
||||
val count = input.read(buffer, read, buffer.size - read)
|
||||
if (count < 0) break
|
||||
require(count >= 0) { "请求体未完整接收" }
|
||||
read += count
|
||||
}
|
||||
return if (read == buffer.size) buffer else buffer.copyOf(read)
|
||||
|
||||
@@ -21,35 +21,50 @@ class FileService(
|
||||
val sha256: String,
|
||||
val token: String,
|
||||
var offset: Long,
|
||||
var complete: Boolean = false,
|
||||
)
|
||||
|
||||
private data class Session(val id: String, val files: MutableMap<String, Entry>)
|
||||
private data class Session(val id: String, val files: MutableMap<String, Entry>, var touched: Long = android.os.SystemClock.elapsedRealtime())
|
||||
|
||||
private val sessions = ConcurrentHashMap<String, Session>()
|
||||
|
||||
fun prepare(body: String): String {
|
||||
@Synchronized fun prepare(body: String): String {
|
||||
expire()
|
||||
require(sessions.size < 8) { "文件会话过多,请稍后重试" }
|
||||
root.mkdirs()
|
||||
val request = JSONObject(body)
|
||||
val files = request.getJSONArray("files")
|
||||
require(files.length() in 1..32) { "文件数量必须为 1~32" }
|
||||
val sessionId = UUID.randomUUID().toString()
|
||||
val entries = mutableMapOf<String, Entry>()
|
||||
val tokens = JSONObject()
|
||||
val rejected = JSONArray()
|
||||
|
||||
var totalSize = 0L
|
||||
for (index in 0 until files.length()) {
|
||||
val file = files.getJSONObject(index)
|
||||
val id = file.getString("id")
|
||||
val name = safeName(file.getString("name"))
|
||||
require(entries.values.none { it.name == name }) { "同一会话不能包含重名文件" }
|
||||
val size = file.getLong("size")
|
||||
require(size in 0..(64L * 1024 * 1024)) { "单文件不能超过 64 MiB" }
|
||||
totalSize += size
|
||||
require(totalSize <= 64L * 1024 * 1024) { "单次传输不能超过 64 MiB" }
|
||||
require(id.isNotBlank() && !entries.containsKey(id)) { "文件 ID 无效或重复" }
|
||||
val hash = file.optString("sha256", "")
|
||||
val target = File(root, "$sessionId-$name")
|
||||
require(hash.isEmpty() || hash.matches(Regex("[0-9a-fA-F]{64}"))) { "SHA-256 格式无效" }
|
||||
val token = UUID.randomUUID().toString()
|
||||
val alreadyThere = target.exists() && target.length() == size && sha256(target) == hash
|
||||
entries[id] = Entry(id, name, size, hash, token, if (alreadyThere) size else 0)
|
||||
entries[id] = Entry(id, name, size, hash, token, 0)
|
||||
tokens.put(id, token)
|
||||
}
|
||||
|
||||
sessions[sessionId] = Session(sessionId, entries)
|
||||
try {
|
||||
entries.values.filter { it.size == 0L }.forEach { entry ->
|
||||
File(root, "$sessionId-${entry.name}.part").writeBytes(byteArrayOf())
|
||||
finish(sessionId, entry)
|
||||
}
|
||||
} catch (error: Exception) { cancel(sessionId); throw error }
|
||||
return JSONObject().apply {
|
||||
put("sessionId", sessionId)
|
||||
put("tokens", tokens)
|
||||
@@ -57,20 +72,26 @@ class FileService(
|
||||
}.toString()
|
||||
}
|
||||
|
||||
fun writeChunk(sessionId: String, fileId: String, token: String, offset: Long, bytes: ByteArray): Int {
|
||||
val entry = sessions[sessionId]?.files?.get(fileId)
|
||||
@Synchronized fun writeChunk(sessionId: String, fileId: String, token: String, offset: Long, bytes: ByteArray): Int {
|
||||
expire()
|
||||
val session = sessions[sessionId] ?: throw IllegalArgumentException("文件会话已过期")
|
||||
val entry = session.files[fileId]
|
||||
?: throw IllegalArgumentException("未知文件会话")
|
||||
if (entry.token != token) throw SecurityException("文件令牌不匹配")
|
||||
val target = File(root, "$sessionId-${entry.name}")
|
||||
require(!entry.complete && offset == entry.offset && offset >= 0 && bytes.isNotEmpty() && bytes.size <= 256 * 1024 && bytes.size.toLong() <= entry.size - offset) { "分片偏移或大小无效" }
|
||||
val target = File(root, "$sessionId-${entry.name}.part")
|
||||
RandomAccessFile(target, "rw").use { file ->
|
||||
file.seek(offset)
|
||||
file.write(bytes)
|
||||
}
|
||||
entry.offset = maxOf(entry.offset, offset + bytes.size)
|
||||
session.touched = android.os.SystemClock.elapsedRealtime()
|
||||
if (entry.offset == entry.size) finish(sessionId, entry)
|
||||
return bytes.size
|
||||
}
|
||||
|
||||
fun progress(sessionId: String): String {
|
||||
@Synchronized fun progress(sessionId: String): String {
|
||||
expire()
|
||||
val session = sessions[sessionId] ?: return JSONObject().put("files", JSONArray()).toString()
|
||||
val array = JSONArray()
|
||||
session.files.values.forEach { entry ->
|
||||
@@ -83,8 +104,25 @@ class FileService(
|
||||
return JSONObject().put("sessionId", sessionId).put("files", array).toString()
|
||||
}
|
||||
|
||||
fun cancel(sessionId: String) {
|
||||
sessions.remove(sessionId)
|
||||
@Synchronized fun cancel(sessionId: String) {
|
||||
sessions.remove(sessionId)?.files?.values?.forEach { entry ->
|
||||
File(root, "$sessionId-${entry.name}.part").delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun expire() {
|
||||
val cutoff = android.os.SystemClock.elapsedRealtime() - 15 * 60 * 1000
|
||||
sessions.values.filter { it.touched < cutoff }.forEach { cancel(it.id) }
|
||||
}
|
||||
|
||||
private fun finish(sessionId: String, entry: Entry) {
|
||||
val partial = File(root, "$sessionId-${entry.name}.part")
|
||||
if (entry.sha256.isNotEmpty() && !sha256(partial).equals(entry.sha256, ignoreCase = true)) {
|
||||
cancel(sessionId)
|
||||
throw IllegalArgumentException("文件 SHA-256 校验失败,已清理临时文件")
|
||||
}
|
||||
check(partial.renameTo(File(root, "$sessionId-${entry.name}"))) { "文件保存失败" }
|
||||
entry.complete = true
|
||||
}
|
||||
|
||||
/** 控制通道 msgType=7 的 `op=list`:浏览 Android 文件目录。 */
|
||||
|
||||
+37
-11
@@ -2,10 +2,18 @@ package com.ttstd.lancast.receiver.session
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
object MediaPackets {
|
||||
const val PROTOCOL = "aes-gcm/2"
|
||||
const val OVERHEAD = 65
|
||||
private val packetSequence = AtomicLong(1)
|
||||
private val frameSequence = AtomicLong(1)
|
||||
fun nextFrameId(): Long = frameSequence.getAndIncrement().also { check(it > 0) { "媒体帧计数耗尽" } }
|
||||
const val FLAG_KEYFRAME = 1
|
||||
const val FLAG_AUDIO = 2
|
||||
// 与 Rust Core 的 media::stream 保持一致的扩展标志位。
|
||||
@@ -16,21 +24,39 @@ object MediaPackets {
|
||||
const val FLAG_FRAGMENT_START = 0x10
|
||||
const val FLAG_FRAGMENT_CONTINUE = 0x20
|
||||
const val FLAG_FRAGMENT_END = 0x40
|
||||
// 单个 UDP 分片的负载上限:13 字节头 + 4 字节 MAC + 1200 负载仍远小于 MTU。
|
||||
const val FRAGMENT_PAYLOAD_SIZE = 1200
|
||||
private const val HEADER_SIZE = 13
|
||||
private const val MAC_SIZE = 4
|
||||
// 1152 + 65 + IPv6/UDP 48 = 1265,低于 IPv6 最小 MTU 1280。
|
||||
const val FRAGMENT_PAYLOAD_SIZE = 1152
|
||||
private const val HEADER_SIZE = 37
|
||||
|
||||
fun encode(payload: ByteArray, pts: Long, flags: Int, sessionKey: ByteArray): ByteArray {
|
||||
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)
|
||||
val sequence = packetSequence.getAndIncrement()
|
||||
check(sequence > 0) { "媒体 nonce 计数耗尽,必须重启并重新握手" }
|
||||
val header = ByteBuffer.allocate(HEADER_SIZE).order(ByteOrder.LITTLE_ENDIAN).apply {
|
||||
putLong(pts)
|
||||
put("TTM2".toByteArray(Charsets.US_ASCII))
|
||||
put(flags.toByte())
|
||||
putLong(pts)
|
||||
putLong(sequence)
|
||||
putLong(frameId)
|
||||
putShort(fragmentIndex.toShort())
|
||||
putShort(fragmentCount.toShort())
|
||||
putInt(payload.size)
|
||||
}.array()
|
||||
val signed = header + payload
|
||||
val mac = Mac.getInstance("HmacSHA256").apply {
|
||||
init(SecretKeySpec(sessionKey, "HmacSHA256"))
|
||||
}.doFinal(signed)
|
||||
return signed + mac.copyOf(MAC_SIZE)
|
||||
val nonce = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN).apply {
|
||||
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))
|
||||
updateAAD(header)
|
||||
}
|
||||
return header + nonce + cipher.doFinal(payload)
|
||||
}
|
||||
|
||||
private fun hmac(key: ByteArray, bytes: ByteArray): ByteArray = Mac.getInstance("HmacSHA256").apply {
|
||||
init(SecretKeySpec(key, "HmacSHA256"))
|
||||
}.doFinal(bytes)
|
||||
}
|
||||
+43
-15
@@ -152,12 +152,10 @@ class ReceiverTransport(
|
||||
|
||||
/** 当前生效的权限等级:`min(主控端请求, 本机上限)`。 */
|
||||
@Volatile
|
||||
var access: Int = AccessLevel.FULL
|
||||
var access: Int = AccessLevel.VIEW
|
||||
private set
|
||||
@Volatile var mediaProtocolReady: Boolean = false
|
||||
private set
|
||||
|
||||
/** 已回送过的最新等级,避免每帧回一次应答。 */
|
||||
@Volatile
|
||||
private var reportedAccess: Int = -1
|
||||
|
||||
/** 因权限不足丢弃的事件计数,只用于日志去抖。 */
|
||||
@Volatile
|
||||
@@ -183,6 +181,10 @@ class ReceiverTransport(
|
||||
executor.execute {
|
||||
var retryDelayMs = INITIAL_RETRY_MS
|
||||
while (active) {
|
||||
if (host.isBlank()) {
|
||||
sleepQuietly(500)
|
||||
continue
|
||||
}
|
||||
if (relayMode) {
|
||||
sleepQuietly(300)
|
||||
continue
|
||||
@@ -280,6 +282,7 @@ class ReceiverTransport(
|
||||
}
|
||||
|
||||
udp = DatagramSocket()
|
||||
resetAccess()
|
||||
running = true
|
||||
consecutiveFailures = 0
|
||||
Log.i(TAG, "已连接主控端 $host:$controlPort")
|
||||
@@ -348,6 +351,7 @@ class ReceiverTransport(
|
||||
|
||||
fun sendControl(event: ControlEvent) {
|
||||
executor.execute {
|
||||
if (event is ControlEvent.Clipboard && access < AccessLevel.CONTROL) return@execute
|
||||
val key = keys?.control ?: return@execute
|
||||
if (!running) return@execute
|
||||
val frame = ControlFrames.encode(event, sequence++)
|
||||
@@ -357,7 +361,7 @@ class ReceiverTransport(
|
||||
|
||||
fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo, hevc: Boolean = false) {
|
||||
val key = keys?.video ?: return
|
||||
if (!running) return
|
||||
if (!running || !mediaProtocolReady) return
|
||||
val duplicate = buffer.duplicate().apply {
|
||||
position(info.offset)
|
||||
limit(info.offset + info.size)
|
||||
@@ -372,9 +376,12 @@ class ReceiverTransport(
|
||||
if (hevc) flags = flags or MediaPackets.FLAG_HEVC
|
||||
val target = InetSocketAddress(host, mediaPort)
|
||||
val chunk = MediaPackets.FRAGMENT_PAYLOAD_SIZE
|
||||
val frameId = MediaPackets.nextFrameId()
|
||||
val fragmentCount = (payload.size + chunk - 1) / chunk
|
||||
if (payload.size > 8 * 1024 * 1024) return
|
||||
try {
|
||||
if (payload.size <= chunk) {
|
||||
val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key)
|
||||
val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key, frameId)
|
||||
dispatchMedia(true, packet, target)
|
||||
return
|
||||
}
|
||||
@@ -392,7 +399,7 @@ class ReceiverTransport(
|
||||
fragmentFlags = fragmentFlags or MediaPackets.FLAG_FRAGMENT_END
|
||||
}
|
||||
val part = payload.copyOfRange(offset, end)
|
||||
val packet = MediaPackets.encode(part, info.presentationTimeUs, fragmentFlags, key)
|
||||
val packet = MediaPackets.encode(part, info.presentationTimeUs, fragmentFlags, key, frameId, offset / chunk, fragmentCount)
|
||||
dispatchMedia(true, packet, target)
|
||||
offset = end
|
||||
}
|
||||
@@ -403,10 +410,16 @@ class ReceiverTransport(
|
||||
/** 发送一段 PCM16(48 kHz 双声道);主控端直接播放,不做解码。 */
|
||||
fun sendAudio(pcm: ByteArray, pts: Long) {
|
||||
val key = keys?.audio ?: return
|
||||
if (!running) return
|
||||
if (!running || !mediaProtocolReady || pcm.isEmpty() || pcm.size > 8 * 1024 * 1024) return
|
||||
val flags = MediaPackets.FLAG_AUDIO or MediaPackets.FLAG_PCM
|
||||
val packet = MediaPackets.encode(pcm, pts, flags, key)
|
||||
dispatchMedia(false, packet, InetSocketAddress(host, audioPort))
|
||||
val chunk = MediaPackets.FRAGMENT_PAYLOAD_SIZE
|
||||
val count = (pcm.size + chunk - 1) / chunk
|
||||
val frameId = MediaPackets.nextFrameId()
|
||||
for (index in 0 until count) {
|
||||
val part = pcm.copyOfRange(index * chunk, minOf(pcm.size, (index + 1) * chunk))
|
||||
val packet = MediaPackets.encode(part, pts, flags, key, frameId, index, count)
|
||||
dispatchMedia(false, packet, InetSocketAddress(host, audioPort))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -527,7 +540,9 @@ class ReceiverTransport(
|
||||
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
|
||||
is ControlEvent.Pong -> Unit
|
||||
// 中继模式同样支持投屏:媒体分片走 `media` 消息(已加密)。
|
||||
is ControlEvent.Mirror -> onMirrorEvent?.invoke(event.action, event.message)
|
||||
is ControlEvent.Mirror -> if (event.action == 0 && !mediaProtocolReady) {
|
||||
sendMirror(5, "媒体协议不兼容,需要 ${MediaPackets.PROTOCOL},请更新主控端")
|
||||
} else onMirrorEvent?.invoke(event.action, event.message)
|
||||
is ControlEvent.SessionConfig -> {
|
||||
applyAccessRequest(event.json)
|
||||
onSessionConfig?.invoke(event.json)
|
||||
@@ -550,9 +565,19 @@ class ReceiverTransport(
|
||||
* 有效等级永远不超过 [maxAccess],结果变化时回送一次 msgType=10 应答,
|
||||
* 主控端据此把超出权限的操作禁掉。
|
||||
*/
|
||||
private fun resetAccess() {
|
||||
access = AccessLevel.VIEW
|
||||
mediaProtocolReady = false
|
||||
}
|
||||
|
||||
private fun applyAccessRequest(json: String) {
|
||||
val requested = try {
|
||||
AccessLevel.parse(JSONObject(json).optString("access"), access)
|
||||
val config = JSONObject(json)
|
||||
mediaProtocolReady = config.optString("mediaProtocol") == MediaPackets.PROTOCOL
|
||||
if (!mediaProtocolReady) {
|
||||
onMirrorEvent?.invoke(1, "媒体协议不兼容")
|
||||
}
|
||||
AccessLevel.parse(config.optString("access"), access)
|
||||
} catch (_: Exception) {
|
||||
return
|
||||
}
|
||||
@@ -561,17 +586,19 @@ class ReceiverTransport(
|
||||
access = next
|
||||
Log.i(TAG, "权限等级 ${AccessLevel.name(next)}(请求 ${AccessLevel.name(requested)},上限 ${AccessLevel.name(maxAccess)})")
|
||||
}
|
||||
if (next != reportedAccess) sendAccessReply(next)
|
||||
// 每次配置均确认,避免主控端重置 UI 后因等级未变化而等不到应答。
|
||||
sendAccessReply(next)
|
||||
}
|
||||
|
||||
/** 主动回送当前有效等级(首次连接、上限调整、主控端重新请求时)。 */
|
||||
fun sendAccessReply(level: Int = access) {
|
||||
reportedAccess = level
|
||||
val payload = JSONObject()
|
||||
.put("level", level)
|
||||
.put("name", AccessLevel.name(level))
|
||||
.put("max", maxAccess)
|
||||
.put("requested", level)
|
||||
.put("mediaProtocol", if (mediaProtocolReady) MediaPackets.PROTOCOL else "")
|
||||
.put("supportedMediaProtocols", org.json.JSONArray().put(MediaPackets.PROTOCOL))
|
||||
sendControl(ControlEvent.Access(payload.toString()))
|
||||
}
|
||||
|
||||
@@ -668,6 +695,7 @@ class ReceiverTransport(
|
||||
relayClient = client
|
||||
crypto = sessionCrypto
|
||||
keys = sessionKeys
|
||||
resetAccess()
|
||||
running = true
|
||||
consecutiveFailures = 0
|
||||
Log.i(TAG, "已通过中继连接 $peerId")
|
||||
|
||||
+6
-2
@@ -34,7 +34,11 @@ class RelayClient(
|
||||
val messages = JSONObject(response).optJSONArray("messages") ?: return emptyList()
|
||||
val result = ArrayList<JSONObject>(messages.length())
|
||||
for (index in 0 until messages.length()) {
|
||||
messages.optJSONObject(index)?.let(result::add)
|
||||
val message = messages.optJSONObject(index) ?: continue
|
||||
val payload = message.optJSONObject("payload") ?: continue
|
||||
if (message.optString("to") != deviceId || message.optString("from").isEmpty() ||
|
||||
payload.optString("from") != message.optString("from")) continue
|
||||
result.add(payload)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -82,7 +86,7 @@ class RelayClient(
|
||||
}
|
||||
|
||||
private fun request(method: String, path: String, body: String?): String {
|
||||
val connection = URL(base + path).openConnection() as HttpURLConnection
|
||||
val connection = SignalingEndpoint.connection(base, path)
|
||||
return try {
|
||||
connection.requestMethod = method
|
||||
connection.connectTimeout = timeoutMs
|
||||
|
||||
+2
-2
@@ -95,8 +95,8 @@ class SessionCrypto {
|
||||
/**
|
||||
* 中继媒体分片加密:输出 = 12 字节随机 nonce + 密文 + 16 字节 tag。
|
||||
*
|
||||
* 直连时媒体走 UDP,只有局域网可见;经信令服务器转发必须再套一层,
|
||||
* 否则服务器能直接看到画面。AAD 固定 `relay-media`,与 Rust 侧解密保持一致。
|
||||
* 内层 MediaPackets v2 已加密;中继保留独立外层,使用基础媒体密钥,
|
||||
* 内层使用派生包密钥,两层 nonce 空间隔离。AAD 与 Rust 对齐为 `relay-media`。
|
||||
*/
|
||||
fun encodeRelayMedia(packet: ByteArray, key: ByteArray): ByteArray {
|
||||
val nonce = ByteArray(12).also { RELAY_NONCE_RANDOM.nextBytes(it) }
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.ttstd.lancast.receiver.session
|
||||
|
||||
import android.net.Uri
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/** Internal fragments never leave the client; all network auth uses a header. */
|
||||
object SignalingEndpoint {
|
||||
fun connection(base: String, path: String): HttpURLConnection {
|
||||
val uri = Uri.parse(base.trim())
|
||||
require(uri.scheme == "https" || uri.scheme == "http") { "信令地址必须为 http/https" }
|
||||
val fragment = uri.encodedFragment.orEmpty()
|
||||
val token = if (fragment.startsWith("token=")) Uri.decode(fragment.substring(6)) else ""
|
||||
require(token.none { it <= ' ' || it >= '\u007f' }) { "信令令牌包含非法字符" }
|
||||
val clean = uri.buildUpon().fragment(null).build().toString().trimEnd('/')
|
||||
return (URL(clean + path).openConnection() as HttpURLConnection).apply {
|
||||
// Do not forward credentials to redirects, including HTTPS -> HTTP.
|
||||
instanceFollowRedirects = false
|
||||
if (token.isNotEmpty()) setRequestProperty("Authorization", "Bearer $token")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
# 媒体 v2 验证
|
||||
|
||||
协议和兼容策略见 README §4.5。需要一起升级 Android、Rust ABI 6 和 Flutter;不接受旧 HMAC 明文包。
|
||||
此文档中的固定测试密钥只用于测试探针,实际会话使用 ECDH 临时密钥。
|
||||
|
||||
## 编译和单元测试
|
||||
|
||||
按 AGENTS.md 执行 Rust 离线检查/测试、Android neutral/aosp Kotlin 编译、Flutter 分析和 Windows Debug 构建。
|
||||
Rust 的媒体回归覆盖密文往返、错误密钥、头/nonce/密文/tag 篡改、截断、旧格式、重放、会话重置、
|
||||
乱序分片、缺片不交付、PCM 完整块重组。FFI 无状态 decode 仅是工具编解码接口;网络入口统一用 MediaReceiver。
|
||||
|
||||
## Android 模拟器与 Linux WSL 互通
|
||||
|
||||
应用自带一个无额外 JUnit 依赖的测试 runner(仅 androidTest APK 包含):
|
||||
|
||||
```powershell
|
||||
cd android_receiver
|
||||
./gradlew :app:assembleAospDebug :app:assembleAospDebugAndroidTest --offline
|
||||
# 按设备现有签名选择 flavor;不要为解决签名冲突卸载主应用。
|
||||
adb -s emulator-5554 install -r app/build/outputs/apk/aosp/debug/app-aosp-debug.apk
|
||||
adb -s emulator-5554 install -r app/build/outputs/apk/androidTest/aosp/debug/app-aosp-debug-androidTest.apk
|
||||
```
|
||||
|
||||
在 WSL Ubuntu 构建探针:
|
||||
|
||||
```bash
|
||||
cd rust_core
|
||||
export CARGO_TARGET_DIR="$PWD/target/linux-wsl"
|
||||
cargo check --offline
|
||||
cargo test --offline --lib
|
||||
cargo build --offline --example media_v2_probe
|
||||
target/linux-wsl/debug/examples/media_v2_probe encode
|
||||
target/linux-wsl/debug/examples/media_v2_probe listen 42004
|
||||
```
|
||||
|
||||
将 encode 输出作为 `rustPacket`,将 WSL 的可达 IPv4 地址作为 `targetHost`:
|
||||
|
||||
```powershell
|
||||
adb -s emulator-5554 shell am instrument -w -e rustPacket RUST_PACKET_HEX -e targetHost WSL_IPV4 -e targetPort 42004 com.ttstd.lancast.receiver.test/com.ttstd.lancast.receiver.MediaProtocolInstrumentation
|
||||
```
|
||||
|
||||
runner 用真实 Android JCA 验证加密、nonce 变化、错误密钥/篡改拒绝、PCM 标记和 Rust 包解密。
|
||||
它返回 `androidPacket`,可用 Linux 探针 `decode ANDROID_PACKET_HEX` 反向验证。
|
||||
它向 WSL 发送 7 个 UDP 数据报,含乱序、重复、损坏 tag 和旧格式。探针应输出
|
||||
`complete=1, replay=2, tamper=1, legacy=1`。默认监听超时 30 秒,先安装 APK,再启动监听和 runner。
|
||||
|
||||
## 实际屏幕流
|
||||
|
||||
```powershell
|
||||
# 根目录;证书指纹从被控端配对信息的 tls 字段获取
|
||||
cargo build --manifest-path rust_core/Cargo.toml --release --offline
|
||||
python rust_core/tests/device_media_smoke.py --core rust_core/target/release/ttstdconnect_core.dll --dump dist/validation/media-v2-direct.h264 --tls-fingerprint DEVICE_TLS_SHA256
|
||||
adb -s emulator-5554 shell am start -n com.ttstd.lancast.receiver/.MainActivity --es host 10.0.2.2
|
||||
```
|
||||
|
||||
在应用正常界面启动待命(已有会话如未使用指定 host,先停止再启动),并正常点击投屏确认;
|
||||
普通签名仍需系统 MediaProjection 授权,不绕过弹窗。探针先验证旧协议请求被拒绝,
|
||||
再协商 v2、请求投屏,收到至少 5 帧后发 stop,检查被控端恢复待命。
|
||||
本次在 emulator-5554(API 36)平台签名直采路径收到 576×1280 H.264,解密重组后的码流通过 FFmpeg 解码。
|
||||
该路径按设计不采音频,实际音频采集/播放未实测;音频包加密和 PCM 分片重组有独立测试。
|
||||
探针拒绝 view 会话收到剪贴板事件,不打印剪贴板内容。
|
||||
|
||||
## Flutter FFI 与中继回归
|
||||
|
||||
```powershell
|
||||
cd flutter_sender
|
||||
dart run tool/media_protocol_smoke.dart ../rust_core/target/release/ttstdconnect_core.dll
|
||||
```
|
||||
|
||||
WSL 使用 Linux `.so` 路径运行同一脚本,验证真实 ABI、65 字节开销和认证失败,不使用 mock。
|
||||
`signaling_server/tests/relay_smoke.py` 验证现有中继外层与 v2 内层组合,仍能完成 ECDH、加密控制和媒体入队。
|
||||
Linux Flutter 可编译且协议/FFI 测试通过,但本轮不增加 Linux 视频/音频播放插件。
|
||||
@@ -0,0 +1,90 @@
|
||||
# 跨网段信令部署与使用
|
||||
|
||||
## 服务端
|
||||
|
||||
在服务器构建 `signaling_server`,为同一受信任设备组生成一个至少 32 字符的随机访问令牌。
|
||||
令牌通过 Authorization: Bearer 传递;不要放到地址查询参数、公开发现信息或日志中。
|
||||
|
||||
```bash
|
||||
cd signaling_server
|
||||
go build -o ttstd-signaling .
|
||||
export SIGNALING_TOKEN="$(openssl rand -hex 32)"
|
||||
# 妥善记录此令牌,供两端配置;重启服务时需设置同一个值。
|
||||
export LISTEN_ADDR=127.0.0.1:8080
|
||||
./ttstd-signaling
|
||||
```
|
||||
|
||||
此方式在回环 HTTP 前部署 HTTPS 反向代理,转发 `/register`、`/heartbeat`、`/list`、
|
||||
`/watch`、`/relay`、`/relay/poll`、`/unregister`。代理必须保留 Authorization 头,
|
||||
`/watch` 需要 WebSocket Upgrade。客户端填写代理的 HTTPS 地址。
|
||||
|
||||
也可直接配置服务端 TLS:
|
||||
|
||||
```bash
|
||||
export LISTEN_ADDR=:443
|
||||
export TLS_CERT_FILE=/path/to/fullchain.pem
|
||||
export TLS_KEY_FILE=/path/to/privkey.pem
|
||||
./ttstd-signaling
|
||||
```
|
||||
|
||||
Rust、Android、Flutter 都验证 HTTPS 证书链和主机名;私有 CA 需安装到对应系统信任库,
|
||||
不提供忽略证书验证选项。Rust 缓存进程启动后的根证书配置,更新信任库后需重启应用。
|
||||
|
||||
未设置令牌时服务端拒绝启动。仅测试受信任内网时,可明确设置 `ALLOW_INSECURE_SIGNALING=1`;
|
||||
桌面端内置本机信令使用这一模式,不适合直接暴露公网。携带令牌的明文 HTTP 默认只能绑定回环;
|
||||
受信任内网调试需显式设置 `ALLOW_HTTP_SIGNALING=1`。
|
||||
|
||||
除只返回存活状态的 `/healthz` 外,设备列表、注册、心跳、注销、WebSocket 和中继接口
|
||||
均需认证。服务端按来源 IP 限流(200 请求/秒、突发 400),每 IP 最多 4 个 watch;
|
||||
反向代理场景按代理来源地址计数,不信任客户端提供的 X-Forwarded-For。
|
||||
|
||||
## 客户端
|
||||
|
||||
1. Android 主界面填写「外部信令地址」和「信令访问令牌」,保存后停止并重新启动待命服务。
|
||||
即使没有局域网信标,仍会向信令注册并监听中继握手。
|
||||
2. 主控端设置关闭「使用本机信令服务器」,填写同一 HTTPS 地址和访问令牌。
|
||||
3. 点击服务检测确认列表访问通过;开启「连接走信令中继」,刷新设备列表并连接。
|
||||
4. 被控端确认投屏后才启动媒体;权限上限仍由被控端决定,握手后默认 view,等待会话配置再授权输入/文件。
|
||||
|
||||
主控设置保存在当前用户配置目录的 `TTSTDConnect/settings.json`,包含令牌;
|
||||
Linux/macOS 文件权限为 0600,Windows 使用用户 AppData 继承权限。此处没有操作系统凭据库加密。
|
||||
主控日志隐藏令牌片段。内部 FFI 用 `#token=...` 传递凭据,发出请求前移除片段并改为请求头,
|
||||
界面不需要手动拼接这种地址。
|
||||
|
||||
## 安全边界与当前限制
|
||||
|
||||
共享令牌是受信任设备组的入场凭据,不是每台设备独立身份;持有相同令牌的参与者仍相互信任,
|
||||
不支持不互信租户共用同一实例。中继检查外层和内层 from 一致,并为未注册的临时主控 ID
|
||||
建立 5 分钟回复路由;这不等于设备私钥签名或硬件身份验证。
|
||||
|
||||
watch 仅发送变更类型和设备 ID,完整设备信息通过已认证 `/list` 获取。
|
||||
媒体仍通过 `/relay` HTTP(S) 批量轮询传输,控制帧和中继媒体均有会话级加密,
|
||||
没有实现独立的 WebSocket 媒体隧道或自动 UDP→WS 降级。
|
||||
直连 UDP 与中继的内层媒体均升级为 `aes-gcm/2`:每分片 AES-GCM、认证头、防重放与完整帧重组。
|
||||
两端必须协商新版协议,旧 HMAC 明文媒体不会被接受;详见 README §4.5。
|
||||
本轮未补齐 Linux/macOS 视频音频播放插件。
|
||||
|
||||
## 文件与状态修复
|
||||
|
||||
文件服务公开 info 的 fingerprint 是应用签名指纹,不再是访问令牌;空令牌拒绝访问,
|
||||
register 只匹配两个准确路径和 POST,鉴权在读取私有请求体前完成。
|
||||
控制通道上传限制单文件及单会话 64 MiB、分片 256 KiB,按连续偏移写 `.part` 文件,
|
||||
新主控发送 SHA-256,完成后校验并重命名,取消或过期清理未完成文件;支持空文件。
|
||||
为兼容旧客户端,缺失 SHA-256 的旧请求仍可接收,但不提供摘要校验,也没有断点续传。
|
||||
单个上传请求会话最多 32 文件、同时最多 8 个会话,空闲 15 分钟后在下次文件操作时回收。
|
||||
|
||||
Windows 串流增加 60 秒授权等待、授权后 15 秒首帧等待,以及 5 秒停帧检测,超时关闭窗口并停止投屏。
|
||||
现有投屏应答没有请求 ID,无法彻底区分旧请求的迟到应答;进一步修复需要同步扩展三端协议。
|
||||
|
||||
## 本地跨组件自测
|
||||
|
||||
```powershell
|
||||
# Windows 仓库根目录(先按 AGENTS.md 编译、测试)
|
||||
go -C signaling_server build -o ../dist/validation/signaling_server.exe .
|
||||
cargo build --manifest-path rust_core/Cargo.toml --release --offline
|
||||
python signaling_server/tests/relay_smoke.py --server dist/validation/signaling_server.exe --core rust_core/target/release/ttstdconnect_core.dll
|
||||
```
|
||||
|
||||
自测启动临时回环 Go 服务,验证匿名拒绝、带令牌注册、真实 Rust ECDH 握手、临时主控回复路由、
|
||||
加密 Ping/Pong 和 AES-GCM 媒体到帧队列;结束后关闭自己启动的进程。
|
||||
它不替代真实 Android 设备、跨路由网络和公网证书部署测试。
|
||||
@@ -9,6 +9,8 @@ import 'discovery_client.dart';
|
||||
import 'local_signaling.dart';
|
||||
import 'models.dart';
|
||||
import 'native_core.dart';
|
||||
import 'signaling_endpoint.dart';
|
||||
import 'settings_store.dart';
|
||||
|
||||
class SenderBridge {
|
||||
SenderBridge({
|
||||
@@ -335,9 +337,12 @@ class SenderBridge {
|
||||
}
|
||||
|
||||
Future<void> saveSettings(AppSettings settings) async {
|
||||
await SettingsStore().save(settings);
|
||||
await _invokeIgnoringMissing('settings', settings.toJson());
|
||||
}
|
||||
|
||||
AppSettings loadSettings() => SettingsStore().load();
|
||||
|
||||
Future<bool> startLocalSignaling(int port) => _localSignaling.start(port: port);
|
||||
|
||||
Future<void> stopLocalSignaling() => _localSignaling.stop();
|
||||
@@ -348,7 +353,7 @@ class SenderBridge {
|
||||
if (settings.useLocalSignaling) {
|
||||
return _localSignaling.url(port: settings.localSignalingPort);
|
||||
}
|
||||
return settings.signalingUrl;
|
||||
return SignalingEndpoint.withToken(settings.signalingUrl, settings.signalingToken);
|
||||
}
|
||||
|
||||
/// 启动 Rust Core 的本机 demo 服务。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
/// 控制通道文件子协议(`msg_type=7`)的客户端。
|
||||
///
|
||||
@@ -37,6 +38,8 @@ class ControlFileClient {
|
||||
throw const ControlFileException('本地文件不存在');
|
||||
}
|
||||
final length = await file.length();
|
||||
if (length > 64 * 1024 * 1024) throw const ControlFileException('单文件不能超过 64 MiB');
|
||||
final digest = await sha256.bind(file.openRead()).first;
|
||||
final name = localPath.split(RegExp(r'[\\/]')).last;
|
||||
final fileId = 'f-${DateTime.now().microsecondsSinceEpoch}';
|
||||
|
||||
@@ -50,8 +53,7 @@ class ControlFileClient {
|
||||
'name': name,
|
||||
'size': length,
|
||||
'mime': 'application/octet-stream',
|
||||
// 没有 crypto 依赖,算不了摘要;被控端只在续传判断时用它。
|
||||
'sha256': '',
|
||||
'sha256': digest.toString(),
|
||||
},
|
||||
],
|
||||
}),
|
||||
@@ -69,7 +71,7 @@ class ControlFileClient {
|
||||
while (offset < length) {
|
||||
await handle.setPosition(offset);
|
||||
final bytes = await handle.read(math.min(chunkSize, length - offset));
|
||||
if (bytes.isEmpty) break;
|
||||
if (bytes.isEmpty) throw const ControlFileException('读取文件提前结束,上传已取消');
|
||||
final ack = await send({
|
||||
'op': 'chunk',
|
||||
'sessionId': sessionId,
|
||||
|
||||
@@ -32,6 +32,7 @@ class DiagnosticLog {
|
||||
}
|
||||
|
||||
void write(String message) {
|
||||
message = message.replaceAll(RegExp(r'#token=[^\s;)]*'), '#token=[redacted]');
|
||||
final file = _file;
|
||||
if (file == null) return;
|
||||
try {
|
||||
|
||||
@@ -3,28 +3,33 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'models.dart';
|
||||
import 'signaling_endpoint.dart';
|
||||
|
||||
class DiscoveryClient {
|
||||
static Future<List<DeviceInfo>> listDevices(
|
||||
String signalingUrl, {
|
||||
Duration timeout = const Duration(seconds: 2),
|
||||
bool throwOnError = false,
|
||||
}) async {
|
||||
final trimmed = signalingUrl.trim();
|
||||
if (trimmed.isEmpty) return const <DeviceInfo>[];
|
||||
final client = HttpClient()..connectionTimeout = timeout;
|
||||
try {
|
||||
final base = Uri.parse(trimmed);
|
||||
final base = Uri.parse(SignalingEndpoint.publicUrl(trimmed));
|
||||
final path = base.path.endsWith('/')
|
||||
? '${base.path}list'
|
||||
: '${base.path}/list';
|
||||
final request = await client.getUrl(base.replace(path: path)).timeout(timeout);
|
||||
request.followRedirects = false;
|
||||
SignalingEndpoint.headers(trimmed).forEach(request.headers.set);
|
||||
final response = await request.close().timeout(timeout);
|
||||
final body = await utf8.decoder.bind(response).join().timeout(timeout);
|
||||
if (response.statusCode != HttpStatus.ok) return const <DeviceInfo>[];
|
||||
if (response.statusCode != HttpStatus.ok) throw HttpException('信令 HTTP ${response.statusCode}(请检查地址和访问令牌)');
|
||||
final value = jsonDecode(body);
|
||||
if (value is! Map) return const <DeviceInfo>[];
|
||||
return DeviceInfo.listFromJson(value['devices']);
|
||||
} on Object {
|
||||
if (throwOnError) rethrow;
|
||||
return const <DeviceInfo>[];
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
|
||||
@@ -22,7 +22,10 @@ class LocalSignalingProcess {
|
||||
binary.path,
|
||||
const <String>[],
|
||||
workingDirectory: binary.parent.path,
|
||||
environment: <String, String>{'LISTEN_ADDR': ':$port'},
|
||||
environment: <String, String>{
|
||||
'LISTEN_ADDR': ':$port', 'ALLOW_INSECURE_SIGNALING': '1',
|
||||
'SIGNALING_TOKEN': '', 'TLS_CERT_FILE': '', 'TLS_KEY_FILE': '',
|
||||
},
|
||||
);
|
||||
process.stdout.listen((_) {});
|
||||
process.stderr.listen((_) {});
|
||||
|
||||
@@ -162,6 +162,7 @@ enum AccessLevel {
|
||||
|
||||
class AppSettings {
|
||||
final String signalingUrl;
|
||||
final String signalingToken;
|
||||
final bool useLocalSignaling;
|
||||
final bool localSignalingEnabled;
|
||||
final int localSignalingPort;
|
||||
@@ -181,6 +182,7 @@ class AppSettings {
|
||||
|
||||
const AppSettings({
|
||||
this.signalingUrl = '',
|
||||
this.signalingToken = '',
|
||||
this.useLocalSignaling = true,
|
||||
this.localSignalingEnabled = true,
|
||||
this.localSignalingPort = 8080,
|
||||
@@ -201,6 +203,7 @@ class AppSettings {
|
||||
|
||||
AppSettings copyWith({
|
||||
String? signalingUrl,
|
||||
String? signalingToken,
|
||||
bool? useLocalSignaling,
|
||||
bool? localSignalingEnabled,
|
||||
int? localSignalingPort,
|
||||
@@ -216,6 +219,7 @@ class AppSettings {
|
||||
}) {
|
||||
return AppSettings(
|
||||
signalingUrl: signalingUrl ?? this.signalingUrl,
|
||||
signalingToken: signalingToken ?? this.signalingToken,
|
||||
useLocalSignaling: useLocalSignaling ?? this.useLocalSignaling,
|
||||
localSignalingEnabled: localSignalingEnabled ?? this.localSignalingEnabled,
|
||||
localSignalingPort: localSignalingPort ?? this.localSignalingPort,
|
||||
@@ -234,6 +238,7 @@ class AppSettings {
|
||||
factory AppSettings.fromJson(Map<String, dynamic> json) {
|
||||
return AppSettings(
|
||||
signalingUrl: (json['signalingUrl'] ?? defaults.signalingUrl).toString(),
|
||||
signalingToken: (json['signalingToken'] ?? '').toString(),
|
||||
useLocalSignaling: json['useLocalSignaling'] as bool? ?? defaults.useLocalSignaling,
|
||||
localSignalingEnabled:
|
||||
json['localSignalingEnabled'] as bool? ?? defaults.localSignalingEnabled,
|
||||
@@ -253,6 +258,7 @@ class AppSettings {
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'signalingUrl': signalingUrl,
|
||||
'signalingToken': signalingToken,
|
||||
'useLocalSignaling': useLocalSignaling,
|
||||
'localSignalingEnabled': localSignalingEnabled,
|
||||
'localSignalingPort': localSignalingPort,
|
||||
|
||||
@@ -7,7 +7,12 @@ import 'package:ffi/ffi.dart';
|
||||
|
||||
/// Rust Core 的 ffi 通道。桌面端通过 cdylib 直接调用,测试环境可注入桩实现。
|
||||
class NativeCore {
|
||||
NativeCore({DynamicLibrary? library}) : _library = library ?? _openLibrary();
|
||||
NativeCore({DynamicLibrary? library}) : _library = library ?? _openLibrary() {
|
||||
if (abiRevision() != 6) throw UnsupportedError('Rust Core 版本不匹配,需要支持媒体 aes-gcm/2 的 ABI 6 动态库');
|
||||
}
|
||||
|
||||
static const mediaProtocol = 'aes-gcm/2';
|
||||
static const mediaPacketOverhead = 37 + 12 + 16;
|
||||
|
||||
static const int ok = 0;
|
||||
static const int errBufferTooSmall = -1;
|
||||
@@ -163,7 +168,7 @@ class NativeCore {
|
||||
Uint8List mediaEncode(int pts, int flags, List<int> key, List<int> payload) {
|
||||
return _withBytes(key, (keyPtr) {
|
||||
return _withBytes(payload, (payloadPtr) {
|
||||
final capacity = 13 + payload.length + 4;
|
||||
final capacity = mediaPacketOverhead + payload.length;
|
||||
final out = calloc<Uint8>(capacity);
|
||||
try {
|
||||
final written = _mediaEncode(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'signaling_endpoint.dart';
|
||||
|
||||
class ServiceCheckResult {
|
||||
const ServiceCheckResult({
|
||||
@@ -32,11 +33,13 @@ class ServiceChecker {
|
||||
if (trimmed.isEmpty) return false;
|
||||
final client = HttpClient()..connectionTimeout = timeout;
|
||||
try {
|
||||
final base = Uri.parse(trimmed);
|
||||
final base = Uri.parse(SignalingEndpoint.publicUrl(trimmed));
|
||||
final path = base.path.endsWith('/')
|
||||
? '${base.path}healthz'
|
||||
: '${base.path}/healthz';
|
||||
? '${base.path}list'
|
||||
: '${base.path}/list';
|
||||
final request = await client.getUrl(base.replace(path: path)).timeout(timeout);
|
||||
request.followRedirects = false;
|
||||
SignalingEndpoint.headers(trimmed).forEach(request.headers.set);
|
||||
final response = await request.close().timeout(timeout);
|
||||
await response.drain<void>().timeout(timeout);
|
||||
return response.statusCode == HttpStatus.ok;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'models.dart';
|
||||
|
||||
class SettingsStore {
|
||||
SettingsStore({File? file}) : file = file ?? File(_defaultPath());
|
||||
final File file;
|
||||
|
||||
static String _defaultPath() {
|
||||
final env = Platform.environment;
|
||||
final home = env['HOME'] ?? env['USERPROFILE'] ?? Directory.current.path;
|
||||
final base = Platform.isWindows
|
||||
? env['APPDATA'] ?? home
|
||||
: Platform.isMacOS
|
||||
? '$home/Library/Application Support'
|
||||
: env['XDG_CONFIG_HOME'] ?? '$home/.config';
|
||||
return '$base/TTSTDConnect/settings.json';
|
||||
}
|
||||
|
||||
AppSettings load() {
|
||||
try {
|
||||
return AppSettings.fromJson(
|
||||
jsonDecode(file.readAsStringSync()) as Map<String, dynamic>);
|
||||
} on Object {
|
||||
return AppSettings.defaults;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> save(AppSettings settings) async {
|
||||
await file.parent.create(recursive: true);
|
||||
final temp =
|
||||
File('${file.path}.${DateTime.now().microsecondsSinceEpoch}.tmp');
|
||||
try {
|
||||
await temp.create();
|
||||
if (!Platform.isWindows) {
|
||||
final result = await Process.run('chmod', ['600', temp.path]);
|
||||
if (result.exitCode != 0)
|
||||
throw FileSystemException('无法保护设置文件', temp.path);
|
||||
}
|
||||
await temp.writeAsString(jsonEncode(settings.toJson()), flush: true);
|
||||
await temp.rename(file.path);
|
||||
} finally {
|
||||
if (await temp.exists()) await temp.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/// Credentials are carried internally in a URL fragment, never in HTTP paths.
|
||||
/// This preserves the Rust FFI ABI while allowing every transport to use Bearer.
|
||||
class SignalingEndpoint {
|
||||
static String withToken(String base, String token) {
|
||||
final uri = Uri.parse(base.trim());
|
||||
return token.trim().isEmpty
|
||||
? uri.removeFragment().toString()
|
||||
: uri
|
||||
.replace(fragment: 'token=${Uri.encodeComponent(token.trim())}')
|
||||
.toString();
|
||||
}
|
||||
|
||||
static String token(String url) {
|
||||
final fragment = Uri.parse(url).fragment;
|
||||
return fragment.startsWith('token=')
|
||||
? Uri.decodeComponent(fragment.substring(6))
|
||||
: '';
|
||||
}
|
||||
|
||||
static String publicUrl(String url) =>
|
||||
Uri.parse(url).removeFragment().toString();
|
||||
|
||||
static Map<String, String> headers(String url) {
|
||||
final value = token(url);
|
||||
return value.isEmpty ? const {} : {'Authorization': 'Bearer $value'};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'signaling_endpoint.dart';
|
||||
|
||||
/// 信令服务器 `WS /watch` 的客户端。
|
||||
///
|
||||
@@ -42,7 +43,7 @@ class SignalingWatch {
|
||||
static Uri? watchUri(String base) {
|
||||
final trimmed = base.trim();
|
||||
if (trimmed.isEmpty) return null;
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
final uri = Uri.tryParse(SignalingEndpoint.publicUrl(trimmed));
|
||||
if (uri == null || uri.host.isEmpty) return null;
|
||||
final scheme = switch (uri.scheme) {
|
||||
'https' || 'wss' => 'wss',
|
||||
@@ -68,7 +69,7 @@ class SignalingWatch {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final socket = await WebSocket.connect(uri.toString()).timeout(_connectTimeout);
|
||||
final socket = await WebSocket.connect(uri.toString(), headers: SignalingEndpoint.headers(signalingUrl)).timeout(_connectTimeout);
|
||||
if (_stopped) {
|
||||
await socket.close();
|
||||
return;
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import '../../core/bridge.dart';
|
||||
import '../../core/models.dart';
|
||||
import '../../core/service_check.dart';
|
||||
import '../../core/signaling_endpoint.dart';
|
||||
|
||||
class SettingsPage extends StatefulWidget {
|
||||
const SettingsPage({
|
||||
@@ -20,6 +21,7 @@ class SettingsPage extends StatefulWidget {
|
||||
|
||||
class _SettingsPageState extends State<SettingsPage> {
|
||||
late final TextEditingController _signalingUrl;
|
||||
late final TextEditingController _signalingToken;
|
||||
late final TextEditingController _localPort;
|
||||
late final TextEditingController _filePort;
|
||||
late final TextEditingController _fileToken;
|
||||
@@ -42,6 +44,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_signalingUrl = TextEditingController(text: widget.settings.signalingUrl);
|
||||
_signalingToken = TextEditingController(text: widget.settings.signalingToken);
|
||||
_localPort = TextEditingController(text: '${widget.settings.localSignalingPort}');
|
||||
_filePort = TextEditingController(text: '${widget.settings.filePort}');
|
||||
_fileToken = TextEditingController(text: widget.settings.fileToken);
|
||||
@@ -62,6 +65,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
@override
|
||||
void dispose() {
|
||||
_signalingUrl.dispose();
|
||||
_signalingToken.dispose();
|
||||
_localPort.dispose();
|
||||
_filePort.dispose();
|
||||
_fileToken.dispose();
|
||||
@@ -102,7 +106,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
final listener = _localListener ?? await widget.bridge.localListener();
|
||||
final host = listener?.ip ?? '127.0.0.1';
|
||||
final results = await Future.wait<bool>([
|
||||
ServiceChecker.checkSignaling(url),
|
||||
ServiceChecker.checkSignaling(_useLocalSignaling ? url : SignalingEndpoint.withToken(url, _signalingToken.text)),
|
||||
ServiceChecker.checkTcp(host, 41001),
|
||||
]);
|
||||
Map<String, dynamic> status = const <String, dynamic>{'running': false};
|
||||
@@ -210,6 +214,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).pop(AppSettings(
|
||||
signalingUrl: _signalingUrl.text.trim(),
|
||||
signalingToken: _signalingToken.text.trim(),
|
||||
useLocalSignaling: _useLocalSignaling,
|
||||
localSignalingEnabled: _localSignalingEnabled,
|
||||
localSignalingPort: _port,
|
||||
@@ -305,7 +310,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
controller: _signalingUrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '外部信令服务器',
|
||||
hintText: 'http://<信令服务器IP>:8080',
|
||||
hintText: 'https://signal.example.com',
|
||||
prefixIcon: Icon(Icons.cloud),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
@@ -315,10 +320,18 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
'跨网段时通过自部署信令服务器交换地址。',
|
||||
'跨网段需两端填写同一服务器及令牌,并开启信令中继。',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
if (!_useLocalSignaling) Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: TextField(
|
||||
controller: _signalingToken,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(labelText: '信令访问令牌', border: OutlineInputBorder()),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
@@ -404,7 +417,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
),
|
||||
SwitchListTile(
|
||||
title: const Text('启用音频'),
|
||||
subtitle: const Text('AudioPlaybackCapture / OPUS'),
|
||||
subtitle: const Text('AudioPlaybackCapture / PCM16 · 48 kHz 双声道'),
|
||||
value: _audioEnabled,
|
||||
onChanged: (value) => setState(() => _audioEnabled = value),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,8 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'core/bridge.dart';
|
||||
import 'core/discovery_client.dart';
|
||||
import 'core/signaling_endpoint.dart';
|
||||
import 'core/diagnostic_log.dart';
|
||||
import 'core/control_file_client.dart';
|
||||
import 'core/native_core.dart';
|
||||
@@ -66,8 +68,9 @@ class _HomePageState extends State<HomePage> {
|
||||
bool _refreshQueued = false;
|
||||
/// 当前控制通道是否走信令中继(媒体分片经中继加密转发,延迟高于直连)。
|
||||
bool _relayActive = false;
|
||||
/// 被控端回送的有效权限等级(msgType=10);被控端未应答前按请求值乐观处理。
|
||||
AccessLevel _grantedAccess = AccessLevel.full;
|
||||
/// 被控端回送的有效权限等级(msgType=10);被控端未应答前仅允许查看。
|
||||
AccessLevel _grantedAccess = AccessLevel.view;
|
||||
bool _mediaProtocolAgreed = false;
|
||||
/// 权限不足提示的去抖时间,避免连续手势把 SnackBar 刷爆。
|
||||
DateTime? _lastAccessWarnAt;
|
||||
|
||||
@@ -87,6 +90,10 @@ class _HomePageState extends State<HomePage> {
|
||||
bool _mirrorRequesting = false;
|
||||
bool _mirrorGranted = false;
|
||||
bool _videoStreaming = false;
|
||||
int _lastWindowFrames = 0;
|
||||
DateTime? _lastVideoFrameAt;
|
||||
DateTime? _mirrorRequestedAt;
|
||||
DateTime? _mirrorGrantedAt;
|
||||
int _videoWindowGeneration = 0;
|
||||
/// 因关窗而停流只下发一次 stopMirror。
|
||||
bool _stopSentForWindowClose = false;
|
||||
@@ -104,6 +111,7 @@ class _HomePageState extends State<HomePage> {
|
||||
_nativeError = error.toString();
|
||||
}
|
||||
_bridge = SenderBridge(nativeCore: _nativeCore);
|
||||
_settings = _bridge.loadSettings();
|
||||
// 独立窗口被用户关闭 → 停止投屏。
|
||||
_bridge.onVideoWindowClosed = _onStreamWindowClosed;
|
||||
// 串流窗口里的鼠标点击/拖拽 → 触摸控制帧。
|
||||
@@ -216,7 +224,8 @@ class _HomePageState extends State<HomePage> {
|
||||
// 刚连上时主动下发一次会话配置,顺带把权限等级请求发过去;
|
||||
// 被控端会用 msgType=10 回送裁剪后的有效等级。
|
||||
if (!wasConnected && _phase.isConnected) {
|
||||
_grantedAccess = _settings.access;
|
||||
_grantedAccess = AccessLevel.view;
|
||||
_mediaProtocolAgreed = false;
|
||||
_applySessionConfig();
|
||||
}
|
||||
} on Object catch (error) {
|
||||
@@ -263,6 +272,7 @@ class _HomePageState extends State<HomePage> {
|
||||
if (!_videoWindowOpen || _stopSentForWindowClose) return;
|
||||
switch (action) {
|
||||
case 2:
|
||||
_mirrorGrantedAt = DateTime.now();
|
||||
setState(() => _mirrorGranted = true);
|
||||
_snack('被控端已允许投屏');
|
||||
case 3:
|
||||
@@ -279,6 +289,9 @@ class _HomePageState extends State<HomePage> {
|
||||
/// [_stopSentForWindowClose] 置位是必须的——窗口是我们自己关的,
|
||||
/// 不能再给对端补发一条 stopMirror。
|
||||
Future<void> _abortMirror(String message) async {
|
||||
if (_phase.isConnected && _videoWindowOpen && !_stopSentForWindowClose) {
|
||||
_bridge.sendControl('stopMirror', const {});
|
||||
}
|
||||
_stopSentForWindowClose = true;
|
||||
final close = _bridge.closeVideoWindow();
|
||||
_clearMirrorState();
|
||||
@@ -292,6 +305,10 @@ class _HomePageState extends State<HomePage> {
|
||||
_videoWindowOpen = false;
|
||||
_mirrorGranted = false;
|
||||
_videoStreaming = false;
|
||||
_lastWindowFrames = 0;
|
||||
_lastVideoFrameAt = null;
|
||||
_mirrorRequestedAt = null;
|
||||
_mirrorGrantedAt = null;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -306,6 +323,7 @@ class _HomePageState extends State<HomePage> {
|
||||
try {
|
||||
final decoded = jsonDecode(text);
|
||||
if (decoded is! Map) return;
|
||||
_mediaProtocolAgreed = decoded['mediaProtocol'] == NativeCore.mediaProtocol;
|
||||
level = AccessLevel.fromValue(decoded['level'], fallback: _grantedAccess);
|
||||
max = AccessLevel.fromValue(decoded['max'], fallback: level).value;
|
||||
} on Object catch (error) {
|
||||
@@ -382,6 +400,7 @@ class _HomePageState extends State<HomePage> {
|
||||
'preferH265': _settings.preferH265,
|
||||
'bitrateMbps': _settings.bitrateMbps,
|
||||
'audioEnabled': _settings.audioEnabled,
|
||||
'mediaProtocol': NativeCore.mediaProtocol,
|
||||
'clipboardSync': _settings.clipboardSync,
|
||||
// 权限只能「请求」:被控端会按本机上限裁剪并用 msgType=10 回送有效等级。
|
||||
'access': _settings.access.code,
|
||||
@@ -408,6 +427,11 @@ class _HomePageState extends State<HomePage> {
|
||||
final id = stats['textureId'];
|
||||
final windowOpen = stats['windowOpen'];
|
||||
final windowFrames = stats['windowFrames'];
|
||||
final now = DateTime.now();
|
||||
if (_videoWindowOpen && windowFrames is int && windowFrames > _lastWindowFrames) {
|
||||
_lastWindowFrames = windowFrames;
|
||||
_lastVideoFrameAt = now;
|
||||
}
|
||||
// 原生窗口被用户关掉(方法通道回调丢失时的兜底)。
|
||||
final closedByUser = windowOpen is bool && !windowOpen && _videoWindowOpen;
|
||||
|
||||
@@ -420,12 +444,23 @@ class _HomePageState extends State<HomePage> {
|
||||
windowOpen == true &&
|
||||
windowFrames is int &&
|
||||
windowFrames > 0) {
|
||||
_videoStreaming = true;
|
||||
_videoStreaming = _lastVideoFrameAt != null && now.difference(_lastVideoFrameAt!) < const Duration(seconds: 5);
|
||||
}
|
||||
});
|
||||
|
||||
if (closedByUser) {
|
||||
await _onStreamWindowClosed();
|
||||
} else if (_videoWindowOpen) {
|
||||
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)) {
|
||||
await _abortMirror('投屏已允许,但等待首帧超时');
|
||||
} else if (lastFrame == null && granted == null && requested != null && now.difference(requested) > const Duration(minutes: 1)) {
|
||||
await _abortMirror('等待投屏确认超时');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,6 +469,10 @@ class _HomePageState extends State<HomePage> {
|
||||
/// 被控端会弹窗确认,确认后才开始推流;这段时间窗口显示「等待画面」。
|
||||
Future<void> _requestMirror() async {
|
||||
if (_videoWindowOpen || _mirrorRequesting) return;
|
||||
if (!_mediaProtocolAgreed) {
|
||||
_snack('媒体加密协议尚未协商或版本不兼容,请升级两端后重新连接');
|
||||
return;
|
||||
}
|
||||
if (!_phase.isConnected) {
|
||||
_snack('请先连接被控端');
|
||||
return;
|
||||
@@ -457,6 +496,10 @@ class _HomePageState extends State<HomePage> {
|
||||
setState(() {
|
||||
_videoWindowGeneration++;
|
||||
_videoWindowOpen = true;
|
||||
_lastWindowFrames = 0;
|
||||
_lastVideoFrameAt = null;
|
||||
_mirrorGrantedAt = null;
|
||||
_mirrorRequestedAt = DateTime.now();
|
||||
});
|
||||
if (!_phase.isConnected) {
|
||||
await _abortMirror('被控端已断开,串流窗口已关闭');
|
||||
@@ -695,7 +738,7 @@ class _HomePageState extends State<HomePage> {
|
||||
'phase=${_phase.wireName} label=${_phase.label}; '
|
||||
'devices=${_devices.length} target=$target refreshing=$_refreshing; '
|
||||
'signaling local=${_settings.useLocalSignaling} '
|
||||
'running=$_localSignalingRunning url=$_effectiveSignalingUrl; '
|
||||
'running=$_localSignalingRunning url=${SignalingEndpoint.publicUrl(_effectiveSignalingUrl)}; '
|
||||
'nativeError=${_nativeError ?? '-'}; textureId=${_textureId ?? '-'}; '
|
||||
'video=$_videoStats; demoStatus=$status',
|
||||
);
|
||||
@@ -892,6 +935,13 @@ class _HomePageState extends State<HomePage> {
|
||||
/// 中继同时承载控制帧与加密媒体分片;媒体延迟高于直连,但可跨网段。
|
||||
Future<void> _connectViaRelay(DeviceInfo device) async {
|
||||
final signalingUrl = await _bridge.resolveSignalingUrl(_settings);
|
||||
try {
|
||||
await DiscoveryClient.listDevices(signalingUrl, throwOnError: true);
|
||||
} on Object catch (error) {
|
||||
if (mounted) _snack('信令连接失败:$error');
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
final error = _bridge.startRelay(device, signalingUrl);
|
||||
if (!mounted) return;
|
||||
if (error != null) {
|
||||
@@ -915,16 +965,16 @@ class _HomePageState extends State<HomePage> {
|
||||
/// 设备指纹校验(TOFU)。
|
||||
///
|
||||
/// 首次连接记录被控端公布的指纹;以后必须一致,不一致时弹窗让用户确认
|
||||
/// (重装/换签名会变,中间人也会变)。被控端没公布指纹(旧版本)时放行并提示。
|
||||
/// (重装/换签名会变,中间人也会变)。被控端没公布指纹时拒绝连接。
|
||||
Future<bool> _confirmFingerprint(DeviceInfo device) async {
|
||||
final key = device.id.trim().isNotEmpty
|
||||
? device.id.trim()
|
||||
: '${device.ip}:${device.controlPort}';
|
||||
final announced = device.fingerprint.trim();
|
||||
if (announced.isEmpty) {
|
||||
_diagnosticLog.write('peer announced empty fp, skip pinning ($key)');
|
||||
_snack('被控端未公布指纹(旧版本),本次连接未经身份校验');
|
||||
return true;
|
||||
_diagnosticLog.write('peer announced empty fp, reject missing fp ($key)');
|
||||
_snack('被控端未公布指纹(旧版本),已拒绝连接,请更新被控端');
|
||||
return false;
|
||||
}
|
||||
final pinned = _pins.pinOf(key);
|
||||
if (pinned == null) {
|
||||
@@ -983,7 +1033,8 @@ class _HomePageState extends State<HomePage> {
|
||||
_phase = ConnectionPhase.idle;
|
||||
_relayActive = false;
|
||||
// 断开后回到「未协商」状态,重连时按设置重新请求。
|
||||
_grantedAccess = _settings.access;
|
||||
_grantedAccess = AccessLevel.view;
|
||||
_mediaProtocolAgreed = false;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1323,8 +1374,8 @@ class _HomePageState extends State<HomePage> {
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Text(
|
||||
_settings.useLocalSignaling
|
||||
? 'mDNS 同网段优先;本机信令${_localSignalingRunning ? '运行中' : '未运行'} · $_effectiveSignalingUrl,探测失败自动降级到信令中转。'
|
||||
: 'mDNS 同网段优先;外部信令 · $_effectiveSignalingUrl,探测失败自动降级到信令中转。',
|
||||
? 'mDNS 同网段优先;本机信令${_localSignalingRunning ? '运行中' : '未运行'} · ${SignalingEndpoint.publicUrl(_effectiveSignalingUrl)},探测失败自动降级到信令中转。'
|
||||
: 'mDNS 同网段优先;外部信令 · ${SignalingEndpoint.publicUrl(_effectiveSignalingUrl)},探测失败自动降级到信令中转。',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -41,6 +41,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.19.1"
|
||||
crypto:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: crypto
|
||||
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "3.0.8"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -10,6 +10,7 @@ dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
ffi: ^2.1.0
|
||||
crypto: ^3.0.6
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ttstd_sender/core/control_file_client.dart';
|
||||
|
||||
void main() {
|
||||
late Directory temp;
|
||||
setUp(() async {
|
||||
temp = await Directory.systemTemp.createTemp('ttstd-upload-');
|
||||
});
|
||||
tearDown(() async {
|
||||
await temp.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('uploads a SHA-256 manifest and preserves chunk bytes', () async {
|
||||
final file = File('${temp.path}/test.txt');
|
||||
await file.writeAsString('abc');
|
||||
final chunks = <int>[];
|
||||
final client = ControlFileClient(send: (request) async {
|
||||
if (request['op'] == 'prepare') {
|
||||
final manifest =
|
||||
(jsonDecode(request['body'] as String)['files'] as List).single;
|
||||
expect(manifest['sha256'],
|
||||
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
|
||||
return {
|
||||
'sessionId': 'session',
|
||||
'tokens': {manifest['id']: 'token'}
|
||||
};
|
||||
}
|
||||
chunks.addAll(base64Decode(request['dataB64'] as String));
|
||||
return {'ok': true};
|
||||
});
|
||||
expect(await client.upload(file.path), 'test.txt');
|
||||
expect(chunks, utf8.encode('abc'));
|
||||
});
|
||||
|
||||
test('empty files are prepared with the empty SHA-256 and no chunks',
|
||||
() async {
|
||||
final file = await File('${temp.path}/empty').create();
|
||||
var requests = 0;
|
||||
final client = ControlFileClient(send: (request) async {
|
||||
requests++;
|
||||
expect(request['op'], 'prepare');
|
||||
final manifest =
|
||||
(jsonDecode(request['body'] as String)['files'] as List).single;
|
||||
expect(manifest['sha256'],
|
||||
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
|
||||
return {
|
||||
'sessionId': 'session',
|
||||
'tokens': {manifest['id']: 'token'}
|
||||
};
|
||||
});
|
||||
await client.upload(file.path);
|
||||
expect(requests, 1);
|
||||
});
|
||||
|
||||
test('a truncated local file cancels the remote session', () async {
|
||||
final file = File('${temp.path}/changed');
|
||||
await file.writeAsString('abc');
|
||||
var cancelled = false;
|
||||
final client = ControlFileClient(send: (request) async {
|
||||
if (request['op'] == 'prepare') {
|
||||
final manifest =
|
||||
(jsonDecode(request['body'] as String)['files'] as List).single;
|
||||
await file.writeAsString('');
|
||||
return {
|
||||
'sessionId': 'session',
|
||||
'tokens': {manifest['id']: 'token'}
|
||||
};
|
||||
}
|
||||
if (request['op'] == 'cancel') cancelled = true;
|
||||
return {};
|
||||
});
|
||||
await expectLater(
|
||||
client.upload(file.path), throwsA(isA<ControlFileException>()));
|
||||
expect(cancelled, isTrue);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ttstd_sender/core/signaling_endpoint.dart';
|
||||
import 'package:ttstd_sender/core/models.dart';
|
||||
import 'package:ttstd_sender/core/watch_client.dart';
|
||||
import 'dart:io';
|
||||
import 'package:ttstd_sender/core/settings_store.dart';
|
||||
|
||||
void main() {
|
||||
test('credentials stay in headers and never in WebSocket URLs', () {
|
||||
final endpoint =
|
||||
SignalingEndpoint.withToken('https://example.com/api/', 'secret+token');
|
||||
expect(SignalingEndpoint.headers(endpoint),
|
||||
{'Authorization': 'Bearer secret+token'});
|
||||
expect(SignalingWatch.watchUri(endpoint).toString(),
|
||||
'wss://example.com/api/watch');
|
||||
expect(SignalingEndpoint.publicUrl(endpoint), 'https://example.com/api/');
|
||||
});
|
||||
test('settings roundtrip preserves signaling credentials', () {
|
||||
final settings = AppSettings.fromJson(
|
||||
const AppSettings(signalingToken: 'secret').toJson());
|
||||
expect(settings.copyWith(audioEnabled: false).signalingToken, 'secret');
|
||||
expect(AppSettings.fromJson({}).signalingToken, '');
|
||||
});
|
||||
test('settings persist across store instances', () async {
|
||||
final temp = await Directory.systemTemp.createTemp('ttstd-settings-');
|
||||
try {
|
||||
final file = File('${temp.path}/settings.json');
|
||||
expect(SettingsStore(file: file).load().signalingToken, '');
|
||||
await SettingsStore(file: file).save(const AppSettings(
|
||||
signalingToken: 'private', useLocalSignaling: false));
|
||||
expect(SettingsStore(file: file).load().signalingToken, 'private');
|
||||
await SettingsStore(file: file)
|
||||
.save(const AppSettings(signalingToken: 'rotated'));
|
||||
expect(SettingsStore(file: file).load().signalingToken, 'rotated');
|
||||
} finally {
|
||||
await temp.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -75,7 +75,7 @@ void main() {
|
||||
await tester.pumpWidget(const TTSTDConnectApp());
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.qr_code_scanner));
|
||||
await tester.tap(find.byTooltip('扫码配对').first);
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
expect(find.text('扫码配对'), findsOneWidget);
|
||||
@@ -87,7 +87,7 @@ void main() {
|
||||
await tester.pumpWidget(const TTSTDConnectApp());
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.qr_code_scanner));
|
||||
await tester.tap(find.byTooltip('扫码配对').first);
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
expect(find.text('当前平台不支持扫码配对'), findsOneWidget);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'dart:ffi';
|
||||
import '../lib/core/native_core.dart';
|
||||
|
||||
// Run against the freshly built platform library, not a mock FFI interface.
|
||||
void main(List<String> args) {
|
||||
if (args.length != 1)
|
||||
throw ArgumentError(
|
||||
'usage: dart run tool/media_protocol_smoke.dart PATH_TO_CORE');
|
||||
final core = NativeCore(library: DynamicLibrary.open(args.single));
|
||||
try {
|
||||
final key = List<int>.generate(32, (index) => index);
|
||||
final payload = 'Flutter encrypted media'.codeUnits;
|
||||
final encoded = core.mediaEncode(42, 1, key, payload);
|
||||
if (encoded.length != payload.length + NativeCore.mediaPacketOverhead)
|
||||
throw StateError('FFI capacity/header mismatch');
|
||||
if (core.mediaDecode(encoded, key)['payloadLen'] != payload.length)
|
||||
throw StateError('FFI roundtrip failed');
|
||||
final changed = encoded.toList()..[encoded.length - 1] ^= 1;
|
||||
var rejected = false;
|
||||
try {
|
||||
core.mediaDecode(changed, key);
|
||||
} on Object {
|
||||
rejected = true;
|
||||
}
|
||||
if (!rejected) throw StateError('tampered packet accepted');
|
||||
final audio = core.mediaEncode(43, 0x82, key, [0, 1, 2, 3]);
|
||||
if (core.mediaDecode(audio, key)['flags'] != 0x82)
|
||||
throw StateError('audio flags lost');
|
||||
print(
|
||||
'PASS Flutter/Rust ABI 6: encrypted media buffer, authentication failure and PCM flags');
|
||||
} finally {
|
||||
core.dispose();
|
||||
}
|
||||
}
|
||||
Generated
+73
@@ -2,6 +2,12 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.3"
|
||||
@@ -18,6 +24,22 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -128,6 +150,12 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
@@ -156,6 +184,18 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.16.0"
|
||||
@@ -176,12 +216,44 @@ dependencies = [
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"core-foundation",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"security-framework-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework-sys"
|
||||
version = "2.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -231,6 +303,7 @@ dependencies = [
|
||||
"mdns-sd",
|
||||
"ring",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -13,5 +13,6 @@ crate-type = ["rlib", "cdylib"]
|
||||
ring = "0.17"
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
mdns-sd = "0.22"
|
||||
rustls-native-certs = "0.8"
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Test-only fixed-key interoperability probe; never use this key in a session.
|
||||
use std::net::UdpSocket;
|
||||
use std::time::Duration;
|
||||
use ttstdconnect_core::media::packet::MediaError;
|
||||
use ttstdconnect_core::media::receiver::MediaReceiver;
|
||||
use ttstdconnect_core::media::{decode_media_packet, encode_media_packet, MediaPacket};
|
||||
fn main() {
|
||||
let key: [u8; 32] = std::array::from_fn(|index| index as u8);
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
match args.get(1).map(String::as_str) {
|
||||
Some("encode") => {
|
||||
let bytes = encode_media_packet(
|
||||
&MediaPacket {
|
||||
pts: 42,
|
||||
flags: 1,
|
||||
payload: b"rust-media-v2".to_vec(),
|
||||
},
|
||||
&key,
|
||||
);
|
||||
println!(
|
||||
"{}",
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect::<String>()
|
||||
);
|
||||
}
|
||||
Some("decode") => {
|
||||
let bytes = ttstdconnect_core::util::hex_decode(&args[2]).expect("hex packet");
|
||||
let (packet, _) = decode_media_packet(&bytes, &key)
|
||||
.expect("authenticated")
|
||||
.expect("complete");
|
||||
println!("{}", String::from_utf8(packet.payload).unwrap());
|
||||
}
|
||||
Some("listen") => {
|
||||
let port = args.get(2).map(String::as_str).unwrap_or("42004");
|
||||
let socket = UdpSocket::bind(format!("0.0.0.0:{port}")).unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(30)))
|
||||
.unwrap();
|
||||
println!("LISTENING {port}");
|
||||
let mut receiver = MediaReceiver::default();
|
||||
let mut buffer = [0; 65536];
|
||||
let (mut completed, mut replay, mut tamper, mut legacy) = (0, 0, 0, 0);
|
||||
for _ in 0..7 {
|
||||
let (size, _) = socket.recv_from(&mut buffer).expect("Android UDP packet");
|
||||
match receiver.receive(&key, &buffer[..size]) {
|
||||
Ok(Some(packet)) => {
|
||||
assert_eq!(packet.payload, b"android-wsl-media");
|
||||
completed += 1;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(MediaError::Replay) => replay += 1,
|
||||
Err(MediaError::InvalidMac) => tamper += 1,
|
||||
Err(MediaError::UnsupportedProtocol) => legacy += 1,
|
||||
other => panic!("unexpected: {other:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!((completed, replay, tamper, legacy), (1, 2, 1, 1));
|
||||
println!("PASS Android->Linux UDP: complete={completed}, replay={replay}, tamper={tamper}, legacy={legacy}");
|
||||
}
|
||||
_ => panic!("usage: media_v2_probe encode | decode HEX | listen [PORT]"),
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,13 @@ use std::time::Duration;
|
||||
|
||||
use ttstdconnect_core::crypto::{derive_subkey, EphemeralKeyPair};
|
||||
use ttstdconnect_core::media::stream::{FLAG_FRAGMENT_CONTINUE, FLAG_FRAGMENT_END, FLAG_FRAGMENT_START};
|
||||
use ttstdconnect_core::media::{encode_media_packet, MediaPacket, FLAG_KEYFRAME};
|
||||
use ttstdconnect_core::media::{MediaPacket, FLAG_KEYFRAME};
|
||||
use ttstdconnect_core::media::packet::encode_media_fragment;
|
||||
|
||||
const DEFAULT_CONTROL_PORT: u16 = 41001;
|
||||
const DEFAULT_VIDEO_PORT: u16 = 41000;
|
||||
const DEFAULT_FPS: u64 = 30;
|
||||
const DEFAULT_CHUNK: usize = 1200;
|
||||
const DEFAULT_CHUNK: usize = 1152;
|
||||
|
||||
fn main() {
|
||||
let mut args = env::args().skip(1);
|
||||
@@ -118,14 +119,15 @@ fn main() {
|
||||
let pts = index as u64 * (1_000_000 / fps);
|
||||
let mut failed = false;
|
||||
if chunk == 0 || payload.len() <= chunk {
|
||||
let packet = encode_media_packet(
|
||||
let packet = encode_media_fragment(
|
||||
&MediaPacket {
|
||||
pts,
|
||||
flags,
|
||||
payload: payload.to_vec(),
|
||||
},
|
||||
&video_key,
|
||||
);
|
||||
index as u64 + 1, 0, 1,
|
||||
).expect("有效媒体包");
|
||||
if let Err(error) = socket.send_to(&packet, ("127.0.0.1", video_port)) {
|
||||
eprintln!("发送视频包失败:{}", error);
|
||||
failed = true;
|
||||
@@ -144,14 +146,17 @@ fn main() {
|
||||
if end == payload.len() {
|
||||
fragment_flags |= FLAG_FRAGMENT_END;
|
||||
}
|
||||
let packet = encode_media_packet(
|
||||
let packet = encode_media_fragment(
|
||||
&MediaPacket {
|
||||
pts,
|
||||
flags: fragment_flags,
|
||||
payload: payload[offset..end].to_vec(),
|
||||
},
|
||||
&video_key,
|
||||
);
|
||||
index as u64 + 1,
|
||||
(offset / chunk) as u16,
|
||||
payload.len().div_ceil(chunk) as u16,
|
||||
).expect("有效分片");
|
||||
if let Err(error) = socket.send_to(&packet, ("127.0.0.1", video_port)) {
|
||||
eprintln!("发送视频分片失败:{}", error);
|
||||
failed = true;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! 1. 被控端反连 TCP 41001,先发送 65 字节 ECDH P-256 公钥。
|
||||
//! 2. 主控端回送 65 字节自己的公钥;双方用 HKDF 派生 control/video/audio 三把 32 字节子密钥。
|
||||
//! 3. 后续控制帧使用 `SecureControlChannel`(8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag)。
|
||||
//! 4. 视频/音频通过 UDP 41000/41002 发送,使用 `MediaPackets` 的 13 字节头 + 4 字节 HMAC。
|
||||
//! 4. 视频/音频通过 UDP 41000/41002 发送,使用媒体 v2 AES-GCM、认证分片和防重放窗口。
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{Read, Write};
|
||||
@@ -23,7 +23,7 @@ use crate::control::{ControlEvent, ControlEventKind};
|
||||
|
||||
use crate::control::SecureControlChannel;
|
||||
use crate::crypto::{derive_subkey, EphemeralKeyPair};
|
||||
use crate::media::decode_media_packet;
|
||||
use crate::media::receiver::MediaReceiver;
|
||||
use crate::session::relay::{self, RelayChannel, RelayMessage};
|
||||
use crate::session::tls::PinnedTlsStream;
|
||||
|
||||
@@ -186,6 +186,8 @@ struct Shared {
|
||||
control_key: Mutex<Option<[u8; 32]>>,
|
||||
video_key: Mutex<Option<[u8; 32]>>,
|
||||
audio_key: Mutex<Option<[u8; 32]>>,
|
||||
video_receiver: Mutex<MediaReceiver>,
|
||||
audio_receiver: Mutex<MediaReceiver>,
|
||||
sender: Mutex<Option<ControlSender>>,
|
||||
events: Mutex<Vec<String>>,
|
||||
inbound: Mutex<VecDeque<InboundEvent>>,
|
||||
@@ -204,6 +206,8 @@ impl Shared {
|
||||
control_key: Mutex::new(None),
|
||||
video_key: Mutex::new(None),
|
||||
audio_key: Mutex::new(None),
|
||||
video_receiver: Mutex::new(MediaReceiver::default()),
|
||||
audio_receiver: Mutex::new(MediaReceiver::default()),
|
||||
sender: Mutex::new(None),
|
||||
events: Mutex::new(Vec::new()),
|
||||
inbound: Mutex::new(VecDeque::new()),
|
||||
@@ -1334,15 +1338,27 @@ fn consume_media_packet(
|
||||
} else {
|
||||
&shared.audio_key
|
||||
};
|
||||
let key = match key_slot.lock().ok().and_then(|guard| *guard) {
|
||||
let key_guard = match key_slot.lock() { Ok(guard) => guard, Err(_) => return };
|
||||
let key = match key_guard.as_ref() {
|
||||
Some(key) => key,
|
||||
None => {
|
||||
shared.push_event(format!("error:{}:no-key", kind));
|
||||
return;
|
||||
}
|
||||
};
|
||||
match decode_media_packet(data, &key) {
|
||||
Ok(Some((packet, _))) => {
|
||||
let receiver_slot = if kind == "video" { &shared.video_receiver } else { &shared.audio_receiver };
|
||||
let result = match receiver_slot.lock() {
|
||||
Ok(mut receiver) => receiver.receive(key, data),
|
||||
Err(_) => return,
|
||||
};
|
||||
// Keep the key slot locked through queue publication so an old session's
|
||||
// final packet cannot be enqueued after a concurrent rekey clears queues.
|
||||
match result {
|
||||
Ok(Some(packet)) => {
|
||||
if (kind == "audio") != (packet.flags & crate::media::FLAG_AUDIO != 0) {
|
||||
shared.push_event(format!("error:{}:wrong-stream", kind));
|
||||
return;
|
||||
}
|
||||
if kind == "video" {
|
||||
if let Some((pts, flags, payload)) =
|
||||
reassembler.push(packet.pts, packet.flags, &packet.payload)
|
||||
@@ -1376,12 +1392,12 @@ fn consume_media_packet(
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(None) => shared.push_event(format!("error:{}:incomplete", kind)),
|
||||
Ok(None) => {}, // authenticated, awaiting the remaining fragments
|
||||
Err(error) => shared.push_event(format!("error:{}:{}", kind, error)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 中继媒体分片在直连格式(头+负载+MAC)外又套了一层 AES-256-GCM:
|
||||
/// 中继媒体分片在 v2 已加密媒体包外再套一层 AES-256-GCM:
|
||||
/// `[nonce:12][密文][tag:16]`,AAD 固定为 `relay-media`。
|
||||
fn decrypt_relay_media(key: &[u8; 32], data: &[u8]) -> Option<Vec<u8>> {
|
||||
if data.len() < crate::crypto::NONCE_LEN + crate::crypto::TAG_LEN {
|
||||
|
||||
@@ -1,17 +1,55 @@
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::json::{self, JsonValue};
|
||||
|
||||
use super::{DeviceInfo, DiscoveryError};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
fn signaling_tls_config() -> Result<Arc<rustls::ClientConfig>, DiscoveryError> {
|
||||
static CONFIG: OnceLock<Result<Arc<rustls::ClientConfig>, String>> = OnceLock::new();
|
||||
CONFIG
|
||||
.get_or_init(|| {
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
for cert in rustls_native_certs::load_native_certs().certs {
|
||||
let _ = roots.add(cert);
|
||||
}
|
||||
if roots.is_empty() {
|
||||
return Err("系统无可信 CA 证书".into());
|
||||
}
|
||||
let config = rustls::ClientConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| e.to_string())?
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
Ok(Arc::new(config))
|
||||
})
|
||||
.clone()
|
||||
.map_err(DiscoveryError::Http)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Endpoint {
|
||||
host: String,
|
||||
authority: String,
|
||||
port: u16,
|
||||
prefix: String,
|
||||
tls: bool,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Endpoint {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Endpoint")
|
||||
.field("host", &self.host)
|
||||
.field("port", &self.port)
|
||||
.field("tls", &self.tls)
|
||||
.field("authenticated", &!self.token.is_empty())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -71,14 +109,28 @@ impl SignalingClient {
|
||||
}
|
||||
|
||||
pub fn poll_relay(&self, device_id: &str) -> Result<Vec<JsonValue>, DiscoveryError> {
|
||||
let path = format!("/relay/poll?deviceId={}", crate::util::url_encode(device_id));
|
||||
let path = format!(
|
||||
"/relay/poll?deviceId={}",
|
||||
crate::util::url_encode(device_id)
|
||||
);
|
||||
let response = self.send_request("GET", &path, None)?;
|
||||
let value = json::parse(&response)?;
|
||||
Ok(value
|
||||
.get("messages")
|
||||
.and_then(JsonValue::as_array)
|
||||
.unwrap_or_default()
|
||||
.to_vec())
|
||||
.iter()
|
||||
.filter_map(|message| {
|
||||
let payload = message.get("payload")?;
|
||||
let from = message.get("from")?.as_str()?;
|
||||
if message.get("to")?.as_str()? != device_id
|
||||
|| payload.get("from")?.as_str()? != from
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(payload.clone())
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn send_request(
|
||||
@@ -87,13 +139,40 @@ impl SignalingClient {
|
||||
path: &str,
|
||||
body: Option<&str>,
|
||||
) -> Result<String, DiscoveryError> {
|
||||
let address = (self.endpoint.host.as_str(), self.endpoint.port)
|
||||
.to_socket_addrs()?
|
||||
.next()
|
||||
.ok_or(DiscoveryError::InvalidUrl("无法解析信令服务器地址"))?;
|
||||
let mut stream = TcpStream::connect_timeout(&address, self.timeout)?;
|
||||
stream.set_read_timeout(Some(self.timeout))?;
|
||||
stream.set_write_timeout(Some(self.timeout))?;
|
||||
let addresses = (self.endpoint.host.as_str(), self.endpoint.port).to_socket_addrs()?;
|
||||
let deadline = std::time::Instant::now() + self.timeout;
|
||||
let mut connected = None;
|
||||
let mut last_error = std::io::Error::new(
|
||||
std::io::ErrorKind::AddrNotAvailable,
|
||||
"无法解析信令服务器地址",
|
||||
);
|
||||
for address in addresses {
|
||||
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
|
||||
if remaining.is_zero() {
|
||||
break;
|
||||
}
|
||||
match TcpStream::connect_timeout(&address, remaining) {
|
||||
Ok(socket) => {
|
||||
connected = Some(socket);
|
||||
break;
|
||||
}
|
||||
Err(error) => last_error = error,
|
||||
}
|
||||
}
|
||||
let socket = connected.ok_or(last_error)?;
|
||||
socket.set_read_timeout(Some(self.timeout))?;
|
||||
socket.set_write_timeout(Some(self.timeout))?;
|
||||
trait Transport: Read + Write {}
|
||||
impl<T: Read + Write> Transport for T {}
|
||||
let mut stream: Box<dyn Transport> = if self.endpoint.tls {
|
||||
let name = rustls::pki_types::ServerName::try_from(self.endpoint.host.clone())
|
||||
.map_err(|_| DiscoveryError::InvalidUrl("TLS 主机名无效"))?;
|
||||
let connection = rustls::ClientConnection::new(signaling_tls_config()?, name)
|
||||
.map_err(|e| DiscoveryError::Http(e.to_string()))?;
|
||||
Box::new(rustls::StreamOwned::new(connection, socket))
|
||||
} else {
|
||||
Box::new(socket)
|
||||
};
|
||||
|
||||
let body = body.unwrap_or("");
|
||||
let full_path = if self.endpoint.prefix.is_empty() {
|
||||
@@ -101,15 +180,20 @@ impl SignalingClient {
|
||||
} else {
|
||||
format!("{}{}", self.endpoint.prefix, path)
|
||||
};
|
||||
let authorization = if self.endpoint.token.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("Authorization: Bearer {}\r\n", self.endpoint.token)
|
||||
};
|
||||
let request = format!(
|
||||
"{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
|
||||
method, full_path, self.endpoint.authority, body.len(), body
|
||||
"{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n{}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
|
||||
method, full_path, self.endpoint.authority, authorization, body.len(), body
|
||||
);
|
||||
stream.write_all(request.as_bytes())?;
|
||||
stream.flush()?;
|
||||
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response)?;
|
||||
stream.take(8 * 1024 * 1024).read_to_string(&mut response)?;
|
||||
let (headers, raw_body) = response
|
||||
.split_once("\r\n\r\n")
|
||||
.ok_or_else(|| DiscoveryError::Http("信令响应缺少头部分隔符".to_string()))?;
|
||||
@@ -129,10 +213,10 @@ impl SignalingClient {
|
||||
raw_body.trim()
|
||||
)));
|
||||
}
|
||||
if headers
|
||||
.lines()
|
||||
.any(|line| line.to_ascii_lowercase().contains("transfer-encoding: chunked"))
|
||||
{
|
||||
if headers.lines().any(|line| {
|
||||
line.to_ascii_lowercase()
|
||||
.contains("transfer-encoding: chunked")
|
||||
}) {
|
||||
decode_chunked(raw_body)
|
||||
} else {
|
||||
Ok(raw_body.to_string())
|
||||
@@ -141,9 +225,22 @@ impl SignalingClient {
|
||||
}
|
||||
|
||||
fn parse_endpoint(base_url: &str) -> Result<Endpoint, DiscoveryError> {
|
||||
let (base_url, fragment) = base_url.split_once('#').unwrap_or((base_url, ""));
|
||||
let token = fragment
|
||||
.strip_prefix("token=")
|
||||
.map(crate::util::url_decode)
|
||||
.unwrap_or_else(|| Some(String::new()))
|
||||
.ok_or(DiscoveryError::InvalidUrl("信令令牌编码无效"))?;
|
||||
if base_url.bytes().any(|b| b <= 32 || b == 127) || token.bytes().any(|b| b <= 32 || b >= 127) {
|
||||
return Err(DiscoveryError::InvalidUrl("信令地址或令牌包含非法字符"));
|
||||
}
|
||||
let tls = base_url.starts_with("https://");
|
||||
let rest = base_url
|
||||
.strip_prefix("http://")
|
||||
.ok_or(DiscoveryError::InvalidUrl("当前版本仅支持 http://,HTTPS 由平台网络栈处理"))?;
|
||||
.strip_prefix("https://")
|
||||
.or_else(|| base_url.strip_prefix("http://"))
|
||||
.ok_or(DiscoveryError::InvalidUrl(
|
||||
"信令地址必须为 http:// 或 https://",
|
||||
))?;
|
||||
let (authority, path) = match rest.find('/') {
|
||||
Some(index) => (&rest[..index], &rest[index..]),
|
||||
None => (rest, ""),
|
||||
@@ -151,11 +248,19 @@ fn parse_endpoint(base_url: &str) -> Result<Endpoint, DiscoveryError> {
|
||||
if authority.is_empty() {
|
||||
return Err(DiscoveryError::InvalidUrl("缺少主机名"));
|
||||
}
|
||||
let (host, port) = if let Some(inner) = authority.strip_prefix('[').and_then(|v| v.strip_suffix(']')) {
|
||||
let port = authority
|
||||
.rsplit_once(':')
|
||||
.and_then(|(_, value)| value.parse::<u16>().ok())
|
||||
.ok_or(DiscoveryError::InvalidUrl("IPv6 地址缺少合法端口"))?;
|
||||
let default_port = if tls { 443 } else { 80 };
|
||||
let (host, port) = if let Some(rest) = authority.strip_prefix('[') {
|
||||
let (inner, suffix) = rest
|
||||
.split_once(']')
|
||||
.ok_or(DiscoveryError::InvalidUrl("IPv6 地址缺少右括号"))?;
|
||||
let port = if suffix.is_empty() {
|
||||
default_port
|
||||
} else {
|
||||
suffix
|
||||
.strip_prefix(':')
|
||||
.and_then(|v| v.parse::<u16>().ok())
|
||||
.ok_or(DiscoveryError::InvalidUrl("IPv6 端口无效"))?
|
||||
};
|
||||
(inner.to_string(), port)
|
||||
} else if let Some((host, raw_port)) = authority.rsplit_once(':') {
|
||||
let port = raw_port
|
||||
@@ -163,7 +268,7 @@ fn parse_endpoint(base_url: &str) -> Result<Endpoint, DiscoveryError> {
|
||||
.map_err(|_| DiscoveryError::InvalidUrl("端口号不是合法数字"))?;
|
||||
(host.to_string(), port)
|
||||
} else {
|
||||
(authority.to_string(), 80)
|
||||
(authority.to_string(), default_port)
|
||||
};
|
||||
if host.is_empty() {
|
||||
return Err(DiscoveryError::InvalidUrl("主机名为空"));
|
||||
@@ -173,6 +278,8 @@ fn parse_endpoint(base_url: &str) -> Result<Endpoint, DiscoveryError> {
|
||||
authority: authority.to_string(),
|
||||
port,
|
||||
prefix: path.trim_end_matches('/').to_string(),
|
||||
tls,
|
||||
token,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -208,6 +315,48 @@ fn decode_chunked(raw: &str) -> Result<String, DiscoveryError> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_https_credentials_and_ipv6_without_sending_fragment() {
|
||||
let endpoint = parse_endpoint("https://[::1]:8443/api/#token=test%2Dtoken").unwrap();
|
||||
assert!(endpoint.tls);
|
||||
assert_eq!(endpoint.host, "::1");
|
||||
assert_eq!(endpoint.port, 8443);
|
||||
assert_eq!(endpoint.prefix, "/api");
|
||||
assert_eq!(endpoint.token, "test-token");
|
||||
assert_eq!(parse_endpoint("https://example.com").unwrap().port, 443);
|
||||
assert!(parse_endpoint("https://example.com/#token=x%0d%0aInjected").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sends_bearer_header_not_url_secret() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let worker = std::thread::spawn(move || {
|
||||
let (mut socket, _) = listener.accept().unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.unwrap();
|
||||
let mut request = Vec::new();
|
||||
let mut byte = [0];
|
||||
while !request.ends_with(b"\r\n\r\n") {
|
||||
socket.read_exact(&mut byte).unwrap();
|
||||
request.push(byte[0]);
|
||||
}
|
||||
let request = String::from_utf8(request).unwrap();
|
||||
assert!(request.starts_with("GET /list HTTP/1.1\r\n"));
|
||||
assert!(request.contains("Authorization: Bearer private-token\r\n"));
|
||||
assert!(!request.contains("#token="));
|
||||
socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 14\r\nConnection: close\r\n\r\n{\"devices\":[]}").unwrap();
|
||||
});
|
||||
let client = SignalingClient::new(
|
||||
format!("http://{address}#token=private-token"),
|
||||
Duration::from_secs(3),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(client.list().unwrap().is_empty());
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_base_url() {
|
||||
let endpoint = parse_endpoint("http://127.0.0.1:8080/api/").unwrap();
|
||||
@@ -218,6 +367,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn decode_chunked_body() {
|
||||
assert_eq!(decode_chunked("5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n").unwrap(), "hello world");
|
||||
assert_eq!(
|
||||
decode_chunked("5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n").unwrap(),
|
||||
"hello world"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use std::slice;
|
||||
|
||||
use crate::control::{ControlEvent, ControlEventKind, SecureControlChannel};
|
||||
use crate::crypto::{derive_subkey, encrypt, EphemeralKeyPair};
|
||||
use crate::media::{decode_media_packet, encode_media_packet, MediaPacket};
|
||||
use crate::media::{decode_media_packet, MediaPacket};
|
||||
|
||||
/// 输出缓冲区不足。
|
||||
pub const ERR_BUFFER_TOO_SMALL: i32 = -1;
|
||||
@@ -168,7 +168,7 @@ pub unsafe extern "C" fn ttstd_aes_encrypt(
|
||||
copy_out(&cipher, out, capacity)
|
||||
}
|
||||
|
||||
/// 媒体包封装:13 字节头 + payload + 4 字节截断 HMAC。
|
||||
/// 媒体 v2:37 字节认证头 + 12 字节 nonce + 密文 + 16 字节 tag。
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn ttstd_media_encode(
|
||||
pts: u64,
|
||||
@@ -187,18 +187,20 @@ pub unsafe extern "C" fn ttstd_media_encode(
|
||||
Ok(value) => value,
|
||||
Err(code) => return code,
|
||||
};
|
||||
let packet = encode_media_packet(
|
||||
if payload.len() > crate::media::packet::MAX_FRAME_SIZE { return ERR_INVALID_ARGUMENT; }
|
||||
let packet = match crate::media::packet::encode_media_fragment(
|
||||
&MediaPacket {
|
||||
pts,
|
||||
flags,
|
||||
payload: payload.to_vec(),
|
||||
},
|
||||
&key,
|
||||
);
|
||||
0, 0, 1,
|
||||
) { Ok(packet) => packet, Err(_) => return ERR_CRYPTO };
|
||||
copy_out(&packet, out, capacity)
|
||||
}
|
||||
|
||||
/// 媒体包解析与 MAC 校验。成功时把解析结果写到 out_packet(JSON UTF-8)。
|
||||
/// 媒体 v2 AES-GCM 解密和认证。此无状态工具接口不替代网络防重放接收器。
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn ttstd_media_decode(
|
||||
buffer: *const u8,
|
||||
@@ -667,5 +669,5 @@ pub extern "C" fn ttstd_discovery_stop() {
|
||||
/// ABI 版本,便于 Dart 侧校验动态库是否匹配。
|
||||
#[no_mangle]
|
||||
pub extern "C" fn ttstd_core_abi_revision() -> i32 {
|
||||
5
|
||||
6
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod audio;
|
||||
pub mod packet;
|
||||
pub mod receiver;
|
||||
pub mod renderer;
|
||||
pub mod stream;
|
||||
|
||||
|
||||
+163
-57
@@ -1,18 +1,22 @@
|
||||
//! Media v2: authenticated header + nonce + AES-256-GCM payload/tag.
|
||||
use crate::crypto::{decrypt, derive_subkey, encrypt};
|
||||
use std::fmt;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::crypto::hmac_sha256;
|
||||
|
||||
pub const PROTOCOL: &str = "aes-gcm/2";
|
||||
pub const MAGIC: &[u8; 4] = b"TTM2";
|
||||
pub const HEADER_LEN: usize = 37;
|
||||
pub const NONCE_LEN: usize = 12;
|
||||
pub const TAG_LEN: usize = 16;
|
||||
pub const OVERHEAD: usize = HEADER_LEN + NONCE_LEN + TAG_LEN;
|
||||
pub const MAX_FRAME_SIZE: usize = 8 * 1024 * 1024;
|
||||
pub const MAX_FRAGMENTS: u16 = 8192;
|
||||
pub const PACKET_KEY_LABEL: &[u8] = b"lancast/media/packet/v2";
|
||||
pub const FLAG_KEYFRAME: u8 = 0x01;
|
||||
pub const FLAG_AUDIO: u8 = 0x02;
|
||||
pub const FLAG_END: u8 = 0x04;
|
||||
|
||||
/// 音频负载是裸 PCM16(48 kHz 双声道小端),不是 Opus。
|
||||
///
|
||||
/// 主控端目前没有 Opus 解码器,被控端在 realtime 场景直接送 PCM,
|
||||
/// 便于跨平台播放;未置位的历史 Opus 包会被丢弃而不是当 PCM 播成噪音。
|
||||
pub const FLAG_PCM: u8 = 0x80;
|
||||
pub const HEADER_LEN: usize = 13;
|
||||
pub const MAC_LEN: usize = 4;
|
||||
static SEQUENCE: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MediaPacket {
|
||||
@@ -20,88 +24,180 @@ pub struct MediaPacket {
|
||||
pub flags: u8,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MediaError {
|
||||
InvalidMac,
|
||||
LengthMismatch,
|
||||
UnsupportedProtocol,
|
||||
InvalidFragment,
|
||||
Replay,
|
||||
}
|
||||
|
||||
impl fmt::Display for MediaError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidMac => write!(formatter, "媒体包 MAC 校验失败"),
|
||||
Self::LengthMismatch => write!(formatter, "媒体包长度字段与实际负载不一致"),
|
||||
}
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::InvalidMac => "媒体 AES-GCM 认证失败",
|
||||
Self::LengthMismatch => "媒体包长度无效",
|
||||
Self::UnsupportedProtocol => "媒体协议不兼容,需要 aes-gcm/2,拒绝明文降级",
|
||||
Self::InvalidFragment => "媒体分片元数据无效",
|
||||
Self::Replay => "媒体包重复或超出防重放窗口",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for MediaError {}
|
||||
|
||||
pub fn encode_media_packet(packet: &MediaPacket, session_key: &[u8; 32]) -> Vec<u8> {
|
||||
let mut output = Vec::with_capacity(HEADER_LEN + packet.payload.len() + MAC_LEN);
|
||||
output.extend_from_slice(&packet.pts.to_le_bytes());
|
||||
output.push(packet.flags);
|
||||
output.extend_from_slice(&(packet.payload.len() as u32).to_le_bytes());
|
||||
output.extend_from_slice(&packet.payload);
|
||||
let mac = hmac_sha256(session_key, &output[..HEADER_LEN + packet.payload.len()]);
|
||||
output.extend_from_slice(&mac[..MAC_LEN]);
|
||||
output
|
||||
pub(crate) struct Fragment {
|
||||
pub packet: MediaPacket,
|
||||
pub sequence: u64,
|
||||
pub frame_id: u64,
|
||||
pub index: u16,
|
||||
pub count: u16,
|
||||
}
|
||||
|
||||
pub fn decode_media_packet(
|
||||
pub fn encode_media_packet(packet: &MediaPacket, key: &[u8; 32]) -> Vec<u8> {
|
||||
encode_media_fragment(packet, key, 0, 0, 1).expect("valid media packet")
|
||||
}
|
||||
/// 0 chooses a unique frame ID for an unfragmented frame. Process-wide packet
|
||||
/// counters never reset while a key may be live; Android/Rust nonce domains differ.
|
||||
pub fn encode_media_fragment(
|
||||
packet: &MediaPacket,
|
||||
key: &[u8; 32],
|
||||
frame_id: u64,
|
||||
index: u16,
|
||||
count: u16,
|
||||
) -> Result<Vec<u8>, MediaError> {
|
||||
if count == 0
|
||||
|| count > MAX_FRAGMENTS
|
||||
|| index >= count
|
||||
|| (count > 1 && frame_id == 0)
|
||||
|| packet.payload.len() > MAX_FRAME_SIZE
|
||||
{
|
||||
return Err(MediaError::InvalidFragment);
|
||||
}
|
||||
let mut sequence = SEQUENCE.load(Ordering::Relaxed);
|
||||
loop {
|
||||
let next = sequence.checked_add(1).ok_or(MediaError::InvalidFragment)?;
|
||||
match SEQUENCE.compare_exchange_weak(sequence, next, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => break,
|
||||
Err(current) => sequence = current,
|
||||
}
|
||||
}
|
||||
let frame_id = if frame_id == 0 { sequence } else { frame_id };
|
||||
let mut header = Vec::with_capacity(HEADER_LEN);
|
||||
header.extend_from_slice(MAGIC);
|
||||
header.push(packet.flags);
|
||||
header.extend_from_slice(&packet.pts.to_le_bytes());
|
||||
header.extend_from_slice(&sequence.to_le_bytes());
|
||||
header.extend_from_slice(&frame_id.to_le_bytes());
|
||||
header.extend_from_slice(&index.to_le_bytes());
|
||||
header.extend_from_slice(&count.to_le_bytes());
|
||||
header.extend_from_slice(&(packet.payload.len() as u32).to_le_bytes());
|
||||
let mut nonce = [0u8; NONCE_LEN];
|
||||
nonce[..4].copy_from_slice(b"rus2");
|
||||
nonce[4..].copy_from_slice(&sequence.to_le_bytes());
|
||||
let packet_key = derive_subkey(key, PACKET_KEY_LABEL).map_err(|_| MediaError::InvalidMac)?;
|
||||
let encrypted = encrypt(&packet_key, &nonce, &packet.payload, &header)
|
||||
.map_err(|_| MediaError::InvalidMac)?;
|
||||
header.extend_from_slice(&nonce);
|
||||
header.extend_from_slice(&encrypted);
|
||||
Ok(header)
|
||||
}
|
||||
pub(crate) fn decode_fragment(
|
||||
buffer: &[u8],
|
||||
session_key: &[u8; 32],
|
||||
) -> Result<Option<(MediaPacket, usize)>, MediaError> {
|
||||
key: &[u8; 32],
|
||||
) -> Result<Option<(Fragment, usize)>, MediaError> {
|
||||
if buffer.len() < 4 {
|
||||
return Ok(None);
|
||||
}
|
||||
if &buffer[..4] != MAGIC {
|
||||
return Err(MediaError::UnsupportedProtocol);
|
||||
}
|
||||
if buffer.len() < HEADER_LEN {
|
||||
return Ok(None);
|
||||
}
|
||||
let pts = u64::from_le_bytes([
|
||||
buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],
|
||||
]);
|
||||
let flags = buffer[8];
|
||||
let declared = u32::from_le_bytes([buffer[9], buffer[10], buffer[11], buffer[12]]) as usize;
|
||||
let total = HEADER_LEN + declared + MAC_LEN;
|
||||
let pts = u64::from_le_bytes(buffer[5..13].try_into().unwrap());
|
||||
let sequence = u64::from_le_bytes(buffer[13..21].try_into().unwrap());
|
||||
let frame_id = u64::from_le_bytes(buffer[21..29].try_into().unwrap());
|
||||
let index = u16::from_le_bytes(buffer[29..31].try_into().unwrap());
|
||||
let count = u16::from_le_bytes(buffer[31..33].try_into().unwrap());
|
||||
let length = u32::from_le_bytes(buffer[33..37].try_into().unwrap()) as usize;
|
||||
if length > MAX_FRAME_SIZE {
|
||||
return Err(MediaError::LengthMismatch);
|
||||
}
|
||||
if sequence == 0 || frame_id == 0 || count == 0 || count > MAX_FRAGMENTS || index >= count {
|
||||
return Err(MediaError::InvalidFragment);
|
||||
}
|
||||
let total = OVERHEAD + length;
|
||||
if buffer.len() < total {
|
||||
return Ok(None);
|
||||
}
|
||||
let signed_part = &buffer[..HEADER_LEN + declared];
|
||||
let expected = hmac_sha256(session_key, signed_part);
|
||||
if expected[..MAC_LEN] != buffer[HEADER_LEN + declared..total] {
|
||||
let nonce: &[u8; NONCE_LEN] = buffer[HEADER_LEN..HEADER_LEN + NONCE_LEN]
|
||||
.try_into()
|
||||
.unwrap();
|
||||
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)?;
|
||||
Ok(Some((
|
||||
MediaPacket {
|
||||
pts,
|
||||
flags,
|
||||
payload: signed_part[HEADER_LEN..].to_vec(),
|
||||
Fragment {
|
||||
packet: MediaPacket {
|
||||
pts,
|
||||
flags: buffer[4],
|
||||
payload,
|
||||
},
|
||||
sequence,
|
||||
frame_id,
|
||||
index,
|
||||
count,
|
||||
},
|
||||
total,
|
||||
)))
|
||||
}
|
||||
|
||||
/// Stateless FFI/tools codec. Network ingestion uses MediaReceiver for replay
|
||||
/// protection and complete-frame reassembly.
|
||||
pub fn decode_media_packet(
|
||||
buffer: &[u8],
|
||||
key: &[u8; 32],
|
||||
) -> Result<Option<(MediaPacket, usize)>, MediaError> {
|
||||
Ok(decode_fragment(buffer, key)?.map(|(fragment, size)| (fragment.packet, size)))
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn packet_roundtrip_and_mac() {
|
||||
let key = [7u8; 32];
|
||||
fn roundtrip_confidentiality_nonce_and_tamper() {
|
||||
let key = [7; 32];
|
||||
let packet = MediaPacket {
|
||||
pts: 1234,
|
||||
flags: FLAG_KEYFRAME,
|
||||
payload: vec![1, 2, 3, 4],
|
||||
payload: b"private video and audio".to_vec(),
|
||||
};
|
||||
let bytes = encode_media_packet(&packet, &key);
|
||||
let (decoded, consumed) = decode_media_packet(&bytes, &key).unwrap().unwrap();
|
||||
assert_eq!(decoded, packet);
|
||||
assert_eq!(consumed, bytes.len());
|
||||
assert_eq!(decode_media_packet(&bytes, &[8u8; 32]), Err(MediaError::InvalidMac));
|
||||
assert_eq!(
|
||||
decode_media_packet(&bytes, &key).unwrap().unwrap().0,
|
||||
packet
|
||||
);
|
||||
assert!(!bytes
|
||||
.windows(packet.payload.len())
|
||||
.any(|v| v == packet.payload));
|
||||
assert_ne!(bytes, encode_media_packet(&packet, &key));
|
||||
assert_eq!(
|
||||
decode_media_packet(&bytes, &[8; 32]),
|
||||
Err(MediaError::InvalidMac)
|
||||
);
|
||||
for index in [4, 5, 13, 21, 29, 31, 33, 37, 49, bytes.len() - 1] {
|
||||
let mut altered = bytes.clone();
|
||||
altered[index] ^= 1;
|
||||
assert!(!matches!(decode_media_packet(&altered, &key), Ok(Some(_))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_packet_waits() {
|
||||
let key = [1u8; 32];
|
||||
fn rejects_legacy_and_waits_for_incomplete_packet() {
|
||||
let key = [1; 32];
|
||||
let bytes = encode_media_packet(
|
||||
&MediaPacket {
|
||||
pts: 0,
|
||||
@@ -110,6 +206,16 @@ mod tests {
|
||||
},
|
||||
&key,
|
||||
);
|
||||
assert_eq!(decode_media_packet(&bytes[..20], &key).unwrap(), None);
|
||||
assert_eq!(decode_media_packet(&bytes[..20], &key), Ok(None));
|
||||
assert_eq!(
|
||||
decode_media_packet(&[0; 40], &key),
|
||||
Err(MediaError::UnsupportedProtocol)
|
||||
);
|
||||
let mut huge = bytes;
|
||||
huge[33..37].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert_eq!(
|
||||
decode_media_packet(&huge, &key),
|
||||
Err(MediaError::LengthMismatch)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
use super::packet::{decode_fragment, MediaError, MediaPacket, MAX_FRAME_SIZE};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::time::{Duration, Instant};
|
||||
const REPLAY_WINDOW: u64 = 16384;
|
||||
const MAX_PENDING_FRAMES: usize = 8;
|
||||
const MAX_PENDING_BYTES: usize = 16 * 1024 * 1024;
|
||||
const FRAGMENT_FLAGS: u8 = 0x70;
|
||||
struct Assembly {
|
||||
pts: u64,
|
||||
flags: u8,
|
||||
created: Instant,
|
||||
parts: Vec<Option<Vec<u8>>>,
|
||||
bytes: usize,
|
||||
filled: usize,
|
||||
}
|
||||
/// One receiver per active media key/stream, shared by UDP and relay.
|
||||
#[derive(Default)]
|
||||
pub struct MediaReceiver {
|
||||
key: Option<[u8; 32]>,
|
||||
highest: u64,
|
||||
seen: BTreeSet<u64>,
|
||||
frames: BTreeMap<u64, Assembly>,
|
||||
last_completed: u64,
|
||||
}
|
||||
impl MediaReceiver {
|
||||
pub fn receive(
|
||||
&mut self,
|
||||
key: &[u8; 32],
|
||||
data: &[u8],
|
||||
) -> Result<Option<MediaPacket>, MediaError> {
|
||||
if data.len() > 65507 {
|
||||
return Err(MediaError::LengthMismatch);
|
||||
}
|
||||
// Never update replay/session state from unauthenticated metadata.
|
||||
let (fragment, size) = decode_fragment(data, 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);
|
||||
}
|
||||
let seq = fragment.sequence;
|
||||
if self.seen.contains(&seq)
|
||||
|| (self.highest >= REPLAY_WINDOW && seq <= self.highest - REPLAY_WINDOW)
|
||||
{
|
||||
return Err(MediaError::Replay);
|
||||
}
|
||||
self.highest = self.highest.max(seq);
|
||||
self.seen.insert(seq);
|
||||
let cutoff = self.highest.saturating_sub(REPLAY_WINDOW);
|
||||
while self.seen.first().is_some_and(|n| *n <= cutoff) {
|
||||
self.seen.pop_first();
|
||||
}
|
||||
let mut packet = fragment.packet;
|
||||
packet.flags &= !FRAGMENT_FLAGS;
|
||||
if fragment.frame_id <= self.last_completed {
|
||||
return Err(MediaError::Replay);
|
||||
}
|
||||
self.frames.retain(|_, frame| frame.created.elapsed() < Duration::from_secs(2));
|
||||
if fragment.count == 1 {
|
||||
self.last_completed = fragment.frame_id;
|
||||
self.frames.retain(|id, _| *id > self.last_completed);
|
||||
return Ok(Some(packet));
|
||||
}
|
||||
if !self.frames.contains_key(&fragment.frame_id) && self.frames.len() >= MAX_PENDING_FRAMES
|
||||
{
|
||||
self.frames.pop_first();
|
||||
}
|
||||
if self.frames.values().map(|f| f.bytes).sum::<usize>() + packet.payload.len()
|
||||
> MAX_PENDING_BYTES
|
||||
{
|
||||
return Err(MediaError::InvalidFragment);
|
||||
}
|
||||
let frame = self
|
||||
.frames
|
||||
.entry(fragment.frame_id)
|
||||
.or_insert_with(|| Assembly {
|
||||
pts: packet.pts,
|
||||
flags: packet.flags,
|
||||
created: Instant::now(),
|
||||
parts: vec![None; fragment.count as usize],
|
||||
bytes: 0,
|
||||
filled: 0,
|
||||
});
|
||||
if frame.pts != packet.pts
|
||||
|| frame.flags != packet.flags
|
||||
|| frame.parts.len() != fragment.count as usize
|
||||
|| frame.bytes + packet.payload.len() > MAX_FRAME_SIZE
|
||||
{
|
||||
self.frames.remove(&fragment.frame_id);
|
||||
return Err(MediaError::InvalidFragment);
|
||||
}
|
||||
let slot = &mut frame.parts[fragment.index as usize];
|
||||
if slot.is_some() {
|
||||
return Err(MediaError::Replay);
|
||||
}
|
||||
frame.bytes += packet.payload.len();
|
||||
frame.filled += 1;
|
||||
*slot = Some(packet.payload);
|
||||
if frame.filled != frame.parts.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
let frame = self.frames.remove(&fragment.frame_id).unwrap();
|
||||
let mut payload = Vec::with_capacity(frame.bytes);
|
||||
for part in frame.parts {
|
||||
payload.extend_from_slice(&part.unwrap());
|
||||
}
|
||||
self.last_completed = fragment.frame_id;
|
||||
self.frames.retain(|id, _| *id > self.last_completed);
|
||||
Ok(Some(MediaPacket {
|
||||
pts: frame.pts,
|
||||
flags: frame.flags,
|
||||
payload,
|
||||
}))
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::media::packet::{encode_media_fragment, encode_media_packet};
|
||||
fn packet(payload: &[u8]) -> MediaPacket {
|
||||
MediaPacket {
|
||||
pts: 12,
|
||||
flags: 1,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn out_of_order_fragments_replay_and_missing_fragment() {
|
||||
let key = [3; 32];
|
||||
let mut receiver = MediaReceiver::default();
|
||||
let first = encode_media_fragment(&packet(b"abc"), &key, 50, 0, 3).unwrap();
|
||||
let middle = encode_media_fragment(&packet(b"def"), &key, 50, 1, 3).unwrap();
|
||||
let last = encode_media_fragment(&packet(b"ghi"), &key, 50, 2, 3).unwrap();
|
||||
assert_eq!(receiver.receive(&key, &last).unwrap(), None);
|
||||
assert_eq!(receiver.receive(&key, &first).unwrap(), None);
|
||||
assert_eq!(receiver.receive(&key, &first), Err(MediaError::Replay));
|
||||
assert_eq!(
|
||||
receiver.receive(&key, &middle).unwrap().unwrap().payload,
|
||||
b"abcdefghi"
|
||||
);
|
||||
assert_eq!(receiver.receive(&key, &last), Err(MediaError::Replay));
|
||||
}
|
||||
#[test]
|
||||
fn forged_high_sequence_does_not_poison_window_and_session_rekeys() {
|
||||
let key = [4; 32];
|
||||
let mut receiver = MediaReceiver::default();
|
||||
let original = encode_media_packet(&packet(b"secret"), &key);
|
||||
let mut forged = original.clone();
|
||||
forged[13..21].copy_from_slice(&u64::MAX.to_le_bytes());
|
||||
assert!(receiver.receive(&key, &forged).is_err());
|
||||
assert!(receiver.receive(&key, &original).unwrap().is_some());
|
||||
let other_key = [5; 32];
|
||||
let other = encode_media_fragment(&packet(b"new session"), &other_key, 1, 0, 1).unwrap();
|
||||
assert!(receiver.receive(&other_key, &original).is_err());
|
||||
assert!(receiver.receive(&other_key, &other).unwrap().is_some());
|
||||
}
|
||||
#[test]
|
||||
fn trailing_bytes_rejected() {
|
||||
let key = [6; 32];
|
||||
let mut bytes = encode_media_packet(&packet(b"one"), &key);
|
||||
bytes.push(0);
|
||||
assert_eq!(
|
||||
MediaReceiver::default().receive(&key, &bytes),
|
||||
Err(MediaError::LengthMismatch)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn pcm_fragments_are_not_played_until_complete() {
|
||||
let key = [9; 32];
|
||||
let mut receiver = MediaReceiver::default();
|
||||
let packet = |bytes: Vec<u8>| MediaPacket {
|
||||
pts: 100,
|
||||
flags: 0x82,
|
||||
payload: bytes,
|
||||
};
|
||||
let first = encode_media_fragment(&packet(vec![0, 1]), &key, 1, 0, 2).unwrap();
|
||||
let second = encode_media_fragment(&packet(vec![2, 3]), &key, 1, 1, 2).unwrap();
|
||||
assert_eq!(receiver.receive(&key, &second).unwrap(), None);
|
||||
let decoded = receiver.receive(&key, &first).unwrap().unwrap();
|
||||
assert_eq!(decoded.flags, 0x82);
|
||||
assert_eq!(decoded.payload, vec![0, 1, 2, 3]);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 视频访问单元队列。
|
||||
//!
|
||||
//! UDP 接收线程把解出 MAC 的视频包(一个访问单元)推进队列,
|
||||
//! UDP 接收线程将经过 AES-GCM 认证、防重放及分片重组的访问单元推进队列,
|
||||
//! 桌面端原生解码线程(Media Foundation)按序取走并解码成纹理。
|
||||
//! 队列只做搬运与限流,不做解码:解码依赖平台的硬件/系统解码器。
|
||||
|
||||
|
||||
@@ -324,7 +324,11 @@ mod tests {
|
||||
let mut kept = Vec::new();
|
||||
for (to, payload) in guard.drain(..) {
|
||||
if to == device {
|
||||
messages.push(payload);
|
||||
let mut message = JsonValue::object();
|
||||
message.insert("from", payload.get("from").cloned().unwrap_or(JsonValue::Null));
|
||||
message.insert("to", JsonValue::from(device.as_str()));
|
||||
message.insert("payload", payload);
|
||||
messages.push(message);
|
||||
} else {
|
||||
kept.push((to, payload));
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::time::Duration;
|
||||
|
||||
use ttstdconnect_core::control::{ControlEvent, ControlEventKind, SecureControlChannel};
|
||||
use ttstdconnect_core::crypto::{derive_subkey, EphemeralKeyPair};
|
||||
use ttstdconnect_core::media::{encode_media_packet, MediaPacket, FLAG_AUDIO};
|
||||
use ttstdconnect_core::media::{encode_media_packet, MediaPacket, FLAG_AUDIO, FLAG_PCM};
|
||||
use ttstdconnect_core::demo_server;
|
||||
|
||||
const CONTROL_PORT: u16 = 44101;
|
||||
@@ -105,8 +105,8 @@ fn demo_server_handshake_control_and_media_roundtrip() {
|
||||
let audio_packet = encode_media_packet(
|
||||
&MediaPacket {
|
||||
pts: 7,
|
||||
flags: FLAG_AUDIO,
|
||||
payload: vec![9, 8, 7],
|
||||
flags: FLAG_AUDIO | FLAG_PCM,
|
||||
payload: vec![0; 8],
|
||||
},
|
||||
&audio_key,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Run the real receiver against Rust UDP ingestion; accept capture in device UI.
|
||||
Usage: python rust_core/tests/device_media_smoke.py --core PATH --dump FILE
|
||||
Start the Android receiver with host 10.0.2.2 and its normal standby/capture UI.
|
||||
"""
|
||||
import argparse
|
||||
import ctypes as c
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--core', required=True)
|
||||
parser.add_argument('--dump', required=True)
|
||||
parser.add_argument('--seconds', type=int, default=180)
|
||||
parser.add_argument('--tls-fingerprint', default='')
|
||||
args = parser.parse_args()
|
||||
os.environ['TTSTD_DUMP_VIDEO'] = os.path.abspath(args.dump)
|
||||
os.makedirs(os.path.dirname(os.environ['TTSTD_DUMP_VIDEO']), exist_ok=True)
|
||||
with open(args.dump, 'wb'):
|
||||
pass
|
||||
lib = c.CDLL(os.path.abspath(args.core))
|
||||
def bind(name, result, *params):
|
||||
method = getattr(lib,name); method.restype=result; method.argtypes=params; return method
|
||||
ptr, size = c.c_void_p, c.c_size_t
|
||||
start=bind('ttstd_demo_start',c.c_int32,c.c_uint16,c.c_uint16,c.c_uint16)
|
||||
set_tls=bind('ttstd_demo_set_tls_fingerprint',c.c_int32,ptr,size)
|
||||
stop=bind('ttstd_demo_stop',None)
|
||||
status=bind('ttstd_demo_status',c.c_int32,ptr,size)
|
||||
events=bind('ttstd_event_next',c.c_int32,ptr,size)
|
||||
stats=bind('ttstd_video_stats',c.c_int32,ptr,size)
|
||||
send=bind('ttstd_demo_send_control',c.c_int32,c.c_uint16,c.c_uint8,ptr,size)
|
||||
output=c.create_string_buffer(16384)
|
||||
deadline=time.monotonic()+args.seconds
|
||||
seq=0
|
||||
def fetch(method):
|
||||
count=method(output,len(output)); return json.loads(output.raw[:count]) if count>0 else None
|
||||
def control(kind,payload):
|
||||
nonlocal seq
|
||||
seq+=1
|
||||
assert send(seq,kind,payload,len(payload)) == 0
|
||||
def wait(predicate,label):
|
||||
while time.monotonic()<deadline:
|
||||
value=predicate()
|
||||
if value: return value
|
||||
time.sleep(.1)
|
||||
raise AssertionError('timeout: '+label)
|
||||
def next_event():
|
||||
event=fetch(events)
|
||||
if event and event['type']==4:
|
||||
raise AssertionError('view-only peer received clipboard content (redacted)')
|
||||
if event: print('EVENT',json.dumps(event,ensure_ascii=False),flush=True)
|
||||
return event
|
||||
try:
|
||||
fingerprint=args.tls_fingerprint.encode()
|
||||
assert set_tls(fingerprint,len(fingerprint))==0
|
||||
assert start(41001,41000,41002)==0, 'ports already occupied'
|
||||
print('LISTENING: waiting for Android standby on TCP 41001',flush=True)
|
||||
wait(lambda: (s if (s:=fetch(status))['keyEstablished'] else None),'ECDH')
|
||||
print('ECDH established',flush=True)
|
||||
legacy=json.dumps({'mediaProtocol':'legacy','access':'view','clipboardSync':False}).encode()
|
||||
control(9,legacy)
|
||||
time.sleep(.3)
|
||||
control(8,b'\x00')
|
||||
wait(lambda: (e if (e:=next_event()) and e['type']==8 and e['action']==5 else None),'legacy rejection')
|
||||
print('PASS legacy mirror request rejected before capture',flush=True)
|
||||
config=json.dumps({'mediaProtocol':'aes-gcm/2','audioEnabled':True,'bitrateMbps':2,'access':'view','clipboardSync':False}).encode()
|
||||
control(9,config)
|
||||
wait(lambda: (e if (e:=next_event()) and e['type']==10 and json.loads(e['text']).get('mediaProtocol')=='aes-gcm/2' else None),'media negotiation')
|
||||
control(8,b'\x00')
|
||||
print('NEGOTIATED: accept the normal Android mirror/capture dialogs',flush=True)
|
||||
def video_progress():
|
||||
event=next_event()
|
||||
if event and event['type']==8 and event['action']==3 and event['text']=='确认超时':
|
||||
control(8,b'\x00')
|
||||
print('RETRY after confirmation timeout: accept the app dialog',flush=True)
|
||||
value=fetch(stats)
|
||||
return value if value['received']>=5 else None
|
||||
video=wait(video_progress,'encrypted video')
|
||||
print('PASS Android direct UDP AES-GCM video:',json.dumps(video),flush=True)
|
||||
control(8,b'\x01')
|
||||
print('STOP sent; screen capture stopped through protocol',flush=True)
|
||||
finally:
|
||||
stop()
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -20,7 +20,8 @@ fn sample_device() -> DeviceInfo {
|
||||
media_port: 41000,
|
||||
control_port: 41001,
|
||||
fingerprint: "sha256:ab12cd34".into(),
|
||||
capabilities: vec!["h264".into(), "opus".into(), "file".into()],
|
||||
tls_fingerprint: String::new(),
|
||||
capabilities: vec!["h264".into(), "pcm16".into(), "file".into()],
|
||||
model: "Pixel8".into(),
|
||||
resolution: "1920x1080".into(),
|
||||
signaling_url: None,
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"ttstdconnect/signaling/internal/registry"
|
||||
@@ -15,15 +16,21 @@ import (
|
||||
type Handler struct {
|
||||
registry *registry.Registry
|
||||
relay *relay.Relay
|
||||
mu sync.Mutex
|
||||
routes map[string]relayRoute
|
||||
}
|
||||
|
||||
type relayRoute struct {
|
||||
peer string
|
||||
updated time.Time
|
||||
}
|
||||
|
||||
func NewHandler(reg *registry.Registry, relayStore *relay.Relay) http.Handler {
|
||||
return &Handler{registry: reg, relay: relayStore}
|
||||
return &Handler{registry: reg, relay: relayStore, routes: make(map[string]relayRoute)}
|
||||
}
|
||||
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
@@ -104,7 +111,43 @@ func (h *Handler) sendRelay(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
if _, ok := h.registry.Get(request.To); !ok {
|
||||
if request.From == "" || request.From == request.To {
|
||||
writeError(w, 400, fmt.Errorf("发送方或目标无效"))
|
||||
return
|
||||
}
|
||||
var envelope struct {
|
||||
From string `json:"from"`
|
||||
Kind string `json:"kind"`
|
||||
Protocol string `json:"ttstd"`
|
||||
}
|
||||
if err := json.Unmarshal(request.Payload, &envelope); err != nil || envelope.From != request.From || envelope.Protocol != "relay/1" {
|
||||
writeError(w, 400, fmt.Errorf("中继信封身份或版本不匹配"))
|
||||
return
|
||||
}
|
||||
_, targetOnline := h.registry.Get(request.To)
|
||||
now := time.Now()
|
||||
h.mu.Lock()
|
||||
for id, route := range h.routes {
|
||||
if now.Sub(route.updated) > 5*time.Minute {
|
||||
delete(h.routes, id)
|
||||
}
|
||||
}
|
||||
route, known := h.routes[request.To]
|
||||
canReply := known && route.peer == request.From
|
||||
if targetOnline && envelope.Kind == "hs" {
|
||||
if len(h.routes) >= 4096 {
|
||||
h.mu.Unlock()
|
||||
writeError(w, 503, fmt.Errorf("中继会话过多"))
|
||||
return
|
||||
}
|
||||
h.routes[request.From] = relayRoute{peer: request.To, updated: now}
|
||||
}
|
||||
if canReply {
|
||||
route.updated = now
|
||||
h.routes[request.To] = route
|
||||
}
|
||||
h.mu.Unlock()
|
||||
if !targetOnline && !canReply {
|
||||
writeError(w, http.StatusNotFound, fmt.Errorf("目标设备 %s 不在线", request.To))
|
||||
return
|
||||
}
|
||||
@@ -137,7 +180,7 @@ func (h *Handler) watch(w http.ResponseWriter, r *http.Request) {
|
||||
events, unsubscribe := h.registry.Subscribe()
|
||||
defer unsubscribe()
|
||||
|
||||
snapshot := map[string]any{"event": "snapshot", "devices": h.registry.List()}
|
||||
snapshot := map[string]any{"event": "snapshot"}
|
||||
if err := websocket.WriteText(conn, mustJSON(snapshot)); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -157,7 +200,7 @@ func (h *Handler) watch(w http.ResponseWriter, r *http.Request) {
|
||||
for {
|
||||
select {
|
||||
case event := <-events:
|
||||
if err := websocket.WriteText(conn, mustJSON(event)); err != nil {
|
||||
if err := websocket.WriteText(conn, mustJSON(map[string]any{"event": event.Event, "deviceId": event.DeviceID})); err != nil {
|
||||
return
|
||||
}
|
||||
case <-ticker.C:
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestRegisterListHeartbeatAndRelay(t *testing.T) {
|
||||
t.Fatalf("心跳失败: %+v", result)
|
||||
}
|
||||
|
||||
relayPayload := `{"from":"b","to":"a","payload":{"type":"offer"}}`
|
||||
relayPayload := `{"from":"b","to":"a","payload":{"ttstd":"relay/1","kind":"hs","from":"b"}}`
|
||||
if result = postJSON(t, server.URL+"/relay", relayPayload); result["ok"] != true {
|
||||
t.Fatalf("relay 失败: %+v", result)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type quota struct {
|
||||
tokens float64
|
||||
updated time.Time
|
||||
watches int
|
||||
}
|
||||
|
||||
// Secure protects discovery, registration and relay with the same private-network
|
||||
// credential. It is not a per-device identity or multi-tenant authorization system.
|
||||
func Secure(next http.Handler, token string) http.Handler {
|
||||
expected := sha256.Sum256([]byte(token))
|
||||
var mu sync.Mutex
|
||||
clients := make(map[string]*quota)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
now := time.Now()
|
||||
mu.Lock()
|
||||
q := clients[host]
|
||||
if q == nil {
|
||||
for key, old := range clients {
|
||||
if now.Sub(old.updated) > 5*time.Minute && old.watches == 0 {
|
||||
delete(clients, key)
|
||||
}
|
||||
}
|
||||
if len(clients) >= 4096 {
|
||||
mu.Unlock()
|
||||
http.Error(w, "server busy", 503)
|
||||
return
|
||||
}
|
||||
q = "a{tokens: 400, updated: now}
|
||||
clients[host] = q
|
||||
}
|
||||
q.tokens += now.Sub(q.updated).Seconds() * 200
|
||||
if q.tokens > 400 {
|
||||
q.tokens = 400
|
||||
}
|
||||
q.updated = now
|
||||
if q.tokens < 1 {
|
||||
mu.Unlock()
|
||||
w.Header().Set("Retry-After", "1")
|
||||
http.Error(w, "rate limited", 429)
|
||||
return
|
||||
}
|
||||
q.tokens--
|
||||
mu.Unlock()
|
||||
if r.URL.Path == "/healthz" && r.Method == http.MethodGet {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if token != "" {
|
||||
auth := r.Header.Get("Authorization")
|
||||
actual := sha256.Sum256([]byte(strings.TrimPrefix(auth, "Bearer ")))
|
||||
if !strings.HasPrefix(auth, "Bearer ") || subtle.ConstantTimeCompare(actual[:], expected[:]) != 1 {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.URL.Path == "/watch" {
|
||||
mu.Lock()
|
||||
if q.watches >= 4 {
|
||||
mu.Unlock()
|
||||
http.Error(w, "too many watches", 429)
|
||||
return
|
||||
}
|
||||
q.watches++
|
||||
mu.Unlock()
|
||||
defer func() { mu.Lock(); q.watches--; mu.Unlock() }()
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"ttstdconnect/signaling/internal/registry"
|
||||
"ttstdconnect/signaling/internal/relay"
|
||||
)
|
||||
|
||||
func TestAuthenticationProtectsEverySensitiveEndpoint(t *testing.T) {
|
||||
const token = "0123456789abcdef0123456789abcdef"
|
||||
handler := Secure(NewHandler(registry.New(time.Minute), relay.New()), token)
|
||||
for _, path := range []string{"/list", "/watch", "/register", "/heartbeat", "/unregister", "/relay", "/relay/poll?deviceId=a"} {
|
||||
for _, credential := range []string{"", "Bearer wrong"} {
|
||||
request := httptest.NewRequest("GET", path, nil)
|
||||
request.Header.Set("Authorization", credential)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != 401 {
|
||||
t.Fatalf("%s: got %d", path, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
request := httptest.NewRequest("GET", "/list", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != 200 {
|
||||
t.Fatal(response.Code)
|
||||
}
|
||||
health := httptest.NewRecorder()
|
||||
handler.ServeHTTP(health, httptest.NewRequest("GET", "/healthz", nil))
|
||||
if health.Code != 200 {
|
||||
t.Fatal(health.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayRepliesToUnregisteredControllerAndRejectsSpoofedEnvelope(t *testing.T) {
|
||||
handler := NewHandler(registry.New(time.Minute), relay.New())
|
||||
server := httptest.NewServer(handler)
|
||||
defer server.Close()
|
||||
postJSON(t, server.URL+"/register", samplePayload)
|
||||
post := func(body string) int {
|
||||
t.Helper()
|
||||
response, err := http.Post(server.URL+"/relay", "application/json", strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
return response.StatusCode
|
||||
}
|
||||
if code := post(`{"from":"host-1","to":"a","payload":{"ttstd":"relay/1","kind":"hs","from":"other"}}`); code != 400 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"a","to":"host-1","payload":{"ttstd":"relay/1","kind":"hsAck","from":"a"}}`); code != 404 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"host-1","to":"a","payload":{"ttstd":"relay/1","kind":"hs","from":"host-1"}}`); code != 200 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"a","to":"host-1","payload":{"ttstd":"relay/1","kind":"hsAck","from":"a"}}`); code != 200 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"a","to":"host-1","payload":{"ttstd":"relay/1","kind":"frame","from":"a"}}`); code != 200 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimit(t *testing.T) {
|
||||
handler := Secure(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }), "")
|
||||
limited := false
|
||||
for i := 0; i < 1000; i++ {
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, httptest.NewRequest("GET", "/list", nil))
|
||||
if response.Code == 429 {
|
||||
limited = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !limited {
|
||||
t.Fatal("expected rate limit")
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ttstdconnect/signaling/internal/httpapi"
|
||||
@@ -14,12 +16,33 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
token := strings.TrimSpace(os.Getenv("SIGNALING_TOKEN"))
|
||||
if token == "" && os.Getenv("ALLOW_INSECURE_SIGNALING") != "1" {
|
||||
log.Fatal("请设置 SIGNALING_TOKEN;仅受信任内网调试可显式设置 ALLOW_INSECURE_SIGNALING=1")
|
||||
}
|
||||
if token != "" && len(token) < 32 {
|
||||
log.Fatal("SIGNALING_TOKEN 至少需要 32 个字符")
|
||||
}
|
||||
for _, ch := range token {
|
||||
if ch <= 32 || ch >= 127 {
|
||||
log.Fatal("SIGNALING_TOKEN 只能包含无空格的 ASCII 字符")
|
||||
}
|
||||
}
|
||||
reg := registry.New(45 * time.Second)
|
||||
relayStore := relay.New()
|
||||
|
||||
address := os.Getenv("LISTEN_ADDR")
|
||||
if address == "" {
|
||||
address = ":8080"
|
||||
address = "127.0.0.1:8080"
|
||||
if os.Getenv("ALLOW_INSECURE_SIGNALING") == "1" || os.Getenv("TLS_CERT_FILE") != "" {
|
||||
address = ":8080"
|
||||
}
|
||||
}
|
||||
if token != "" && os.Getenv("TLS_CERT_FILE") == "" && os.Getenv("ALLOW_HTTP_SIGNALING") != "1" {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err != nil || (host != "localhost" && (net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback())) {
|
||||
log.Fatal("携带令牌的明文 HTTP 默认只监听回环地址;请配置 TLS,或在受信内网显式设置 ALLOW_HTTP_SIGNALING=1")
|
||||
}
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
@@ -28,7 +51,7 @@ func main() {
|
||||
|
||||
server := &http.Server{
|
||||
Addr: address,
|
||||
Handler: httpapi.NewHandler(reg, relayStore),
|
||||
Handler: httpapi.Secure(httpapi.NewHandler(reg, relayStore), token),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 0,
|
||||
@@ -36,7 +59,17 @@ func main() {
|
||||
}
|
||||
|
||||
log.Printf("TTSTDConnect 信令服务器监听 %s", address)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
cert, key := os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE")
|
||||
if (cert == "") != (key == "") {
|
||||
log.Fatal("TLS_CERT_FILE 和 TLS_KEY_FILE 必须同时配置")
|
||||
}
|
||||
var serveError error
|
||||
if cert != "" {
|
||||
serveError = server.ListenAndServeTLS(cert, key)
|
||||
} else {
|
||||
serveError = server.ListenAndServe()
|
||||
}
|
||||
if err := serveError; err != nil && err != http.ErrServerClosed {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Real Go server + Rust FFI auth/ECDH/encrypted-control smoke test.
|
||||
|
||||
python signaling_server/tests/relay_smoke.py --server PATH --core PATH
|
||||
Uses only Python's standard library; does not require Android or open any UI.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import ctypes as c
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--server', required=True)
|
||||
parser.add_argument('--core', required=True)
|
||||
args = parser.parse_args()
|
||||
with socket.socket() as probe:
|
||||
probe.bind(('127.0.0.1', 0))
|
||||
port = probe.getsockname()[1]
|
||||
token = secrets.token_hex(32)
|
||||
base = f'http://127.0.0.1:{port}'
|
||||
env = dict(os.environ, SIGNALING_TOKEN=token, LISTEN_ADDR=f'127.0.0.1:{port}', TLS_CERT_FILE='', TLS_KEY_FILE='')
|
||||
process = subprocess.Popen([os.path.abspath(args.server)], env=env, stdout=subprocess.DEVNULL,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
lib = None
|
||||
channel = 0
|
||||
def request(path, body=None, authenticated=True):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if authenticated:
|
||||
headers['Authorization'] = f'Bearer {token}'
|
||||
req = urllib.request.Request(base + path, data=data, headers=headers)
|
||||
# Ignore the developer machine's outbound HTTP proxy for loopback tests.
|
||||
with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(req, timeout=3) as response:
|
||||
return json.load(response)
|
||||
try:
|
||||
for _ in range(50):
|
||||
try:
|
||||
request('/healthz', authenticated=False)
|
||||
break
|
||||
except (OSError, urllib.error.URLError):
|
||||
time.sleep(.1)
|
||||
try:
|
||||
request('/list', authenticated=False)
|
||||
raise AssertionError('anonymous access accepted')
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 401
|
||||
request('/register', {'deviceId': 'smoke-receiver', 'name': 'smoke', 'ip': '127.0.0.1',
|
||||
'controlPort': 41001, 'mediaPort': 41000, 'fp': 'test-fingerprint'})
|
||||
lib = c.CDLL(os.path.abspath(args.core))
|
||||
def bind(name, restype, *argtypes):
|
||||
func = getattr(lib, name)
|
||||
func.restype, func.argtypes = restype, argtypes
|
||||
return func
|
||||
ptr, size, i64 = c.c_void_p, c.c_size_t, c.c_int64
|
||||
start = bind('ttstd_relay_start', c.c_int32, ptr, size, ptr, size, ptr, size)
|
||||
status = bind('ttstd_demo_status', c.c_int32, ptr, size)
|
||||
generate = bind('ttstd_ecdh_generate', i64, ptr, size)
|
||||
agree = bind('ttstd_ecdh_agree', c.c_int32, i64, ptr, size, ptr, size)
|
||||
derive = bind('ttstd_derive_subkey', c.c_int32, ptr, size, ptr, size, ptr, size)
|
||||
new_channel = bind('ttstd_control_channel_new', i64, ptr)
|
||||
ping = bind('ttstd_control_encode_ping', c.c_int32, i64, c.c_uint16, c.c_uint64, ptr, size)
|
||||
decode = bind('ttstd_control_decode', c.c_int32, i64, ptr, size, ptr, size)
|
||||
media_encode = bind('ttstd_media_encode', c.c_int32, c.c_uint64, c.c_uint8, ptr, ptr, size, ptr, size)
|
||||
aes_encrypt = bind('ttstd_aes_encrypt', c.c_int32, ptr, ptr, ptr, size, ptr, size, ptr, size)
|
||||
video_stats = bind('ttstd_video_stats', c.c_int32, ptr, size)
|
||||
bind('ttstd_control_channel_free', None, i64)
|
||||
bind('ttstd_relay_stop', None)
|
||||
output = c.create_string_buffer(8192)
|
||||
endpoint, receiver = f'{base}#token={token}'.encode(), b'smoke-receiver'
|
||||
count = start(endpoint, len(endpoint), receiver, len(receiver), output, len(output))
|
||||
assert json.loads(output.raw[:count])['ok']
|
||||
hello = None
|
||||
for _ in range(100):
|
||||
for message in request('/relay/poll?deviceId=smoke-receiver')['messages']:
|
||||
if message['payload']['kind'] == 'hs':
|
||||
hello = message['payload']
|
||||
if hello:
|
||||
break
|
||||
time.sleep(.05)
|
||||
assert hello, 'Rust hello did not reach registered receiver'
|
||||
public = c.create_string_buffer(65)
|
||||
handle = generate(public, 65)
|
||||
assert handle > 0
|
||||
remote = base64.b64decode(hello['pub'])
|
||||
secret = c.create_string_buffer(32)
|
||||
assert agree(handle, remote, len(remote), secret, 32) == 32
|
||||
key = c.create_string_buffer(32)
|
||||
label = b'lancast/control/v1'
|
||||
assert derive(secret, 32, label, len(label), key, 32) == 32
|
||||
channel = new_channel(key)
|
||||
def send(payload):
|
||||
return request('/relay', {'from': 'smoke-receiver', 'to': hello['from'], 'payload': payload})
|
||||
send({'ttstd': 'relay/1', 'kind': 'hsAck', 'from': 'smoke-receiver',
|
||||
'pub': base64.b64encode(public.raw).decode()})
|
||||
for _ in range(100):
|
||||
count = status(output, len(output))
|
||||
if json.loads(output.raw[:count])['keyEstablished']:
|
||||
break
|
||||
time.sleep(.05)
|
||||
else:
|
||||
raise AssertionError('Rust did not establish relay keys')
|
||||
count = ping(channel, 1, 123456, output, len(output))
|
||||
assert count > 0
|
||||
send({'ttstd': 'relay/1', 'kind': 'frame', 'from': 'smoke-receiver',
|
||||
'data': base64.b64encode(output.raw[:count]).decode()})
|
||||
for _ in range(100):
|
||||
for message in request('/relay/poll?deviceId=smoke-receiver')['messages']:
|
||||
payload = message['payload']
|
||||
if payload['kind'] != 'frame':
|
||||
continue
|
||||
frame = base64.b64decode(payload['data'])
|
||||
count = decode(channel, frame, len(frame), output, len(output))
|
||||
if count > 0 and json.loads(output.raw[:count])['kind'] == 'pong':
|
||||
video_key = c.create_string_buffer(32)
|
||||
label = b'lancast/video/v1'
|
||||
assert derive(secret, 32, label, len(label), video_key, 32) == 32
|
||||
sample = b'\x00\x00\x00\x01\x65\x01\x02'
|
||||
count = media_encode(123456, 1, video_key, sample, len(sample), output, len(output))
|
||||
assert count > 0
|
||||
packet = output.raw[:count]
|
||||
nonce, aad = secrets.token_bytes(12), b'relay-media'
|
||||
count = aes_encrypt(video_key, nonce, packet, len(packet), aad, len(aad), output, len(output))
|
||||
assert count > 0
|
||||
encrypted = nonce + output.raw[:count]
|
||||
send({'ttstd': 'relay/1', 'kind': 'media', 'from': 'smoke-receiver',
|
||||
'video': [base64.b64encode(encrypted).decode()], 'audio': []})
|
||||
for _ in range(100):
|
||||
count = video_stats(output, len(output))
|
||||
if json.loads(output.raw[:count])['received'] >= 1:
|
||||
print('PASS: anonymous rejected; authenticated registration, Rust/Go ECDH, encrypted ping/pong and AES-GCM relay media')
|
||||
return
|
||||
time.sleep(.05)
|
||||
raise AssertionError('encrypted media did not reach Rust frame queue')
|
||||
time.sleep(.05)
|
||||
raise AssertionError('encrypted pong did not return to receiver')
|
||||
finally:
|
||||
if lib:
|
||||
lib.ttstd_relay_stop()
|
||||
if channel:
|
||||
lib.ttstd_control_channel_free(channel)
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user