Compare commits
38 Commits
dffee5365d
...
v0.4.16
| Author | SHA1 | Date | |
|---|---|---|---|
| f248deac17 | |||
| 1c5e015285 | |||
| 8b3f5c0216 | |||
| d7a29e035f | |||
| 144b7d1a8e | |||
| c1a4dbbd7a | |||
| 65223dafe4 | |||
| eccd93266e | |||
| f9e25819ee | |||
| 9c16cc1690 | |||
| 2bb6ce63ae | |||
| 4c294d4270 | |||
| 7b18c6a661 | |||
| b2edb3048a | |||
| 13624d9747 | |||
| 6abd932872 | |||
| f62fe8d23b | |||
| ae2c36fa54 | |||
| dec132cf3e | |||
| 22c7d7f22d | |||
| b5d124abe5 | |||
| 0281382c39 | |||
| ae41267221 | |||
| 90800b9a21 | |||
| 32b58d121a | |||
| 99be46acf7 | |||
| 375ae8a956 | |||
| bcadcf0b53 | |||
| 0f0dbaef47 | |||
| bdb822233f | |||
| 3e4d5861aa | |||
| 84643bff5e | |||
| d2669fb2e4 | |||
| 92237ff76f | |||
| 376ffba96e | |||
| a960ad91d8 | |||
| 20ac4dc6c7 | |||
| cb92397300 |
@@ -19,3 +19,5 @@ ios/**/xcuserdata/
|
|||||||
ios/**/*.xcworkspace/xcuserdata/
|
ios/**/*.xcworkspace/xcuserdata/
|
||||||
ios/build/
|
ios/build/
|
||||||
DerivedData/
|
DerivedData/
|
||||||
|
# package.sh 打包产物
|
||||||
|
/dist
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# QFT v0.4.6 implementation status
|
# QFT v0.4.16 implementation status
|
||||||
|
|
||||||
## Windows → Android optical
|
## Windows → Android optical
|
||||||
|
|
||||||
@@ -40,17 +40,31 @@
|
|||||||
- [x] wait for actual IPv4/link route before discovery
|
- [x] wait for actual IPv4/link route before discovery
|
||||||
- [x] UDP QFTDISC2 receiver discovery
|
- [x] UDP QFTDISC2 receiver discovery
|
||||||
- [x] QR endpoint + gateway + directed broadcast + subnet fallback
|
- [x] QR endpoint + gateway + directed broadcast + subnet fallback
|
||||||
|
- [x] dedicated Wi-Fi immediate parallel gateway + actual-subnet probe
|
||||||
- [x] HTTP bound to selected Android Network
|
- [x] HTTP bound to selected Android Network
|
||||||
- [x] local cleartext network security config
|
- [x] local cleartext network security config
|
||||||
- [x] local/private IPv4 + session-token validation
|
- [x] local/private IPv4 + session-token validation
|
||||||
- [x] Parallel v2 init/chunk/finish
|
- [x] Parallel v2 init/chunk/finish
|
||||||
- [x] adaptive 4/8/16 MiB chunks
|
- [x] adaptive 64 KiB–16 MiB chunks, targeting eight flows per file
|
||||||
- [x] up to 8 Android workers per file
|
- [x] up to 8 Android workers per file
|
||||||
- [x] Windows positioned concurrent writes
|
- [x] Windows positioned concurrent writes
|
||||||
- [x] temporary `.qftpart`, final SHA-256 and rename
|
- [x] temporary `.qftpart`, final SHA-256 and rename
|
||||||
|
- [x] accepted sockets return to timeout-bound blocking I/O before file transfer
|
||||||
|
- [x] inline Android file selection + removable, pre-transfer sortable queue
|
||||||
|
- [x] crash-safe drag commit without detaching the active touched view
|
||||||
- [x] loopback UDP + HTTP + out-of-order parallel integration test
|
- [x] loopback UDP + HTTP + out-of-order parallel integration test
|
||||||
- [ ] physical Windows Wi-Fi Direct adapter / driver / firewall matrix
|
- [ ] physical Windows Wi-Fi Direct adapter / driver / firewall matrix
|
||||||
|
|
||||||
|
## Windows → Android local direct
|
||||||
|
|
||||||
|
- [x] direction-specific pairing QR starts automatic local download after scan
|
||||||
|
- [x] HTTP `Range` responses return the exact requested range (`206` + `Content-Range`)
|
||||||
|
- [x] Android parallel Range downloader targets eight workers per file
|
||||||
|
- [x] adaptive 64 KiB–16 MiB chunks
|
||||||
|
- [x] `.qftpart` completion ledger resumes only verified completed ranges
|
||||||
|
- [x] five retries per range, final SHA-256, then save to `Downloads/QFT`
|
||||||
|
- [x] regression test for delayed large download after nonblocking accept
|
||||||
|
|
||||||
## Android compatibility
|
## Android compatibility
|
||||||
|
|
||||||
- [x] minSdk 24 (Android 7.0)
|
- [x] minSdk 24 (Android 7.0)
|
||||||
|
|||||||
@@ -1,13 +1,125 @@
|
|||||||
# QFT · 超速二维码文件传输 v0.4.6
|
# QFT · 超速二维码文件传输 v0.4.16
|
||||||
|
|
||||||
Windows + Android 双向候选版。v0.4 的核心目标不是继续堆“4 码理论吞吐”,而是解决 Android 端实际识别慢的问题:**删除 2×2/4 通道,改成一个大二维码 + 动态 ROI 锁定 + 高频局部解码**。
|
Windows + Android 双向正式版。v0.4 的核心目标不是继续堆“4 码理论吞吐”,而是解决 Android 端实际识别慢的问题:**删除 2×2/4 通道,改成一个大二维码 + 动态 ROI 锁定 + 高频局部解码**。
|
||||||
|
|
||||||
两个方向仍然采用不同链路:
|
v0.4.16 提供两套互不依赖的传输方式:
|
||||||
|
|
||||||
- **Windows → Android:纯光学**。文件数据只经过 Windows 屏幕 → Android 摄像头;Wi‑Fi、蓝牙、局域网和互联网都不参与文件数据传输。
|
- **电脑 → 手机(纯光学)**:文件数据只经过 Windows 屏幕 → Android 摄像头;Wi‑Fi、蓝牙、局域网和互联网都不参与文件数据传输。
|
||||||
- **Android → Windows:扫码本地直连**。Windows 选择保存目录并启动 QFT Direct/LAN 接收服务;Android 扫码、配网、自动发现电脑,然后并行分块上传,不经过外网。
|
- **扫码本地直传(双向)**:Windows 为“手机上传”和“电脑下发”分别生成方向明确的二维码。Android 扫码后连接 QFT 本地网络、通过 UDP/网关/子网探测定位电脑,并按二维码指定方向自动进入选文件上传或接收下载;文件数据不经过外网。
|
||||||
|
|
||||||
> v0.4.6 已完成协议、图像合成解码、ROI、并行上传、UDP 发现、内存预算和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
|
### v0.4.16 直传稳定性与并发策略
|
||||||
|
|
||||||
|
- **双向均使用并行分块**:每个可分块文件以 8 路为目标并发数;分块大小根据文件大小自适应,范围为 **64 KiB–16 MiB**。小于一个最小分块的文件会自然只有一个请求。
|
||||||
|
- **手机 → 电脑**:Android 使用 offset 定位的 Parallel v2 上传;Windows 对每块进行定位写入,重复块与完成请求可安全重试,最终以 SHA-256 校验后原子改名。
|
||||||
|
- **电脑 → 手机**:Windows 支持精确的 HTTP `Range`(`206 Partial Content`);Android 对未完成块创建多个独立 Range 请求,并用 `.qftpart` 与完成位图恢复中断传输。每块最多重试 5 次,完成后校验 SHA-256 再保存至 `Downloads/QFT`。
|
||||||
|
- **连接稳定性**:Windows 监听器保持非阻塞以便及时停止服务,但已连接的文件套接字会切换为带读写超时的阻塞模式,避免 Windows `WSAEWOULDBLOCK (10035)` 造成大文件中途失败。
|
||||||
|
|
||||||
|
> v0.4.16 已完成协议、图像合成解码、ROI、双向并发传输、专用 Wi-Fi 快速发现、队列拖动稳定性和关键 Kotlin 源码测试。当前生成环境没有真实 Windows 显示器、Android 相机或 Wi‑Fi Direct 适配器,因此物理 30/45/60 FPS 和真实扫码配网仍需在你的设备上跑 `VERIFY_WINDOWS_HOST.ps1` 后做最终验收;详见 `TEST_REPORT.md`。
|
||||||
|
|
||||||
|
## v0.4.8:跨平台桌面端 + 电脑 ↔ 电脑互传
|
||||||
|
|
||||||
|
### macOS:请用 QFT超速文件传输.app 启动,不要直接跑裸二进制
|
||||||
|
|
||||||
|
`./package.sh` 在 macOS 上会同时产出 `QFT超速文件传输`(裸二进制)和
|
||||||
|
`QFT超速文件传输.app`,**推荐使用 `.app` 版本**。
|
||||||
|
|
||||||
|
直接运行裸二进制时,AppKit 的部分行为会不稳定——最典型的是点「选择文件」时
|
||||||
|
`+[NSOpenPanel openPanel]` 返回 NULL:
|
||||||
|
|
||||||
|
```
|
||||||
|
panicked at objc2-app-kit/src/generated/NSOpenPanel.rs:
|
||||||
|
unexpected NULL returned from +[NSOpenPanel openPanel]
|
||||||
|
```
|
||||||
|
|
||||||
|
程序侧已经兜住了这个 panic(不会再崩溃,只提示"对话框没有返回结果"),
|
||||||
|
但要彻底避免,用 `.app` 启动即可。
|
||||||
|
|
||||||
|
任何情况下都可以**直接把文件拖进窗口**——拖拽不经过系统文件对话框。
|
||||||
|
|
||||||
|
### Windows 构建报 `os error 5 拒绝访问`
|
||||||
|
|
||||||
|
```
|
||||||
|
error: failed to remove file `...\target\release\qft-desktop.exe`
|
||||||
|
Caused by: 拒绝访问。 (os error 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
**QFT 窗口还开着**,正在运行的 exe 锁住了产物文件。关掉窗口再构建即可。
|
||||||
|
`VERIFY_WINDOWS_HOST.ps1` 会在构建前检测并询问是否结束进程。
|
||||||
|
|
||||||
|
若关掉后仍然报错,通常是 Windows Defender 正在扫描刚生成的 exe,
|
||||||
|
稍等几秒重试;也可以把 `desktop\target` 加入 Defender 排除目录。
|
||||||
|
|
||||||
|
### 防火墙放行(手动)
|
||||||
|
|
||||||
|
|
||||||
|
接收端要监听入站 TCP,Windows 防火墙默认会拦截未授权程序,表现是
|
||||||
|
「对方能解析连接码但连接一直超时」。
|
||||||
|
|
||||||
|
程序在「电脑 ↔ 电脑 → 我要接收」页会**只读检测**防火墙状态,并提供
|
||||||
|
「放行防火墙(需要管理员授权)」按钮——**提权只在你点击时发生**,
|
||||||
|
不会在启动时自动弹 UAC。
|
||||||
|
|
||||||
|
也可以自己加规则。两个必须注意的点:
|
||||||
|
|
||||||
|
1. 二进制已从 `qft-windows.exe` 改名为 `qft-desktop.exe`,**此前给旧名字
|
||||||
|
放行的规则对新程序不生效**。
|
||||||
|
2. **profile 必须是 `Any`**。Windows 对没见过的 Wi-Fi 默认归类为
|
||||||
|
「公用网络」,此时只覆盖 `Private,Domain` 的规则根本不适用——
|
||||||
|
规则建了、`Get-NetFirewallRule` 也显示 Enabled,但连接照样被拦。
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$exe = "<完整路径>\qft-desktop.exe"
|
||||||
|
# 先清掉可能存在的阻止规则:Windows 里 Block 永远优先于 Allow
|
||||||
|
Get-NetFirewallApplicationFilter -Program $exe -ErrorAction SilentlyContinue |
|
||||||
|
Get-NetFirewallRule | Where-Object Action -eq 'Block' | Remove-NetFirewallRule
|
||||||
|
New-NetFirewallRule -DisplayName "QFT Desktop" -Direction Inbound `
|
||||||
|
-Program $exe -Action Allow -Profile Any
|
||||||
|
```
|
||||||
|
|
||||||
|
排查时先看这两列:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
Get-NetConnectionProfile | Format-List Name,NetworkCategory
|
||||||
|
Get-NetFirewallApplicationFilter | Where-Object Program -like "*qft*" |
|
||||||
|
ForEach-Object { $r = $_ | Get-NetFirewallRule
|
||||||
|
[PSCustomObject]@{ 规则=$r.DisplayName; 动作=$r.Action; 配置=$r.Profile } } | Format-Table
|
||||||
|
```
|
||||||
|
|
||||||
|
若 `NetworkCategory` 是 `Public` 而规则的 `配置` 只有 `Domain, Private`,
|
||||||
|
就是这个原因。
|
||||||
|
|
||||||
|
管理员 PowerShell:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
New-NetFirewallRule -DisplayName "QFT Desktop" -Direction Inbound `
|
||||||
|
-Program "<完整路径>\qft-desktop.exe" -Action Allow -Profile Private,Domain
|
||||||
|
```
|
||||||
|
|
||||||
|
或在「允许应用通过 Windows Defender 防火墙」里勾选 `qft-desktop.exe` 的**专用网络**。
|
||||||
|
|
||||||
|
排查顺序:对端 `ping` 不通且 TCP 端口连不上,但 `arp -a` 能看到对方 MAC,
|
||||||
|
基本可以判定是对端主机在丢包(防火墙),而不是网络不通。
|
||||||
|
|
||||||
|
|
||||||
|
桌面端目录从 `windows/` 改名为 `desktop/`,crate 更名 `qft-desktop`,
|
||||||
|
**现已可在 macOS / Linux / Windows 三平台编译运行**。平台差异全部收敛在
|
||||||
|
`desktop/src/platform.rs`(配置目录、下载目录、设备名、Direct AP 能力),
|
||||||
|
其余模块不再出现 `#[cfg(target_os)]`。
|
||||||
|
|
||||||
|
新增两块此前完全缺失的能力:
|
||||||
|
|
||||||
|
- `desktop/src/client.rs` —— 桌面端的**发起侧**。此前桌面只有服务端,
|
||||||
|
`TcpStream::connect` 仅存在于测试中,因此 PC 无法主动连接另一台 PC。
|
||||||
|
- `desktop/src/discovery.rs` —— 局域网节点浏览(UDP 广播 `QFTBROWSE3`)。
|
||||||
|
既有的 `QFTDISC2` 是「已知令牌找机器」,用于手机扫码之后;
|
||||||
|
PC↔PC 没有摄像头,必须先能列出附近有哪些节点。
|
||||||
|
|
||||||
|
配对方式:接收方启动后显示 **6 位配对码**,发送方搜索到对方后输入该码
|
||||||
|
换取会话令牌(`POST /qft/pair`)。6 位约 20 bit 熵,靠严格失败计数兜底——
|
||||||
|
错 5 次即作废整个码,需要重新启动接收。
|
||||||
|
|
||||||
|
已知限制:UDP 广播只覆盖同一广播域,跨网段或开了 AP 隔离的 Wi-Fi
|
||||||
|
搜索不到对方,此时在界面上手动输入对方 IP。
|
||||||
|
|
||||||
## v0.4 光学链路改动
|
## v0.4 光学链路改动
|
||||||
|
|
||||||
@@ -93,7 +205,7 @@ Windows 光传页面已经改成“二维码优先”:
|
|||||||
|
|
||||||
推荐初次真机测试从 **30 FPS** 开始,看 Android 的“新帧/s”,再切 45、60。目标不是 Windows 数字最大,而是 Android **实际新帧/s 最大**。
|
推荐初次真机测试从 **30 FPS** 开始,看 Android 的“新帧/s”,再切 45、60。目标不是 Windows 数字最大,而是 Android **实际新帧/s 最大**。
|
||||||
|
|
||||||
## Android → Windows
|
## 扫码本地直传(Android ↔ Windows)
|
||||||
|
|
||||||
v0.3 的稳定性优化继续保留:
|
v0.3 的稳定性优化继续保留:
|
||||||
|
|
||||||
@@ -104,9 +216,10 @@ v0.3 的稳定性优化继续保留:
|
|||||||
- gateway / endpoint / 当前子网 fallback;
|
- gateway / endpoint / 当前子网 fallback;
|
||||||
- HTTP 请求明确绑定扫码建立的 `Network`;
|
- HTTP 请求明确绑定扫码建立的 `Network`;
|
||||||
- 配网请求在传输页持续持有,仅返回首页时释放;短暂网络波动会自动接入新的 `Network`;
|
- 配网请求在传输页持续持有,仅返回首页时释放;短暂网络波动会自动接入新的 `Network`;
|
||||||
- 上传与下载单文件均最高 8 worker 并行;
|
- 手机上传和电脑下发均以 8 路为目标并发数;
|
||||||
- 4/8/16 MiB 自适应上传块;
|
- 64 KiB–16 MiB 自适应分块;
|
||||||
- 16 MiB 有界 Range 并行下载,完成位图支持掉线/重启后只补缺块;
|
- 电脑下发使用精确 Range 响应,手机以 `.qftpart` + 位图断点续传;
|
||||||
|
- 手机上传使用定位写入和幂等完成确认;
|
||||||
- Windows positioned writes + `.qftpart` + SHA-256 + 最终 rename。
|
- Windows positioned writes + `.qftpart` + SHA-256 + 最终 rename。
|
||||||
|
|
||||||
## Android 版本
|
## Android 版本
|
||||||
@@ -121,7 +234,7 @@ v0.3 的稳定性优化继续保留:
|
|||||||
### Windows
|
### Windows
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cd windows
|
cd desktop
|
||||||
cargo check
|
cargo check
|
||||||
cargo test
|
cargo test
|
||||||
cargo build --release
|
cargo build --release
|
||||||
@@ -143,7 +256,7 @@ APK:
|
|||||||
|
|
||||||
## 一键打包
|
## 一键打包
|
||||||
|
|
||||||
脚本会执行 Windows/桌面端 release 构建、Android 单元测试与可安装 debug APK 构建,随后把二进制、APK、协议说明和 SHA-256 校验文件收集到带时间戳的 `dist/QFT-*` 目录并生成压缩包:
|
脚本执行锁定依赖的 Rust 测试和正式构建,随后把桌面程序、中文说明、协议及 SHA-256 校验收集到带时间戳的 `dist/QFT-正式版-*` 目录。脚本不会安装、下载或调用 Android SDK、Java、Gradle;如果已经在 Windows 上构建好 APK,则会自动将它收集进同一个中文正式包:
|
||||||
|
|
||||||
```bat
|
```bat
|
||||||
package.bat
|
package.bat
|
||||||
@@ -155,7 +268,7 @@ package.bat
|
|||||||
|
|
||||||
## 字体
|
## 字体
|
||||||
|
|
||||||
Windows UI 优先读取 `windows/assets/qft-ui.ttf`,也可用 `QFT_FONT_PATH` 指向你自己的中文 TTF。仓库不附带第三方字体文件。
|
桌面端 UI 优先读取 `desktop/assets/qft-ui.ttf`,也可用 `QFT_FONT_PATH` 指向你自己的中文 TTF。仓库不附带第三方字体文件。
|
||||||
|
|
||||||
## 自动验证
|
## 自动验证
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# QFT 超速文件传输 v0.4.16 正式版
|
||||||
|
|
||||||
|
这是 Windows 与 Android 双端统一版本号的中文正式版。
|
||||||
|
|
||||||
|
## 本版重点
|
||||||
|
|
||||||
|
- Windows 扫码直传默认保持普通并排布局,专注二维码模式改为用户手动进入。
|
||||||
|
- 优化直传控制、防火墙、二维码、连接状态区域布局,减少无效留白。
|
||||||
|
- Windows 自动创建 QFT 专用 Wi-Fi Direct 网络,二维码不再强制携带电脑既有网卡地址。
|
||||||
|
- Android 连接专用 Wi-Fi 后立即并行探测实际网关与当前子网,缩短“搜索电脑”时间。
|
||||||
|
- Windows 已确认防火墙规则后复用检测结果,并移除专用网络启动后的固定等待。
|
||||||
|
- Android 文件选择直接打开系统文件选择器,支持队列删除和传输前拖动排序。
|
||||||
|
- Android 拖动采用松手后一次性提交顺序,修复部分厂商系统点击拖动闪退。
|
||||||
|
- PC 接收完成后不再残留“预计剩余 <1 秒”,改为显示最终平均速度。
|
||||||
|
|
||||||
|
## 版本信息
|
||||||
|
|
||||||
|
- Windows 桌面端:`0.4.16`
|
||||||
|
- Android 端:`0.4.16`(versionCode 23)
|
||||||
|
- 最低 Android 版本:Android 7.0(API 24)
|
||||||
|
- Windows:Windows 10/11 x64,使用 QFT Direct 时需要支持 Wi-Fi Direct 的无线网卡
|
||||||
|
|
||||||
|
## 中文封版打包
|
||||||
|
|
||||||
|
- Windows:运行 `package.bat`。
|
||||||
|
- macOS/Linux:运行 `./package.sh`。
|
||||||
|
- 打包脚本会执行 Rust 锁定依赖测试与正式构建,生成中文文件名、中文说明和 SHA-256 校验文件。
|
||||||
|
- 脚本不会安装、下载或调用 Android SDK/Gradle;如果 Windows 上已经生成 APK,会自动收集到同一个正式包中。
|
||||||
|
|
||||||
|
## 验证状态
|
||||||
|
|
||||||
|
- Rust Windows 目标 `cargo check` 通过。
|
||||||
|
- Rust 桌面端 71 项自动测试通过。
|
||||||
|
- Android 配对协议、并行传输及兼容性静态检查通过。
|
||||||
|
- Windows Wi-Fi Direct 与 Android 相机属于硬件链路,最终安装包仍应在目标 Windows 电脑和实际 Android 手机上完成一次扫码传输验收。
|
||||||
+11
-9
@@ -1,12 +1,12 @@
|
|||||||
# QFT v0.4.6 test report
|
# QFT v0.4.16 test report
|
||||||
|
|
||||||
Date: 2026-08-10
|
Date: 2026-08-12
|
||||||
|
|
||||||
This report separates **tests actually executed in the current environment** from **physical hardware acceptance that cannot be simulated here**.
|
This report separates **tests actually executed in the current environment** from **physical hardware acceptance that cannot be simulated here**.
|
||||||
|
|
||||||
## What this RC changes
|
## What this release changes
|
||||||
|
|
||||||
The v0.4.6 optical path is deliberately simpler than v0.3:
|
The v0.4.16 optical path is deliberately simpler than v0.3:
|
||||||
|
|
||||||
- 2×2 / 4-channel QR removed;
|
- 2×2 / 4-channel QR removed;
|
||||||
- one large QR only;
|
- one large QR only;
|
||||||
@@ -21,6 +21,8 @@ The v0.4.6 optical path is deliberately simpler than v0.3:
|
|||||||
- Windows draggable split pane / focus-QR mode.
|
- Windows draggable split pane / focus-QR mode.
|
||||||
|
|
||||||
Android→Windows QFTPAIR2/discovery/parallel upload remains and is regression-tested.
|
Android→Windows QFTPAIR2/discovery/parallel upload remains and is regression-tested.
|
||||||
|
The release also adds immediate gateway/subnet probing after dedicated Wi-Fi association,
|
||||||
|
crash-safe Android queue reordering, and a completed PC receive state without stale ETA text.
|
||||||
|
|
||||||
## Executed and passed
|
## Executed and passed
|
||||||
|
|
||||||
@@ -152,7 +154,7 @@ The guard models the Windows single-QR 1024×1024 RGBA pre-render queue:
|
|||||||
|
|
||||||
This is a design-budget check, not an OS-enforced RSS hard cap. GPU/runtime allocators can add platform-specific memory.
|
This is a design-budget check, not an OS-enforced RSS hard cap. GPU/runtime allocators can add platform-specific memory.
|
||||||
|
|
||||||
## Important implementation decisions validated during v0.4.6
|
## Important implementation decisions validated during v0.4.16
|
||||||
|
|
||||||
### QFT2 uses Result.text, not ZXing rawBytes
|
### QFT2 uses Result.text, not ZXing rawBytes
|
||||||
|
|
||||||
@@ -160,7 +162,7 @@ The active path is Base45 text. Android reconstructs the QFT binary frame from `
|
|||||||
|
|
||||||
### Duplicate camera hits are not duplicate assembler work
|
### Duplicate camera hits are not duplicate assembler work
|
||||||
|
|
||||||
At 45/60 display FPS, a camera can observe the same displayed QR in multiple exposures. v0.4.6 still counts every successful decode in diagnostics, but only a changed QFT2 text fingerprint is delivered to `SessionAssembler`.
|
At 45/60 display FPS, a camera can observe the same displayed QR in multiple exposures. v0.4.16 still counts every successful decode in diagnostics, but only a changed QFT2 text fingerprint is delivered to `SessionAssembler`.
|
||||||
|
|
||||||
### AF/AE does not run on a fixed periodic timer
|
### AF/AE does not run on a fixed periodic timer
|
||||||
|
|
||||||
@@ -168,16 +170,16 @@ The scanner performs initial focus/metering, then re-meters after first lock or
|
|||||||
|
|
||||||
## Not executable in this environment
|
## Not executable in this environment
|
||||||
|
|
||||||
The current generation environment does not contain the Windows MSVC Rust toolchain, Android SDK, a physical Android camera, a Windows display or a Windows Wi-Fi Direct adapter. Therefore the following are **not claimed as passed here**:
|
The current generation environment does not contain the Windows MSVC Rust toolchain, Android SDK, a physical Android camera, a Windows display or a Windows Wi-Fi Direct adapter. The Windows GNU target `cargo check`, native desktop release build and 71 Rust tests passed, but the following are **not claimed as passed here**:
|
||||||
|
|
||||||
1. Windows `cargo check/test/build --release` for v0.4.6.
|
1. Linking and running the final Windows `.exe` on a real Windows host.
|
||||||
2. Android Gradle `:app:testDebugUnitTest :app:assembleDebug` against the real Android SDK.
|
2. Android Gradle `:app:testDebugUnitTest :app:assembleDebug` against the real Android SDK.
|
||||||
3. Actual 30/45/60 displayed FPS → CameraX/ZXing effective new-frame throughput.
|
3. Actual 30/45/60 displayed FPS → CameraX/ZXing effective new-frame throughput.
|
||||||
4. Lock acquisition/reacquisition timing on Android 7 and different phone camera pipelines.
|
4. Lock acquisition/reacquisition timing on Android 7 and different phone camera pipelines.
|
||||||
5. PreviewView overlay mapping on every OEM sensor/crop/rotation combination.
|
5. PreviewView overlay mapping on every OEM sensor/crop/rotation combination.
|
||||||
6. Real Windows QFT Direct adapter / driver / firewall behavior.
|
6. Real Windows QFT Direct adapter / driver / firewall behavior.
|
||||||
|
|
||||||
The package remains an **RC** until those physical checks pass.
|
The source is sealed as **v0.4.16**. The Windows executable and Android APK still require the physical acceptance below before public binary distribution.
|
||||||
|
|
||||||
## Required physical acceptance
|
## Required physical acceptance
|
||||||
|
|
||||||
|
|||||||
+9
-3
@@ -1,5 +1,11 @@
|
|||||||
QFT v0.4.6 test results
|
QFT v0.4.16 test results
|
||||||
UTC 2026-08-10T08:45:56Z
|
Updated 2026-08-12 Asia/Shanghai
|
||||||
|
|
||||||
|
== v0.4.16 release increment ==
|
||||||
|
PASS Windows GNU target cargo check
|
||||||
|
PASS native desktop cargo test: 71 passed, 0 failed
|
||||||
|
PASS native desktop cargo build --release --locked
|
||||||
|
PASS Chinese release package generation with SHA-256 manifest
|
||||||
|
|
||||||
== protocol_selftest.py ==
|
== protocol_selftest.py ==
|
||||||
PASS QFT2/Base45 single-QR: 1200123 bytes, 2667 chunks, 22% frame loss, recovered in 6 rounds; QR-L v15 vs legacy Base64 v18, 12px/module@1024, text=722 chars, theoretical payload=26.4 KiB/s
|
PASS QFT2/Base45 single-QR: 1200123 bytes, 2667 chunks, 22% frame loss, recovered in 6 rounds; QR-L v15 vs legacy Base64 v18, 12px/module@1024, text=722 chars, theoretical payload=26.4 KiB/s
|
||||||
@@ -16,7 +22,7 @@ PASS loopback Parallel v2 integration: UDP discovery + HTTP auth + 6 out-of-orde
|
|||||||
== memory_budget_selftest.py ==
|
== memory_budget_selftest.py ==
|
||||||
PASS memory budget: single-QR cache=192 frames/768.0 MiB + 96 MiB transient allowance < 1100 MiB
|
PASS memory budget: single-QR cache=192 frames/768.0 MiB + 96 MiB transient allowance < 1100 MiB
|
||||||
== android_compat_selftest.py ==
|
== android_compat_selftest.py ==
|
||||||
PASS Android static guards: API24+, 640x480 single-QR ROI, reusable luma buffer, QFT2/Base45 text parse, dynamic lock/refocus, Camera2 FPS request, legacy/new Wi-Fi compatibility
|
PASS Android static guards: API24+, fast-pair/subnet discovery, crash-safe sortable upload queue, QFT2/Base45, dynamic lock/refocus, legacy/new Wi-Fi compatibility
|
||||||
== single_channel_guard_selftest.py ==
|
== single_channel_guard_selftest.py ==
|
||||||
PASS single-channel guard: one large QFT2/Base45 QR, 450B chunks, no 2x2/4-lane path, Android locked-ROI text decode only
|
PASS single-channel guard: one large QFT2/Base45 QR, 450B chunks, no 2x2/4-lane path, Android locked-ROI text decode only
|
||||||
== kotlin_host_smoke.py ==
|
== kotlin_host_smoke.py ==
|
||||||
|
|||||||
+23
-4
@@ -1,7 +1,7 @@
|
|||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
|
||||||
Write-Host "== QFT v0.4.6 Windows host verification ==" -ForegroundColor Cyan
|
Write-Host "== QFT v0.4.16 Windows host verification ==" -ForegroundColor Cyan
|
||||||
|
|
||||||
if (Get-Command python -ErrorAction SilentlyContinue) {
|
if (Get-Command python -ErrorAction SilentlyContinue) {
|
||||||
Write-Host "[1/4] Core protocol/selftests"
|
Write-Host "[1/4] Core protocol/selftests"
|
||||||
@@ -14,8 +14,27 @@ if (Get-Command python -ErrorAction SilentlyContinue) {
|
|||||||
Write-Warning "python not found; skipping repository Python selftests"
|
Write-Warning "python not found; skipping repository Python selftests"
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host "[2/4] Windows Rust compile/test/release"
|
Write-Host "[2/4] Desktop Rust compile/test/release"
|
||||||
Push-Location "$Root\windows"
|
|
||||||
|
# 正在运行的 qft-desktop.exe 会锁住产物文件,cargo 只会抛出
|
||||||
|
# "failed to remove file ... 拒绝访问 (os error 5)" 这种看不出原因的错误。
|
||||||
|
# 这里提前识别并说清楚,而不是让用户去猜。
|
||||||
|
$Running = Get-Process -Name 'qft-desktop' -ErrorAction SilentlyContinue
|
||||||
|
if ($Running) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Warning "检测到 qft-desktop.exe 正在运行(PID: $($Running.Id -join ', '))。"
|
||||||
|
Write-Warning "它会锁住 target\release\qft-desktop.exe,导致构建报 'os error 5 拒绝访问'。"
|
||||||
|
$Answer = Read-Host "是否结束这些进程后继续构建?(y/N)"
|
||||||
|
if ($Answer -eq 'y' -or $Answer -eq 'Y') {
|
||||||
|
$Running | Stop-Process -Force
|
||||||
|
Start-Sleep -Milliseconds 500
|
||||||
|
Write-Host "已结束,继续构建。"
|
||||||
|
} else {
|
||||||
|
throw "请先关闭 QFT 窗口再重新运行本脚本"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Push-Location "$Root\desktop"
|
||||||
try {
|
try {
|
||||||
& cargo check
|
& cargo check
|
||||||
if ($LASTEXITCODE -ne 0) { throw "cargo check failed" }
|
if ($LASTEXITCODE -ne 0) { throw "cargo check failed" }
|
||||||
@@ -37,7 +56,7 @@ try {
|
|||||||
} finally { Pop-Location }
|
} finally { Pop-Location }
|
||||||
|
|
||||||
Write-Host "[4/4] Artifact locations" -ForegroundColor Cyan
|
Write-Host "[4/4] Artifact locations" -ForegroundColor Cyan
|
||||||
Write-Host "Windows EXE: $Root\windows\target\release\qft-windows.exe"
|
Write-Host "Windows EXE: $Root\desktop\target\release\qft-desktop.exe"
|
||||||
Write-Host "Android APK: $Root\android\app\build\outputs\apk\debug\app-debug.apk"
|
Write-Host "Android APK: $Root\android\app\build\outputs\apk\debug\app-debug.apk"
|
||||||
Write-Host "`nHOST BUILD VERIFICATION PASSED" -ForegroundColor Green
|
Write-Host "`nHOST BUILD VERIFICATION PASSED" -ForegroundColor Green
|
||||||
Write-Host "Next: perform the physical display/camera and Wi-Fi Direct acceptance matrix in TEST_REPORT.md."
|
Write-Host "Next: perform the physical display/camera and Wi-Fi Direct acceptance matrix in TEST_REPORT.md."
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ android {
|
|||||||
applicationId = "com.qft.optical"
|
applicationId = "com.qft.optical"
|
||||||
minSdk = 24
|
minSdk = 24
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 18
|
versionCode = 23
|
||||||
versionName = "0.4.6"
|
versionName = "0.4.16"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
@@ -36,6 +36,10 @@ android {
|
|||||||
kotlinOptions {
|
kotlinOptions {
|
||||||
jvmTarget = "17"
|
jvmTarget = "17"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
buildConfig = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||||
|
<!-- WifiLock 需要:传输期间阻止 Wi-Fi 进入省电休眠 -->
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="32" />
|
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="32" />
|
||||||
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
|
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import java.io.OutputStream
|
|||||||
import java.io.RandomAccessFile
|
import java.io.RandomAccessFile
|
||||||
import java.net.HttpURLConnection
|
import java.net.HttpURLConnection
|
||||||
import java.net.URL
|
import java.net.URL
|
||||||
|
import java.nio.ByteBuffer
|
||||||
import java.security.MessageDigest
|
import java.security.MessageDigest
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.atomic.AtomicInteger
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
@@ -29,16 +30,108 @@ object DownloadClient {
|
|||||||
private const val TAG = "QftDownload"
|
private const val TAG = "QftDownload"
|
||||||
private const val BUFFER_SIZE = 1024 * 1024
|
private const val BUFFER_SIZE = 1024 * 1024
|
||||||
private const val SERIAL_ATTEMPTS = 3
|
private const val SERIAL_ATTEMPTS = 3
|
||||||
private const val RANGE_ATTEMPTS = 10
|
// Kept only for the old sequential compatibility path below. New direct
|
||||||
|
// sessions always use the concurrent Range downloader.
|
||||||
private const val PARALLEL_MIN_FILE_SIZE = 32L * 1024L * 1024L
|
private const val PARALLEL_MIN_FILE_SIZE = 32L * 1024L * 1024L
|
||||||
private const val PARALLEL_CHUNK_SIZE = 16L * 1024L * 1024L
|
private const val PARALLEL_CHUNK_SIZE = 16L * 1024L * 1024L
|
||||||
private const val MAX_WORKERS = 8
|
private const val MAX_WORKERS = 8
|
||||||
|
private const val RANGE_WORKERS = 8
|
||||||
|
private const val RANGE_ATTEMPTS = 5
|
||||||
|
private const val MIN_RANGE_CHUNK = 64L * 1024L
|
||||||
|
private const val MAX_RANGE_CHUNK = 16L * 1024L * 1024L
|
||||||
/** 整份重下的轮数。仅在 SHA-256 不匹配(缓存已损坏)时才会用到第二轮。 */
|
/** 整份重下的轮数。仅在 SHA-256 不匹配(缓存已损坏)时才会用到第二轮。 */
|
||||||
private const val VERIFY_ROUNDS = 2
|
private const val VERIFY_ROUNDS = 2
|
||||||
|
|
||||||
/** 落盘阶段的失败与「下载失败」是两回事,用独立异常类型区分。 */
|
/** 落盘阶段的失败与「下载失败」是两回事,用独立异常类型区分。 */
|
||||||
class SaveFailure(message: String, cause: Throwable?) : Exception(message, cause)
|
class SaveFailure(message: String, cause: Throwable?) : Exception(message, cause)
|
||||||
|
|
||||||
|
/** Persistent received-range map. The data file is preallocated, so its
|
||||||
|
* length is not used as a completion signal; only an atomically replaced
|
||||||
|
* map entry marks a range safe to resume. */
|
||||||
|
private class ChunkLedger private constructor(
|
||||||
|
private val partial: File,
|
||||||
|
private val map: File,
|
||||||
|
private val size: Long,
|
||||||
|
val chunkSize: Long,
|
||||||
|
val totalChunks: Int,
|
||||||
|
private val completed: BooleanArray,
|
||||||
|
) {
|
||||||
|
private val lock = Any()
|
||||||
|
|
||||||
|
fun isComplete(index: Int): Boolean = synchronized(lock) { completed[index] }
|
||||||
|
|
||||||
|
fun allComplete(): Boolean = synchronized(lock) { completed.all { it } }
|
||||||
|
|
||||||
|
fun bytesComplete(): Long = synchronized(lock) {
|
||||||
|
completed.indices.sumOf { index -> if (completed[index]) chunkLength(index) else 0L }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun chunkOffset(index: Int): Long = index.toLong() * chunkSize
|
||||||
|
|
||||||
|
fun chunkLength(index: Int): Long = minOf(chunkSize, size - chunkOffset(index))
|
||||||
|
|
||||||
|
fun markComplete(index: Int) = synchronized(lock) {
|
||||||
|
if (!completed[index]) {
|
||||||
|
completed[index] = true
|
||||||
|
persistLocked()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun discard() = synchronized(lock) {
|
||||||
|
partial.delete()
|
||||||
|
map.delete()
|
||||||
|
File("${map.path}.tmp").delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun persistLocked() {
|
||||||
|
val temp = File("${map.path}.tmp")
|
||||||
|
temp.bufferedWriter().use { writer ->
|
||||||
|
writer.appendLine("$size:$chunkSize:$totalChunks")
|
||||||
|
writer.write(buildString(totalChunks) {
|
||||||
|
completed.forEach { append(if (it) '1' else '0') }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (map.exists()) map.delete()
|
||||||
|
if (!temp.renameTo(map)) {
|
||||||
|
temp.copyTo(map, overwrite = true)
|
||||||
|
temp.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun open(partial: File, size: Long, chunkSize: Long): ChunkLedger {
|
||||||
|
val totalLong = if (size == 0L) 0L else (size + chunkSize - 1L) / chunkSize
|
||||||
|
require(totalLong <= Int.MAX_VALUE) { "文件分块数过大" }
|
||||||
|
val total = totalLong.toInt()
|
||||||
|
val map = File("${partial.path}.map")
|
||||||
|
val restored = runCatching {
|
||||||
|
val pieces = map.readText().split('\n', limit = 2)
|
||||||
|
val header = pieces.firstOrNull()?.split(':') ?: emptyList()
|
||||||
|
val bits = pieces.getOrNull(1).orEmpty()
|
||||||
|
if (
|
||||||
|
partial.length() == size && header.size == 3 &&
|
||||||
|
header[0].toLong() == size && header[1].toLong() == chunkSize &&
|
||||||
|
header[2].toInt() == total && bits.length >= total
|
||||||
|
) {
|
||||||
|
BooleanArray(total) { bits[it] == '1' }
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}.getOrNull()
|
||||||
|
val ledger = ChunkLedger(partial, map, size, chunkSize, total, restored ?: BooleanArray(total))
|
||||||
|
if (restored == null) {
|
||||||
|
partial.parentFile?.let { if (!it.exists()) it.mkdirs() }
|
||||||
|
RandomAccessFile(partial, "rw").use { file ->
|
||||||
|
file.setLength(0L)
|
||||||
|
file.setLength(size)
|
||||||
|
}
|
||||||
|
ledger.persistLocked()
|
||||||
|
}
|
||||||
|
return ledger
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun download(
|
fun download(
|
||||||
context: Context,
|
context: Context,
|
||||||
resolver: ContentResolver,
|
resolver: ContentResolver,
|
||||||
@@ -59,10 +152,7 @@ object DownloadClient {
|
|||||||
val expectedSha = requireNotNull(pairing.sha256)
|
val expectedSha = requireNotNull(pairing.sha256)
|
||||||
val partial = partialFile(context, pairing.session)
|
val partial = partialFile(context, pairing.session)
|
||||||
partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") }
|
partial.parentFile?.let { if (!it.exists() && !it.mkdirs()) error("无法创建接收缓存目录") }
|
||||||
if (partial.length() > expectedSize) {
|
if (partial.length() > expectedSize) discardTransferState(partial)
|
||||||
partial.delete()
|
|
||||||
completionMapFile(partial).delete()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 落盘时缓存文件与目标文件同时存在,需要约 2 倍空间。
|
// 落盘时缓存文件与目标文件同时存在,需要约 2 倍空间。
|
||||||
// 不预检的话,这里会在下载 100% 之后才失败,用户看到的是「快结束时失败」。
|
// 不预检的话,这里会在下载 100% 之后才失败,用户看到的是「快结束时失败」。
|
||||||
@@ -83,15 +173,13 @@ object DownloadClient {
|
|||||||
// 这一步失败与网络无关,重下多少次都没用,直接如实报错
|
// 这一步失败与网络无关,重下多少次都没用,直接如实报错
|
||||||
throw SaveFailure("文件已完整收到,但保存到 Downloads/QFT 失败:${failureDetail(e)}", e)
|
throw SaveFailure("文件已完整收到,但保存到 Downloads/QFT 失败:${failureDetail(e)}", e)
|
||||||
}
|
}
|
||||||
partial.delete()
|
discardTransferState(partial)
|
||||||
completionMapFile(partial).delete()
|
|
||||||
Log.i(TAG, "completed size=$expectedSize")
|
Log.i(TAG, "completed size=$expectedSize")
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
|
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
|
||||||
partial.delete()
|
discardTransferState(partial)
|
||||||
completionMapFile(partial).delete()
|
|
||||||
if (round + 1 >= VERIFY_ROUNDS) {
|
if (round + 1 >= VERIFY_ROUNDS) {
|
||||||
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
|
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
|
||||||
}
|
}
|
||||||
@@ -101,7 +189,8 @@ object DownloadClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 传输阶段:断点续传 + 有限重试。只有这一段的失败才算「下载失败」。 */
|
/** 传输阶段:断点续传 + 有限重试。只有这一段的失败才算「下载失败」。 */
|
||||||
private fun receiveUntilComplete(
|
@Suppress("unused")
|
||||||
|
private fun receiveSequentialCompatibility(
|
||||||
networkProvider: () -> Network?,
|
networkProvider: () -> Network?,
|
||||||
baseUrl: String,
|
baseUrl: String,
|
||||||
pairing: PairingPayload,
|
pairing: PairingPayload,
|
||||||
@@ -446,6 +535,189 @@ object DownloadClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 100%。 */
|
/** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 100%。 */
|
||||||
|
private fun receiveUntilComplete(
|
||||||
|
networkProvider: () -> Network?,
|
||||||
|
baseUrl: String,
|
||||||
|
pairing: PairingPayload,
|
||||||
|
deviceName: String,
|
||||||
|
partial: File,
|
||||||
|
expectedSize: Long,
|
||||||
|
abortReason: () -> String?,
|
||||||
|
onProgress: (received: Long, total: Long) -> Unit,
|
||||||
|
) {
|
||||||
|
val ledger = ChunkLedger.open(partial, expectedSize, desiredRangeChunkSize(expectedSize))
|
||||||
|
val initial = ledger.bytesComplete()
|
||||||
|
onProgress(initial, expectedSize)
|
||||||
|
if (ledger.allComplete()) return
|
||||||
|
|
||||||
|
val workers = ledger.totalChunks.coerceAtMost(RANGE_WORKERS).coerceAtLeast(1)
|
||||||
|
Log.i(TAG, "parallel start: chunks=${ledger.totalChunks}, workers=$workers, completed=$initial/$expectedSize")
|
||||||
|
val pool = Executors.newFixedThreadPool(workers)
|
||||||
|
val next = AtomicInteger(0)
|
||||||
|
val futures = (0 until workers).map {
|
||||||
|
pool.submit {
|
||||||
|
while (!Thread.currentThread().isInterrupted) {
|
||||||
|
abortReason()?.let { error(it) }
|
||||||
|
val index = next.getAndIncrement()
|
||||||
|
if (index >= ledger.totalChunks) break
|
||||||
|
if (ledger.isComplete(index)) continue
|
||||||
|
receiveRangeWithRetry(
|
||||||
|
networkProvider,
|
||||||
|
baseUrl,
|
||||||
|
pairing,
|
||||||
|
deviceName,
|
||||||
|
partial,
|
||||||
|
expectedSize,
|
||||||
|
ledger,
|
||||||
|
index,
|
||||||
|
abortReason,
|
||||||
|
)
|
||||||
|
onProgress(ledger.bytesComplete(), expectedSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
futures.forEach { future -> future.get() }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
futures.forEach { it.cancel(true) }
|
||||||
|
throw (e.cause ?: e)
|
||||||
|
} finally {
|
||||||
|
pool.shutdownNow()
|
||||||
|
}
|
||||||
|
// Flushing every parallel range serializes the workers on Android's
|
||||||
|
// storage barrier and can make Wi-Fi look much slower than it is. One
|
||||||
|
// barrier after all ranges preserves the completed-file durability;
|
||||||
|
// SHA-256 still rejects and re-downloads an interrupted/corrupt cache.
|
||||||
|
RandomAccessFile(partial, "rw").use { it.fd.sync() }
|
||||||
|
if (!ledger.allComplete()) {
|
||||||
|
error("并行下载未完成:${ledger.bytesComplete()}/$expectedSize")
|
||||||
|
}
|
||||||
|
Log.i(TAG, "parallel complete: chunks=${ledger.totalChunks}, bytes=$expectedSize")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun receiveRangeWithRetry(
|
||||||
|
networkProvider: () -> Network?,
|
||||||
|
baseUrl: String,
|
||||||
|
pairing: PairingPayload,
|
||||||
|
deviceName: String,
|
||||||
|
partial: File,
|
||||||
|
expectedSize: Long,
|
||||||
|
ledger: ChunkLedger,
|
||||||
|
index: Int,
|
||||||
|
abortReason: () -> String?,
|
||||||
|
) {
|
||||||
|
var last: Exception? = null
|
||||||
|
repeat(RANGE_ATTEMPTS) { attempt ->
|
||||||
|
abortReason()?.let { throw IllegalStateException(it, last) }
|
||||||
|
try {
|
||||||
|
receiveRange(
|
||||||
|
networkProvider(),
|
||||||
|
baseUrl,
|
||||||
|
pairing,
|
||||||
|
deviceName,
|
||||||
|
partial,
|
||||||
|
expectedSize,
|
||||||
|
ledger,
|
||||||
|
index,
|
||||||
|
)
|
||||||
|
ledger.markComplete(index)
|
||||||
|
return
|
||||||
|
} catch (e: Exception) {
|
||||||
|
last = e
|
||||||
|
Log.w(
|
||||||
|
TAG,
|
||||||
|
"range=$index/${ledger.totalChunks} attempt=${attempt + 1}/$RANGE_ATTEMPTS failed: ${failureDetail(e)}",
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
if (attempt + 1 < RANGE_ATTEMPTS) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(180L * (attempt + 1))
|
||||||
|
} catch (interrupted: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw IllegalStateException(
|
||||||
|
"分块 $index 下载失败,已重试 $RANGE_ATTEMPTS 次:${failureDetail(last)}",
|
||||||
|
last,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun receiveRange(
|
||||||
|
network: Network?,
|
||||||
|
baseUrl: String,
|
||||||
|
pairing: PairingPayload,
|
||||||
|
deviceName: String,
|
||||||
|
partial: File,
|
||||||
|
expectedSize: Long,
|
||||||
|
ledger: ChunkLedger,
|
||||||
|
index: Int,
|
||||||
|
) {
|
||||||
|
val offset = ledger.chunkOffset(index)
|
||||||
|
val length = ledger.chunkLength(index)
|
||||||
|
val end = offset + length - 1L
|
||||||
|
val conn = open(network, URL("$baseUrl/qft/download"))
|
||||||
|
try {
|
||||||
|
conn.requestMethod = "GET"
|
||||||
|
conn.connectTimeout = 5_000
|
||||||
|
conn.readTimeout = 20_000
|
||||||
|
conn.useCaches = false
|
||||||
|
conn.setRequestProperty("Connection", "close")
|
||||||
|
conn.setRequestProperty("X-QFT-Token", pairing.session)
|
||||||
|
conn.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8)))
|
||||||
|
conn.setRequestProperty("Range", "bytes=$offset-$end")
|
||||||
|
|
||||||
|
val code = conn.responseCode
|
||||||
|
if (code != HttpURLConnection.HTTP_PARTIAL) {
|
||||||
|
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText().take(300) } } catch (_: Exception) { null }
|
||||||
|
error("电脑下载服务未返回并行 Range(HTTP $code)${message?.let { ": $it" } ?: ""}")
|
||||||
|
}
|
||||||
|
val expectedRange = "bytes $offset-$end/$expectedSize"
|
||||||
|
if (conn.getHeaderField("Content-Range") != expectedRange) {
|
||||||
|
error("下载服务返回了无效范围:${conn.getHeaderField("Content-Range")}")
|
||||||
|
}
|
||||||
|
if (conn.contentLengthLong >= 0L && conn.contentLengthLong != length) {
|
||||||
|
error("分块 $index 长度不匹配:${conn.contentLengthLong} != $length")
|
||||||
|
}
|
||||||
|
|
||||||
|
var received = 0L
|
||||||
|
conn.inputStream.use { input ->
|
||||||
|
RandomAccessFile(partial, "rw").use { output ->
|
||||||
|
output.channel.use { channel ->
|
||||||
|
channel.position(offset)
|
||||||
|
val buffer = ByteArray(BUFFER_SIZE)
|
||||||
|
while (received < length) {
|
||||||
|
val n = input.read(buffer, 0, minOf(buffer.size.toLong(), length - received).toInt())
|
||||||
|
if (n < 0) break
|
||||||
|
if (n == 0) continue
|
||||||
|
val bytes = ByteBuffer.wrap(buffer, 0, n)
|
||||||
|
while (bytes.hasRemaining()) channel.write(bytes)
|
||||||
|
received += n.toLong()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (received != length) error("分块 $index 提前结束:$received/$length")
|
||||||
|
Log.d(TAG, "range=$index/${ledger.totalChunks} complete bytes=$length")
|
||||||
|
} finally {
|
||||||
|
conn.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun desiredRangeChunkSize(fileSize: Long): Long {
|
||||||
|
if (fileSize <= 0L) return MIN_RANGE_CHUNK
|
||||||
|
return ((fileSize + RANGE_WORKERS - 1L) / RANGE_WORKERS)
|
||||||
|
.coerceIn(MIN_RANGE_CHUNK, MAX_RANGE_CHUNK)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun discardTransferState(partial: File) {
|
||||||
|
partial.delete()
|
||||||
|
File("${partial.path}.map").delete()
|
||||||
|
File("${partial.path}.map.tmp").delete()
|
||||||
|
}
|
||||||
|
|
||||||
private fun sha256(file: File, onProgress: (Long, Long) -> Unit): String {
|
private fun sha256(file: File, onProgress: (Long, Long) -> Unit): String {
|
||||||
val digest = MessageDigest.getInstance("SHA-256")
|
val digest = MessageDigest.getInstance("SHA-256")
|
||||||
val total = file.length()
|
val total = file.length()
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.qft.optical
|
||||||
|
|
||||||
|
import java.net.URI
|
||||||
|
|
||||||
|
/** Pure IPv4 routing helpers kept Android-free so candidate selection is testable. */
|
||||||
|
object EndpointRouting {
|
||||||
|
/**
|
||||||
|
* A dedicated QFT Wi-Fi must never reuse QR/LAN adapter addresses. Its only
|
||||||
|
* direct candidates are gateways supplied by Android for that exact Network.
|
||||||
|
* Current-LAN fallback mode may additionally use advertised same-subnet IPs.
|
||||||
|
*/
|
||||||
|
fun afterConnection(
|
||||||
|
dedicatedWifi: Boolean,
|
||||||
|
gatewayEndpoints: List<String>,
|
||||||
|
routedAdvertisedEndpoints: List<String>,
|
||||||
|
): List<String> = if (dedicatedWifi) {
|
||||||
|
gatewayEndpoints.distinct()
|
||||||
|
} else {
|
||||||
|
(gatewayEndpoints + routedAdvertisedEndpoints).distinct()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same isolation rule for retry/recovery after the first gateway probe. */
|
||||||
|
fun forRecovery(
|
||||||
|
dedicatedWifi: Boolean,
|
||||||
|
discoveredEndpoint: String?,
|
||||||
|
gatewayEndpoints: List<String>,
|
||||||
|
advertisedEndpoints: List<String>,
|
||||||
|
): List<String> {
|
||||||
|
val candidates = listOfNotNull(discoveredEndpoint) + gatewayEndpoints
|
||||||
|
return (candidates + if (dedicatedWifi) emptyList() else advertisedEndpoints).distinct()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onAnySubnet(
|
||||||
|
endpoints: List<String>,
|
||||||
|
expectedPort: Int,
|
||||||
|
localLinks: List<Pair<String, Int>>,
|
||||||
|
): List<String> {
|
||||||
|
val subnets = localLinks.mapNotNull { (address, prefix) ->
|
||||||
|
ipv4(address)?.let { it to prefix.coerceIn(0, 32) }
|
||||||
|
}
|
||||||
|
if (subnets.isEmpty()) return emptyList()
|
||||||
|
|
||||||
|
return endpoints.filter { endpoint ->
|
||||||
|
val uri = try { URI(endpoint) } catch (_: Exception) { return@filter false }
|
||||||
|
if (uri.scheme != "http" || uri.port != expectedPort) return@filter false
|
||||||
|
val candidate = ipv4(uri.host ?: return@filter false) ?: return@filter false
|
||||||
|
subnets.any { (local, prefix) -> sameSubnet(local, candidate, prefix) }
|
||||||
|
}.distinct()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sameSubnet(a: Long, b: Long, prefix: Int): Boolean {
|
||||||
|
if (prefix == 0) return true
|
||||||
|
val mask = (0xFFFF_FFFFL shl (32 - prefix)) and 0xFFFF_FFFFL
|
||||||
|
return (a and mask) == (b and mask)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ipv4(value: String): Long? {
|
||||||
|
val parts = value.split('.')
|
||||||
|
if (parts.size != 4) return null
|
||||||
|
var result = 0L
|
||||||
|
for (part in parts) {
|
||||||
|
val octet = part.toIntOrNull()?.takeIf { it in 0..255 } ?: return null
|
||||||
|
result = (result shl 8) or octet.toLong()
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ import android.util.Size
|
|||||||
import android.view.Gravity
|
import android.view.Gravity
|
||||||
import android.view.MotionEvent
|
import android.view.MotionEvent
|
||||||
import android.view.ScaleGestureDetector
|
import android.view.ScaleGestureDetector
|
||||||
|
import android.view.View
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
import android.widget.Button
|
import android.widget.Button
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
@@ -79,15 +80,17 @@ class MainActivity : ComponentActivity() {
|
|||||||
@Volatile private var connectedNetwork: Network? = null
|
@Volatile private var connectedNetwork: Network? = null
|
||||||
private var connectedBaseUrl: String? = null
|
private var connectedBaseUrl: String? = null
|
||||||
private val selectedFiles = mutableListOf<SelectedFile>()
|
private val selectedFiles = mutableListOf<SelectedFile>()
|
||||||
private var managingFilesForPair: PairingPayload? = null
|
|
||||||
private var managingFilesForBaseUrl: String? = null
|
|
||||||
private var sendStatusText: TextView? = null
|
private var sendStatusText: TextView? = null
|
||||||
private var sendFilesText: TextView? = null
|
private var sendFilesText: TextView? = null
|
||||||
|
private var sendFilesContainer: LinearLayout? = null
|
||||||
|
private var sendAddButton: Button? = null
|
||||||
|
private var sendClearButton: Button? = null
|
||||||
private var sendProgress: ProgressBar? = null
|
private var sendProgress: ProgressBar? = null
|
||||||
private var sendButton: Button? = null
|
private var sendButton: Button? = null
|
||||||
private var connectingStatusText: TextView? = null
|
private var connectingStatusText: TextView? = null
|
||||||
private var downloadStatusText: TextView? = null
|
private var downloadStatusText: TextView? = null
|
||||||
@Volatile private var downloadRunning = false
|
@Volatile private var downloadRunning = false
|
||||||
|
@Volatile private var uploadRunning = false
|
||||||
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
|
/** 非 null 表示当前传输应立刻中止(QFT 临时网络断开等)。
|
||||||
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
|
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
|
||||||
@Volatile private var transferAbortReason: String? = null
|
@Volatile private var transferAbortReason: String? = null
|
||||||
@@ -117,18 +120,16 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||||
|
if (uploadRunning) {
|
||||||
|
sendStatusText?.text = "传输已经开始,当前队列已锁定"
|
||||||
|
return@registerForActivityResult
|
||||||
|
}
|
||||||
var unknown = 0
|
var unknown = 0
|
||||||
for (uri in uris) {
|
for (uri in uris) {
|
||||||
val file = UploadClient.describeFile(contentResolver, uri)
|
val file = UploadClient.describeFile(contentResolver, uri)
|
||||||
if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
|
if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
|
||||||
}
|
}
|
||||||
renderSelectedFiles()
|
renderSelectedFiles()
|
||||||
val pair = managingFilesForPair
|
|
||||||
val baseUrl = managingFilesForBaseUrl
|
|
||||||
if (pair != null && baseUrl != null) {
|
|
||||||
showFileSelection(pair, baseUrl)
|
|
||||||
return@registerForActivityResult
|
|
||||||
}
|
|
||||||
if (unknown > 0) {
|
if (unknown > 0) {
|
||||||
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
|
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
|
||||||
} else if (selectedFiles.isNotEmpty()) {
|
} else if (selectedFiles.isNotEmpty()) {
|
||||||
@@ -151,6 +152,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
stopCamera()
|
stopCamera()
|
||||||
scannerMode = ScannerMode.NONE
|
scannerMode = ScannerMode.NONE
|
||||||
pairConsumed.set(false)
|
pairConsumed.set(false)
|
||||||
|
wifiConnector.releaseHighPerfLock()
|
||||||
wifiConnector.release()
|
wifiConnector.release()
|
||||||
pendingPair = null
|
pendingPair = null
|
||||||
connectedNetwork = null
|
connectedNetwork = null
|
||||||
@@ -158,8 +160,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
downloadRunning = false
|
downloadRunning = false
|
||||||
downloadStatusText = null
|
downloadStatusText = null
|
||||||
selectedFiles.clear()
|
selectedFiles.clear()
|
||||||
managingFilesForPair = null
|
uploadRunning = false
|
||||||
managingFilesForBaseUrl = null
|
sendFilesContainer = null
|
||||||
|
sendAddButton = null
|
||||||
|
sendClearButton = null
|
||||||
|
sendFilesText = null
|
||||||
|
sendStatusText = null
|
||||||
|
sendProgress = null
|
||||||
|
sendButton = null
|
||||||
|
|
||||||
val root = pageColumn()
|
val root = pageColumn()
|
||||||
root.addView(text("QFT", 30f, Color.WHITE, true))
|
root.addView(text("QFT", 30f, Color.WHITE, true))
|
||||||
@@ -194,7 +202,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
) { showReceivedFiles() })
|
) { showReceivedFiles() })
|
||||||
root.addView(space(22))
|
root.addView(space(22))
|
||||||
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
||||||
root.addView(text("QFT v0.4.6 · Android 7+ 到最新", 12f, MUTED))
|
root.addView(text("QFT v0.4.16 · Android 7+ 到最新", 12f, MUTED))
|
||||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,10 +317,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
)
|
)
|
||||||
currentAnalyzer = analyzer
|
currentAnalyzer = analyzer
|
||||||
|
|
||||||
// v0.4 single large QR is intentionally analyzed at 640x480. With the
|
// Pairing QR codes carry network/file metadata and can be much denser
|
||||||
// QR occupying most of the view this still leaves several camera
|
// than one optical QFT2 frame. Give PAIR_FAST more sensor pixels per
|
||||||
// pixels/module, while substantially reducing Y-copy + ZXing work.
|
// module; the continuous optical path stays at 640x480 to preserve FPS.
|
||||||
val targetSize = Size(640, 480)
|
val targetSize = if (mode == ScannerMode.PAIR) Size(960, 720) else Size(640, 480)
|
||||||
val analysisBuilder = ImageAnalysis.Builder()
|
val analysisBuilder = ImageAnalysis.Builder()
|
||||||
.setTargetResolution(targetSize)
|
.setTargetResolution(targetSize)
|
||||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||||
@@ -604,6 +612,14 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun connectPair(pair: PairingPayload) {
|
private fun connectPair(pair: PairingPayload) {
|
||||||
val attempt = ++pairConnectionAttempt
|
val attempt = ++pairConnectionAttempt
|
||||||
transferAbortReason = null
|
transferAbortReason = null
|
||||||
|
connectedBaseUrl = null
|
||||||
|
// 携带 Wi-Fi 身份的 QFT Direct 会无条件先连接那张专用网络。
|
||||||
|
// 不再尝试二维码/电脑当前 LAN 地址;“当前局域网”仍是桌面端用户
|
||||||
|
// 明确选择的独立备用模式(wifi == null)。
|
||||||
|
connectViaWifi(pair, attempt)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun connectViaWifi(pair: PairingPayload, attempt: Long) {
|
||||||
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
|
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
|
||||||
wifiConnector.connect(
|
wifiConnector.connect(
|
||||||
pairing = pair,
|
pairing = pair,
|
||||||
@@ -619,28 +635,79 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (connectedBaseUrl != null) return@available
|
if (connectedBaseUrl != null) return@available
|
||||||
transferExecutor.execute {
|
transferExecutor.execute {
|
||||||
if (attempt != pairConnectionAttempt) return@execute
|
if (attempt != pairConnectionAttempt) return@execute
|
||||||
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
|
val dedicatedWifi = pair.wifi != null
|
||||||
val discovered = UploadClient.discoverUdp(
|
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
|
||||||
network = network,
|
val routedEndpoints = if (dedicatedWifi) emptyList() else {
|
||||||
pairing = pair,
|
wifiConnector.endpointsOnNetwork(network, pair.endpoints, pair.port)
|
||||||
hosts = wifiConnector.discoveryHosts(network),
|
}
|
||||||
|
var subnet = if (dedicatedWifi) {
|
||||||
|
wifiConnector.subnetEndpoints(network, pair.port)
|
||||||
|
} else {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
val directCandidates = EndpointRouting.afterConnection(
|
||||||
|
dedicatedWifi = dedicatedWifi,
|
||||||
|
gatewayEndpoints = gateways,
|
||||||
|
routedAdvertisedEndpoints = routedEndpoints,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Direct AP 的网关由这次专用连接的 LinkProperties 给出,
|
||||||
|
// 不使用二维码地址,也不猜测 192.168.137/49 网段。
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
updateConnectingStatus(
|
updateConnectingStatus(
|
||||||
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
|
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证网关和电脑…"
|
||||||
else "UDP 未响应 · 正在并行探测网关与本地 IP…"
|
else "网络已就绪 · 正在连接同网段电脑…"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
|
val direct = if (dedicatedWifi) {
|
||||||
val subnet = wifiConnector.subnetEndpoints(network, pair.port)
|
UploadClient.probeConnectedNetwork(
|
||||||
if (discovered == null) {
|
network = network,
|
||||||
|
pairing = pair,
|
||||||
|
deviceName = receiverDeviceLabel,
|
||||||
|
endpoints = directCandidates + subnet,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
UploadClient.probeEndpoints(
|
||||||
|
network = network,
|
||||||
|
pairing = pair,
|
||||||
|
deviceName = receiverDeviceLabel,
|
||||||
|
endpoints = directCandidates,
|
||||||
|
connectMs = 400,
|
||||||
|
readMs = 600,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 网关/子网并行快探不通才退回 UDP,并刷新路由后再恢复。
|
||||||
|
var discovered: String? = null
|
||||||
|
if (direct == null) {
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
updateConnectingStatus("正在并行探测网关;必要时自动扫描当前 QFT 子网…")
|
updateConnectingStatus(
|
||||||
|
if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…"
|
||||||
|
else "同网段地址未应答 · 正在 UDP 快速发现电脑…"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
discovered = UploadClient.discoverUdp(
|
||||||
|
network = network,
|
||||||
|
pairing = pair,
|
||||||
|
hosts = wifiConnector.discoveryHosts(network),
|
||||||
|
deviceName = receiverDeviceLabel,
|
||||||
|
)
|
||||||
|
// LinkProperties may have gained routes while the first
|
||||||
|
// scan was running; refresh the actual connected subnet.
|
||||||
|
if (dedicatedWifi) {
|
||||||
|
subnet = wifiConnector.subnetEndpoints(network, pair.port)
|
||||||
|
}
|
||||||
|
runOnUiThread {
|
||||||
|
updateConnectingStatus(
|
||||||
|
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
|
||||||
|
else "仅在当前连接的 QFT 子网内并行查找电脑…"
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val base = UploadClient.probeRobust(
|
|
||||||
|
val base = direct ?: UploadClient.probeRobust(
|
||||||
network = network,
|
network = network,
|
||||||
pairing = pair,
|
pairing = pair.copy(endpoints = routedEndpoints),
|
||||||
deviceName = receiverDeviceLabel,
|
deviceName = receiverDeviceLabel,
|
||||||
preferredEndpoints = gateways,
|
preferredEndpoints = gateways,
|
||||||
discoveredEndpoint = discovered,
|
discoveredEndpoint = discovered,
|
||||||
@@ -648,8 +715,31 @@ class MainActivity : ComponentActivity() {
|
|||||||
)
|
)
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||||||
|
// 如果 Wi-Fi 波动后系统已交付了新的 Network,旧探测结果
|
||||||
|
// 不得覆盖新连接或短暂显示失败页。
|
||||||
|
if (connectedNetwork != network) return@runOnUiThread
|
||||||
if (base == null) {
|
if (base == null) {
|
||||||
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
|
// 把手机实际所处的网络写进报错。否则"找不到"这三个字
|
||||||
|
// 无法区分:手机在别的网段?没拿到网关?还是对端真的没开。
|
||||||
|
val diagnosis = buildString {
|
||||||
|
append(
|
||||||
|
if (dedicatedWifi) {
|
||||||
|
"QFT 专用 Wi-Fi 已连接,但在该专用网络的实际网关和子网内未找到服务。\n\n"
|
||||||
|
} else {
|
||||||
|
"Wi-Fi 已连接,但在当前局域网内未找到 QFT 服务。\n\n"
|
||||||
|
}
|
||||||
|
)
|
||||||
|
append("手机侧:").append(wifiConnector.describeNetwork(network)).append("\n")
|
||||||
|
append("连接模式:")
|
||||||
|
append(if (dedicatedWifi) "QFT 专用 Wi-Fi(不使用二维码/电脑本地网卡地址)" else "当前局域网备用模式")
|
||||||
|
append("\n探测过的网关地址:")
|
||||||
|
append(gateways.joinToString("、").ifEmpty { "(无)" })
|
||||||
|
append("\n子网扫描范围:").append(subnet.size).append(" 个地址\n\n")
|
||||||
|
append("请对照检查:① Windows 上 QFT Direct 是否仍显示已就绪;")
|
||||||
|
append("② 防火墙是否放行 qft-desktop.exe 的当前专用网络类型;")
|
||||||
|
append("③ 手机是否仍连接二维码内的 QFT 专用网络。")
|
||||||
|
}
|
||||||
|
showPairError(pair, diagnosis)
|
||||||
} else {
|
} else {
|
||||||
connectedBaseUrl = base
|
connectedBaseUrl = base
|
||||||
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||||
@@ -734,18 +824,40 @@ class MainActivity : ComponentActivity() {
|
|||||||
root.addView(card().apply {
|
root.addView(card().apply {
|
||||||
addView(text("连接状态", 14f, MUTED))
|
addView(text("连接状态", 14f, MUTED))
|
||||||
addView(text("● 本地直连已就绪", 17f, SUCCESS, true), matchWrap(top = 8))
|
addView(text("● 本地直连已就绪", 17f, SUCCESS, true), matchWrap(top = 8))
|
||||||
addView(text(if (pair.version >= 2) "Parallel v2 · 自适应最高 8 路并发 · 4/8/16 MiB 自适应分块" else "兼容单流模式", 13f, ACCENT), matchWrap(top = 5))
|
addView(text(if (pair.version >= 2) "Parallel v2 · 目标 8 路并发 · 64 KiB–16 MiB 自适应分块" else "兼容单流模式", 13f, ACCENT), matchWrap(top = 5))
|
||||||
addView(text("目标:$baseUrl", 12f, MUTED), matchWrap(top = 6))
|
addView(text("目标:$baseUrl", 12f, MUTED), matchWrap(top = 6))
|
||||||
pair.wifi?.let { addView(text("QFT 临时网络:${it.ssid}", 12f, MUTED), matchWrap(top = 4)) }
|
pair.wifi?.let { addView(text("QFT 临时网络:${it.ssid}", 12f, MUTED), matchWrap(top = 4)) }
|
||||||
})
|
})
|
||||||
root.addView(space(14))
|
root.addView(space(14))
|
||||||
root.addView(card().apply {
|
root.addView(card().apply {
|
||||||
addView(text("选择文件", 17f, Color.WHITE, true))
|
addView(text("传输队列", 17f, Color.WHITE, true))
|
||||||
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
|
sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
|
||||||
addView(sendFilesText, matchWrap(top = 8))
|
addView(sendFilesText, matchWrap(top = 8))
|
||||||
addView(button("选择文件(可多选)").apply {
|
sendFilesContainer = LinearLayout(this@MainActivity).apply {
|
||||||
setOnClickListener { showFileSelection(pair, baseUrl) }
|
orientation = LinearLayout.VERTICAL
|
||||||
}, matchWrap(top = 12))
|
}
|
||||||
|
addView(sendFilesContainer, matchWrap(top = 6))
|
||||||
|
val actions = LinearLayout(this@MainActivity).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
}
|
||||||
|
sendAddButton = button("添加文件").apply {
|
||||||
|
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
|
||||||
|
}
|
||||||
|
sendClearButton = button("清空").apply {
|
||||||
|
setOnClickListener {
|
||||||
|
if (!uploadRunning) {
|
||||||
|
selectedFiles.clear()
|
||||||
|
renderSelectedFiles()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
actions.addView(sendAddButton, LinearLayout.LayoutParams(0, dp(48), 1f).apply {
|
||||||
|
marginEnd = dp(8)
|
||||||
|
})
|
||||||
|
actions.addView(sendClearButton, LinearLayout.LayoutParams(dp(96), dp(48)))
|
||||||
|
addView(actions, matchWrap(top = 12))
|
||||||
|
addView(text("按住“拖动”上下移动可调整发送优先级;传输开始后队列会锁定。", 12f, MUTED), matchWrap(top = 8))
|
||||||
})
|
})
|
||||||
root.addView(space(14))
|
root.addView(space(14))
|
||||||
root.addView(card().apply {
|
root.addView(card().apply {
|
||||||
@@ -755,10 +867,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
|
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
|
||||||
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
|
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
|
||||||
sendButton = button("选择传输文件").apply {
|
sendButton = button("选择传输文件").apply {
|
||||||
isEnabled = connectedBaseUrl != null
|
isEnabled = false
|
||||||
setOnClickListener {
|
setOnClickListener {
|
||||||
if (selectedFiles.isEmpty()) showFileSelection(pair, baseUrl)
|
startUploads(pair, baseUrl)
|
||||||
else startUploads(pair, baseUrl)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
addView(sendButton, matchWrap(top = 14))
|
addView(sendButton, matchWrap(top = 14))
|
||||||
@@ -800,11 +911,31 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
downloadRunning = true
|
downloadRunning = true
|
||||||
transferAbortReason = null
|
transferAbortReason = null
|
||||||
|
// 传输期间阻止 Wi-Fi 进入省电休眠。Android 默认会在包间隙让
|
||||||
|
// Wi-Fi 芯片休眠,对持续大流量传输会明显压低吞吐。
|
||||||
|
wifiConnector.acquireHighPerfLock()
|
||||||
|
val linkAtStart = wifiConnector.describeLink()
|
||||||
transferExecutor.execute {
|
transferExecutor.execute {
|
||||||
// 「传输 / 校验 / 保存」三个阶段各自的速率含义不同,
|
// 「传输 / 校验 / 保存」三个阶段各自的速率含义完全不同,混在一起
|
||||||
// 每进入一个新阶段就重新计时,否则显示出来的速率毫无意义。
|
// 平均出来的数字毫无意义。逐段记账,结束后一并列出——
|
||||||
var phaseLabel = "正在接收"
|
// 这样"到底是哪一段慢"一眼就能看出来,不必再靠猜。
|
||||||
|
val phases = java.util.Collections.synchronizedList(
|
||||||
|
mutableListOf<Triple<String, Long, Long>>() // 名称、毫秒、字节
|
||||||
|
)
|
||||||
|
var phaseLabel = "接收"
|
||||||
var phaseStartedAt = android.os.SystemClock.elapsedRealtime()
|
var phaseStartedAt = android.os.SystemClock.elapsedRealtime()
|
||||||
|
// 并行下载的进度回调来自多个 worker 线程(DownloadClient 里
|
||||||
|
// pool.submit 的闭包),普通 var 记账会有竞态,必须用原子变量。
|
||||||
|
val phaseFirstBytes = java.util.concurrent.atomic.AtomicLong(-1L)
|
||||||
|
val phaseLastBytes = java.util.concurrent.atomic.AtomicLong(0L)
|
||||||
|
|
||||||
|
fun closePhase() {
|
||||||
|
val millis = android.os.SystemClock.elapsedRealtime() - phaseStartedAt
|
||||||
|
val first = phaseFirstBytes.get().coerceAtLeast(0L)
|
||||||
|
val bytes = (phaseLastBytes.get() - first).coerceAtLeast(0L)
|
||||||
|
if (millis > 0L && bytes > 0L) phases += Triple(phaseLabel, millis, bytes)
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val saved = DownloadClient.download(
|
val saved = DownloadClient.download(
|
||||||
context = this@MainActivity,
|
context = this@MainActivity,
|
||||||
@@ -815,23 +946,49 @@ class MainActivity : ComponentActivity() {
|
|||||||
deviceName = receiverDeviceLabel,
|
deviceName = receiverDeviceLabel,
|
||||||
abortReason = { transferAbortReason },
|
abortReason = { transferAbortReason },
|
||||||
onPhase = { label ->
|
onPhase = { label ->
|
||||||
phaseLabel = label
|
closePhase()
|
||||||
|
// 去掉文案里的修饰,只留阶段名,汇总表才对得齐
|
||||||
|
phaseLabel = label.removePrefix("正在").removeSuffix("…")
|
||||||
|
.substringBefore("到 ").substringBefore("文件完整性").ifBlank { label }
|
||||||
phaseStartedAt = android.os.SystemClock.elapsedRealtime()
|
phaseStartedAt = android.os.SystemClock.elapsedRealtime()
|
||||||
|
phaseFirstBytes.set(-1L)
|
||||||
|
phaseLastBytes.set(0L)
|
||||||
runOnUiThread { status.text = label }
|
runOnUiThread { status.text = label }
|
||||||
},
|
},
|
||||||
) { received, expected ->
|
) { received, expected ->
|
||||||
|
phaseFirstBytes.compareAndSet(-1L, received)
|
||||||
|
phaseLastBytes.set(received)
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
val fraction = if (expected <= 0) 0 else ((received * 1000L) / expected).toInt().coerceIn(0, 1000)
|
val fraction = if (expected <= 0) 0 else ((received * 1000L) / expected).toInt().coerceIn(0, 1000)
|
||||||
val elapsed = (android.os.SystemClock.elapsedRealtime() - phaseStartedAt).coerceAtLeast(1L)
|
val elapsed = (android.os.SystemClock.elapsedRealtime() - phaseStartedAt).coerceAtLeast(1L)
|
||||||
val rate = received * 1000.0 / elapsed
|
val done = (received - phaseFirstBytes.get().coerceAtLeast(0L)).coerceAtLeast(0L)
|
||||||
|
val rate = done * 1000.0 / elapsed
|
||||||
bar.progress = fraction
|
bar.progress = fraction
|
||||||
status.text = "$phaseLabel ${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
|
status.text = "$phaseLabel ${humanBytes(received)} / ${humanBytes(expected)} · ${humanBytes(rate.toLong())}/s"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
closePhase()
|
||||||
|
|
||||||
|
val summary = buildString {
|
||||||
|
append("接收完成:已保存到 Downloads/QFT/").append(saved.name)
|
||||||
|
var totalMillis = 0L
|
||||||
|
for ((label, millis, bytes) in phases) {
|
||||||
|
totalMillis += millis
|
||||||
|
append("\n").append(label).append(" ")
|
||||||
|
append(humanDuration(millis / 1000.0)).append(" · ")
|
||||||
|
append(humanBytes((bytes * 1000.0 / millis).toLong())).append("/s")
|
||||||
|
}
|
||||||
|
if (phases.size > 1 && totalMillis > 0L) {
|
||||||
|
append("\n合计 ").append(humanDuration(totalMillis / 1000.0)).append(" · ")
|
||||||
|
append(humanBytes((saved.size * 1000.0 / totalMillis).toLong())).append("/s")
|
||||||
|
}
|
||||||
|
// 带上链路协商速率:判断"慢"是软件问题还是链路上限的唯一依据
|
||||||
|
append("\n").append(linkAtStart)
|
||||||
|
}
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
bar.progress = 1000
|
bar.progress = 1000
|
||||||
status.setTextColor(SUCCESS)
|
status.setTextColor(SUCCESS)
|
||||||
status.text = "接收完成:已保存到 Downloads/QFT/${saved.name}"
|
status.text = summary
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
@@ -842,6 +999,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
downloadRunning = false
|
downloadRunning = false
|
||||||
|
// 无论成功失败都要释放,否则 Wi-Fi 会一直停留在高功耗模式
|
||||||
|
wifiConnector.releaseHighPerfLock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -889,95 +1048,128 @@ class MainActivity : ComponentActivity() {
|
|||||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun showFileSelection(pair: PairingPayload, baseUrl: String) {
|
|
||||||
managingFilesForPair = pair
|
|
||||||
managingFilesForBaseUrl = baseUrl
|
|
||||||
val root = pageColumn()
|
|
||||||
root.addView(text("选择发送文件", 28f, Color.WHITE, true))
|
|
||||||
root.addView(text("可多次添加文件,并在列表中单独移除。", 14f, MUTED))
|
|
||||||
root.addView(space(14))
|
|
||||||
val total = selectedFiles.sumOf { it.size }
|
|
||||||
root.addView(card().apply {
|
|
||||||
addView(text("已选 ${selectedFiles.size} 个 · ${humanBytes(total)}", 16f, ACCENT, true))
|
|
||||||
if (selectedFiles.isEmpty()) {
|
|
||||||
addView(text("请先选择需要传输的文件", 14f, WARNING), matchWrap(top = 8))
|
|
||||||
} else {
|
|
||||||
selectedFiles.toList().forEach { file ->
|
|
||||||
val row = LinearLayout(this@MainActivity).apply {
|
|
||||||
orientation = LinearLayout.HORIZONTAL
|
|
||||||
gravity = Gravity.CENTER_VERTICAL
|
|
||||||
}
|
|
||||||
row.addView(
|
|
||||||
text("${file.name}\n${humanBytes(file.size)}", 14f, Color.WHITE),
|
|
||||||
LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) },
|
|
||||||
)
|
|
||||||
row.addView(button("移除").apply {
|
|
||||||
setOnClickListener {
|
|
||||||
selectedFiles.removeAll { it.uri == file.uri }
|
|
||||||
showFileSelection(pair, baseUrl)
|
|
||||||
}
|
|
||||||
}, LinearLayout.LayoutParams(dp(82), dp(44)))
|
|
||||||
addView(row, matchWrap(top = 10))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
root.addView(space(14))
|
|
||||||
root.addView(button("添加文件(可多选)").apply {
|
|
||||||
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
|
|
||||||
})
|
|
||||||
if (selectedFiles.isNotEmpty()) {
|
|
||||||
root.addView(space(10))
|
|
||||||
root.addView(button("清空选择").apply {
|
|
||||||
setOnClickListener {
|
|
||||||
selectedFiles.clear()
|
|
||||||
showFileSelection(pair, baseUrl)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
root.addView(space(10))
|
|
||||||
root.addView(button("完成并返回传输").apply {
|
|
||||||
isEnabled = selectedFiles.isNotEmpty()
|
|
||||||
setOnClickListener {
|
|
||||||
managingFilesForPair = null
|
|
||||||
managingFilesForBaseUrl = null
|
|
||||||
showSendReady(pair, baseUrl)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
root.addView(space(10))
|
|
||||||
root.addView(button("取消并返回传输").apply {
|
|
||||||
setOnClickListener {
|
|
||||||
managingFilesForPair = null
|
|
||||||
managingFilesForBaseUrl = null
|
|
||||||
showSendReady(pair, baseUrl)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun renderSelectedFiles() {
|
private fun renderSelectedFiles() {
|
||||||
val total = selectedFiles.sumOf { it.size }
|
val total = selectedFiles.sumOf { it.size }
|
||||||
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
sendFilesText?.text = if (selectedFiles.isEmpty()) {
|
||||||
"请先选择需要传输的文件"
|
"请先选择需要传输的文件"
|
||||||
} else {
|
} else {
|
||||||
buildString {
|
"已选 ${selectedFiles.size} 个 · ${humanBytes(total)} · 按列表顺序发送"
|
||||||
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
|
}
|
||||||
if (selectedFiles.size > 8) append("…另外 ${selectedFiles.size - 8} 个文件\n")
|
sendFilesText?.setTextColor(if (selectedFiles.isEmpty()) WARNING else ACCENT)
|
||||||
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
|
|
||||||
}.trim()
|
val container = sendFilesContainer
|
||||||
|
container?.removeAllViews()
|
||||||
|
selectedFiles.toList().forEachIndexed { index, file ->
|
||||||
|
val row = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.HORIZONTAL
|
||||||
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
|
setPadding(0, dp(4), 0, dp(4))
|
||||||
|
}
|
||||||
|
val drag = button("拖动").apply {
|
||||||
|
isEnabled = !uploadRunning
|
||||||
|
textSize = 12f
|
||||||
|
}
|
||||||
|
row.addView(drag, LinearLayout.LayoutParams(dp(76), dp(44)).apply {
|
||||||
|
marginEnd = dp(8)
|
||||||
|
})
|
||||||
|
row.addView(
|
||||||
|
text("${index + 1}. ${file.name}\n${humanBytes(file.size)}", 14f, Color.WHITE),
|
||||||
|
LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) },
|
||||||
|
)
|
||||||
|
row.addView(button("删除").apply {
|
||||||
|
isEnabled = !uploadRunning
|
||||||
|
textSize = 12f
|
||||||
|
setOnClickListener {
|
||||||
|
if (!uploadRunning) {
|
||||||
|
selectedFiles.removeAll { it.uri == file.uri }
|
||||||
|
renderSelectedFiles()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, LinearLayout.LayoutParams(dp(76), dp(44)))
|
||||||
|
container?.addView(row, matchWrap(top = if (index == 0) 2 else 4))
|
||||||
|
if (container != null && !uploadRunning) {
|
||||||
|
installFileQueueDrag(drag, row, file, container)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendAddButton?.isEnabled = !uploadRunning
|
||||||
|
sendClearButton?.isEnabled = !uploadRunning && selectedFiles.isNotEmpty()
|
||||||
|
sendButton?.text = when {
|
||||||
|
uploadRunning -> "传输中 · 队列已锁定"
|
||||||
|
selectedFiles.isEmpty() -> "请先添加文件"
|
||||||
|
else -> "开始传输 ${selectedFiles.size} 个文件"
|
||||||
|
}
|
||||||
|
sendButton?.isEnabled = connectedBaseUrl != null && selectedFiles.isNotEmpty() && !uploadRunning
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun installFileQueueDrag(
|
||||||
|
handle: View,
|
||||||
|
row: View,
|
||||||
|
file: SelectedFile,
|
||||||
|
container: LinearLayout,
|
||||||
|
) {
|
||||||
|
var downRawY = 0f
|
||||||
|
var startIndex = -1
|
||||||
|
handle.setOnTouchListener { view, event ->
|
||||||
|
if (uploadRunning) return@setOnTouchListener false
|
||||||
|
when (event.actionMasked) {
|
||||||
|
MotionEvent.ACTION_DOWN -> {
|
||||||
|
view.parent?.requestDisallowInterceptTouchEvent(true)
|
||||||
|
downRawY = event.rawY
|
||||||
|
startIndex = selectedFiles.indexOfFirst { it.uri == file.uri }
|
||||||
|
row.alpha = 0.72f
|
||||||
|
row.translationZ = dp(8).toFloat()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_MOVE -> {
|
||||||
|
// Never remove/reinsert the touched View here. Several OEM
|
||||||
|
// frameworks crash when a Button is detached while its
|
||||||
|
// dispatchTouchEvent is still on the stack. Move only the
|
||||||
|
// visual row; commit the list order once on ACTION_UP.
|
||||||
|
row.translationY = event.rawY - downRawY
|
||||||
|
true
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||||
|
view.parent?.requestDisallowInterceptTouchEvent(false)
|
||||||
|
row.alpha = 1f
|
||||||
|
row.translationZ = 0f
|
||||||
|
val averageHeight = (0 until container.childCount)
|
||||||
|
.map { container.getChildAt(it).height.coerceAtLeast(1) }
|
||||||
|
.average()
|
||||||
|
.takeIf { it.isFinite() && it > 0.0 }
|
||||||
|
?: row.height.coerceAtLeast(1).toDouble()
|
||||||
|
val deltaRows = kotlin.math.round(row.translationY.toDouble() / averageHeight).toInt()
|
||||||
|
row.translationY = 0f
|
||||||
|
if (
|
||||||
|
event.actionMasked == MotionEvent.ACTION_UP &&
|
||||||
|
startIndex >= 0 &&
|
||||||
|
selectedFiles.isNotEmpty()
|
||||||
|
) {
|
||||||
|
val target = (startIndex + deltaRows).coerceIn(0, selectedFiles.lastIndex)
|
||||||
|
moveQueueItem(selectedFiles, startIndex, target)
|
||||||
|
view.performClick()
|
||||||
|
}
|
||||||
|
container.post { renderSelectedFiles() }
|
||||||
|
true
|
||||||
|
}
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
sendButton?.text = if (selectedFiles.isEmpty()) "选择传输文件" else "开始传输"
|
|
||||||
sendButton?.isEnabled = connectedBaseUrl != null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startUploads(pair: PairingPayload, baseUrl: String) {
|
private fun startUploads(pair: PairingPayload, baseUrl: String) {
|
||||||
|
if (uploadRunning) return
|
||||||
if (selectedFiles.isEmpty()) {
|
if (selectedFiles.isEmpty()) {
|
||||||
sendStatusText?.setTextColor(WARNING)
|
sendStatusText?.setTextColor(WARNING)
|
||||||
sendStatusText?.text = "请先选择需要传输的文件"
|
sendStatusText?.text = "请先选择需要传输的文件"
|
||||||
showFileSelection(pair, baseUrl)
|
pickFiles.launch(arrayOf("*/*"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val files = selectedFiles.toList()
|
val files = selectedFiles.toList()
|
||||||
sendButton?.isEnabled = false
|
uploadRunning = true
|
||||||
|
transferAbortReason = null
|
||||||
|
renderSelectedFiles()
|
||||||
|
wifiConnector.acquireHighPerfLock()
|
||||||
transferExecutor.execute {
|
transferExecutor.execute {
|
||||||
try {
|
try {
|
||||||
files.forEachIndexed { index, file ->
|
files.forEachIndexed { index, file ->
|
||||||
@@ -1012,12 +1204,16 @@ class MainActivity : ComponentActivity() {
|
|||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
sendProgress?.progress = 1000
|
sendProgress?.progress = 1000
|
||||||
sendStatusText?.text = "全部完成 · 已发送 ${files.size} 个文件"
|
sendStatusText?.text = "全部完成 · 已发送 ${files.size} 个文件"
|
||||||
sendButton?.isEnabled = true
|
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
sendStatusText?.text = "传输失败:${e.message}"
|
sendStatusText?.text = "传输失败:${e.message}"
|
||||||
sendButton?.isEnabled = true
|
}
|
||||||
|
} finally {
|
||||||
|
wifiConnector.releaseHighPerfLock()
|
||||||
|
runOnUiThread {
|
||||||
|
uploadRunning = false
|
||||||
|
renderSelectedFiles()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -124,26 +124,29 @@ class QrAnalyzer(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
// Acquisition is center-first, but unlike the old path it establishes
|
// Pairing needs one reliable first hit, not sustained decode FPS. Keep a
|
||||||
// a QR ROI immediately after the first hit. Full-frame work is only a
|
// generous center crop so a large desktop QR is not clipped at the quiet
|
||||||
// recovery path for deliberately off-center QR codes.
|
// zone, and prefer Hybrid thresholding on every frame: it is markedly
|
||||||
val center = LockRect.centeredSearch(image.width, image.height, 0.82f)
|
// more tolerant of monitor glare, PWM bands and uneven exposure.
|
||||||
|
val center = LockRect.centeredSearch(image.width, image.height, 0.92f)
|
||||||
val centered = grayBuffer.capture(image, center)
|
val centered = grayBuffer.capture(image, center)
|
||||||
decodeDense(centered, hybrid = false)?.let { result ->
|
decodeDense(centered, hybrid = true)?.let { result ->
|
||||||
updatePairRegion(result, centered)
|
updatePairRegion(result, centered)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
if (frameCounter % 3L == 0L) {
|
// Global thresholding remains a cheap fallback for very clean displays,
|
||||||
decodeDense(centered, hybrid = true)?.let { result ->
|
// but no longer delays the robust path until the third camera frame.
|
||||||
|
if (frameCounter % 2L == 0L) {
|
||||||
|
decodeDense(centered, hybrid = false)?.let { result ->
|
||||||
updatePairRegion(result, centered)
|
updatePairRegion(result, centered)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (frameCounter % 4L == 0L) {
|
if (frameCounter % 3L == 0L) {
|
||||||
val full = grayBuffer.capture(image)
|
val full = grayBuffer.capture(image)
|
||||||
decodeDense(full, hybrid = false)?.let { result ->
|
decodeDense(full, hybrid = true)?.let { result ->
|
||||||
updatePairRegion(result, full)
|
updatePairRegion(result, full)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.qft.optical
|
||||||
|
|
||||||
|
/** Move one item while preserving every other item's relative order. */
|
||||||
|
internal fun <T> moveQueueItem(items: MutableList<T>, from: Int, to: Int): Boolean {
|
||||||
|
if (from !in items.indices || to !in items.indices || from == to) return false
|
||||||
|
items.add(to, items.removeAt(from))
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -30,17 +30,44 @@ data class SelectedFile(
|
|||||||
val uploadKey: String = UUID.randomUUID().toString(),
|
val uploadKey: String = UUID.randomUUID().toString(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wait for completed probes, rather than counting empty queue polls as failed
|
||||||
|
* addresses. This matters immediately after joining QFT Direct: the first ARP
|
||||||
|
* and Windows firewall transition can take longer than a short poll slice even
|
||||||
|
* though the authenticated HTTP request is already reaching the desktop.
|
||||||
|
*/
|
||||||
|
internal fun <T> awaitFirstNonNull(
|
||||||
|
completion: ExecutorCompletionService<T?>,
|
||||||
|
submitted: Int,
|
||||||
|
timeoutMs: Long,
|
||||||
|
): T? {
|
||||||
|
val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs.coerceAtLeast(0L))
|
||||||
|
var completed = 0
|
||||||
|
while (completed < submitted) {
|
||||||
|
val remainingNanos = deadline - System.nanoTime()
|
||||||
|
if (remainingNanos <= 0L) return null
|
||||||
|
val future = completion.poll(remainingNanos, TimeUnit.NANOSECONDS) ?: return null
|
||||||
|
completed += 1
|
||||||
|
try {
|
||||||
|
future.get()?.let { return it }
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// One broken address must not discard successful probes still queued.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun directDiscoveryRequest(session: String, deviceName: String): ByteArray =
|
||||||
|
"QFTDISC2:$session:${Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8))}"
|
||||||
|
.toByteArray(Charsets.US_ASCII)
|
||||||
|
|
||||||
object UploadClient {
|
object UploadClient {
|
||||||
private const val TAG = "QftUpload"
|
private const val TAG = "QftUpload"
|
||||||
private const val DISCOVERY_PORT = 39392
|
private const val DISCOVERY_PORT = 39392
|
||||||
private const val CHUNK_SMALL = 4L * 1024L * 1024L
|
|
||||||
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
|
|
||||||
private const val CHUNK_LARGE = 16L * 1024L * 1024L
|
|
||||||
private const val MAX_WORKERS = 8
|
private const val MAX_WORKERS = 8
|
||||||
|
private const val MIN_PARALLEL_CHUNK = 64L * 1024L
|
||||||
|
private const val MAX_PARALLEL_CHUNK = 16L * 1024L * 1024L
|
||||||
private const val STREAM_BUFFER = 1024 * 1024
|
private const val STREAM_BUFFER = 1024 * 1024
|
||||||
// A single request is materially more reliable for small files on Wi-Fi
|
|
||||||
// Direct, and a 4 MiB parallel chunk gives no throughput benefit there.
|
|
||||||
private const val PARALLEL_MIN_FILE_SIZE = 32L * 1024L * 1024L
|
|
||||||
// QFT Direct can briefly reset a TCP flow while the Android network route
|
// QFT Direct can briefly reset a TCP flow while the Android network route
|
||||||
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
|
// settles. Chunk PUTs and the init/finish control calls are safe to retry;
|
||||||
// the Windows receiver treats a repeated chunk as an idempotent success.
|
// the Windows receiver treats a repeated chunk as an idempotent success.
|
||||||
@@ -73,6 +100,7 @@ object UploadClient {
|
|||||||
network: Network?,
|
network: Network?,
|
||||||
pairing: PairingPayload,
|
pairing: PairingPayload,
|
||||||
hosts: List<InetAddress>,
|
hosts: List<InetAddress>,
|
||||||
|
deviceName: String,
|
||||||
): String? {
|
): String? {
|
||||||
if (hosts.isEmpty()) return null
|
if (hosts.isEmpty()) return null
|
||||||
val socket = DatagramSocket()
|
val socket = DatagramSocket()
|
||||||
@@ -80,7 +108,7 @@ object UploadClient {
|
|||||||
network?.bindSocket(socket)
|
network?.bindSocket(socket)
|
||||||
socket.broadcast = true
|
socket.broadcast = true
|
||||||
socket.soTimeout = 160
|
socket.soTimeout = 160
|
||||||
val request = "QFTDISC2:${pairing.session}".toByteArray(Charsets.US_ASCII)
|
val request = directDiscoveryRequest(pairing.session, deviceName)
|
||||||
// Two directed/broadcast bursts fit within the initial routing
|
// Two directed/broadcast bursts fit within the initial routing
|
||||||
// window while keeping service discovery below 600 ms.
|
// window while keeping service discovery below 600 ms.
|
||||||
repeat(2) {
|
repeat(2) {
|
||||||
@@ -121,18 +149,49 @@ object UploadClient {
|
|||||||
discoveredEndpoint: String? = null,
|
discoveredEndpoint: String? = null,
|
||||||
subnetEndpoints: List<String> = emptyList(),
|
subnetEndpoints: List<String> = emptyList(),
|
||||||
): String? {
|
): String? {
|
||||||
val common = listOf(
|
val dedicatedWifi = pairing.wifi != null
|
||||||
"http://192.168.137.1:${pairing.port}",
|
// Direct mode must use only facts obtained from the dedicated Network:
|
||||||
"http://192.168.49.1:${pairing.port}",
|
// its actual gateway and an authenticated UDP reply. Never inject LAN,
|
||||||
|
// VPN or guessed Windows ICS addresses into this candidate list.
|
||||||
|
val fast = EndpointRouting.forRecovery(
|
||||||
|
dedicatedWifi = dedicatedWifi,
|
||||||
|
discoveredEndpoint = discoveredEndpoint,
|
||||||
|
gatewayEndpoints = preferredEndpoints,
|
||||||
|
advertisedEndpoints = pairing.endpoints,
|
||||||
)
|
)
|
||||||
val fast = (listOfNotNull(discoveredEndpoint) + preferredEndpoints + pairing.endpoints + common)
|
|
||||||
.map { it.trim().removeSuffix("/") }
|
.map { it.trim().removeSuffix("/") }
|
||||||
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
||||||
.distinct()
|
.distinct()
|
||||||
|
|
||||||
// Stage 1: QR-carried endpoints and actual gateway. This is the normal
|
val scan = subnetEndpoints
|
||||||
// path and must complete well inside the 10-second pairing budget.
|
.map { it.trim().removeSuffix("/") }
|
||||||
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 1_050
|
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
||||||
|
.filterNot { it in fast }
|
||||||
|
.distinct()
|
||||||
|
|
||||||
|
if (dedicatedWifi) {
|
||||||
|
// The group-owner route may remain absent on some Huawei/Windows
|
||||||
|
// combinations even though DHCP already supplied a usable /24.
|
||||||
|
// Probe gateway and the real connected subnet together, repeating
|
||||||
|
// while Windows finishes accepting the Wi-Fi Direct peer.
|
||||||
|
val candidates = (fast + scan).distinct()
|
||||||
|
val deadline = android.os.SystemClock.elapsedRealtime() + 6_000L
|
||||||
|
while (candidates.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
|
||||||
|
probeCandidatesParallel(
|
||||||
|
network, pairing, deviceName, candidates,
|
||||||
|
workers = 48, connectMs = 180, readMs = 220,
|
||||||
|
)?.let { return it }
|
||||||
|
try { Thread.sleep(80) } catch (_: InterruptedException) { return null }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Give a newly associated Direct network enough time for ARP, the group
|
||||||
|
// owner route and Windows' new-network firewall profile to settle. A
|
||||||
|
// successful candidate still returns immediately, so this extends only
|
||||||
|
// the failure/recovery path.
|
||||||
|
val fastWindowMs = 1_050L
|
||||||
|
val fastDeadline = android.os.SystemClock.elapsedRealtime() + fastWindowMs
|
||||||
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
|
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
|
||||||
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260)
|
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 220, readMs = 260)
|
||||||
?.let { return it }
|
?.let { return it }
|
||||||
@@ -142,19 +201,14 @@ object UploadClient {
|
|||||||
// Stage 2: actual connected subnet fallback. This specifically fixes the
|
// Stage 2: actual connected subnet fallback. This specifically fixes the
|
||||||
// case where Windows Wi-Fi Direct is up but uses an unexpected gateway
|
// case where Windows Wi-Fi Direct is up but uses an unexpected gateway
|
||||||
// address. Up to /24 is scanned concurrently and still session-authenticated.
|
// address. Up to /24 is scanned concurrently and still session-authenticated.
|
||||||
val scan = subnetEndpoints
|
|
||||||
.map { it.trim().removeSuffix("/") }
|
|
||||||
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
|
|
||||||
.filterNot { it in fast }
|
|
||||||
.distinct()
|
|
||||||
if (scan.isNotEmpty()) {
|
if (scan.isNotEmpty()) {
|
||||||
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 48, connectMs = 180, readMs = 220)
|
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 48, connectMs = 180, readMs = 220)
|
||||||
?.let { return it }
|
?.let { return it }
|
||||||
}
|
}
|
||||||
|
|
||||||
// One short final pass covers a just-finished ARP/Windows firewall
|
// One final pass covers a route/firewall transition that completed while
|
||||||
// transition without adding the former two-second tail latency.
|
// the actual connected subnet fallback was running.
|
||||||
val deadline = android.os.SystemClock.elapsedRealtime() + 500
|
val deadline = android.os.SystemClock.elapsedRealtime() + 500L
|
||||||
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
|
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
|
||||||
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260)
|
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 12, connectMs = 240, readMs = 260)
|
||||||
?.let { return it }
|
?.let { return it }
|
||||||
@@ -163,6 +217,50 @@ object UploadClient {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在指定网络(`network` 为 null 表示系统默认网络)上并发探测一组地址,
|
||||||
|
* 返回第一个应答的。
|
||||||
|
*
|
||||||
|
* Direct 模式只传入专用网络的实际网关;当前局域网备用模式传入经过
|
||||||
|
* 同网段过滤的二维码地址。调用方必须显式绑定对应的 Network。
|
||||||
|
*/
|
||||||
|
fun probeEndpoints(
|
||||||
|
network: Network?,
|
||||||
|
pairing: PairingPayload,
|
||||||
|
deviceName: String,
|
||||||
|
endpoints: List<String>,
|
||||||
|
connectMs: Int,
|
||||||
|
readMs: Int,
|
||||||
|
): String? = probeCandidatesParallel(
|
||||||
|
network = network,
|
||||||
|
pairing = pairing,
|
||||||
|
deviceName = deviceName,
|
||||||
|
candidates = endpoints,
|
||||||
|
workers = endpoints.size.coerceAtMost(8).coerceAtLeast(1),
|
||||||
|
connectMs = connectMs,
|
||||||
|
readMs = readMs,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dedicated Wi-Fi fast path. The Windows group owner is normally the first
|
||||||
|
* host in the actual connected subnet, so scan it immediately instead of
|
||||||
|
* waiting several seconds for Android to publish a default gateway route.
|
||||||
|
*/
|
||||||
|
fun probeConnectedNetwork(
|
||||||
|
network: Network?,
|
||||||
|
pairing: PairingPayload,
|
||||||
|
deviceName: String,
|
||||||
|
endpoints: List<String>,
|
||||||
|
): String? = probeCandidatesParallel(
|
||||||
|
network = network,
|
||||||
|
pairing = pairing,
|
||||||
|
deviceName = deviceName,
|
||||||
|
candidates = endpoints.distinct(),
|
||||||
|
workers = 48,
|
||||||
|
connectMs = 180,
|
||||||
|
readMs = 220,
|
||||||
|
)
|
||||||
|
|
||||||
private fun probeCandidatesParallel(
|
private fun probeCandidatesParallel(
|
||||||
network: Network?,
|
network: Network?,
|
||||||
pairing: PairingPayload,
|
pairing: PairingPayload,
|
||||||
@@ -183,15 +281,11 @@ object UploadClient {
|
|||||||
return try {
|
return try {
|
||||||
val overallMs = (connectMs + readMs + 150).toLong() *
|
val overallMs = (connectMs + readMs + 150).toLong() *
|
||||||
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
|
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
|
||||||
val deadline = android.os.SystemClock.elapsedRealtime() + overallMs.coerceAtMost(2_400L)
|
awaitFirstNonNull(
|
||||||
repeat(candidates.size) {
|
completion = completion,
|
||||||
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
|
submitted = candidates.size,
|
||||||
if (remaining <= 0) return null
|
timeoutMs = overallMs.coerceAtMost(2_400L),
|
||||||
val future = completion.poll(remaining.coerceAtMost(350L), TimeUnit.MILLISECONDS) ?: return@repeat
|
)
|
||||||
val result = future.get()
|
|
||||||
if (result != null) return result
|
|
||||||
}
|
|
||||||
null
|
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
} finally {
|
} finally {
|
||||||
@@ -230,10 +324,7 @@ object UploadClient {
|
|||||||
abortReason: () -> String? = { null },
|
abortReason: () -> String? = { null },
|
||||||
onProgress: (sent: Long, total: Long) -> Unit,
|
onProgress: (sent: Long, total: Long) -> Unit,
|
||||||
) {
|
) {
|
||||||
if (pairing.version >= 2 && file.size >= PARALLEL_MIN_FILE_SIZE) {
|
if (pairing.version >= 2 && isSeekable(resolver, file)) {
|
||||||
require(isSeekable(resolver, file)) {
|
|
||||||
"大文件必须使用可随机读取的本地文件才能并行直传;请先把云盘文件下载到手机本地后再选择"
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
uploadParallel(resolver, networkProvider, baseUrl, pairing, deviceName, file, abortReason, onProgress)
|
uploadParallel(resolver, networkProvider, baseUrl, pairing, deviceName, file, abortReason, onProgress)
|
||||||
return
|
return
|
||||||
@@ -247,7 +338,7 @@ object UploadClient {
|
|||||||
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
|
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Log.i(TAG, "using single-stream upload: size=${file.size}, endpoint=$baseUrl")
|
Log.i(TAG, "using compatibility single-stream upload: size=${file.size}, endpoint=$baseUrl")
|
||||||
uploadLegacy(resolver, networkProvider(), baseUrl, pairing, deviceName, file, abortReason, onProgress)
|
uploadLegacy(resolver, networkProvider(), baseUrl, pairing, deviceName, file, abortReason, onProgress)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -374,10 +465,13 @@ object UploadClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private fun desiredChunkSize(fileSize: Long): Long = when {
|
private fun desiredChunkSize(fileSize: Long): Long {
|
||||||
fileSize < 32L * 1024L * 1024L -> CHUNK_SMALL
|
if (fileSize <= 0L) return MIN_PARALLEL_CHUNK
|
||||||
fileSize >= 512L * 1024L * 1024L -> CHUNK_LARGE
|
// Aim for eight independent HTTP flows on every transferable file.
|
||||||
else -> CHUNK_DEFAULT
|
// The floor keeps QR Direct overhead reasonable for tiny files, while
|
||||||
|
// the ceiling protects memory and TCP fairness on very large files.
|
||||||
|
return ((fileSize + MAX_WORKERS - 1) / MAX_WORKERS)
|
||||||
|
.coerceIn(MIN_PARALLEL_CHUNK, MAX_PARALLEL_CHUNK)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun initUpload(
|
private fun initUpload(
|
||||||
|
|||||||
@@ -20,7 +20,11 @@ import java.net.InetAddress
|
|||||||
import java.util.concurrent.atomic.AtomicBoolean
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
class WifiConnector(context: Context) {
|
class WifiConnector(context: Context) {
|
||||||
private companion object { const val TAG = "QftWifi" }
|
private companion object {
|
||||||
|
const val TAG = "QftWifi"
|
||||||
|
/** 超过这个时长仍未出结果的配网请求视为卡死,重试时不再复用 */
|
||||||
|
const val REUSE_WINDOW_MS = 20_000L
|
||||||
|
}
|
||||||
private val appContext = context.applicationContext
|
private val appContext = context.applicationContext
|
||||||
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||||
@@ -65,7 +69,13 @@ class WifiConnector(context: Context) {
|
|||||||
|
|
||||||
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
|
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
|
||||||
// 千万不要 unregister 再重新 requestNetwork。
|
// 千万不要 unregister 再重新 requestNetwork。
|
||||||
if (wifi != null && callback != null && pendingSsid == wifi.ssid &&
|
// 复用必须有时间上限。系统偶尔会让一个 WifiNetworkSpecifier 请求
|
||||||
|
// 既不回 onAvailable 也不回 onUnavailable 地一直挂着;若无条件复用,
|
||||||
|
// 用户每次点「重试连接」都只是再等一次那个死掉的请求,表现就是
|
||||||
|
// 「配网越来越慢、几分钟都没反应」。超窗就推倒重来。
|
||||||
|
val reusable = pendingStartedAt > 0L &&
|
||||||
|
SystemClock.elapsedRealtime() - pendingStartedAt < REUSE_WINDOW_MS
|
||||||
|
if (wifi != null && callback != null && pendingSsid == wifi.ssid && reusable &&
|
||||||
pendingTerminal?.get() == false) {
|
pendingTerminal?.get() == false) {
|
||||||
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
|
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
|
||||||
listener = Listener(onStatus, onAvailable, onUnavailable)
|
listener = Listener(onStatus, onAvailable, onUnavailable)
|
||||||
@@ -103,11 +113,22 @@ class WifiConnector(context: Context) {
|
|||||||
@Suppress("MissingPermission")
|
@Suppress("MissingPermission")
|
||||||
private fun connectModern(run: Int, wifi: WifiCredentials) {
|
private fun connectModern(run: Int, wifi: WifiCredentials) {
|
||||||
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
|
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
|
||||||
notifyStatus("正在等待 Android 系统连接确认;确认后本页将继续显示进度")
|
// Ask the radio for a fresh scan immediately before presenting the
|
||||||
|
// NetworkSpecifier chooser. Some OEMs otherwise reuse an old scan cache
|
||||||
|
// and keep showing “searching” even though Windows has just started the
|
||||||
|
// QFT SSID. Android may throttle this call; requestNetwork still runs.
|
||||||
|
try {
|
||||||
|
val scanStarted = wifiManager.startScan()
|
||||||
|
Log.i(TAG, "attempt=$run active scan requested=$scanStarted")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "attempt=$run active scan unavailable: ${e.message}")
|
||||||
|
}
|
||||||
|
notifyStatus("正在刷新 Wi-Fi 列表并连接 ${wifi.ssid}…")
|
||||||
val specifier = try {
|
val specifier = try {
|
||||||
WifiNetworkSpecifier.Builder()
|
WifiNetworkSpecifier.Builder()
|
||||||
.setSsid(wifi.ssid)
|
.setSsid(wifi.ssid)
|
||||||
.setWpa2Passphrase(wifi.passphrase)
|
.setWpa2Passphrase(wifi.passphrase)
|
||||||
|
.setIsHiddenSsid(false)
|
||||||
.build()
|
.build()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
notifyUnavailable("配网参数无效:${e.message}")
|
notifyUnavailable("配网参数无效:${e.message}")
|
||||||
@@ -214,7 +235,7 @@ class WifiConnector(context: Context) {
|
|||||||
|
|
||||||
handler.postDelayed({
|
handler.postDelayed({
|
||||||
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
|
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
|
||||||
}, 8_000)
|
}, 4_000)
|
||||||
handler.postDelayed({
|
handler.postDelayed({
|
||||||
if (pending()) listener?.onStatus?.invoke(
|
if (pending()) listener?.onStatus?.invoke(
|
||||||
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +
|
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +
|
||||||
@@ -306,17 +327,133 @@ class WifiConnector(context: Context) {
|
|||||||
|
|
||||||
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true
|
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true
|
||||||
|
|
||||||
|
fun endpointsOnNetwork(network: Network?, endpoints: List<String>, port: Int): List<String> {
|
||||||
|
if (network == null) return emptyList()
|
||||||
|
val links = connectivity.getLinkProperties(network)?.linkAddresses
|
||||||
|
?.mapNotNull { link ->
|
||||||
|
val address = link.address as? Inet4Address ?: return@mapNotNull null
|
||||||
|
val text = address.hostAddress ?: return@mapNotNull null
|
||||||
|
text to link.prefixLength
|
||||||
|
}
|
||||||
|
.orEmpty()
|
||||||
|
return EndpointRouting.onAnySubnet(endpoints, port, links)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 传输期间持有的 Wi-Fi 高性能锁。
|
||||||
|
*
|
||||||
|
* Android 默认会让 Wi-Fi 芯片在包间隙进入省电休眠,代价是额外的唤醒
|
||||||
|
* 延迟。对于持续大流量传输,这会明显压低吞吐——这是 Android 上最常见
|
||||||
|
* 也最容易被忽略的一项限速。锁只在传输期间持有,结束立即释放。
|
||||||
|
*/
|
||||||
|
private var transferLock: WifiManager.WifiLock? = null
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
fun acquireHighPerfLock() {
|
||||||
|
if (transferLock != null) return
|
||||||
|
val mode = if (Build.VERSION.SDK_INT >= 29) {
|
||||||
|
WifiManager.WIFI_MODE_FULL_LOW_LATENCY
|
||||||
|
} else {
|
||||||
|
WifiManager.WIFI_MODE_FULL_HIGH_PERF
|
||||||
|
}
|
||||||
|
transferLock = try {
|
||||||
|
wifiManager.createWifiLock(mode, "qft:transfer").apply {
|
||||||
|
setReferenceCounted(false)
|
||||||
|
acquire()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "无法获取 Wi-Fi 高性能锁:${e.message}")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun releaseHighPerfLock() {
|
||||||
|
try { transferLock?.takeIf { it.isHeld }?.release() } catch (_: Exception) {}
|
||||||
|
transferLock = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前 Wi-Fi 链路的协商速率与信号强度。
|
||||||
|
*
|
||||||
|
* 判断"传输慢"到底是软件问题还是链路本身的上限,这两个数字是唯一
|
||||||
|
* 依据:协商 866 Mbps 却只跑到 136 Mbps 说明有优化空间;
|
||||||
|
* 协商本来就只有 150 Mbps 就已经接近满速,改代码也没用。
|
||||||
|
*/
|
||||||
|
@Suppress("DEPRECATION", "MissingPermission")
|
||||||
|
fun describeLink(): String = try {
|
||||||
|
val info = wifiManager.connectionInfo
|
||||||
|
if (info == null || info.linkSpeed <= 0) {
|
||||||
|
"链路信息不可用"
|
||||||
|
} else {
|
||||||
|
val band = if (Build.VERSION.SDK_INT >= 21 && info.frequency >= 4900) "5GHz" else "2.4GHz"
|
||||||
|
"链路 ${info.linkSpeed} Mbps · $band · 信号 ${info.rssi} dBm"
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"链路信息读取失败:${e.message}"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前网络的自述:本机地址/掩码、网关、SSID。
|
||||||
|
*
|
||||||
|
* 「找不到接收服务」是最难远程排查的一类失败——光看这句话,无法区分
|
||||||
|
* 手机在哪个网段、有没有拿到网关、还是对端真的没开。把这些直接写进
|
||||||
|
* 报错里,用户截个图就能定位,不必再来回猜。
|
||||||
|
*/
|
||||||
|
fun describeNetwork(network: Network?): String {
|
||||||
|
if (network == null) return "未绑定到任何网络"
|
||||||
|
val props = connectivity.getLinkProperties(network)
|
||||||
|
?: return "已连接,但系统尚未提供链路信息"
|
||||||
|
val addresses = props.linkAddresses
|
||||||
|
.filter { it.address is Inet4Address }
|
||||||
|
.joinToString("、") { "${it.address.hostAddress}/${it.prefixLength}" }
|
||||||
|
.ifEmpty { "(尚未取得 IPv4)" }
|
||||||
|
val gateways = props.routes
|
||||||
|
.mapNotNull { (it.gateway as? Inet4Address)?.hostAddress }
|
||||||
|
.distinct()
|
||||||
|
.joinToString("、")
|
||||||
|
.ifEmpty { "(无)" }
|
||||||
|
@Suppress("DEPRECATION", "MissingPermission")
|
||||||
|
val ssid = try {
|
||||||
|
normalizeSsid(wifiManager.connectionInfo?.ssid).takeIf { it.isNotBlank() && it != "<unknown ssid>" }
|
||||||
|
} catch (_: Exception) { null } ?: "未知"
|
||||||
|
return "本机 $addresses · 网关 $gateways · Wi-Fi $ssid"
|
||||||
|
}
|
||||||
|
|
||||||
fun gatewayEndpoints(network: Network?, port: Int): List<String> {
|
fun gatewayEndpoints(network: Network?, port: Int): List<String> {
|
||||||
if (network == null) return emptyList()
|
if (network == null) return emptyList()
|
||||||
val props = connectivity.getLinkProperties(network) ?: return emptyList()
|
val props = connectivity.getLinkProperties(network) ?: return emptyList()
|
||||||
return props.routes
|
return props.routes
|
||||||
.asSequence()
|
.asSequence()
|
||||||
.mapNotNull { it.gateway as? Inet4Address }
|
.mapNotNull { it.gateway as? Inet4Address }
|
||||||
|
// 默认路由的网关可能是 0.0.0.0(直连链路,无下一跳),
|
||||||
|
// 回环和组播地址也不可能是对端。全都探测一遍纯属浪费时间,
|
||||||
|
// 而且会把真正的候选挤到后面。
|
||||||
|
.filterNot { it.isAnyLocalAddress || it.isLoopbackAddress || it.isMulticastAddress }
|
||||||
.map { "http://${it.hostAddress}:$port" }
|
.map { "http://${it.hostAddress}:$port" }
|
||||||
.distinct()
|
.distinct()
|
||||||
.toList()
|
.toList()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WifiNetworkSpecifier may report IPv4 a few callbacks before DHCP routes
|
||||||
|
* include the group-owner gateway. Wait on the transfer worker for the route
|
||||||
|
* belonging to this exact Network instead of guessing Windows ICS ranges.
|
||||||
|
*/
|
||||||
|
fun awaitGatewayEndpoints(network: Network?, port: Int, timeoutMs: Long): List<String> {
|
||||||
|
val deadline = SystemClock.elapsedRealtime() + timeoutMs.coerceAtLeast(0L)
|
||||||
|
do {
|
||||||
|
gatewayEndpoints(network, port).takeIf { it.isNotEmpty() }?.let { return it }
|
||||||
|
if (SystemClock.elapsedRealtime() >= deadline || Thread.currentThread().isInterrupted) break
|
||||||
|
try {
|
||||||
|
Thread.sleep(100)
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} while (true)
|
||||||
|
return gatewayEndpoints(network, port)
|
||||||
|
}
|
||||||
|
|
||||||
fun discoveryHosts(network: Network?): List<InetAddress> {
|
fun discoveryHosts(network: Network?): List<InetAddress> {
|
||||||
val out = mutableListOf<InetAddress>()
|
val out = mutableListOf<InetAddress>()
|
||||||
if (network != null) {
|
if (network != null) {
|
||||||
|
|||||||
@@ -4,9 +4,138 @@ import org.junit.Assert.*
|
|||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import java.nio.ByteBuffer
|
import java.nio.ByteBuffer
|
||||||
import java.nio.ByteOrder
|
import java.nio.ByteOrder
|
||||||
|
import java.util.concurrent.Callable
|
||||||
|
import java.util.concurrent.ExecutorCompletionService
|
||||||
|
import java.util.concurrent.Executors
|
||||||
import java.util.zip.CRC32
|
import java.util.zip.CRC32
|
||||||
|
|
||||||
class ProtocolTest {
|
class ProtocolTest {
|
||||||
|
@Test
|
||||||
|
fun directDiscoveryCarriesTheAndroidDeviceName() {
|
||||||
|
val request = directDiscoveryRequest(
|
||||||
|
session = "abcdefghijklmnopqrstuvwxyz012345",
|
||||||
|
deviceName = "HUAWEI CDY-AN90",
|
||||||
|
).toString(Charsets.US_ASCII)
|
||||||
|
val encoded = request.substringAfterLast(':')
|
||||||
|
|
||||||
|
assertTrue(request.startsWith("QFTDISC2:abcdefghijklmnopqrstuvwxyz012345:"))
|
||||||
|
assertEquals("HUAWEI CDY-AN90", Base64Url.decode(encoded)?.toString(Charsets.UTF_8))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun dedicatedWifiNeverProbesQrOrComputerLanAddresses() {
|
||||||
|
assertEquals(
|
||||||
|
listOf("http://192.168.137.1:39393"),
|
||||||
|
EndpointRouting.afterConnection(
|
||||||
|
dedicatedWifi = true,
|
||||||
|
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
|
||||||
|
routedAdvertisedEndpoints = listOf(
|
||||||
|
"http://192.168.8.162:39393",
|
||||||
|
"http://192.168.49.1:39393",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun dedicatedWifiRecoveryStillRejectsAdvertisedAndGuessedAddresses() {
|
||||||
|
assertEquals(
|
||||||
|
listOf("http://192.168.137.1:39393"),
|
||||||
|
EndpointRouting.forRecovery(
|
||||||
|
dedicatedWifi = true,
|
||||||
|
discoveredEndpoint = null,
|
||||||
|
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
|
||||||
|
advertisedEndpoints = listOf(
|
||||||
|
"http://192.168.8.162:39393",
|
||||||
|
"http://192.168.49.1:39393",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun currentLanModeCanUseSameSubnetAdvertisedAddresses() {
|
||||||
|
assertEquals(
|
||||||
|
listOf("http://192.168.8.1:39393", "http://192.168.8.162:39393"),
|
||||||
|
EndpointRouting.afterConnection(
|
||||||
|
dedicatedWifi = false,
|
||||||
|
gatewayEndpoints = listOf("http://192.168.8.1:39393"),
|
||||||
|
routedAdvertisedEndpoints = listOf("http://192.168.8.162:39393"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun probeCompletionWaitsForARealResultInsteadOfConsumingAnEmptyPoll() {
|
||||||
|
val pool = Executors.newSingleThreadExecutor()
|
||||||
|
try {
|
||||||
|
val completion = ExecutorCompletionService<String?>(pool)
|
||||||
|
completion.submit(Callable {
|
||||||
|
Thread.sleep(380)
|
||||||
|
"http://192.168.137.1:39393"
|
||||||
|
})
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"http://192.168.137.1:39393",
|
||||||
|
awaitFirstNonNull(completion, submitted = 1, timeoutMs = 800),
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
pool.shutdownNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun probeCompletionKeepsWaitingAfterAnEarlierAddressFails() {
|
||||||
|
val pool = Executors.newFixedThreadPool(2)
|
||||||
|
try {
|
||||||
|
val completion = ExecutorCompletionService<String?>(pool)
|
||||||
|
completion.submit(Callable { null })
|
||||||
|
completion.submit(Callable {
|
||||||
|
Thread.sleep(30)
|
||||||
|
"http://192.168.137.1:39393"
|
||||||
|
})
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"http://192.168.137.1:39393",
|
||||||
|
awaitFirstNonNull(completion, submitted = 2, timeoutMs = 500),
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
pool.shutdownNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun routeCandidatesOnlyKeepEndpointsOnTheActiveSubnet() {
|
||||||
|
val endpoints = listOf(
|
||||||
|
"http://192.168.137.1:39393",
|
||||||
|
"http://192.168.49.1:39393",
|
||||||
|
"http://192.168.1.20:39393",
|
||||||
|
"http://10.20.30.40:39393",
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
listOf("http://192.168.1.20:39393"),
|
||||||
|
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf("http://10.20.30.40:39393"),
|
||||||
|
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("10.20.99.2" to 16)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun routeCandidatesRejectWrongPortsAndMalformedAddresses() {
|
||||||
|
val endpoints = listOf(
|
||||||
|
"http://192.168.1.20:39394",
|
||||||
|
"http://192.168.1.999:39393",
|
||||||
|
"http://192.168.1.30:39393",
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
listOf("http://192.168.1.30:39393"),
|
||||||
|
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun parsesPcToPhoneAutomaticDownloadPairing() {
|
fun parsesPcToPhoneAutomaticDownloadPairing() {
|
||||||
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":["http://192.168.49.1:39393"],"d":"d","f":"sample.bin","z":42,"h":"${"00".repeat(32)}"}"""
|
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":["http://192.168.49.1:39393"],"d":"d","f":"sample.bin","z":42,"h":"${"00".repeat(32)}"}"""
|
||||||
@@ -17,6 +146,18 @@ class ProtocolTest {
|
|||||||
assertEquals(42L, payload.fileSize)
|
assertEquals(42L, payload.fileSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun parsesDedicatedWifiPairingWithoutAdvertisedComputerAddresses() {
|
||||||
|
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":[],"w":["QFT-DESKTOP-abc123","0123456789abcdef"]}"""
|
||||||
|
val payload = PairingProtocol.parse(
|
||||||
|
PairingProtocol.PREFIX_V2 + Base64Url.encode(json.toByteArray()),
|
||||||
|
)!!
|
||||||
|
|
||||||
|
assertNotNull(payload.wifi)
|
||||||
|
assertEquals("QFT-DESKTOP-abc123", payload.wifi?.ssid)
|
||||||
|
assertTrue(payload.endpoints.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun base45KnownVectors() {
|
fun base45KnownVectors() {
|
||||||
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.qft.optical
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class TransferQueueTest {
|
||||||
|
@Test
|
||||||
|
fun movesFilesInBothDirectionsWithoutLosingItems() {
|
||||||
|
val queue = mutableListOf("A", "B", "C", "D")
|
||||||
|
assertTrue(moveQueueItem(queue, 0, 2))
|
||||||
|
assertEquals(listOf("B", "C", "A", "D"), queue)
|
||||||
|
assertTrue(moveQueueItem(queue, 3, 1))
|
||||||
|
assertEquals(listOf("B", "D", "C", "A"), queue)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rejectsInvalidOrNoOpMoves() {
|
||||||
|
val queue = mutableListOf("A", "B")
|
||||||
|
assertFalse(moveQueueItem(queue, -1, 0))
|
||||||
|
assertFalse(moveQueueItem(queue, 0, 2))
|
||||||
|
assertFalse(moveQueueItem(queue, 1, 1))
|
||||||
|
assertEquals(listOf("A", "B"), queue)
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
Binary file not shown.
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.5-bin.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
validateDistributionUrl=true
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
|||||||
Generated
+20
-2
@@ -2586,8 +2586,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "qft-windows"
|
name = "qft-desktop"
|
||||||
version = "0.4.6"
|
version = "0.4.16"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64",
|
||||||
@@ -2601,6 +2601,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
"whoami",
|
||||||
"windows",
|
"windows",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -3471,6 +3472,12 @@ dependencies = [
|
|||||||
"wit-bindgen",
|
"wit-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasite"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen"
|
name = "wasm-bindgen"
|
||||||
version = "0.2.127"
|
version = "0.2.127"
|
||||||
@@ -3881,6 +3888,17 @@ dependencies = [
|
|||||||
"web-sys",
|
"web-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "whoami"
|
||||||
|
version = "1.6.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"
|
||||||
|
dependencies = [
|
||||||
|
"libredox",
|
||||||
|
"wasite",
|
||||||
|
"web-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winapi-util"
|
name = "winapi-util"
|
||||||
version = "0.1.11"
|
version = "0.1.11"
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "qft-windows"
|
name = "qft-desktop"
|
||||||
version = "0.4.6"
|
version = "0.4.16"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.95"
|
rust-version = "1.95"
|
||||||
|
|
||||||
@@ -17,9 +17,13 @@ serde = { version = "1.0.219", features = ["derive"] }
|
|||||||
serde_json = "1.0.143"
|
serde_json = "1.0.143"
|
||||||
if-addrs = "0.13.4"
|
if-addrs = "0.13.4"
|
||||||
rayon = "1.11.0"
|
rayon = "1.11.0"
|
||||||
|
# 跨平台取本机名:macOS 上 HOSTNAME 环境变量通常不存在,
|
||||||
|
# Linux 上默认也不导出,只靠 env 会退化成占位名。
|
||||||
|
whoami = "1.6"
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
windows = { version = "0.62.2", features = [
|
windows = { version = "0.62.2", features = [
|
||||||
|
"Devices_Enumeration",
|
||||||
"Devices_WiFiDirect",
|
"Devices_WiFiDirect",
|
||||||
"Security_Credentials",
|
"Security_Credentials",
|
||||||
] }
|
] }
|
||||||
@@ -0,0 +1,798 @@
|
|||||||
|
//! 桌面端的**发起侧**。
|
||||||
|
//!
|
||||||
|
//! v0.4.7 之前桌面端只有服务端(`receiver.rs` / `sender.rs`),
|
||||||
|
//! `TcpStream::connect` 只出现在测试里,因此 PC 无法主动连接另一台 PC。
|
||||||
|
//! 本模块补上这一半,PC↔PC 才成立。
|
||||||
|
//!
|
||||||
|
//! 线格式与 Android `UploadClient.kt`/`DownloadClient.kt`、
|
||||||
|
//! iOS `UploadClient.swift`/`DownloadClient.swift` 完全一致——沿用现有 v2 HTTP,
|
||||||
|
//! 不引入 HTTP 客户端依赖:服务端本来就是手写的,两边保持同一套解析更容易对齐。
|
||||||
|
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
fs::{File, OpenOptions},
|
||||||
|
io::{BufRead, BufReader, Read, Seek, SeekFrom, Write},
|
||||||
|
net::{SocketAddr, TcpStream, ToSocketAddrs},
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::{
|
||||||
|
atomic::{AtomicU32, AtomicU64, Ordering},
|
||||||
|
Arc,
|
||||||
|
},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
const IO_BUFFER: usize = 1024 * 1024;
|
||||||
|
/// 与移动端一致:按文件大小自适应 4/8/16 MiB
|
||||||
|
const CHUNK_SMALL: u64 = 4 * 1024 * 1024;
|
||||||
|
const CHUNK_DEFAULT: u64 = 8 * 1024 * 1024;
|
||||||
|
const CHUNK_LARGE: u64 = 16 * 1024 * 1024;
|
||||||
|
const MAX_WORKERS: usize = 8;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct PeerClient {
|
||||||
|
/// 形如 `http://192.168.1.20:39393`
|
||||||
|
pub base_url: String,
|
||||||
|
pub token: String,
|
||||||
|
pub device_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Progress {
|
||||||
|
pub done: u64,
|
||||||
|
/// 单个文件的总量。多文件发送时 UI 用的是跨文件的累计总量,
|
||||||
|
/// 因此当前没有读者;保留是为了让回调本身自洽,
|
||||||
|
/// 单文件场景(如 P2 的目录传输逐项进度)会用到。
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub total: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PeerClient {
|
||||||
|
pub fn new(base_url: impl Into<String>, token: impl Into<String>, device_name: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
base_url: base_url.into(),
|
||||||
|
token: token.into(),
|
||||||
|
device_name: device_name.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn address(&self) -> Result<SocketAddr> {
|
||||||
|
let rest = self
|
||||||
|
.base_url
|
||||||
|
.strip_prefix("http://")
|
||||||
|
.context("端点必须以 http:// 开头")?;
|
||||||
|
let rest = rest.trim_end_matches('/');
|
||||||
|
if rest.contains('/') {
|
||||||
|
bail!("端点不允许带路径:{}", self.base_url)
|
||||||
|
}
|
||||||
|
rest.to_socket_addrs()
|
||||||
|
.with_context(|| format!("无法解析端点 {}", self.base_url))?
|
||||||
|
.next()
|
||||||
|
.with_context(|| format!("端点无可用地址 {}", self.base_url))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auth_headers(&self) -> Vec<(String, String)> {
|
||||||
|
vec![
|
||||||
|
("X-QFT-Token".into(), self.token.clone()),
|
||||||
|
(
|
||||||
|
"X-QFT-Device".into(),
|
||||||
|
URL_SAFE_NO_PAD.encode(self.device_name.as_bytes()),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /qft/ping`。用于发现阶段快速验证「这个地址上确实是我要找的那台 QFT」。
|
||||||
|
// 供 P1.5 的发现流程与后续的可达性诊断使用,当前 UI 尚未接线
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn ping(&self, timeout: Duration) -> Result<serde_json::Value> {
|
||||||
|
let address = self.address()?;
|
||||||
|
let mut response = send_request(address, "GET", "/qft/ping", &self.auth_headers(), None, timeout)?;
|
||||||
|
if response.status != 200 {
|
||||||
|
bail!("ping 返回 HTTP {}", response.status)
|
||||||
|
}
|
||||||
|
let body = response.read_body()?;
|
||||||
|
serde_json::from_slice(&body).context("ping 响应不是 JSON")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /qft/pair`:用 6 位配对码换取会话令牌。
|
||||||
|
///
|
||||||
|
/// PC↔PC 的入口——桌面端没有摄像头,扫不了二维码,
|
||||||
|
/// 只能由用户把对方屏幕上的 6 位数字敲进来。
|
||||||
|
pub fn pair(base_url: &str, code: &str, device_name: &str) -> Result<String> {
|
||||||
|
let probe = PeerClient::new(base_url, String::new(), device_name.to_owned());
|
||||||
|
let address = probe.address()?;
|
||||||
|
let mut headers = vec![
|
||||||
|
("X-QFT-Code".to_string(), code.to_string()),
|
||||||
|
(
|
||||||
|
"X-QFT-Device".to_string(),
|
||||||
|
URL_SAFE_NO_PAD.encode(device_name.as_bytes()),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
headers.push(("Content-Length".to_string(), "0".to_string()));
|
||||||
|
|
||||||
|
let mut response = send_request(
|
||||||
|
address,
|
||||||
|
"POST",
|
||||||
|
"/qft/pair",
|
||||||
|
&headers[..2],
|
||||||
|
Some(&[]),
|
||||||
|
// 配对只是一次极小的请求,4 秒还没建连基本就是不通了。
|
||||||
|
// 拖到 10 秒只会让用户以为程序卡死。
|
||||||
|
Duration::from_secs(4),
|
||||||
|
)?;
|
||||||
|
let body = response.read_body()?;
|
||||||
|
let value: serde_json::Value = serde_json::from_slice(&body).unwrap_or(serde_json::Value::Null);
|
||||||
|
match response.status {
|
||||||
|
200 => value["token"]
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.context("配对响应缺少 token"),
|
||||||
|
403 => {
|
||||||
|
let remaining = value["remaining"].as_u64().unwrap_or(0);
|
||||||
|
bail!("配对码错误,还可尝试 {remaining} 次")
|
||||||
|
}
|
||||||
|
429 => bail!("配对码已作废,请让对方在电脑上重新启动接收"),
|
||||||
|
other => bail!("配对返回 HTTP {other}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ 上传
|
||||||
|
|
||||||
|
/// 把本地文件推送到对端的接收服务(对端跑 `receiver.rs`)。
|
||||||
|
pub fn upload_file(
|
||||||
|
&self,
|
||||||
|
path: &Path,
|
||||||
|
mut on_progress: impl FnMut(Progress) + Send,
|
||||||
|
) -> Result<String> {
|
||||||
|
let address = self.address()?;
|
||||||
|
let size = std::fs::metadata(path)
|
||||||
|
.with_context(|| format!("读取 {} 失败", path.display()))?
|
||||||
|
.len();
|
||||||
|
let name = path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|v| v.to_str())
|
||||||
|
.filter(|v| !v.is_empty())
|
||||||
|
.unwrap_or("qft-upload.bin");
|
||||||
|
|
||||||
|
let session = self.init_upload(address, name, size)?;
|
||||||
|
if session.total_chunks == 0 {
|
||||||
|
on_progress(Progress { done: 0, total: 0 });
|
||||||
|
return self.finish_upload(address, &session.upload_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
let next = Arc::new(AtomicU32::new(0));
|
||||||
|
let sent = Arc::new(AtomicU64::new(0));
|
||||||
|
let workers = (session.total_chunks as usize).min(MAX_WORKERS).max(1);
|
||||||
|
|
||||||
|
// 进度回调在主线程汇总:worker 只累加原子计数,避免把 FnMut 塞进多个线程。
|
||||||
|
// 主线程随后在此轮询上报——早先只在 scope 结束后报一次,
|
||||||
|
// 结果传 1 GB 的过程中进度条一直是 0%,最后才跳到 100%。
|
||||||
|
let failure = std::thread::scope(|scope| -> Result<()> {
|
||||||
|
let mut handles = Vec::with_capacity(workers);
|
||||||
|
for _ in 0..workers {
|
||||||
|
let next = next.clone();
|
||||||
|
let sent = sent.clone();
|
||||||
|
let session = &session;
|
||||||
|
handles.push(scope.spawn(move || -> Result<()> {
|
||||||
|
let mut file = File::open(path)?;
|
||||||
|
let mut buffer = vec![0u8; session.chunk_size as usize];
|
||||||
|
loop {
|
||||||
|
let index = next.fetch_add(1, Ordering::Relaxed);
|
||||||
|
if index >= session.total_chunks {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let offset = index as u64 * session.chunk_size;
|
||||||
|
let length = (size - offset).min(session.chunk_size) as usize;
|
||||||
|
file.seek(SeekFrom::Start(offset))?;
|
||||||
|
file.read_exact(&mut buffer[..length])?;
|
||||||
|
self.put_chunk(address, &session.upload_id, index, &buffer[..length], &sent)?;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
// worker 跑着的时候持续上报,不要等它们全部结束
|
||||||
|
while !handles.iter().all(|h| h.is_finished()) {
|
||||||
|
on_progress(Progress {
|
||||||
|
done: sent.load(Ordering::Relaxed).min(size),
|
||||||
|
total: size,
|
||||||
|
});
|
||||||
|
std::thread::sleep(Duration::from_millis(40));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut error = None;
|
||||||
|
for handle in handles {
|
||||||
|
match handle.join() {
|
||||||
|
Ok(Ok(())) => {}
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
error.get_or_insert(e);
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
error.get_or_insert(anyhow::anyhow!("上传线程崩溃"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match error {
|
||||||
|
Some(e) => Err(e),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
failure?;
|
||||||
|
|
||||||
|
on_progress(Progress { done: size, total: size });
|
||||||
|
self.finish_upload(address, &session.upload_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init_upload(&self, address: SocketAddr, name: &str, size: u64) -> Result<UploadSession> {
|
||||||
|
let chunk_size = desired_chunk_size(size);
|
||||||
|
let mut headers = self.auth_headers();
|
||||||
|
headers.push((
|
||||||
|
"X-QFT-Filename".into(),
|
||||||
|
URL_SAFE_NO_PAD.encode(name.as_bytes()),
|
||||||
|
));
|
||||||
|
headers.push(("X-QFT-Size".into(), size.to_string()));
|
||||||
|
headers.push(("X-QFT-Chunk-Size".into(), chunk_size.to_string()));
|
||||||
|
|
||||||
|
let mut response = send_request(
|
||||||
|
address,
|
||||||
|
"POST",
|
||||||
|
"/qft/upload/init",
|
||||||
|
&headers,
|
||||||
|
Some(&[]),
|
||||||
|
Duration::from_secs(15),
|
||||||
|
)?;
|
||||||
|
if response.status != 200 {
|
||||||
|
bail!("init 返回 HTTP {}", response.status)
|
||||||
|
}
|
||||||
|
let body = response.read_body()?;
|
||||||
|
let value: serde_json::Value = serde_json::from_slice(&body).context("init 响应不是 JSON")?;
|
||||||
|
Ok(UploadSession {
|
||||||
|
upload_id: value["upload_id"]
|
||||||
|
.as_str()
|
||||||
|
.context("init 响应缺少 upload_id")?
|
||||||
|
.to_owned(),
|
||||||
|
chunk_size: value["chunk_size"].as_u64().context("init 响应缺少 chunk_size")?,
|
||||||
|
total_chunks: value["total_chunks"]
|
||||||
|
.as_u64()
|
||||||
|
.context("init 响应缺少 total_chunks")? as u32,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_chunk(
|
||||||
|
&self,
|
||||||
|
address: SocketAddr,
|
||||||
|
upload_id: &str,
|
||||||
|
index: u32,
|
||||||
|
body: &[u8],
|
||||||
|
sent: &AtomicU64,
|
||||||
|
) -> Result<()> {
|
||||||
|
let path = format!("/qft/upload/chunk/{upload_id}/{index}");
|
||||||
|
// 接收端对重复分块是幂等的,因此重试安全。
|
||||||
|
// 局域网上首次连接常被 Windows 防火墙首包丢弃,一次重试就能救回来。
|
||||||
|
let mut last = None;
|
||||||
|
for attempt in 0..3 {
|
||||||
|
// 本次尝试写出的字节单独计一份:失败时要从总数里扣回去,
|
||||||
|
// 否则重试会让进度虚高甚至超过 100%
|
||||||
|
let attempted = AtomicU64::new(0);
|
||||||
|
let mut sink = |n: usize| {
|
||||||
|
attempted.fetch_add(n as u64, Ordering::Relaxed);
|
||||||
|
sent.fetch_add(n as u64, Ordering::Relaxed);
|
||||||
|
};
|
||||||
|
let outcome = send_request_with_progress(
|
||||||
|
address,
|
||||||
|
"POST",
|
||||||
|
&path,
|
||||||
|
&self.auth_headers(),
|
||||||
|
Some(body),
|
||||||
|
Duration::from_secs(60),
|
||||||
|
Some(&mut sink),
|
||||||
|
);
|
||||||
|
drop(sink);
|
||||||
|
if outcome.is_err() || outcome.as_ref().is_ok_and(|r| r.status != 200) {
|
||||||
|
sent.fetch_sub(attempted.load(Ordering::Relaxed), Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
match outcome {
|
||||||
|
Ok(mut response) => {
|
||||||
|
let payload = response.read_body()?;
|
||||||
|
if response.status == 200 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
last = Some(anyhow::anyhow!(
|
||||||
|
"chunk {index} 返回 HTTP {}:{}",
|
||||||
|
response.status,
|
||||||
|
String::from_utf8_lossy(&payload[..payload.len().min(200)])
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(e) => last = Some(e),
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(120 << attempt));
|
||||||
|
}
|
||||||
|
Err(last.unwrap_or_else(|| anyhow::anyhow!("chunk {index} 失败")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_upload(&self, address: SocketAddr, upload_id: &str) -> Result<String> {
|
||||||
|
let path = format!("/qft/upload/finish/{upload_id}");
|
||||||
|
let mut response = send_request(
|
||||||
|
address,
|
||||||
|
"POST",
|
||||||
|
&path,
|
||||||
|
&self.auth_headers(),
|
||||||
|
Some(&[]),
|
||||||
|
Duration::from_secs(120),
|
||||||
|
)?;
|
||||||
|
let body = response.read_body()?;
|
||||||
|
if response.status != 200 {
|
||||||
|
bail!(
|
||||||
|
"finish 返回 HTTP {}:{}",
|
||||||
|
response.status,
|
||||||
|
String::from_utf8_lossy(&body[..body.len().min(200)])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
let value: serde_json::Value = serde_json::from_slice(&body).context("finish 响应不是 JSON")?;
|
||||||
|
value["sha256"]
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.context("finish 响应缺少 sha256")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ 下载
|
||||||
|
|
||||||
|
/// 从对端的发送服务拉取文件(对端跑 `sender.rs`)。
|
||||||
|
/// 支持断点续传:`dest` 已存在的部分会作为 Range 起点。
|
||||||
|
// PC↔PC 目前只做「推送」,「主动拉取」在 P2 的会话模型里才用得上
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn download_file(
|
||||||
|
&self,
|
||||||
|
dest: &Path,
|
||||||
|
expected_size: Option<u64>,
|
||||||
|
mut on_progress: impl FnMut(Progress),
|
||||||
|
) -> Result<PathBuf> {
|
||||||
|
let address = self.address()?;
|
||||||
|
let part = dest.with_extension("qftpart");
|
||||||
|
let mut offset = part.metadata().map(|m| m.len()).unwrap_or(0);
|
||||||
|
if let Some(expected) = expected_size {
|
||||||
|
if offset > expected {
|
||||||
|
let _ = std::fs::remove_file(&part);
|
||||||
|
offset = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut headers = self.auth_headers();
|
||||||
|
if offset > 0 {
|
||||||
|
headers.push(("Range".into(), format!("bytes={offset}-")));
|
||||||
|
}
|
||||||
|
let mut response = send_request(
|
||||||
|
address,
|
||||||
|
"GET",
|
||||||
|
"/qft/download",
|
||||||
|
&headers,
|
||||||
|
None,
|
||||||
|
Duration::from_secs(30),
|
||||||
|
)?;
|
||||||
|
if response.status != 200 && response.status != 206 {
|
||||||
|
bail!("下载返回 HTTP {}", response.status)
|
||||||
|
}
|
||||||
|
if response.status == 200 {
|
||||||
|
// 服务端忽略了 Range(旧版本),只能从头写
|
||||||
|
offset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let remaining = response
|
||||||
|
.headers
|
||||||
|
.get("content-length")
|
||||||
|
.and_then(|v| v.parse::<u64>().ok());
|
||||||
|
let total = expected_size.or_else(|| remaining.map(|r| offset + r)).unwrap_or(0);
|
||||||
|
|
||||||
|
if let Some(parent) = part.parent() {
|
||||||
|
platform_ensure_dir(parent)?;
|
||||||
|
}
|
||||||
|
let mut out = OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.write(true)
|
||||||
|
.open(&part)
|
||||||
|
.with_context(|| format!("创建 {} 失败", part.display()))?;
|
||||||
|
out.seek(SeekFrom::Start(offset))?;
|
||||||
|
out.set_len(offset)?;
|
||||||
|
|
||||||
|
let mut done = offset;
|
||||||
|
let mut buffer = vec![0u8; IO_BUFFER];
|
||||||
|
loop {
|
||||||
|
let n = response.reader.read(&mut buffer)?;
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out.write_all(&buffer[..n])?;
|
||||||
|
done += n as u64;
|
||||||
|
on_progress(Progress { done, total });
|
||||||
|
}
|
||||||
|
out.flush()?;
|
||||||
|
drop(out);
|
||||||
|
|
||||||
|
if let Some(expected) = expected_size {
|
||||||
|
if done != expected {
|
||||||
|
bail!("下载提前结束:{done}/{expected}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::fs::rename(&part, dest)
|
||||||
|
.with_context(|| format!("重命名 {} 失败", part.display()))?;
|
||||||
|
Ok(dest.to_path_buf())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UploadSession {
|
||||||
|
upload_id: String,
|
||||||
|
chunk_size: u64,
|
||||||
|
total_chunks: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn desired_chunk_size(size: u64) -> u64 {
|
||||||
|
if size < 32 * 1024 * 1024 {
|
||||||
|
CHUNK_SMALL
|
||||||
|
} else if size >= 512 * 1024 * 1024 {
|
||||||
|
CHUNK_LARGE
|
||||||
|
} else {
|
||||||
|
CHUNK_DEFAULT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)] // 仅被尚未接线的 download_file 使用
|
||||||
|
fn platform_ensure_dir(path: &Path) -> Result<()> {
|
||||||
|
crate::platform::ensure_dir(path)
|
||||||
|
.with_context(|| format!("创建目录 {} 失败", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 把底层 io 错误翻译成能指导下一步的说法。
|
||||||
|
///
|
||||||
|
/// 「超时」和「被拒绝」的成因完全不同:前者是包被丢了(防火墙、主机不可达、
|
||||||
|
/// AP 客户端隔离),后者是端口上没人监听(对方没点"启动接收")。
|
||||||
|
/// 给用户一句笼统的"连接失败"等于什么都没说。
|
||||||
|
fn describe_connect_failure(address: SocketAddr, error: &std::io::Error) -> anyhow::Error {
|
||||||
|
use std::io::ErrorKind;
|
||||||
|
let ip = address.ip();
|
||||||
|
match error.kind() {
|
||||||
|
ErrorKind::TimedOut => anyhow::anyhow!(
|
||||||
|
"连接 {address} 超时:数据包发出去了但没有任何回应。\n\
|
||||||
|
常见原因:① 对方电脑的防火墙拦截了入站连接(Windows 上需要放行 qft-desktop.exe 的专用网络);\
|
||||||
|
② Wi-Fi 开了客户端隔离,同网段设备之间不能互通;\
|
||||||
|
③ 对方已经关掉接收或换了网络。"
|
||||||
|
),
|
||||||
|
ErrorKind::ConnectionRefused => anyhow::anyhow!(
|
||||||
|
"{ip} 明确拒绝了连接:主机在线,但 {} 端口上没有程序在监听。\n\
|
||||||
|
请确认对方已经在「我要接收」里点了「启动接收」,并且连接码是最新的那一串。",
|
||||||
|
address.port()
|
||||||
|
),
|
||||||
|
ErrorKind::HostUnreachable | ErrorKind::NetworkUnreachable => anyhow::anyhow!(
|
||||||
|
"路由不可达:本机没有能到达 {ip} 的路由。请确认两台设备连在同一个网络里。"
|
||||||
|
),
|
||||||
|
_ => anyhow::anyhow!("连接 {address} 失败:{error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 极简 HTTP 客户端
|
||||||
|
|
||||||
|
struct HttpResponse {
|
||||||
|
status: u16,
|
||||||
|
headers: HashMap<String, String>,
|
||||||
|
reader: BufReader<TcpStream>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HttpResponse {
|
||||||
|
/// 读完整个响应体。服务端总是发 `Connection: close`,
|
||||||
|
/// 所以按 Content-Length 读,没有该头则读到 EOF。
|
||||||
|
fn read_body(&mut self) -> Result<Vec<u8>> {
|
||||||
|
let mut body = Vec::new();
|
||||||
|
match self.headers.get("content-length").and_then(|v| v.parse::<u64>().ok()) {
|
||||||
|
Some(length) => {
|
||||||
|
body.resize(length as usize, 0);
|
||||||
|
self.reader.read_exact(&mut body)?;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
self.reader.read_to_end(&mut body)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_request(
|
||||||
|
address: SocketAddr,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
headers: &[(String, String)],
|
||||||
|
body: Option<&[u8]>,
|
||||||
|
timeout: Duration,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
|
send_request_with_progress(address, method, path, headers, body, timeout, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `on_body_written` 会在请求体每写出一片后被调用。
|
||||||
|
/// 大文件分块是 16 MiB,若等整块写完才计数,进度条就是一格一格跳的。
|
||||||
|
fn send_request_with_progress(
|
||||||
|
address: SocketAddr,
|
||||||
|
method: &str,
|
||||||
|
path: &str,
|
||||||
|
headers: &[(String, String)],
|
||||||
|
body: Option<&[u8]>,
|
||||||
|
timeout: Duration,
|
||||||
|
mut on_body_written: Option<&mut dyn FnMut(usize)>,
|
||||||
|
) -> Result<HttpResponse> {
|
||||||
|
let stream = TcpStream::connect_timeout(&address, timeout.min(Duration::from_secs(10)))
|
||||||
|
.map_err(|e| describe_connect_failure(address, &e))?;
|
||||||
|
stream.set_nodelay(true).ok();
|
||||||
|
stream.set_read_timeout(Some(timeout))?;
|
||||||
|
stream.set_write_timeout(Some(timeout))?;
|
||||||
|
|
||||||
|
let mut request = String::with_capacity(256);
|
||||||
|
request.push_str(&format!("{method} {path} HTTP/1.1\r\n"));
|
||||||
|
request.push_str(&format!("Host: {address}\r\n"));
|
||||||
|
request.push_str("Connection: close\r\n");
|
||||||
|
for (name, value) in headers {
|
||||||
|
request.push_str(&format!("{name}: {value}\r\n"));
|
||||||
|
}
|
||||||
|
if let Some(body) = body {
|
||||||
|
request.push_str("Content-Type: application/octet-stream\r\n");
|
||||||
|
request.push_str(&format!("Content-Length: {}\r\n", body.len()));
|
||||||
|
}
|
||||||
|
request.push_str("\r\n");
|
||||||
|
|
||||||
|
let mut writer = stream.try_clone()?;
|
||||||
|
writer.write_all(request.as_bytes())?;
|
||||||
|
if let Some(body) = body {
|
||||||
|
// 256 KiB 一片:足够小,进度看起来是连续的;
|
||||||
|
// 又足够大,不会因为频繁 write 拖慢吞吐
|
||||||
|
const SLICE: usize = 256 * 1024;
|
||||||
|
for part in body.chunks(SLICE) {
|
||||||
|
writer.write_all(part)?;
|
||||||
|
if let Some(sink) = on_body_written.as_deref_mut() {
|
||||||
|
sink(part.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writer.flush()?;
|
||||||
|
|
||||||
|
let mut reader = BufReader::with_capacity(64 * 1024, stream);
|
||||||
|
let mut status_line = String::new();
|
||||||
|
reader.read_line(&mut status_line)?;
|
||||||
|
if status_line.is_empty() {
|
||||||
|
bail!("对端在返回状态行前关闭了连接")
|
||||||
|
}
|
||||||
|
let status: u16 = status_line
|
||||||
|
.split_whitespace()
|
||||||
|
.nth(1)
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.with_context(|| format!("无法解析状态行:{}", status_line.trim()))?;
|
||||||
|
|
||||||
|
let mut response_headers = HashMap::new();
|
||||||
|
loop {
|
||||||
|
let mut line = String::new();
|
||||||
|
let n = reader.read_line(&mut line)?;
|
||||||
|
if n == 0 {
|
||||||
|
bail!("对端在返回响应头前关闭了连接")
|
||||||
|
}
|
||||||
|
if line == "\r\n" || line == "\n" {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some((name, value)) = line.split_once(':') {
|
||||||
|
response_headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse {
|
||||||
|
status,
|
||||||
|
headers: response_headers,
|
||||||
|
reader,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_endpoints_with_path_or_wrong_scheme() {
|
||||||
|
let make = |url: &str| PeerClient::new(url, "token", "dev").address();
|
||||||
|
assert!(make("https://192.168.1.1:39393").is_err());
|
||||||
|
assert!(make("http://192.168.1.1:39393/qft").is_err());
|
||||||
|
assert!(make("192.168.1.1:39393").is_err());
|
||||||
|
assert!(make("http://127.0.0.1:39393").is_ok());
|
||||||
|
// 结尾斜杠应被容忍
|
||||||
|
assert!(make("http://127.0.0.1:39393/").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chunk_size_matches_mobile_clients() {
|
||||||
|
assert_eq!(desired_chunk_size(1024), CHUNK_SMALL);
|
||||||
|
assert_eq!(desired_chunk_size(31 * 1024 * 1024), CHUNK_SMALL);
|
||||||
|
assert_eq!(desired_chunk_size(64 * 1024 * 1024), CHUNK_DEFAULT);
|
||||||
|
assert_eq!(desired_chunk_size(600 * 1024 * 1024), CHUNK_LARGE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod integration_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::receiver::{ReceiverEvent, ReceiverServer};
|
||||||
|
use std::sync::mpsc;
|
||||||
|
|
||||||
|
/// 端到端:起一个真实的接收服务,用真实的 HTTP 客户端配对 + 上传,
|
||||||
|
/// 校验落盘文件的 SHA-256 与接收端返回值一致。
|
||||||
|
/// 这就是 PC↔PC 的完整链路,只是两端在同一进程里。
|
||||||
|
#[test]
|
||||||
|
fn pairs_then_uploads_a_real_file() {
|
||||||
|
let root = std::env::temp_dir().join(format!("qft-pcpc-{}", std::process::id()));
|
||||||
|
let inbox = root.join("inbox");
|
||||||
|
std::fs::create_dir_all(&inbox).unwrap();
|
||||||
|
let source = root.join("payload.bin");
|
||||||
|
// 跨越多个分块边界的大小,确保并发路径被覆盖
|
||||||
|
let payload: Vec<u8> = (0..(9 * 1024 * 1024 + 777)).map(|i| (i % 251) as u8).collect();
|
||||||
|
std::fs::write(&source, &payload).unwrap();
|
||||||
|
|
||||||
|
let token = crate::pairing::new_session_token();
|
||||||
|
let (tx, rx) = mpsc::channel::<ReceiverEvent>();
|
||||||
|
let server = ReceiverServer::start(inbox.clone(), token.clone(), tx).unwrap();
|
||||||
|
let base_url = format!("http://127.0.0.1:{}", server.port);
|
||||||
|
|
||||||
|
// 走完整的连接码链路:编码 → 用户输入 → 解码 → 换令牌
|
||||||
|
let code = crate::connect_code::ConnectCode::new(
|
||||||
|
std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
|
||||||
|
server.port,
|
||||||
|
server.secret,
|
||||||
|
);
|
||||||
|
let typed = code.encode();
|
||||||
|
let parsed = crate::connect_code::ConnectCode::decode(&typed).expect("连接码应能解析");
|
||||||
|
assert_eq!(parsed.base_url(), base_url, "码里解出的地址应与实际服务一致");
|
||||||
|
|
||||||
|
// 错误秘密必须被拒
|
||||||
|
assert!(PeerClient::pair(&base_url, "000000", "tester").is_err());
|
||||||
|
|
||||||
|
let paired = PeerClient::pair(&base_url, &parsed.secret_hex(), "tester").unwrap();
|
||||||
|
assert_eq!(paired, token, "配对应返回真实会话令牌");
|
||||||
|
|
||||||
|
let client = PeerClient::new(base_url, paired, "tester");
|
||||||
|
let mut samples: Vec<Progress> = Vec::new();
|
||||||
|
let sha = client.upload_file(&source, |p| samples.push(p)).unwrap();
|
||||||
|
let last = *samples.last().expect("至少应有一次进度回调");
|
||||||
|
assert_eq!(last.done, payload.len() as u64, "进度应抵达文件全长");
|
||||||
|
|
||||||
|
// 回环传输太快,采样次数不稳定,这里只断言稳健的性质;
|
||||||
|
// 「边传边报」的机制由 body_progress_is_reported_incrementally 覆盖。
|
||||||
|
assert!(
|
||||||
|
samples.windows(2).all(|w| w[0].done <= w[1].done),
|
||||||
|
"进度必须单调不减:{samples:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
samples.iter().all(|p| p.done <= payload.len() as u64),
|
||||||
|
"进度不得超过文件总长(重试重复计数会导致这种情况):{samples:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let landed = inbox.join("payload.bin");
|
||||||
|
let saved = std::fs::read(&landed).expect("文件应已落盘");
|
||||||
|
assert_eq!(saved.len(), payload.len());
|
||||||
|
assert_eq!(saved, payload, "落盘内容必须逐字节一致");
|
||||||
|
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let expected = Sha256::digest(&payload);
|
||||||
|
let expected_hex: String = expected.iter().map(|b| format!("{b:02x}")).collect();
|
||||||
|
assert_eq!(sha, expected_hex, "接收端返回的 SHA-256 必须与本地一致");
|
||||||
|
|
||||||
|
drop(server);
|
||||||
|
while rx.try_recv().is_ok() {}
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod failure_message_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// 不可达地址必须给出「超时」类的排查建议,而不是一句空洞的失败。
|
||||||
|
#[test]
|
||||||
|
fn unreachable_host_yields_actionable_timeout_message() {
|
||||||
|
// 192.0.2.0/24 是 RFC 5737 保留的文档用网段,不会有真实主机应答
|
||||||
|
let error = PeerClient::pair("http://192.0.2.1:39393", "abcdef", "tester")
|
||||||
|
.expect_err("不可达地址必须失败");
|
||||||
|
let text = format!("{error:#}");
|
||||||
|
assert!(text.contains("防火墙") || text.contains("超时") || text.contains("路由"),
|
||||||
|
"应给出可执行的排查方向,实得:{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本机没人监听的端口会被内核直接拒绝,提示必须与"超时"区分开。
|
||||||
|
#[test]
|
||||||
|
fn refused_port_says_receiver_not_started() {
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
drop(listener); // 端口随即空出,连接会被拒绝
|
||||||
|
|
||||||
|
let error = PeerClient::pair(&format!("http://127.0.0.1:{port}"), "abcdef", "tester")
|
||||||
|
.expect_err("空端口必须失败");
|
||||||
|
let text = format!("{error:#}");
|
||||||
|
assert!(text.contains("启动接收") || text.contains("拒绝"),
|
||||||
|
"被拒绝时应提示对方没启动接收,实得:{text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod progress_tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::{BufRead, Read, Write};
|
||||||
|
use std::sync::atomic::AtomicUsize;
|
||||||
|
|
||||||
|
/// 极简 mock:按 Content-Length 精确读完请求体再应答。
|
||||||
|
///
|
||||||
|
/// 不能用 read_to_end——那会一直等到客户端关闭写端,
|
||||||
|
/// 而客户端此时正在等响应,两边互等直接死锁。
|
||||||
|
fn serve_once(listener: std::net::TcpListener) -> std::thread::JoinHandle<usize> {
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let Ok((stream, _)) = listener.accept() else { return 0 };
|
||||||
|
let mut reader = std::io::BufReader::new(stream.try_clone().unwrap());
|
||||||
|
let mut length = 0usize;
|
||||||
|
loop {
|
||||||
|
let mut line = String::new();
|
||||||
|
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if line == "\r\n" || line == "\n" {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some((name, value)) = line.split_once(':') {
|
||||||
|
if name.trim().eq_ignore_ascii_case("content-length") {
|
||||||
|
length = value.trim().parse().unwrap_or(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut body = vec![0u8; length];
|
||||||
|
let _ = reader.read_exact(&mut body);
|
||||||
|
let mut out = stream;
|
||||||
|
let _ = out.write_all(
|
||||||
|
b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
|
||||||
|
);
|
||||||
|
let _ = out.flush();
|
||||||
|
length
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 锁住「边写边报」这个行为。
|
||||||
|
///
|
||||||
|
/// 早先 `on_progress` 只在所有 worker 结束后调用一次,传 1 GB 时
|
||||||
|
/// 进度条全程 0%、最后才跳到 100%。这里直接验证请求体是分片写出并
|
||||||
|
/// 逐片上报的——回环速度太快时集成测试采样不到,只有这一层能稳定拦住回归。
|
||||||
|
#[test]
|
||||||
|
fn body_progress_is_reported_incrementally() {
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let server = serve_once(listener);
|
||||||
|
|
||||||
|
let body = vec![7u8; 5 * 256 * 1024]; // 正好 5 片
|
||||||
|
let calls = AtomicUsize::new(0);
|
||||||
|
let total = AtomicU64::new(0);
|
||||||
|
let mut sink = |n: usize| {
|
||||||
|
calls.fetch_add(1, Ordering::Relaxed);
|
||||||
|
total.fetch_add(n as u64, Ordering::Relaxed);
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = send_request_with_progress(
|
||||||
|
address, "POST", "/x", &[], Some(&body),
|
||||||
|
Duration::from_secs(10), Some(&mut sink),
|
||||||
|
);
|
||||||
|
drop(sink);
|
||||||
|
assert!(response.is_ok(), "请求应成功:{:?}", response.err());
|
||||||
|
assert_eq!(server.join().unwrap(), body.len(), "服务端应收到完整请求体");
|
||||||
|
|
||||||
|
assert_eq!(calls.load(Ordering::Relaxed), 5, "5 片体应上报 5 次");
|
||||||
|
assert_eq!(
|
||||||
|
total.load(Ordering::Relaxed),
|
||||||
|
body.len() as u64,
|
||||||
|
"上报总量应等于请求体长度"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_progress_sink_is_allowed() {
|
||||||
|
// init/finish/ping 都不需要进度,不传 sink 时不能出问题
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let server = serve_once(listener);
|
||||||
|
let result = send_request(address, "POST", "/x", &[], Some(b"hi"), Duration::from_secs(10));
|
||||||
|
assert!(result.is_ok(), "无 sink 时请求也应成功:{:?}", result.err());
|
||||||
|
assert_eq!(server.join().unwrap(), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
//! QFT 连接码:把「去哪连」和「凭什么连」压进一串可口述的短码。
|
||||||
|
//!
|
||||||
|
//! 此前 PC↔PC 要用户分别念 IP、端口、6 位配对码三样东西,既啰嗦又容易错。
|
||||||
|
//! 连接码把它们合成一串,**地址就编在码里**,所以发送方拿到码即可直连,
|
||||||
|
//! 不需要广播、不需要在同一网段——只要 IP 层路由可达即可。
|
||||||
|
//! 同一路由器下的不同 VLAN/网段正属于这种情况。
|
||||||
|
//!
|
||||||
|
//! 必须说清的边界:连接码解决的是「找不到对方」和「输入太繁琐」。
|
||||||
|
//! 如果两台机器在 IP 层根本互不可达(AP 客户端隔离、各自在不同的物理网络),
|
||||||
|
//! 任何客户端侧协议都无法凭空造出可达性,只能换链路或引入第三方中转。
|
||||||
|
//!
|
||||||
|
//! 编码
|
||||||
|
//! ```text
|
||||||
|
//! byte0 version(3) | kind(3) | default_port(1) | reserved(1)
|
||||||
|
//! addr 2~4 字节(按 kind 压缩私有网段)或 16 字节(IPv6)
|
||||||
|
//! port 2 字节,仅当非默认端口时存在
|
||||||
|
//! secret 3 字节(24 bit)
|
||||||
|
//! crc 1 字节 CRC-8
|
||||||
|
//! ```
|
||||||
|
//! 典型的 `192.168.a.b:39393` 共 7 字节 → Crockford Base32 → **12 个字符**。
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
/// Crockford Base32:去掉了容易混淆的 I、L、O、U。
|
||||||
|
const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
||||||
|
const VERSION: u8 = 1;
|
||||||
|
pub const DEFAULT_PORT: u16 = 39393;
|
||||||
|
pub const SECRET_LEN: usize = 3;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
enum AddrKind {
|
||||||
|
/// 192.168.a.b —— 2 字节
|
||||||
|
Private192 = 0,
|
||||||
|
/// 10.a.b.c —— 3 字节
|
||||||
|
Private10 = 1,
|
||||||
|
/// 172.(16..=31).a.b —— 3 字节
|
||||||
|
Private172 = 2,
|
||||||
|
/// 任意 IPv4 —— 4 字节
|
||||||
|
FullV4 = 3,
|
||||||
|
/// IPv6 —— 16 字节。码会长到 32 字符左右,适合复制粘贴而非口述,
|
||||||
|
/// 但它是「双方都有公网 IPv6 时无需任何服务器即可直连」的唯一途径。
|
||||||
|
V6 = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AddrKind {
|
||||||
|
fn from_bits(bits: u8) -> Option<Self> {
|
||||||
|
Some(match bits {
|
||||||
|
0 => Self::Private192,
|
||||||
|
1 => Self::Private10,
|
||||||
|
2 => Self::Private172,
|
||||||
|
3 => Self::FullV4,
|
||||||
|
4 => Self::V6,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub struct ConnectCode {
|
||||||
|
pub address: IpAddr,
|
||||||
|
pub port: u16,
|
||||||
|
pub secret: [u8; SECRET_LEN],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum CodeError {
|
||||||
|
/// 长度不对,多半是漏敲或多敲了字符
|
||||||
|
Length,
|
||||||
|
/// 出现了字母表之外的字符
|
||||||
|
Alphabet(char),
|
||||||
|
/// 校验位不匹配——几乎可以肯定是输错了某一位
|
||||||
|
Checksum,
|
||||||
|
/// 版本或地址类型无法识别
|
||||||
|
Unsupported,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for CodeError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Length => write!(f, "连接码长度不对,请检查是否漏敲或多敲了字符"),
|
||||||
|
Self::Alphabet(ch) => write!(f, "连接码里有无效字符 '{ch}'"),
|
||||||
|
Self::Checksum => write!(f, "连接码校验失败,请核对后重新输入"),
|
||||||
|
Self::Unsupported => write!(f, "无法识别的连接码版本"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for CodeError {}
|
||||||
|
|
||||||
|
impl ConnectCode {
|
||||||
|
pub fn new(address: IpAddr, port: u16, secret: [u8; SECRET_LEN]) -> Self {
|
||||||
|
Self { address, port, secret }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 秘密的线上表示:6 个小写十六进制字符,放在 `X-QFT-Code` 头里。
|
||||||
|
pub fn secret_hex(&self) -> String {
|
||||||
|
self.secret.iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn base_url(&self) -> String {
|
||||||
|
match self.address {
|
||||||
|
IpAddr::V4(v4) => format!("http://{v4}:{}", self.port),
|
||||||
|
IpAddr::V6(v6) => format!("http://[{v6}]:{}", self.port),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 编码为分组显示的字符串,例如 `K7M2-9X4P-QR3T`。
|
||||||
|
pub fn encode(&self) -> String {
|
||||||
|
let bytes = self.to_bytes();
|
||||||
|
let raw = base32_encode(&bytes);
|
||||||
|
raw.as_bytes()
|
||||||
|
.chunks(4)
|
||||||
|
.map(|chunk| std::str::from_utf8(chunk).unwrap_or_default())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("-")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析用户输入。分隔符、大小写、以及 I/L→1、O→0 的手误都会被容忍。
|
||||||
|
pub fn decode(text: &str) -> Result<Self, CodeError> {
|
||||||
|
let (bytes, padding_ok) = base32_decode(text)?;
|
||||||
|
// 先判长度:码太短时「长度不对」比「校验失败」更能指导用户,
|
||||||
|
// 再判填充位与 CRC。
|
||||||
|
let code = Self::from_bytes(&bytes)?;
|
||||||
|
if !padding_ok {
|
||||||
|
return Err(CodeError::Checksum);
|
||||||
|
}
|
||||||
|
Ok(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_bytes(&self) -> Vec<u8> {
|
||||||
|
let (kind, addr_bytes) = match self.address {
|
||||||
|
IpAddr::V4(v4) => {
|
||||||
|
let o = v4.octets();
|
||||||
|
match (o[0], o[1]) {
|
||||||
|
(192, 168) => (AddrKind::Private192, vec![o[2], o[3]]),
|
||||||
|
(10, _) => (AddrKind::Private10, vec![o[1], o[2], o[3]]),
|
||||||
|
(172, 16..=31) => (AddrKind::Private172, vec![o[1] - 16, o[2], o[3]]),
|
||||||
|
_ => (AddrKind::FullV4, o.to_vec()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
IpAddr::V6(v6) => (AddrKind::V6, v6.octets().to_vec()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let default_port = self.port == DEFAULT_PORT;
|
||||||
|
let mut out = Vec::with_capacity(1 + addr_bytes.len() + 2 + SECRET_LEN + 1);
|
||||||
|
out.push((VERSION << 5) | ((kind as u8) << 2) | ((default_port as u8) << 1));
|
||||||
|
out.extend_from_slice(&addr_bytes);
|
||||||
|
if !default_port {
|
||||||
|
out.extend_from_slice(&self.port.to_be_bytes());
|
||||||
|
}
|
||||||
|
out.extend_from_slice(&self.secret);
|
||||||
|
out.push(crc8(&out));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_bytes(bytes: &[u8]) -> Result<Self, CodeError> {
|
||||||
|
if bytes.len() < 1 + 2 + SECRET_LEN + 1 {
|
||||||
|
return Err(CodeError::Length);
|
||||||
|
}
|
||||||
|
let (payload, checksum) = bytes.split_at(bytes.len() - 1);
|
||||||
|
if crc8(payload) != checksum[0] {
|
||||||
|
return Err(CodeError::Checksum);
|
||||||
|
}
|
||||||
|
|
||||||
|
let header = payload[0];
|
||||||
|
if header >> 5 != VERSION {
|
||||||
|
return Err(CodeError::Unsupported);
|
||||||
|
}
|
||||||
|
let kind = AddrKind::from_bits((header >> 2) & 0b111).ok_or(CodeError::Unsupported)?;
|
||||||
|
let default_port = (header >> 1) & 1 == 1;
|
||||||
|
|
||||||
|
let addr_len = match kind {
|
||||||
|
AddrKind::Private192 => 2,
|
||||||
|
AddrKind::Private10 | AddrKind::Private172 => 3,
|
||||||
|
AddrKind::FullV4 => 4,
|
||||||
|
AddrKind::V6 => 16,
|
||||||
|
};
|
||||||
|
let port_len = if default_port { 0 } else { 2 };
|
||||||
|
if payload.len() != 1 + addr_len + port_len + SECRET_LEN {
|
||||||
|
return Err(CodeError::Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
let addr_slice = &payload[1..1 + addr_len];
|
||||||
|
let address = match kind {
|
||||||
|
AddrKind::Private192 => {
|
||||||
|
IpAddr::V4(Ipv4Addr::new(192, 168, addr_slice[0], addr_slice[1]))
|
||||||
|
}
|
||||||
|
AddrKind::Private10 => {
|
||||||
|
IpAddr::V4(Ipv4Addr::new(10, addr_slice[0], addr_slice[1], addr_slice[2]))
|
||||||
|
}
|
||||||
|
AddrKind::Private172 => {
|
||||||
|
// 第二个八位组只可能是 16..=31,编码时减了 16
|
||||||
|
if addr_slice[0] > 15 {
|
||||||
|
return Err(CodeError::Unsupported);
|
||||||
|
}
|
||||||
|
IpAddr::V4(Ipv4Addr::new(172, addr_slice[0] + 16, addr_slice[1], addr_slice[2]))
|
||||||
|
}
|
||||||
|
AddrKind::FullV4 => IpAddr::V4(Ipv4Addr::new(
|
||||||
|
addr_slice[0], addr_slice[1], addr_slice[2], addr_slice[3],
|
||||||
|
)),
|
||||||
|
AddrKind::V6 => {
|
||||||
|
let mut octets = [0u8; 16];
|
||||||
|
octets.copy_from_slice(addr_slice);
|
||||||
|
IpAddr::V6(Ipv6Addr::from(octets))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut cursor = 1 + addr_len;
|
||||||
|
let port = if default_port {
|
||||||
|
DEFAULT_PORT
|
||||||
|
} else {
|
||||||
|
let value = u16::from_be_bytes([payload[cursor], payload[cursor + 1]]);
|
||||||
|
cursor += 2;
|
||||||
|
value
|
||||||
|
};
|
||||||
|
let mut secret = [0u8; SECRET_LEN];
|
||||||
|
secret.copy_from_slice(&payload[cursor..cursor + SECRET_LEN]);
|
||||||
|
|
||||||
|
Ok(Self { address, port, secret })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_secret() -> [u8; SECRET_LEN] {
|
||||||
|
use rand::RngCore;
|
||||||
|
let mut secret = [0u8; SECRET_LEN];
|
||||||
|
rand::rng().fill_bytes(&mut secret);
|
||||||
|
secret
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Base32
|
||||||
|
|
||||||
|
fn base32_encode(bytes: &[u8]) -> String {
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 8 / 5 + 1);
|
||||||
|
let mut buffer: u32 = 0;
|
||||||
|
let mut bits = 0u32;
|
||||||
|
for &byte in bytes {
|
||||||
|
buffer = (buffer << 8) | byte as u32;
|
||||||
|
bits += 8;
|
||||||
|
while bits >= 5 {
|
||||||
|
bits -= 5;
|
||||||
|
out.push(ALPHABET[((buffer >> bits) & 0x1f) as usize] as char);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bits > 0 {
|
||||||
|
out.push(ALPHABET[((buffer << (5 - bits)) & 0x1f) as usize] as char);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 返回 (字节, 末尾填充位是否为 0)。
|
||||||
|
fn base32_decode(text: &str) -> Result<(Vec<u8>, bool), CodeError> {
|
||||||
|
let mut buffer: u32 = 0;
|
||||||
|
let mut bits = 0u32;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut symbols = 0usize;
|
||||||
|
|
||||||
|
for ch in text.chars() {
|
||||||
|
// 分隔符与空白一律忽略,用户怎么断句都行
|
||||||
|
if ch == '-' || ch == ' ' || ch == '_' || ch == '\t' {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let upper = ch.to_ascii_uppercase();
|
||||||
|
// Crockford 的容错映射:手写/口述时 I、L 常被当成 1,O 被当成 0
|
||||||
|
let normalized = match upper {
|
||||||
|
'I' | 'L' => '1',
|
||||||
|
'O' => '0',
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
|
let value = ALPHABET
|
||||||
|
.iter()
|
||||||
|
.position(|&c| c as char == normalized)
|
||||||
|
.ok_or(CodeError::Alphabet(ch))? as u32;
|
||||||
|
symbols += 1;
|
||||||
|
buffer = (buffer << 5) | value;
|
||||||
|
bits += 5;
|
||||||
|
if bits >= 8 {
|
||||||
|
bits -= 8;
|
||||||
|
out.push(((buffer >> bits) & 0xff) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if symbols == 0 {
|
||||||
|
return Err(CodeError::Length);
|
||||||
|
}
|
||||||
|
// 5 位一组和 8 位一字节对不齐,末尾会剩几个填充位。编码时填的是 0,
|
||||||
|
// 必须校验它们仍是 0:否则改动最后一个字符有 1/2^bits 的概率
|
||||||
|
// 解出完全相同的字节序列,CRC 根本没机会发现(修复前实测漏检率 4%)。
|
||||||
|
let padding_ok = bits == 0 || (buffer & ((1 << bits) - 1)) == 0;
|
||||||
|
Ok((out, padding_ok))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn crc8(bytes: &[u8]) -> u8 {
|
||||||
|
let mut crc = 0u8;
|
||||||
|
for &byte in bytes {
|
||||||
|
crc ^= byte;
|
||||||
|
for _ in 0..8 {
|
||||||
|
crc = if crc & 0x80 != 0 { (crc << 1) ^ 0x07 } else { crc << 1 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crc
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn code(ip: &str, port: u16) -> ConnectCode {
|
||||||
|
ConnectCode::new(ip.parse().unwrap(), port, [0xAB, 0xCD, 0xEF])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typical_home_address_fits_in_twelve_characters() {
|
||||||
|
let encoded = code("192.168.1.20", DEFAULT_PORT).encode();
|
||||||
|
let symbols = encoded.chars().filter(|c| *c != '-').count();
|
||||||
|
assert_eq!(symbols, 12, "常见家庭网段应压到 12 个字符,实得 {encoded}");
|
||||||
|
assert_eq!(encoded.matches('-').count(), 2, "应分成三组便于口述");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trips_every_address_kind() {
|
||||||
|
let cases = [
|
||||||
|
("192.168.1.20", DEFAULT_PORT),
|
||||||
|
("192.168.255.255", DEFAULT_PORT),
|
||||||
|
("10.0.0.5", DEFAULT_PORT),
|
||||||
|
("10.255.255.254", 8080),
|
||||||
|
("172.16.0.1", DEFAULT_PORT),
|
||||||
|
("172.31.255.254", 1),
|
||||||
|
("100.64.0.1", DEFAULT_PORT), // CGNAT,落到 FullV4
|
||||||
|
("127.0.0.1", 65535),
|
||||||
|
("2001:db8::1", DEFAULT_PORT),
|
||||||
|
("fe80::1", 39393),
|
||||||
|
];
|
||||||
|
for (ip, port) in cases {
|
||||||
|
let original = code(ip, port);
|
||||||
|
let decoded = ConnectCode::decode(&original.encode())
|
||||||
|
.unwrap_or_else(|e| panic!("{ip}:{port} 解码失败:{e}"));
|
||||||
|
assert_eq!(decoded, original, "{ip}:{port} 往返不一致");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn accepts_sloppy_user_input() {
|
||||||
|
let original = code("192.168.1.20", DEFAULT_PORT);
|
||||||
|
let canonical = original.encode();
|
||||||
|
let sloppy = [
|
||||||
|
canonical.to_lowercase(),
|
||||||
|
canonical.replace('-', ""),
|
||||||
|
canonical.replace('-', " "),
|
||||||
|
format!(" {canonical} "),
|
||||||
|
];
|
||||||
|
for text in sloppy {
|
||||||
|
assert_eq!(ConnectCode::decode(&text).unwrap(), original, "应容忍:{text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn confusable_letters_map_to_digits() {
|
||||||
|
// 口述时 I/L 常被听成 1,O 被听成 0。字母表里本就没有这些字母,
|
||||||
|
// 所以把它们映射回数字是安全的,不会和真实字符冲突。
|
||||||
|
let original = code("192.168.1.20", DEFAULT_PORT);
|
||||||
|
let canonical = original.encode();
|
||||||
|
let mangled = canonical.replace('1', "I").replace('0', "O");
|
||||||
|
if mangled != canonical {
|
||||||
|
assert_eq!(ConnectCode::decode(&mangled).unwrap(), original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn single_character_typo_is_caught_by_checksum() {
|
||||||
|
let canonical = code("192.168.1.20", DEFAULT_PORT).encode();
|
||||||
|
let mut caught = 0;
|
||||||
|
let mut total = 0;
|
||||||
|
for (index, ch) in canonical.char_indices() {
|
||||||
|
if ch == '-' {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for &replacement in ALPHABET.iter() {
|
||||||
|
if replacement as char == ch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut mangled: Vec<char> = canonical.chars().collect();
|
||||||
|
mangled[index] = replacement as char;
|
||||||
|
let text: String = mangled.into_iter().collect();
|
||||||
|
total += 1;
|
||||||
|
if ConnectCode::decode(&text).is_err() {
|
||||||
|
caught += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// CRC-8 理论漏检率约 1/256;这里要求实测拦截率高于 99%
|
||||||
|
let rate = caught as f64 / total as f64;
|
||||||
|
assert!(rate > 0.99, "单字符输错的拦截率只有 {:.3},太低", rate);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_malformed_input() {
|
||||||
|
assert_eq!(ConnectCode::decode(""), Err(CodeError::Length));
|
||||||
|
assert_eq!(ConnectCode::decode("---"), Err(CodeError::Length));
|
||||||
|
assert!(matches!(ConnectCode::decode("K7M2!9X4"), Err(CodeError::Alphabet('!'))));
|
||||||
|
assert_eq!(ConnectCode::decode("K7M2"), Err(CodeError::Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn secret_hex_is_stable_and_lowercase() {
|
||||||
|
let value = code("192.168.1.20", DEFAULT_PORT);
|
||||||
|
assert_eq!(value.secret_hex(), "abcdef");
|
||||||
|
assert_eq!(value.base_url(), "http://192.168.1.20:39393");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ipv6_code_is_long_but_valid() {
|
||||||
|
let value = code("2001:db8::1", DEFAULT_PORT);
|
||||||
|
let encoded = value.encode();
|
||||||
|
let symbols = encoded.chars().filter(|c| *c != '-').count();
|
||||||
|
// IPv6 地址本身就 16 字节,码必然长,适合复制粘贴而不是口述
|
||||||
|
assert!(symbols > 24, "IPv6 码应明显更长,实得 {symbols}");
|
||||||
|
assert_eq!(ConnectCode::decode(&encoded).unwrap(), value);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn secrets_differ_between_sessions() {
|
||||||
|
let a = new_secret();
|
||||||
|
let b = new_secret();
|
||||||
|
assert_ne!(a, b, "每次生成的秘密必须不同");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
|
// Context 只在 Windows 的 WiFiDirect 分支里用;非 Windows 上整段被编译掉。
|
||||||
|
#[cfg(windows)]
|
||||||
|
use anyhow::Context;
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows::{
|
||||||
|
core::HSTRING,
|
||||||
|
Devices::WiFiDirect::{
|
||||||
|
WiFiDirectAdvertisementListenStateDiscoverability, WiFiDirectAdvertisementPublisher,
|
||||||
|
WiFiDirectAdvertisementPublisherStatus,
|
||||||
|
WiFiDirectAdvertisementPublisherStatusChangedEventArgs, WiFiDirectConnectionListener,
|
||||||
|
WiFiDirectConnectionRequestedEventArgs, WiFiDirectDevice,
|
||||||
|
},
|
||||||
|
Foundation::TypedEventHandler,
|
||||||
|
Security::Credentials::PasswordCredential,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn create_connection_listener(
|
||||||
|
connected_devices: &Arc<Mutex<Vec<WiFiDirectDevice>>>,
|
||||||
|
) -> windows::core::Result<(WiFiDirectConnectionListener, i64)> {
|
||||||
|
let callback_devices = Arc::clone(connected_devices);
|
||||||
|
let listener = WiFiDirectConnectionListener::new()?;
|
||||||
|
let handler = TypedEventHandler::<
|
||||||
|
WiFiDirectConnectionListener,
|
||||||
|
WiFiDirectConnectionRequestedEventArgs,
|
||||||
|
>::new(move |_sender, args| {
|
||||||
|
let request = args.ok()?.GetConnectionRequest()?;
|
||||||
|
let device_id = request.DeviceInformation()?.Id()?;
|
||||||
|
let operation = WiFiDirectDevice::FromIdAsync(&device_id)?;
|
||||||
|
let devices = Arc::clone(&callback_devices);
|
||||||
|
|
||||||
|
// Do not block the WinRT event thread while Windows completes the peer
|
||||||
|
// connection. `join` also keeps the async operation alive until it
|
||||||
|
// yields the device we must retain.
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
if let Ok(device) = operation.join() {
|
||||||
|
if let Ok(mut devices) = devices.lock() {
|
||||||
|
devices.retain(|known| known.DeviceId().ok() != device.DeviceId().ok());
|
||||||
|
devices.push(device);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
let token = listener.ConnectionRequested(&handler)?;
|
||||||
|
Ok((listener, token))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct DirectAp {
|
||||||
|
pub ssid: String,
|
||||||
|
#[cfg(windows)]
|
||||||
|
publisher: WiFiDirectAdvertisementPublisher,
|
||||||
|
/// Legacy AP 只负责让普通 Wi-Fi 客户端关联和取得 DHCP 地址;Windows
|
||||||
|
/// 还要求应用接受 Wi-Fi Direct connection request,数据通道才会真正建立。
|
||||||
|
#[cfg(windows)]
|
||||||
|
connection_listener: WiFiDirectConnectionListener,
|
||||||
|
#[cfg(windows)]
|
||||||
|
connection_requested_token: i64,
|
||||||
|
/// 必须长期持有 `WiFiDirectDevice`。对象一旦被释放,Windows 会拆掉该
|
||||||
|
/// peer 的 Wi-Fi Direct 会话,表现为手机仍连着 SSID、却访问不到网关端口。
|
||||||
|
#[cfg(windows)]
|
||||||
|
connected_devices: Arc<Mutex<Vec<WiFiDirectDevice>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DirectAp {
|
||||||
|
pub fn start(ssid: String, passphrase: String) -> Result<Self> {
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
let _ = (ssid, passphrase);
|
||||||
|
bail!("QFT Direct AP 仅支持 Windows")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
let publisher = WiFiDirectAdvertisementPublisher::new()
|
||||||
|
.context("创建 Wi-Fi Direct publisher 失败")?;
|
||||||
|
let ad = publisher.Advertisement()
|
||||||
|
.context("读取 Wi-Fi Direct advertisement 失败")?;
|
||||||
|
// WinRT defaults this property to `None`, which still lets the
|
||||||
|
// publisher report `Started` but does not make the AP discoverable.
|
||||||
|
// Android then waits in the system Wi-Fi picker until it times out,
|
||||||
|
// exactly as if the hotspot had never been started. Intensive keeps
|
||||||
|
// the legacy SSID discoverable even when the desktop window is not
|
||||||
|
// foregrounded during the phone-side connection flow.
|
||||||
|
ad.SetListenStateDiscoverability(
|
||||||
|
WiFiDirectAdvertisementListenStateDiscoverability::Intensive,
|
||||||
|
)
|
||||||
|
.context("启用 QFT Wi-Fi Direct 可发现性失败")?;
|
||||||
|
ad.SetIsAutonomousGroupOwnerEnabled(true)
|
||||||
|
.context("启用 Autonomous Group Owner 失败")?;
|
||||||
|
let legacy = ad.LegacySettings()
|
||||||
|
.context("读取 LegacySettings 失败")?;
|
||||||
|
legacy.SetIsEnabled(true)
|
||||||
|
.context("启用 Wi-Fi Direct Legacy AP 失败")?;
|
||||||
|
legacy.SetSsid(&HSTRING::from(&ssid))
|
||||||
|
.context("设置 QFT SSID 失败")?;
|
||||||
|
let credential = PasswordCredential::new()
|
||||||
|
.context("创建 Wi-Fi Direct 密码对象失败")?;
|
||||||
|
credential.SetPassword(&HSTRING::from(&passphrase))
|
||||||
|
.context("设置 QFT 热点密码失败")?;
|
||||||
|
legacy.SetPassphrase(&credential)
|
||||||
|
.context("应用 QFT 热点密码失败")?;
|
||||||
|
|
||||||
|
// Follow Microsoft's Legacy AP lifecycle exactly: install the
|
||||||
|
// connection listener from the publisher's Started callback. QFT
|
||||||
|
// keeps a stable SSID/password, so Android can auto-reassociate as
|
||||||
|
// soon as the AP appears; polling first and adding the listener
|
||||||
|
// afterwards can miss that one connection request.
|
||||||
|
type ListenerResult = std::result::Result<
|
||||||
|
(WiFiDirectConnectionListener, i64),
|
||||||
|
String,
|
||||||
|
>;
|
||||||
|
let connected_devices = Arc::new(Mutex::new(Vec::<WiFiDirectDevice>::new()));
|
||||||
|
let listener_state = Arc::new(Mutex::new(None::<ListenerResult>));
|
||||||
|
let callback_devices = Arc::clone(&connected_devices);
|
||||||
|
let callback_state = Arc::clone(&listener_state);
|
||||||
|
let status_handler = TypedEventHandler::<
|
||||||
|
WiFiDirectAdvertisementPublisher,
|
||||||
|
WiFiDirectAdvertisementPublisherStatusChangedEventArgs,
|
||||||
|
>::new(move |_sender, args| {
|
||||||
|
if args.ok()?.Status()? == WiFiDirectAdvertisementPublisherStatus::Started {
|
||||||
|
let result = create_connection_listener(&callback_devices)
|
||||||
|
.map_err(|error| error.to_string());
|
||||||
|
if let Ok(mut state) = callback_state.lock() {
|
||||||
|
if state.is_none() {
|
||||||
|
*state = Some(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
let status_token = publisher
|
||||||
|
.StatusChanged(&status_handler)
|
||||||
|
.context("监听 Wi-Fi Direct AP 启动状态失败")?;
|
||||||
|
|
||||||
|
publisher.Start().context("启动 QFT Wi-Fi Direct AP 失败")?;
|
||||||
|
|
||||||
|
// Publisher startup is asynchronous. Do not expose the pairing QR until
|
||||||
|
// Windows reports Started; otherwise Android can scan a network that is
|
||||||
|
// not yet discoverable.
|
||||||
|
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||||
|
let (connection_listener, connection_requested_token) = loop {
|
||||||
|
if let Ok(mut state) = listener_state.lock() {
|
||||||
|
if let Some(result) = state.take() {
|
||||||
|
break result.map_err(anyhow::Error::msg)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let status = publisher.Status().context("读取 AP 状态失败")?;
|
||||||
|
if status == WiFiDirectAdvertisementPublisherStatus::Aborted {
|
||||||
|
bail!("Wi-Fi Direct AP 启动被系统中止。请确认 Windows Wi-Fi 已开启,且系统移动热点未占用 Wi-Fi Direct。")
|
||||||
|
}
|
||||||
|
if std::time::Instant::now() >= deadline {
|
||||||
|
bail!("Wi-Fi Direct AP 或连接监听器启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。")
|
||||||
|
}
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(25));
|
||||||
|
};
|
||||||
|
let _ = publisher.RemoveStatusChanged(status_token);
|
||||||
|
|
||||||
|
// This is not optional bookkeeping. Microsoft's Legacy AP sample
|
||||||
|
// creates the connection listener after the publisher reaches
|
||||||
|
// Started, accepts each request with FromIdAsync, and retains the
|
||||||
|
// resulting WiFiDirectDevice. Without these steps Android still
|
||||||
|
// associates and receives 192.168.137.x via DHCP, but TCP/UDP to
|
||||||
|
// 192.168.137.1 never reaches the desktop process.
|
||||||
|
Ok(Self {
|
||||||
|
ssid,
|
||||||
|
publisher,
|
||||||
|
connection_listener,
|
||||||
|
connection_requested_token,
|
||||||
|
connected_devices,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for DirectAp {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
let _ = self
|
||||||
|
.connection_listener
|
||||||
|
.RemoveConnectionRequested(self.connection_requested_token);
|
||||||
|
if let Ok(mut devices) = self.connected_devices.lock() {
|
||||||
|
for device in devices.drain(..) {
|
||||||
|
let _ = device.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = self.publisher.Stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
//! 局域网节点发现(v3 浏览)。
|
||||||
|
//!
|
||||||
|
//! 与既有的 `QFTDISC2:<token>` 不同:那是「我已经知道令牌,帮我找到那台机器」,
|
||||||
|
//! 用于手机扫码之后。PC↔PC 没有摄像头,必须先能**列出附近有哪些节点**,
|
||||||
|
//! 用户再从列表里挑一台,所以需要一个不带令牌的广播查询。
|
||||||
|
//!
|
||||||
|
//! 为什么不是 mDNS:
|
||||||
|
//! - 本阶段目标是尽快让 PC↔PC 可测,UDP 广播零新依赖,且仓库里已有同样的模式;
|
||||||
|
//! - macOS 上 mDNS 在沙盒/强化运行时下需要额外 entitlement,Windows 上常被
|
||||||
|
//! 企业策略关掉,行为差异反而更多。
|
||||||
|
//! mDNS 作为跨网段与「AP 隔离」场景的补充留到后续,不阻塞本阶段。
|
||||||
|
//!
|
||||||
|
//! 局限(必须在 UI 上说清楚):UDP 广播只覆盖同一个广播域。跨网段、
|
||||||
|
//! 或开了 AP 隔离的 Wi-Fi 上发现不到对方,此时走手动输入 IP。
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 广播查询;任何在监听的 QFT 节点都应答。
|
||||||
|
pub const BROWSE_QUERY: &str = "QFTBROWSE3";
|
||||||
|
/// 应答前缀,后接紧凑 JSON。
|
||||||
|
pub const BROWSE_REPLY_PREFIX: &str = "QFTNODE3:";
|
||||||
|
|
||||||
|
/// 节点自我介绍。刻意用短键名——UDP 应答要留在单个数据报里。
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct NodeAnnounce {
|
||||||
|
/// 设备名
|
||||||
|
pub n: String,
|
||||||
|
/// 平台标识:windows / macos / linux
|
||||||
|
pub p: String,
|
||||||
|
/// 传输服务的 TCP 端口
|
||||||
|
pub t: u16,
|
||||||
|
/// 当前是否正在等待配对(未在接收状态的节点不会被误选)
|
||||||
|
pub r: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 发现到的对端。
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Peer {
|
||||||
|
pub name: String,
|
||||||
|
pub platform: String,
|
||||||
|
pub address: Ipv4Addr,
|
||||||
|
pub port: u16,
|
||||||
|
pub ready: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Peer {
|
||||||
|
pub fn base_url(&self) -> String {
|
||||||
|
format!("http://{}:{}", self.address, self.port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 构造应答报文。接收端的 UDP 线程用它回应 `QFTBROWSE3`。
|
||||||
|
pub fn browse_reply(announce: &NodeAnnounce) -> Vec<u8> {
|
||||||
|
let json = serde_json::to_string(announce).unwrap_or_else(|_| "{}".into());
|
||||||
|
format!("{BROWSE_REPLY_PREFIX}{json}").into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 向局域网广播一次查询并收集应答。
|
||||||
|
///
|
||||||
|
/// 同时发往受限广播地址和各网卡的定向广播地址:部分 Wi-Fi 驱动会丢弃
|
||||||
|
/// 255.255.255.255,而定向广播能过。
|
||||||
|
pub fn browse(port: u16, timeout: Duration) -> Result<Vec<Peer>> {
|
||||||
|
let socket = UdpSocket::bind(("0.0.0.0", 0)).context("绑定发现端口失败")?;
|
||||||
|
socket.set_broadcast(true).ok();
|
||||||
|
socket
|
||||||
|
.set_read_timeout(Some(Duration::from_millis(200)))
|
||||||
|
.context("设置发现超时失败")?;
|
||||||
|
|
||||||
|
let mut targets: Vec<Ipv4Addr> = vec![Ipv4Addr::BROADCAST];
|
||||||
|
for address in directed_broadcasts() {
|
||||||
|
if !targets.contains(&address) {
|
||||||
|
targets.push(address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for target in &targets {
|
||||||
|
let _ = socket.send_to(BROWSE_QUERY.as_bytes(), SocketAddr::from((*target, port)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 同一台机器可能从多个网卡应答,用「地址+端口」去重
|
||||||
|
let mut found: HashMap<(Ipv4Addr, u16), Peer> = HashMap::new();
|
||||||
|
let deadline = Instant::now() + timeout;
|
||||||
|
let mut buffer = [0u8; 1024];
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
match socket.recv_from(&mut buffer) {
|
||||||
|
Ok((n, from)) => {
|
||||||
|
let IpAddr::V4(address) = from.ip() else { continue };
|
||||||
|
let Some(peer) = parse_reply(&buffer[..n], address) else { continue };
|
||||||
|
found.insert((peer.address, peer.port), peer);
|
||||||
|
}
|
||||||
|
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
|
||||||
|
Err(e) => return Err(e).context("接收发现应答失败"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut peers: Vec<Peer> = found.into_values().collect();
|
||||||
|
// 正在等待接收的排前面,其次按名字,保证列表顺序稳定不跳动
|
||||||
|
peers.sort_by(|a, b| {
|
||||||
|
b.ready
|
||||||
|
.cmp(&a.ready)
|
||||||
|
.then_with(|| a.name.cmp(&b.name))
|
||||||
|
.then_with(|| a.address.cmp(&b.address))
|
||||||
|
});
|
||||||
|
Ok(peers)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_reply(bytes: &[u8], address: Ipv4Addr) -> Option<Peer> {
|
||||||
|
let text = std::str::from_utf8(bytes).ok()?;
|
||||||
|
let json = text.strip_prefix(BROWSE_REPLY_PREFIX)?;
|
||||||
|
let announce: NodeAnnounce = serde_json::from_str(json).ok()?;
|
||||||
|
if announce.t == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Peer {
|
||||||
|
name: crate::platform::sanitize_device_name(&announce.n),
|
||||||
|
platform: announce.p.chars().filter(|c| c.is_ascii_alphanumeric()).take(16).collect(),
|
||||||
|
address,
|
||||||
|
port: announce.t,
|
||||||
|
ready: announce.r,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 各网卡的定向广播地址(如 192.168.1.255)。
|
||||||
|
fn directed_broadcasts() -> Vec<Ipv4Addr> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let Ok(interfaces) = if_addrs::get_if_addrs() else { return out };
|
||||||
|
for interface in interfaces {
|
||||||
|
if interface.is_loopback() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let if_addrs::IfAddr::V4(v4) = interface.addr else { continue };
|
||||||
|
let Some(netmask) = Some(v4.netmask) else { continue };
|
||||||
|
let ip = u32::from(v4.ip);
|
||||||
|
let mask = u32::from(netmask);
|
||||||
|
if mask == 0 || mask == u32::MAX {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let broadcast = Ipv4Addr::from(ip | !mask);
|
||||||
|
if !out.contains(&broadcast) {
|
||||||
|
out.push(broadcast);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reply_round_trip() {
|
||||||
|
let announce = NodeAnnounce {
|
||||||
|
n: "MacBook-Pro".into(),
|
||||||
|
p: "macos".into(),
|
||||||
|
t: 39393,
|
||||||
|
r: true,
|
||||||
|
};
|
||||||
|
let bytes = browse_reply(&announce);
|
||||||
|
let peer = parse_reply(&bytes, Ipv4Addr::new(192, 168, 1, 20)).expect("应能解析");
|
||||||
|
assert_eq!(peer.name, "MacBook-Pro");
|
||||||
|
assert_eq!(peer.platform, "macos");
|
||||||
|
assert_eq!(peer.port, 39393);
|
||||||
|
assert!(peer.ready);
|
||||||
|
assert_eq!(peer.base_url(), "http://192.168.1.20:39393");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_foreign_or_malformed_datagrams() {
|
||||||
|
let address = Ipv4Addr::LOCALHOST;
|
||||||
|
assert!(parse_reply(b"QFTHERE2:token:39393", address).is_none());
|
||||||
|
assert!(parse_reply(b"QFTNODE3:not-json", address).is_none());
|
||||||
|
assert!(parse_reply(&[0xff, 0xfe, 0x00], address).is_none());
|
||||||
|
// 端口 0 的应答无意义,必须丢弃
|
||||||
|
assert!(parse_reply(br#"QFTNODE3:{"n":"x","p":"linux","t":0,"r":true}"#, address).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn announce_fits_in_one_datagram() {
|
||||||
|
let announce = NodeAnnounce {
|
||||||
|
n: "x".repeat(64),
|
||||||
|
p: "windows".into(),
|
||||||
|
t: 65535,
|
||||||
|
r: false,
|
||||||
|
};
|
||||||
|
assert!(browse_reply(&announce).len() < 512);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peer_name_is_sanitized_from_untrusted_datagram() {
|
||||||
|
// 应答来自网络,是不可信输入:控制字符必须被清掉
|
||||||
|
let bytes = format!("{BROWSE_REPLY_PREFIX}{{\"n\":\"bad\\u0000name\",\"p\":\"linux!!\",\"t\":1,\"r\":true}}");
|
||||||
|
let peer = parse_reply(bytes.as_bytes(), Ipv4Addr::LOCALHOST).expect("应能解析");
|
||||||
|
assert!(!peer.name.chars().any(char::is_control));
|
||||||
|
assert_eq!(peer.platform, "linux");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,750 @@
|
|||||||
|
//! 系统防火墙放行。
|
||||||
|
//!
|
||||||
|
//! 接收端要监听入站 TCP,而 Windows 防火墙默认拦截未授权程序的入站连接,
|
||||||
|
//! 表现是「对方能解析连接码,但连接一直超时」——这类问题用户几乎不可能
|
||||||
|
//! 自己联想到防火墙。所以由程序主动检测并申请放行。
|
||||||
|
//!
|
||||||
|
//! 三条设计约束:
|
||||||
|
//! 1. **只在确实缺规则时申请**。每次启动都弹 UAC 是骚扰。
|
||||||
|
//! 2. **没有放行就不宣称 Direct 已就绪**。用户明确点击“启动直传/接收”时,
|
||||||
|
//! 可以走一次标准 UAC;拒绝或复检失败就停止启动,不生成不可用二维码。
|
||||||
|
//! 3. **规则尽量窄**。程序规则之外只开放 QFT 固定的 TCP/UDP 两个端口,
|
||||||
|
//! 绝不整体关闭防火墙;但**不能按网络配置文件收窄**——见下方
|
||||||
|
//! `grant()` 里的说明。
|
||||||
|
//!
|
||||||
|
//! 提权本身由操作系统的标准机制完成(Windows 的 UAC、macOS 的
|
||||||
|
//! 授权对话框),程序不接触也不存储任何凭据。
|
||||||
|
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
/// 规则显示名。检测与添加都用它,改名会导致旧规则失效。
|
||||||
|
// 仅 Windows 分支使用;其余平台整段被 cfg 编译掉
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
pub const RULE_NAME: &str = "QFT Desktop";
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
const DIRECT_TCP_RULE: &str = "QFT-Desktop-Direct-TCP-v2";
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
const DIRECT_UDP_RULE: &str = "QFT-Desktop-Direct-UDP-v2";
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
const DIRECT_TCP_PORT: u16 = 39393;
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
const DIRECT_UDP_PORT: u16 = 39392;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum FirewallStatus {
|
||||||
|
/// 已放行,或系统防火墙未开启,总之入站不会被拦
|
||||||
|
Allowed,
|
||||||
|
/// 缺少放行规则,入站很可能被拦
|
||||||
|
Missing,
|
||||||
|
/// 规则本身没问题,但系统层面的策略让任何放行规则都不生效。
|
||||||
|
///
|
||||||
|
/// 对应 Windows 的「阻止所有传入连接,包括位于允许应用列表中的应用」
|
||||||
|
/// (`BlockInboundAlways`)。这一项打开时,用户点多少次「放行防火墙」
|
||||||
|
/// 都不会有任何变化——必须先把它关掉,所以要单独报出来。
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
BlockedByPolicy(String),
|
||||||
|
/// 存在针对本程序的「阻止」入站规则,压过了我们的放行规则。
|
||||||
|
///
|
||||||
|
/// 通常是用户在 Windows「安全警报」弹窗上点了取消后系统自动建的,
|
||||||
|
/// 规则名是程序名而非 `QFT Desktop`。这一类提权后可以自动清掉,
|
||||||
|
/// 所以和 [`BlockedByPolicy`](Self::BlockedByPolicy) 分开表示。
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
BlockedByRule(String),
|
||||||
|
/// 查不出来(命令不可用、输出无法解析等),不要据此吓唬用户
|
||||||
|
Unknown(String),
|
||||||
|
/// 本平台不做自动放行(目前只有 Linux 会返回)
|
||||||
|
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
|
||||||
|
Unsupported(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FirewallStatus {
|
||||||
|
pub fn needs_action(&self) -> bool {
|
||||||
|
matches!(
|
||||||
|
self,
|
||||||
|
Self::Missing | Self::BlockedByPolicy(_) | Self::BlockedByRule(_)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 提权后加/删规则能否解决。
|
||||||
|
///
|
||||||
|
/// `BlockedByPolicy` 是系统级开关,我们不去动它——那属于用户的安全设置,
|
||||||
|
/// 只做提示,由用户自己决定是否关闭。
|
||||||
|
pub fn fixable_by_grant(&self) -> bool {
|
||||||
|
matches!(self, Self::Missing | Self::BlockedByRule(_))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 给界面用的一句话说明。
|
||||||
|
pub fn detail(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::Allowed => "入站已放行".into(),
|
||||||
|
Self::Missing => "缺少放行规则,手机可能连不上".into(),
|
||||||
|
Self::BlockedByPolicy(reason) | Self::Unknown(reason) => reason.clone(),
|
||||||
|
Self::BlockedByRule(names) => format!(
|
||||||
|
"存在阻止本程序入站的规则({names}),它的优先级高于放行规则。\
|
||||||
|
点「放行防火墙」会连同这些阻止规则一起清掉。"
|
||||||
|
),
|
||||||
|
Self::Unsupported(reason) => (*reason).to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_exe() -> Result<PathBuf> {
|
||||||
|
std::env::current_exe().context("无法获取本程序路径")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Windows
|
||||||
|
|
||||||
|
/// 探测脚本。刻意用 PowerShell 而不是 netsh:
|
||||||
|
///
|
||||||
|
/// `netsh advfirewall show` 的**值**也会跟随系统语言本地化(中文 Windows 上
|
||||||
|
/// 是「允许 / 阻止 / 任何 / 是」),按英文关键字匹配在中文系统上必然误判;
|
||||||
|
/// 而 `Get-NetFirewallRule` 返回的是枚举,`Allow`/`Block`/`Any`/`True`
|
||||||
|
/// 在任何语言下都是这几个字面量。
|
||||||
|
///
|
||||||
|
/// 输出被压成一行一条的管道分隔记录,便于用纯函数解析、也便于在非 Windows
|
||||||
|
/// 上对解析逻辑写测试。
|
||||||
|
/// 注意查询是**按程序路径**做的,不是只按规则显示名。
|
||||||
|
///
|
||||||
|
/// 用户在 Windows 弹出「安全警报」时点了「取消」,系统会自己建一条针对该
|
||||||
|
/// 可执行文件的**阻止**规则,名字是程序名而不是我们的 `QFT Desktop`。
|
||||||
|
/// 只按显示名查完全看不到它,却又是它压着我们的放行规则——
|
||||||
|
/// 表现就是「点了放行、界面显示已放行,手机依然连不上」。
|
||||||
|
fn probe_script(exe: &str) -> String {
|
||||||
|
format!(
|
||||||
|
r#"
|
||||||
|
$ErrorActionPreference='SilentlyContinue'
|
||||||
|
$exe = '{exe}'
|
||||||
|
Get-NetFirewallProfile | ForEach-Object {{
|
||||||
|
"PROFILE|$($_.Name)|$($_.Enabled)|$($_.DefaultInboundAction)|$($_.AllowInboundRules)"
|
||||||
|
}}
|
||||||
|
# 只查询当前 exe 路径。同名旧规则可能属于上一次构建目录;把它算成有效
|
||||||
|
# 会让界面显示绿色,但当前 qft-desktop.exe 的入站仍被全部拦截。
|
||||||
|
Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Sort-Object -Property Name -Unique | ForEach-Object {{
|
||||||
|
"RULE|$($_.Enabled)|$($_.Direction)|$($_.Action)|$($_.Profile)|$($_.DisplayName)"
|
||||||
|
}}
|
||||||
|
Get-NetFirewallRule -Name '{DIRECT_TCP_RULE}','{DIRECT_UDP_RULE}' | ForEach-Object {{
|
||||||
|
$rule = $_
|
||||||
|
$filter = $rule | Get-NetFirewallPortFilter
|
||||||
|
"PORT|$($rule.Enabled)|$($rule.Direction)|$($rule.Action)|$($rule.Profile)|$($filter.Protocol)|$($filter.LocalPort)|$($rule.Name)"
|
||||||
|
}}
|
||||||
|
"#,
|
||||||
|
// PowerShell 单引号字符串里只需把单引号写成两个,反斜杠不转义,
|
||||||
|
// 正好适合 Windows 路径
|
||||||
|
exe = exe.replace('\'', "''"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析 [`PROBE_SCRIPT`] 的输出。放在这里而不是内联,是为了能在任意平台
|
||||||
|
/// 上用真实样本做测试——Windows 专有逻辑最容易腐烂在没人跑的地方。
|
||||||
|
///
|
||||||
|
/// 判定顺序是有讲究的:
|
||||||
|
/// 1. **先看系统级策略**。`AllowInboundRules=False` 对应「阻止所有传入连接,
|
||||||
|
/// 包括位于允许应用列表中的应用」。这项打开时用户点多少次放行都没有
|
||||||
|
/// 任何变化,必须先报出来,否则会得出「规则已就绪」的错误结论。
|
||||||
|
/// 2. **再看有没有阻止规则**。Windows 里 Block 永远压过 Allow,旧版本残留
|
||||||
|
/// 的阻止规则会让新加的放行规则彻底失效,而界面上两条都显示「已启用」。
|
||||||
|
/// 3. **最后才看放行规则**,且必须是 `Any` profile——手机连的那块 Direct AP
|
||||||
|
/// 虚拟网卡会被判为「公用网络」,只覆盖专用/域的规则在它上面不适用。
|
||||||
|
pub fn classify_probe(probe_output: &str) -> FirewallStatus {
|
||||||
|
let mut any_firewall_on = false;
|
||||||
|
let mut blanket_block: Vec<&str> = Vec::new();
|
||||||
|
let mut has_block_rule = false;
|
||||||
|
let mut blocking_rules: Vec<&str> = Vec::new();
|
||||||
|
let mut has_usable_allow = false;
|
||||||
|
let mut has_direct_tcp = false;
|
||||||
|
let mut has_direct_udp = false;
|
||||||
|
|
||||||
|
for line in probe_output.lines() {
|
||||||
|
let fields: Vec<&str> = line.trim().split('|').collect();
|
||||||
|
match fields.as_slice() {
|
||||||
|
["PROFILE", name, enabled, _default_inbound, allow_inbound] => {
|
||||||
|
let on = enabled.eq_ignore_ascii_case("true");
|
||||||
|
any_firewall_on |= on;
|
||||||
|
// AllowInboundRules 还可能是 NotConfigured,那不算封禁
|
||||||
|
if on && allow_inbound.eq_ignore_ascii_case("false") {
|
||||||
|
blanket_block.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
["RULE", enabled, direction, action, profile, display_name] => {
|
||||||
|
if !direction.eq_ignore_ascii_case("inbound") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 只有启用中的阻止规则才真正生效
|
||||||
|
if action.eq_ignore_ascii_case("block") && enabled.eq_ignore_ascii_case("true") {
|
||||||
|
has_block_rule = true;
|
||||||
|
blocking_rules.push(*display_name);
|
||||||
|
} else if enabled.eq_ignore_ascii_case("true")
|
||||||
|
&& action.eq_ignore_ascii_case("allow")
|
||||||
|
&& profile.eq_ignore_ascii_case("any")
|
||||||
|
{
|
||||||
|
has_usable_allow = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
["PORT", enabled, direction, action, profile, protocol, local_port, _name] => {
|
||||||
|
let usable = enabled.eq_ignore_ascii_case("true")
|
||||||
|
&& direction.eq_ignore_ascii_case("inbound")
|
||||||
|
&& action.eq_ignore_ascii_case("allow")
|
||||||
|
&& profile.eq_ignore_ascii_case("any");
|
||||||
|
let port = local_port.parse::<u16>().ok();
|
||||||
|
if usable
|
||||||
|
&& (protocol.eq_ignore_ascii_case("tcp") || *protocol == "6")
|
||||||
|
&& port == Some(DIRECT_TCP_PORT)
|
||||||
|
{
|
||||||
|
has_direct_tcp = true;
|
||||||
|
}
|
||||||
|
if usable
|
||||||
|
&& (protocol.eq_ignore_ascii_case("udp") || *protocol == "17")
|
||||||
|
&& port == Some(DIRECT_UDP_PORT)
|
||||||
|
{
|
||||||
|
has_direct_udp = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !blanket_block.is_empty() {
|
||||||
|
return FirewallStatus::BlockedByPolicy(format!(
|
||||||
|
"{} 配置文件启用了「阻止所有传入连接,包括位于允许应用列表中的应用」。\
|
||||||
|
这一项打开时,放行规则不起任何作用,必须先在\
|
||||||
|
「Windows 安全中心 → 防火墙和网络保护」里把它关掉。",
|
||||||
|
blanket_block.join("、")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if has_block_rule {
|
||||||
|
// 这类规则多半是用户在「安全警报」弹窗上点了取消后由系统自动建的,
|
||||||
|
// 名字五花八门,所以把实际名字列出来,用户手动排查时才有的放矢。
|
||||||
|
return FirewallStatus::BlockedByRule(blocking_rules.join("、"));
|
||||||
|
}
|
||||||
|
// 防火墙整个关着时入站不会被拦,没必要要求存在规则
|
||||||
|
if !any_firewall_on || (has_usable_allow && has_direct_tcp && has_direct_udp) {
|
||||||
|
FirewallStatus::Allowed
|
||||||
|
} else {
|
||||||
|
FirewallStatus::Missing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 生成提权后要执行的放行脚本。
|
||||||
|
///
|
||||||
|
/// 不加 `#[cfg]`,好让脚本文本在任何平台上都能被测试——这段脚本上一版
|
||||||
|
/// 里混进了一个 `\` 续行(bash 语法,PowerShell 用反引号 `),
|
||||||
|
/// 结果脚本在用户机器上直接语法错误,而外层 `Start-Process -Wait` 返回的
|
||||||
|
/// 是启动器的退出码,程序还以为放行成功了。所以现在:
|
||||||
|
/// **一条命令占一行,绝不使用任何续行**,并且由脚本自己写一个成功标记,
|
||||||
|
/// 让调用方能验证它是真的跑完了。
|
||||||
|
fn grant_script(exe: &str, marker: &str) -> String {
|
||||||
|
let exe = exe.replace('\'', "''");
|
||||||
|
let marker = marker.replace('\'', "''");
|
||||||
|
format!(
|
||||||
|
"$ErrorActionPreference = 'Stop'\r\n\
|
||||||
|
$exe = '{exe}'\r\n\
|
||||||
|
$marker = '{marker}'\r\n\
|
||||||
|
# 先清掉一切针对本程序的入站阻止规则。Windows 在用户点掉「安全警报」\r\n\
|
||||||
|
# 弹窗时会自动建这种规则,名字是程序名,且优先级高于任何放行规则。\r\n\
|
||||||
|
$blocking = Get-NetFirewallApplicationFilter -Program $exe -ErrorAction SilentlyContinue | Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }}\r\n\
|
||||||
|
if ($blocking) {{ $blocking | Remove-NetFirewallRule -ErrorAction SilentlyContinue }}\r\n\
|
||||||
|
# 重建放行规则。Profile Any 是刻意的:Windows 把没见过的网络\r\n\
|
||||||
|
# (尤其是 Direct AP 虚拟网卡)默认归为公用网络。\r\n\
|
||||||
|
Remove-NetFirewallRule -DisplayName '{RULE_NAME}' -ErrorAction SilentlyContinue\r\n\
|
||||||
|
New-NetFirewallRule -DisplayName '{RULE_NAME}' -Direction Inbound -Program $exe -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
|
||||||
|
# 两条窄端口规则不依赖 exe 路径字符串的 WFP 归一化结果,专门兜住\r\n\
|
||||||
|
# Wi-Fi Direct 虚拟网卡上的 TCP/UDP 数据通道。\r\n\
|
||||||
|
Remove-NetFirewallRule -Name '{DIRECT_TCP_RULE}','{DIRECT_UDP_RULE}' -ErrorAction SilentlyContinue\r\n\
|
||||||
|
New-NetFirewallRule -Name '{DIRECT_TCP_RULE}' -DisplayName 'QFT Direct TCP' -Direction Inbound -Protocol TCP -LocalPort {DIRECT_TCP_PORT} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
|
||||||
|
New-NetFirewallRule -Name '{DIRECT_UDP_RULE}' -DisplayName 'QFT Direct UDP' -Direction Inbound -Protocol UDP -LocalPort {DIRECT_UDP_PORT} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
|
||||||
|
# 只有真的建成了才写标记,调用方据此判断成败\r\n\
|
||||||
|
Set-Content -Path $marker -Value 'ok' -Encoding ASCII\r\n"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
fn run_powershell(script: &str) -> std::io::Result<std::process::Output> {
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||||
|
std::process::Command::new("powershell")
|
||||||
|
.args(["-NoProfile", "-NonInteractive", "-Command", script])
|
||||||
|
.creation_flags(CREATE_NO_WINDOW)
|
||||||
|
.output()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn status() -> FirewallStatus {
|
||||||
|
let exe = match current_exe() {
|
||||||
|
Ok(path) => path.display().to_string(),
|
||||||
|
Err(e) => return FirewallStatus::Unknown(format!("{e}")),
|
||||||
|
};
|
||||||
|
match run_powershell(&probe_script(&exe)) {
|
||||||
|
Ok(out) => {
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout);
|
||||||
|
if text.trim().is_empty() {
|
||||||
|
return FirewallStatus::Unknown(
|
||||||
|
"防火墙查询没有返回任何内容,可能是 PowerShell 执行策略受限".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
classify_probe(&text)
|
||||||
|
}
|
||||||
|
Err(e) => FirewallStatus::Unknown(format!("无法执行 PowerShell:{e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 触发 UAC 并添加入站放行规则。
|
||||||
|
///
|
||||||
|
/// 用临时批处理承载命令,而不是把参数塞进 PowerShell 的 `-ArgumentList`:
|
||||||
|
/// 程序路径里带空格时,经过 PowerShell 再到 netsh 会被重新分词,
|
||||||
|
/// 引号层层嵌套极易出错。批处理文件由我们自己写死引号,不再被二次解析。
|
||||||
|
///
|
||||||
|
/// `profile=any` 是刻意的,早先写成 `private,domain` 是个真实的 bug:
|
||||||
|
/// Windows 对没见过的 Wi-Fi 默认归类为**公用网络**,此时 private 规则
|
||||||
|
/// 根本不适用——规则建了、也显示已启用,但连接照样被拦,极难排查。
|
||||||
|
/// 收窄到某个 profile 并不能带来实际安全收益:QFT 的入站真正靠的是
|
||||||
|
/// 连接码里的秘密加失败计数,没有秘密的连接一律被拒。
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn grant() -> Result<()> {
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||||
|
|
||||||
|
let exe = current_exe()?;
|
||||||
|
let temp = std::env::temp_dir();
|
||||||
|
let pid = std::process::id();
|
||||||
|
// 写成 .ps1 文件而不是把命令塞进 -ArgumentList:程序路径里带空格时,
|
||||||
|
// 经过 PowerShell 再到子进程会被重新分词,引号层层嵌套极易出错。
|
||||||
|
// 脚本文件里的单引号字符串不会被二次解析。
|
||||||
|
let script = temp.join(format!("qft-firewall-{pid}.ps1"));
|
||||||
|
let marker = temp.join(format!("qft-firewall-{pid}.ok"));
|
||||||
|
let _ = std::fs::remove_file(&marker);
|
||||||
|
std::fs::write(
|
||||||
|
&script,
|
||||||
|
grant_script(&exe.display().to_string(), &marker.display().to_string()),
|
||||||
|
)
|
||||||
|
.context("写入临时放行脚本失败")?;
|
||||||
|
|
||||||
|
let status = std::process::Command::new("powershell")
|
||||||
|
.args([
|
||||||
|
"-NoProfile",
|
||||||
|
"-WindowStyle",
|
||||||
|
"Hidden",
|
||||||
|
"-Command",
|
||||||
|
&format!(
|
||||||
|
"Start-Process -FilePath powershell -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','\"{}\"' -Verb RunAs -WindowStyle Hidden -Wait",
|
||||||
|
script.display()
|
||||||
|
),
|
||||||
|
])
|
||||||
|
.creation_flags(CREATE_NO_WINDOW)
|
||||||
|
.status();
|
||||||
|
|
||||||
|
let _ = std::fs::remove_file(&script);
|
||||||
|
// 外层退出码只能说明「UAC 弹窗流程本身」没出错,说明不了脚本跑没跑通:
|
||||||
|
// Start-Process -Wait 返回的是启动器的退出码,不是被提权进程的。
|
||||||
|
// 上一版就是因此把一个语法错误的脚本误报成了放行成功。
|
||||||
|
let succeeded = marker.exists();
|
||||||
|
let _ = std::fs::remove_file(&marker);
|
||||||
|
match status {
|
||||||
|
// 用户在 UAC 上点了「否」时 Start-Process 会失败,退出码非 0
|
||||||
|
Ok(s) if s.success() && succeeded => Ok(()),
|
||||||
|
Ok(s) if s.success() => bail!(
|
||||||
|
"提权成功但放行脚本没有跑完,规则未生效。请点「复制手动放行命令」,\
|
||||||
|
在管理员 PowerShell 里执行并把报错发出来"
|
||||||
|
),
|
||||||
|
Ok(_) => bail!("未获得管理员授权,防火墙规则没有添加"),
|
||||||
|
Err(e) => bail!("调用提权失败:{e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- macOS
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
pub fn status() -> FirewallStatus {
|
||||||
|
const TOOL: &str = "/usr/libexec/ApplicationFirewall/socketfilterfw";
|
||||||
|
if !std::path::Path::new(TOOL).exists() {
|
||||||
|
return FirewallStatus::Unknown("系统上没有 socketfilterfw".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 应用层防火墙没开时,入站根本不会被拦,不需要做任何事
|
||||||
|
match std::process::Command::new(TOOL).arg("--getglobalstate").output() {
|
||||||
|
Ok(out) => {
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout);
|
||||||
|
if text.contains("disabled") {
|
||||||
|
return FirewallStatus::Allowed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => return FirewallStatus::Unknown(format!("无法执行 socketfilterfw:{e}")),
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(exe) = current_exe() else {
|
||||||
|
return FirewallStatus::Unknown("无法获取本程序路径".into());
|
||||||
|
};
|
||||||
|
match std::process::Command::new(TOOL)
|
||||||
|
.args(["--getappblocked", &exe.display().to_string()])
|
||||||
|
.output()
|
||||||
|
{
|
||||||
|
Ok(out) => {
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
|
||||||
|
if text.contains("blocked") && !text.contains("not blocked") {
|
||||||
|
FirewallStatus::Missing
|
||||||
|
} else {
|
||||||
|
FirewallStatus::Allowed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => FirewallStatus::Unknown(format!("查询失败:{e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 通过系统授权对话框把本程序加入放行列表。
|
||||||
|
///
|
||||||
|
/// macOS 通常会在首次监听时自己弹「是否允许接受传入网络连接」,
|
||||||
|
/// 那一步就够了;这里只处理用户当时点了「拒绝」的情况。
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
pub fn grant() -> Result<()> {
|
||||||
|
let exe = current_exe()?;
|
||||||
|
let path = exe.display().to_string();
|
||||||
|
if path.contains('"') || path.contains('\\') {
|
||||||
|
bail!("程序路径包含无法安全转义的字符,请手动在「系统设置 → 网络 → 防火墙」里放行")
|
||||||
|
}
|
||||||
|
let inner = format!(
|
||||||
|
"/usr/libexec/ApplicationFirewall/socketfilterfw --add '{path}' && \
|
||||||
|
/usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp '{path}'"
|
||||||
|
);
|
||||||
|
let script = format!("do shell script \"{inner}\" with administrator privileges");
|
||||||
|
|
||||||
|
let status = std::process::Command::new("osascript")
|
||||||
|
.args(["-e", &script])
|
||||||
|
.status()
|
||||||
|
.context("调用 osascript 失败")?;
|
||||||
|
if status.success() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
bail!("未获得授权,防火墙放行没有生效")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Linux
|
||||||
|
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
pub fn status() -> FirewallStatus {
|
||||||
|
// 各发行版的防火墙前端差异过大(ufw / firewalld / 裸 iptables / nftables),
|
||||||
|
// 自动改规则风险高于收益,只做检测与提示。
|
||||||
|
FirewallStatus::Unsupported("Linux 上请按下方提示手动放行")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
pub fn grant() -> Result<()> {
|
||||||
|
bail!("Linux 上不自动修改防火墙,请按界面提示手动执行")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 手动说明
|
||||||
|
|
||||||
|
/// 自动放行失败或不支持时,给用户可以照抄的命令。
|
||||||
|
pub fn manual_instructions(port: u16) -> String {
|
||||||
|
let exe = current_exe()
|
||||||
|
.map(|p| p.display().to_string())
|
||||||
|
.unwrap_or_else(|_| "qft-desktop".into());
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
// -Profile Any 是必须的。这里早先写的是 Private,Domain,与本模块
|
||||||
|
// grant() 的注释自相矛盾,照抄的用户会重建出一条在公用网络上
|
||||||
|
// (也就是 Direct AP 虚拟网卡上)根本不适用的规则。
|
||||||
|
// 剪贴板里**只放命令**,不放任何说明文字。用户是整段粘进 PowerShell 的,
|
||||||
|
// 混在里面的中文散文会被当成 cmdlet 名逐行报错,把真正的报错淹没掉。
|
||||||
|
// 同理绝不使用 `\` 续行——那是 bash 语法,PowerShell 用反引号;
|
||||||
|
// 一条命令就写一行,宁可长。
|
||||||
|
format!(
|
||||||
|
concat!(
|
||||||
|
"# 在管理员 PowerShell 中整段粘贴执行\n",
|
||||||
|
"$exe = \"{exe}\"\n",
|
||||||
|
"Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} | Remove-NetFirewallRule\n",
|
||||||
|
"Remove-NetFirewallRule -DisplayName \"{RULE_NAME}\" -ErrorAction SilentlyContinue\n",
|
||||||
|
"New-NetFirewallRule -DisplayName \"{RULE_NAME}\" -Direction Inbound -Program $exe -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
|
||||||
|
"Remove-NetFirewallRule -Name \"{DIRECT_TCP_RULE}\",\"{DIRECT_UDP_RULE}\" -ErrorAction SilentlyContinue\n",
|
||||||
|
"New-NetFirewallRule -Name \"{DIRECT_TCP_RULE}\" -DisplayName \"QFT Direct TCP\" -Direction Inbound -Protocol TCP -LocalPort {port} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
|
||||||
|
"New-NetFirewallRule -Name \"{DIRECT_UDP_RULE}\" -DisplayName \"QFT Direct UDP\" -Direction Inbound -Protocol UDP -LocalPort {udp_port} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
|
||||||
|
"Get-NetFirewallProfile | Select-Object Name,Enabled,AllowInboundRules\n",
|
||||||
|
"Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Select-Object DisplayName,Enabled,Direction,Action,Profile\n",
|
||||||
|
),
|
||||||
|
exe = exe,
|
||||||
|
RULE_NAME = RULE_NAME,
|
||||||
|
DIRECT_TCP_RULE = DIRECT_TCP_RULE,
|
||||||
|
DIRECT_UDP_RULE = DIRECT_UDP_RULE,
|
||||||
|
port = port,
|
||||||
|
udp_port = port.saturating_sub(1),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
let _ = port;
|
||||||
|
format!(
|
||||||
|
"打开「系统设置 → 网络 → 防火墙 → 选项」,把下面这个程序设为\
|
||||||
|
「允许传入连接」:\n\n{exe}\n\n\
|
||||||
|
若防火墙本身是关闭的,则无需任何操作。"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
{
|
||||||
|
let _ = exe;
|
||||||
|
format!(
|
||||||
|
"按你所用的防火墙执行其一:\n\n\
|
||||||
|
ufw: sudo ufw allow {port}/tcp && sudo ufw allow {}/udp\n\
|
||||||
|
firewalld: sudo firewall-cmd --add-port={port}/tcp --add-port={}/udp --permanent && sudo firewall-cmd --reload",
|
||||||
|
port - 1,
|
||||||
|
port - 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_query_never_panics_and_is_classified() {
|
||||||
|
// 只做只读查询,不改动任何系统设置
|
||||||
|
let value = status();
|
||||||
|
match &value {
|
||||||
|
FirewallStatus::Allowed
|
||||||
|
| FirewallStatus::Missing
|
||||||
|
| FirewallStatus::Unsupported(_) => {}
|
||||||
|
FirewallStatus::Unknown(reason)
|
||||||
|
| FirewallStatus::BlockedByPolicy(reason)
|
||||||
|
| FirewallStatus::BlockedByRule(reason) => {
|
||||||
|
assert!(!reason.is_empty(), "原因说明不能为空")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Allowed / Unknown / Unsupported 都不该催促用户去点按钮
|
||||||
|
assert_eq!(
|
||||||
|
value.needs_action(),
|
||||||
|
matches!(
|
||||||
|
value,
|
||||||
|
FirewallStatus::Missing
|
||||||
|
| FirewallStatus::BlockedByPolicy(_)
|
||||||
|
| FirewallStatus::BlockedByRule(_)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn manual_instructions_mention_the_actual_program() {
|
||||||
|
let text = manual_instructions(39393);
|
||||||
|
assert!(!text.trim().is_empty());
|
||||||
|
// 说明里必须出现可操作的东西:程序路径或具体端口
|
||||||
|
assert!(
|
||||||
|
text.contains("qft") || text.contains("39393") || text.contains("防火墙"),
|
||||||
|
"说明应包含可操作信息:{text}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 探测脚本的输出形状是固定的,解析逻辑在任何平台上都能测。
|
||||||
|
// Windows 专有代码最容易腐烂在没人跑的地方,这几个用例就是防这个的。
|
||||||
|
const PROFILES_OK: &str = "PROFILE|Domain|True|Block|True\n\
|
||||||
|
PROFILE|Private|True|Block|True\n\
|
||||||
|
PROFILE|Public|True|Block|True";
|
||||||
|
const DIRECT_PORTS_OK: &str = "PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
|
||||||
|
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn allow_rule_must_cover_any_profile() {
|
||||||
|
let only_private = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Domain, Private|QFT Desktop");
|
||||||
|
assert_eq!(classify_probe(&only_private), FirewallStatus::Missing);
|
||||||
|
|
||||||
|
let any = format!(
|
||||||
|
"{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop\n{DIRECT_PORTS_OK}"
|
||||||
|
);
|
||||||
|
assert_eq!(classify_probe(&any), FirewallStatus::Allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disabled_allow_rule_does_not_count() {
|
||||||
|
let text = format!("{PROFILES_OK}\nRULE|False|Inbound|Allow|Any|QFT Desktop");
|
||||||
|
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_program_rule_without_direct_ports_is_migrated() {
|
||||||
|
let old = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop");
|
||||||
|
assert_eq!(classify_probe(&old), FirewallStatus::Missing);
|
||||||
|
|
||||||
|
let only_tcp = format!("{old}\n{}", DIRECT_PORTS_OK.lines().next().unwrap());
|
||||||
|
assert_eq!(classify_probe(&only_tcp), FirewallStatus::Missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outbound_rules_are_irrelevant() {
|
||||||
|
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Allow|Any|QFT Desktop");
|
||||||
|
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||||||
|
// 出站的阻止规则同样不该被误判成入站被拦
|
||||||
|
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Block|Any|随便什么");
|
||||||
|
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 这是「点了放行还是连不上」最常见的成因:用户在安全警报弹窗上点了取消,
|
||||||
|
/// 系统按程序路径建了一条阻止规则,名字和我们的规则完全不同。
|
||||||
|
#[test]
|
||||||
|
fn auto_created_block_rule_beats_our_allow_rule() {
|
||||||
|
let text = format!(
|
||||||
|
"{PROFILES_OK}\n\
|
||||||
|
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||||
|
RULE|True|Inbound|Block|Public|qft-desktop.exe"
|
||||||
|
);
|
||||||
|
match classify_probe(&text) {
|
||||||
|
FirewallStatus::BlockedByRule(names) => {
|
||||||
|
assert!(names.contains("qft-desktop.exe"), "要报出实际规则名:{names}");
|
||||||
|
}
|
||||||
|
other => panic!("阻止规则必须压过放行规则,实际判定为 {other:?}"),
|
||||||
|
}
|
||||||
|
// 这一类是可以靠提权自动清掉的
|
||||||
|
assert!(classify_probe(&text).fixable_by_grant());
|
||||||
|
assert!(classify_probe(&text).needs_action());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disabled_block_rule_is_harmless() {
|
||||||
|
let text = format!(
|
||||||
|
"{PROFILES_OK}\n\
|
||||||
|
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||||
|
RULE|False|Inbound|Block|Public|qft-desktop.exe\n\
|
||||||
|
{DIRECT_PORTS_OK}"
|
||||||
|
);
|
||||||
|
assert_eq!(classify_probe(&text), FirewallStatus::Allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 「阻止所有传入连接」打开时,加多少放行规则都没用,
|
||||||
|
/// 必须报成另一种状态,否则用户会一直点那个不起作用的按钮。
|
||||||
|
#[test]
|
||||||
|
fn blanket_inbound_block_is_reported_separately() {
|
||||||
|
let text = "PROFILE|Domain|True|Block|True\n\
|
||||||
|
PROFILE|Private|True|Block|True\n\
|
||||||
|
PROFILE|Public|True|Block|False\n\
|
||||||
|
RULE|True|Inbound|Allow|Any|QFT Desktop";
|
||||||
|
match classify_probe(text) {
|
||||||
|
FirewallStatus::BlockedByPolicy(reason) => {
|
||||||
|
assert!(reason.contains("Public"), "要指出是哪个配置文件:{reason}");
|
||||||
|
}
|
||||||
|
other => panic!("应报告系统级封禁,实际为 {other:?}"),
|
||||||
|
}
|
||||||
|
// 这一类我们不去动,属于用户的安全设置
|
||||||
|
assert!(!classify_probe(text).fixable_by_grant());
|
||||||
|
assert!(classify_probe(text).needs_action());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blanket_block_on_a_disabled_profile_is_ignored() {
|
||||||
|
// 防火墙本身关着的配置文件,AllowInboundRules 是什么都无所谓
|
||||||
|
let text = "PROFILE|Domain|True|Block|True\n\
|
||||||
|
PROFILE|Private|True|Block|True\n\
|
||||||
|
PROFILE|Public|False|Block|False\n\
|
||||||
|
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||||
|
PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
|
||||||
|
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
|
||||||
|
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn firewall_entirely_off_needs_no_rule() {
|
||||||
|
let text = "PROFILE|Domain|False|Block|True\n\
|
||||||
|
PROFILE|Private|False|Block|True\n\
|
||||||
|
PROFILE|Public|False|Block|True";
|
||||||
|
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn not_configured_inbound_setting_is_not_a_blanket_block() {
|
||||||
|
let text = "PROFILE|Public|True|Block|NotConfigured\n\
|
||||||
|
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
|
||||||
|
PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
|
||||||
|
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
|
||||||
|
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_status_has_a_non_empty_detail() {
|
||||||
|
for value in [
|
||||||
|
FirewallStatus::Allowed,
|
||||||
|
FirewallStatus::Missing,
|
||||||
|
FirewallStatus::BlockedByPolicy("策略".into()),
|
||||||
|
FirewallStatus::BlockedByRule("规则名".into()),
|
||||||
|
FirewallStatus::Unknown("原因".into()),
|
||||||
|
FirewallStatus::Unsupported("不支持"),
|
||||||
|
] {
|
||||||
|
assert!(!value.detail().trim().is_empty(), "{value:?} 缺少说明文案");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn manual_instructions_never_recreate_the_profile_bug() {
|
||||||
|
let text = manual_instructions(39393);
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
assert!(
|
||||||
|
text.contains("-Profile Any"),
|
||||||
|
"手动命令必须覆盖所有网络类型,否则在公用网络上无效:{text}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!text.contains("Private,Domain"),
|
||||||
|
"照抄这条命令会重建出在 Direct AP 网卡上不适用的规则:{text}"
|
||||||
|
);
|
||||||
|
// 用户是整段粘进 PowerShell 的,任何非命令行都会被当成 cmdlet 报错
|
||||||
|
for line in text.lines() {
|
||||||
|
let line = line.trim();
|
||||||
|
assert!(
|
||||||
|
line.is_empty()
|
||||||
|
|| line.starts_with('#')
|
||||||
|
|| line.starts_with('$')
|
||||||
|
|| line.starts_with("Get-")
|
||||||
|
|| line.starts_with("New-")
|
||||||
|
|| line.starts_with("Remove-"),
|
||||||
|
"剪贴板里只能有命令和注释,这一行会被 PowerShell 当成 cmdlet:{line}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `\` 续行是 bash 语法,PowerShell 用反引号。上一版在提权脚本和手动
|
||||||
|
/// 命令里都写了 `\`,导致脚本在用户机器上直接语法错误,而外层退出码
|
||||||
|
/// 又是 0,程序还误报了「放行成功」。
|
||||||
|
#[test]
|
||||||
|
fn generated_scripts_use_no_backslash_continuation() {
|
||||||
|
let script = grant_script(r"C:\Program Files\QFT\qft-desktop.exe", r"C:\Temp\qft.ok");
|
||||||
|
for (index, line) in script.lines().enumerate() {
|
||||||
|
assert!(
|
||||||
|
!line.trim_end().ends_with('\\'),
|
||||||
|
"第 {} 行用了 bash 的 `\\` 续行,PowerShell 不认:{line}",
|
||||||
|
index + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(!manual_instructions(39393).contains("\\\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grant_script_quotes_paths_and_reports_success() {
|
||||||
|
let script = grant_script(r"C:\Program Files\QFT\qft-desktop.exe", r"C:\Temp\qft.ok");
|
||||||
|
// 带空格的路径必须整体在单引号里,否则会被重新分词
|
||||||
|
assert!(script.contains(r"$exe = 'C:\Program Files\QFT\qft-desktop.exe'"));
|
||||||
|
// 必须写成功标记,否则调用方无法区分「跑通了」和「脚本报错了」
|
||||||
|
assert!(script.contains("Set-Content -Path $marker"));
|
||||||
|
assert!(script.contains("-Profile Any"));
|
||||||
|
assert!(script.contains("-EdgeTraversalPolicy Allow"));
|
||||||
|
assert!(script.contains("-Protocol TCP -LocalPort 39393"));
|
||||||
|
assert!(script.contains("-Protocol UDP -LocalPort 39392"));
|
||||||
|
// 单引号要按 PowerShell 的规则翻倍转义
|
||||||
|
let tricky = grant_script("C:\\o'brien\\qft.exe", "C:\\t.ok");
|
||||||
|
assert!(tricky.contains("'C:\\o''brien\\qft.exe'"), "{tricky}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn probe_never_counts_a_same_named_rule_for_an_old_executable() {
|
||||||
|
let script = probe_script(r"C:\new-build\qft-desktop.exe");
|
||||||
|
assert!(script.contains("Get-NetFirewallApplicationFilter -Program $exe"));
|
||||||
|
assert!(
|
||||||
|
!script.contains("Get-NetFirewallRule -DisplayName"),
|
||||||
|
"只按同名规则查询会把旧构建路径误判为已放行:{script}"
|
||||||
|
);
|
||||||
|
assert!(script.contains("Get-NetFirewallRule -Name 'QFT-Desktop-Direct-TCP-v2'"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_is_read_only_and_repeatable() {
|
||||||
|
// 检测必须无副作用:连续调用结果一致,且不改动任何系统设置
|
||||||
|
assert_eq!(status(), status());
|
||||||
|
}
|
||||||
|
}
|
||||||
+2338
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,424 @@
|
|||||||
|
use anyhow::{Context, Result};
|
||||||
|
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||||
|
use rand::RngCore;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
net::{IpAddr, Ipv4Addr},
|
||||||
|
path::PathBuf,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const PAIR_PREFIX: &str = "QFTPAIR2:";
|
||||||
|
pub const SEND_PREFIX: &str = "QFTSEND2:";
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct PairingPayload {
|
||||||
|
pub v: u8,
|
||||||
|
pub session: String,
|
||||||
|
pub pc_name: String,
|
||||||
|
pub transport: String,
|
||||||
|
pub port: u16,
|
||||||
|
pub endpoints: Vec<String>,
|
||||||
|
pub wifi: Option<WifiCredentials>,
|
||||||
|
/// `upload` means Android uploads to this PC. `download` means the PC has
|
||||||
|
/// selected a file and Android downloads it immediately after pairing.
|
||||||
|
pub direction: PairingDirection,
|
||||||
|
pub file_name: Option<String>,
|
||||||
|
pub file_size: Option<u64>,
|
||||||
|
pub sha256: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum PairingDirection {
|
||||||
|
Upload,
|
||||||
|
Download,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct WifiCredentials {
|
||||||
|
pub ssid: String,
|
||||||
|
pub passphrase: String,
|
||||||
|
pub security: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
struct DirectApIdentity {
|
||||||
|
version: u8,
|
||||||
|
ssid: String,
|
||||||
|
passphrase: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PairingPayload {
|
||||||
|
/// v2 intentionally uses short JSON keys. A Direct-AP QR carries only the
|
||||||
|
/// dedicated Wi-Fi identity, session and port: Android must join that Wi-Fi
|
||||||
|
/// and obtain the desktop gateway from the resulting route table. Existing
|
||||||
|
/// LAN/virtual-adapter addresses are deliberately excluded so they cannot
|
||||||
|
/// bypass or delay dedicated pairing.
|
||||||
|
pub fn encode_text(&self) -> Result<String> {
|
||||||
|
let endpoints: Vec<&str> = if self.wifi.is_some() {
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
self.endpoints.iter().take(4).map(String::as_str).collect()
|
||||||
|
};
|
||||||
|
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
|
||||||
|
let mut value = json!({
|
||||||
|
"v": 2,
|
||||||
|
"s": self.session,
|
||||||
|
"n": self.pc_name,
|
||||||
|
"p": self.port,
|
||||||
|
"e": endpoints,
|
||||||
|
"w": wifi,
|
||||||
|
});
|
||||||
|
// Keep the common Android → PC QR as small as before. File metadata is
|
||||||
|
// needed only for the new PC → Android automatic-download QR.
|
||||||
|
if self.direction == PairingDirection::Download {
|
||||||
|
let object = value.as_object_mut().expect("pairing JSON object");
|
||||||
|
object.insert("d".into(), Value::String("d".into()));
|
||||||
|
object.insert("f".into(), serde_json::to_value(&self.file_name)?);
|
||||||
|
object.insert("z".into(), serde_json::to_value(self.file_size)?);
|
||||||
|
object.insert("h".into(), serde_json::to_value(&self.sha256)?);
|
||||||
|
}
|
||||||
|
let json = serde_json::to_vec(&value).context("serialize pairing payload")?;
|
||||||
|
let prefix = match self.direction {
|
||||||
|
PairingDirection::Upload => PAIR_PREFIX,
|
||||||
|
PairingDirection::Download => SEND_PREFIX,
|
||||||
|
};
|
||||||
|
Ok(format!("{prefix}{}", URL_SAFE_NO_PAD.encode(json)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_session_token() -> String {
|
||||||
|
let mut bytes = [0u8; 16];
|
||||||
|
rand::rng().fill_bytes(&mut bytes);
|
||||||
|
URL_SAFE_NO_PAD.encode(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode an authenticated Direct discovery datagram. `Some(None)` preserves
|
||||||
|
/// compatibility with older Android builds that did not include a device name.
|
||||||
|
pub fn discovery_device(text: &str, session: &str) -> Option<Option<String>> {
|
||||||
|
let prefix = format!("QFTDISC2:{session}");
|
||||||
|
if text == prefix {
|
||||||
|
return Some(None);
|
||||||
|
}
|
||||||
|
let encoded = text.strip_prefix(&(prefix + ":"))?;
|
||||||
|
let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
|
||||||
|
let name = String::from_utf8(bytes).ok()?;
|
||||||
|
let clean: String = name
|
||||||
|
.chars()
|
||||||
|
.filter(|c| !c.is_control())
|
||||||
|
.take(80)
|
||||||
|
.collect();
|
||||||
|
(!clean.trim().is_empty()).then_some(Some(clean))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep one random AP identity per Windows device so Android can remember the
|
||||||
|
/// user's approval for that exact local-only network. The AP itself is only
|
||||||
|
/// active while QFT receive mode is running; the file-transfer session token is
|
||||||
|
/// regenerated every time receive mode starts.
|
||||||
|
pub fn load_or_create_direct_ap_credentials(pc_name: &str) -> Result<(String, String)> {
|
||||||
|
let path = direct_ap_identity_path();
|
||||||
|
if let Ok(bytes) = fs::read(&path) {
|
||||||
|
if let Ok(identity) = serde_json::from_slice::<DirectApIdentity>(&bytes) {
|
||||||
|
if identity.version == 1
|
||||||
|
&& !identity.ssid.trim().is_empty()
|
||||||
|
&& (8..=63).contains(&identity.passphrase.len())
|
||||||
|
{
|
||||||
|
return Ok((identity.ssid, identity.passphrase));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (ssid, passphrase) = new_direct_ap_credentials(pc_name);
|
||||||
|
let identity = DirectApIdentity {
|
||||||
|
version: 1,
|
||||||
|
ssid: ssid.clone(),
|
||||||
|
passphrase: passphrase.clone(),
|
||||||
|
};
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
fs::create_dir_all(parent)
|
||||||
|
.with_context(|| format!("创建 QFT 配置目录 {} 失败", parent.display()))?;
|
||||||
|
}
|
||||||
|
let tmp = path.with_extension("json.tmp");
|
||||||
|
let json = serde_json::to_vec_pretty(&identity)?;
|
||||||
|
fs::write(&tmp, json)
|
||||||
|
.with_context(|| format!("保存 QFT Direct 身份 {} 失败", tmp.display()))?;
|
||||||
|
if path.exists() {
|
||||||
|
let _ = fs::remove_file(&path);
|
||||||
|
}
|
||||||
|
fs::rename(&tmp, &path)
|
||||||
|
.with_context(|| format!("完成 QFT Direct 身份保存 {} 失败", path.display()))?;
|
||||||
|
Ok((ssid, passphrase))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset_direct_ap_credentials() -> Result<()> {
|
||||||
|
let path = direct_ap_identity_path();
|
||||||
|
if path.exists() {
|
||||||
|
fs::remove_file(&path)
|
||||||
|
.with_context(|| format!("删除 QFT Direct 身份 {} 失败", path.display()))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn direct_ap_identity_path() -> PathBuf {
|
||||||
|
crate::platform::config_dir().join("direct-ap.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_direct_ap_credentials(pc_name: &str) -> (String, String) {
|
||||||
|
let suffix = new_session_token();
|
||||||
|
let suffix = &suffix[..6.min(suffix.len())];
|
||||||
|
let base: String = pc_name
|
||||||
|
.chars()
|
||||||
|
.filter(|c| c.is_ascii_alphanumeric())
|
||||||
|
.take(10)
|
||||||
|
.collect();
|
||||||
|
let base = if base.is_empty() { "PC" } else { &base };
|
||||||
|
let ssid = format!("QFT-{base}-{suffix}");
|
||||||
|
|
||||||
|
let mut random = [0u8; 12];
|
||||||
|
rand::rng().fill_bytes(&mut random);
|
||||||
|
let password = URL_SAFE_NO_PAD.encode(random);
|
||||||
|
(ssid, password[..16.min(password.len())].to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本机可用的私有 IPv4 地址,按「最可能是对方看得到的那一个」排序。
|
||||||
|
///
|
||||||
|
/// 连接码把地址编进码里,所以这里的排序直接决定了用户第一眼看到的那串码
|
||||||
|
/// 是否好用。虚拟网卡(Docker/VPN/虚拟机桥接)会排到后面。
|
||||||
|
pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
|
||||||
|
let mut ips = Vec::<Ipv4Addr>::new();
|
||||||
|
if let Ok(addrs) = if_addrs::get_if_addrs() {
|
||||||
|
for iface in addrs {
|
||||||
|
let IpAddr::V4(ip) = iface.ip() else { continue };
|
||||||
|
if ip.is_loopback() || ip.is_unspecified() || ip.is_link_local() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !ip.is_private() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !ips.contains(&ip) {
|
||||||
|
ips.push(ip);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ips.sort_by_key(|ip| {
|
||||||
|
let o = ip.octets();
|
||||||
|
if is_likely_virtual(*ip) {
|
||||||
|
return 4;
|
||||||
|
}
|
||||||
|
match (o[0], o[1]) {
|
||||||
|
(192, 168) => 1,
|
||||||
|
(10, _) => 2,
|
||||||
|
(172, 16..=31) => 3,
|
||||||
|
_ => 4,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ips
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 供二维码使用的端点列表。
|
||||||
|
///
|
||||||
|
/// Direct AP 模式不广播任何电脑现有网卡地址。手机必须先加入二维码中的
|
||||||
|
/// 专用 Wi-Fi,再从 Android 为该连接提供的实际路由表读取网关。这样不会
|
||||||
|
/// 猜测 192.168.137.1/49.1,也不会误连 LAN、VPN、WSL 或虚拟机网卡。
|
||||||
|
pub fn qr_endpoints(port: u16, direct_ap_active: bool) -> Vec<String> {
|
||||||
|
if direct_ap_active {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
local_ipv4_endpoints(port)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_likely_virtual(ip: Ipv4Addr) -> bool {
|
||||||
|
let o = ip.octets();
|
||||||
|
if o[3] != 1 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match (o[0], o[1]) {
|
||||||
|
// VMware Workstation 常用 192.168.(1..=254).1 里的高位段;
|
||||||
|
// 这里只挑实测遇到的与常见默认值,避免误伤家用 192.168.0/1.1
|
||||||
|
(192, 168) => matches!(o[2], 30 | 31 | 56 | 99 | 100 | 152 | 174 | 226),
|
||||||
|
// WSL2 / Hyper-V 默认在 172.16-31 段
|
||||||
|
(172, 16..=31) => true,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
|
||||||
|
// 备用 LAN 模式也只广播系统中真实存在的私有地址,不再追加
|
||||||
|
// 192.168.137.1/49.1 等猜测值。Android 随后还会按实际子网过滤。
|
||||||
|
local_ipv4_addresses().into_iter()
|
||||||
|
.map(|ip| format!("http://{ip}:{port}"))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn discovery_request_reports_android_name_and_accepts_legacy_format() {
|
||||||
|
let session = "abcdefghijklmnopqrstuvwxyz012345";
|
||||||
|
let name = URL_SAFE_NO_PAD.encode("HUAWEI CDY-AN90".as_bytes());
|
||||||
|
assert_eq!(
|
||||||
|
discovery_device(&format!("QFTDISC2:{session}:{name}"), session),
|
||||||
|
Some(Some("HUAWEI CDY-AN90".into()))
|
||||||
|
);
|
||||||
|
assert_eq!(discovery_device(&format!("QFTDISC2:{session}"), session), Some(None));
|
||||||
|
assert_eq!(discovery_device("QFTDISC2:wrong", session), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_pairing_uses_dedicated_short_prefix() {
|
||||||
|
let payload = PairingPayload {
|
||||||
|
v: 2,
|
||||||
|
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
|
||||||
|
pc_name: "DESKTOP-QFT".into(),
|
||||||
|
transport: "http-download-v2".into(),
|
||||||
|
port: 39393,
|
||||||
|
endpoints: vec!["http://192.168.49.1:39393".into()],
|
||||||
|
wifi: None,
|
||||||
|
direction: PairingDirection::Download,
|
||||||
|
file_name: Some("sample.bin".into()),
|
||||||
|
file_size: Some(42),
|
||||||
|
sha256: Some("00".repeat(32)),
|
||||||
|
};
|
||||||
|
let text = payload.encode_text().unwrap();
|
||||||
|
assert!(text.starts_with(SEND_PREFIX));
|
||||||
|
assert!(text.len() < 800);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod endpoint_order_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn current_lan_endpoints_are_all_real_private_interfaces() {
|
||||||
|
let endpoints = local_ipv4_endpoints(39393);
|
||||||
|
let real: Vec<Ipv4Addr> = local_ipv4_addresses();
|
||||||
|
let expected: Vec<String> = real
|
||||||
|
.iter()
|
||||||
|
.map(|address| format!("http://{address}:39393"))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(endpoints, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn direct_pairing_excludes_every_preexisting_computer_address() {
|
||||||
|
let payload = PairingPayload {
|
||||||
|
v: 2,
|
||||||
|
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
|
||||||
|
pc_name: "PC".into(),
|
||||||
|
transport: "http-parallel-v2".into(),
|
||||||
|
port: 39393,
|
||||||
|
endpoints: vec![
|
||||||
|
"http://192.168.137.1:39393".into(),
|
||||||
|
"http://192.168.8.68:39393".into(),
|
||||||
|
],
|
||||||
|
wifi: Some(WifiCredentials {
|
||||||
|
ssid: "QFT-PC-abc".into(),
|
||||||
|
passphrase: "0123456789ab".into(),
|
||||||
|
security: "WPA2".into(),
|
||||||
|
}),
|
||||||
|
direction: PairingDirection::Upload,
|
||||||
|
file_name: None,
|
||||||
|
file_size: None,
|
||||||
|
sha256: None,
|
||||||
|
};
|
||||||
|
let text = payload.encode_text().unwrap();
|
||||||
|
let json = String::from_utf8(
|
||||||
|
base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||||
|
.decode(text.trim_start_matches(PAIR_PREFIX))
|
||||||
|
.unwrap(),
|
||||||
|
).unwrap();
|
||||||
|
assert!(!json.contains("192.168.8.68"), "Direct 二维码不得携带 LAN 地址:{json}");
|
||||||
|
assert!(!json.contains("192.168.137.1"), "Direct 二维码不得猜测 AP 网关:{json}");
|
||||||
|
assert!(json.contains("\"e\":[]"), "Direct 二维码端点必须为空:{json}");
|
||||||
|
assert!(json.contains("QFT-PC-abc"), "专用 Wi-Fi 身份必须保留:{json}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod qr_endpoint_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn direct_ap_never_advertises_guessed_or_local_addresses() {
|
||||||
|
let endpoints = qr_endpoints(39393, true);
|
||||||
|
assert!(endpoints.is_empty(), "Direct 模式只能由手机读取实际网关:{endpoints:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn direct_ap_encoding_stays_address_free_even_with_input_endpoints() {
|
||||||
|
let payload = PairingPayload {
|
||||||
|
v: 2,
|
||||||
|
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
|
||||||
|
pc_name: "PC".into(),
|
||||||
|
transport: "http-parallel-v2".into(),
|
||||||
|
port: 39393,
|
||||||
|
endpoints: vec![
|
||||||
|
"http://192.168.137.1:39393".into(),
|
||||||
|
"http://10.20.30.40:39393".into(),
|
||||||
|
],
|
||||||
|
wifi: Some(WifiCredentials {
|
||||||
|
ssid: "QFT-PC-abc".into(),
|
||||||
|
passphrase: "0123456789ab".into(),
|
||||||
|
security: "WPA2".into(),
|
||||||
|
}),
|
||||||
|
direction: PairingDirection::Upload,
|
||||||
|
file_name: None,
|
||||||
|
file_size: None,
|
||||||
|
sha256: None,
|
||||||
|
};
|
||||||
|
let text = payload.encode_text().unwrap();
|
||||||
|
let json = String::from_utf8(
|
||||||
|
base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||||
|
.decode(text.trim_start_matches(PAIR_PREFIX))
|
||||||
|
.unwrap(),
|
||||||
|
).unwrap();
|
||||||
|
assert!(!json.contains("192.168.137.1"), "不得携带猜测网关:{json}");
|
||||||
|
assert!(!json.contains("10.20.30.40"), "不得携带本地网卡:{json}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn without_direct_ap_no_guessed_addresses_are_added() {
|
||||||
|
let endpoints = qr_endpoints(39393, false);
|
||||||
|
let real = local_ipv4_addresses();
|
||||||
|
for guessed in ["192.168.137.1", "192.168.49.1"] {
|
||||||
|
if !real.iter().any(|ip| ip.to_string() == guessed) {
|
||||||
|
assert!(
|
||||||
|
!endpoints.iter().any(|endpoint| endpoint.contains(guessed)),
|
||||||
|
"不存在的地址不得加入二维码:{endpoints:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod virtual_adapter_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// 实测中这三个虚拟网卡地址把 Direct AP 网关挤出了二维码。
|
||||||
|
#[test]
|
||||||
|
fn known_virtual_ranges_are_recognised() {
|
||||||
|
for ip in ["192.168.30.1", "192.168.31.1", "172.21.96.1", "172.17.0.1"] {
|
||||||
|
assert!(is_likely_virtual(ip.parse().unwrap()), "{ip} 应被识别为虚拟网卡");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 家用路由器最常见的网关不能被误伤,否则真实局域网地址反被降权。
|
||||||
|
#[test]
|
||||||
|
fn common_home_gateways_are_not_treated_as_virtual() {
|
||||||
|
for ip in ["192.168.0.1", "192.168.1.1", "192.168.8.1", "10.0.0.1"] {
|
||||||
|
assert!(!is_likely_virtual(ip.parse().unwrap()), "{ip} 不应被当作虚拟网卡");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只有 .1 结尾才可能是虚拟网关;普通主机地址一律不降权。
|
||||||
|
#[test]
|
||||||
|
fn only_gateway_addresses_are_considered() {
|
||||||
|
assert!(!is_likely_virtual("192.168.30.55".parse().unwrap()));
|
||||||
|
assert!(!is_likely_virtual("172.21.96.200".parse().unwrap()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
//! 平台差异的唯一收敛点。
|
||||||
|
//!
|
||||||
|
//! 约定:除本文件与 `direct_ap.rs` 外,其余模块不得出现 `#[cfg(target_os = ...)]`。
|
||||||
|
//! 新增平台差异时先在这里补一个函数,不要就地 cfg —— 否则跨平台移植会重新变成
|
||||||
|
//! 满仓库找 cfg 的考古工作。
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// QFT 的持久化配置目录(Direct AP 身份、信任库等)。
|
||||||
|
///
|
||||||
|
/// - Windows: `%LOCALAPPDATA%\QFT`
|
||||||
|
/// - macOS: `~/Library/Application Support/QFT`
|
||||||
|
/// - Linux: `$XDG_CONFIG_HOME/qft`,未设置时 `~/.config/qft`
|
||||||
|
pub fn config_dir() -> PathBuf {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
if let Some(root) = non_empty_env("LOCALAPPDATA") {
|
||||||
|
return PathBuf::from(root).join("QFT");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
if let Some(home) = home_dir() {
|
||||||
|
return home.join("Library").join("Application Support").join("QFT");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
{
|
||||||
|
if let Some(root) = non_empty_env("XDG_CONFIG_HOME") {
|
||||||
|
return PathBuf::from(root).join("qft");
|
||||||
|
}
|
||||||
|
if let Some(home) = home_dir() {
|
||||||
|
return home.join(".config").join("qft");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 环境变量全都拿不到时退回当前目录下的隐藏目录,保证功能不中断
|
||||||
|
PathBuf::from(".qft")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 接收文件的默认保存目录。
|
||||||
|
pub fn default_download_dir() -> PathBuf {
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
{
|
||||||
|
// Linux 桌面环境会把"下载"本地化(中文系统是 ~/下载),
|
||||||
|
// 目录名记录在 user-dirs.dirs 里,直接拼 "Downloads" 会建出一个用户看不见的目录。
|
||||||
|
if let Some(dir) = xdg_user_dir("XDG_DOWNLOAD_DIR") {
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(home) = home_dir() {
|
||||||
|
let downloads = home.join("Downloads");
|
||||||
|
if downloads.is_dir() {
|
||||||
|
return downloads;
|
||||||
|
}
|
||||||
|
return home;
|
||||||
|
}
|
||||||
|
PathBuf::from(".")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 展示给对端的本机名称。
|
||||||
|
pub fn device_name() -> String {
|
||||||
|
let raw = whoami::fallible::hostname().unwrap_or_else(|_| whoami::devicename());
|
||||||
|
sanitize_device_name(&raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设备名会进入配对二维码、mDNS TXT 与对端的设备列表,
|
||||||
|
/// 必须去掉控制字符、去掉 mDNS 的 `.local` 后缀并限长。
|
||||||
|
pub fn sanitize_device_name(raw: &str) -> String {
|
||||||
|
let cleaned: String = raw
|
||||||
|
.chars()
|
||||||
|
.filter(|ch| !ch.is_control())
|
||||||
|
.take(64)
|
||||||
|
.collect();
|
||||||
|
// macOS/Linux 取到的常是 mDNS 主机名(如 zdeMacBook-Air.local),
|
||||||
|
// 后缀对用户没有意义,列在对方设备列表里只会更长更难认。
|
||||||
|
let cleaned = cleaned
|
||||||
|
.strip_suffix(".local")
|
||||||
|
.or_else(|| cleaned.strip_suffix(".lan"))
|
||||||
|
.unwrap_or(&cleaned)
|
||||||
|
.to_owned();
|
||||||
|
let trimmed = cleaned.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
default_device_name().to_owned()
|
||||||
|
} else {
|
||||||
|
trimmed.to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn default_device_name() -> &'static str {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
"Windows-PC"
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
"Mac"
|
||||||
|
}
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
{
|
||||||
|
"Linux-PC"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 系统自带的中文字体候选,按优先级排列。
|
||||||
|
///
|
||||||
|
/// 仓库不附带第三方字体,界面文字全是中文,找不到字体就会满屏豆腐块。
|
||||||
|
/// 注意 macOS 与多数 Linux 发行版的中文字体是 **`.ttc` 字体集合**,
|
||||||
|
/// 只按 `.ttf` 扩展名筛选会把它们全部漏掉。
|
||||||
|
pub fn system_font_candidates() -> Vec<PathBuf> {
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
vec![
|
||||||
|
PathBuf::from("/System/Library/Fonts/PingFang.ttc"),
|
||||||
|
PathBuf::from("/System/Library/Fonts/Hiragino Sans GB.ttc"),
|
||||||
|
PathBuf::from("/System/Library/Fonts/STHeiti Medium.ttc"),
|
||||||
|
PathBuf::from("/System/Library/Fonts/STHeiti Light.ttc"),
|
||||||
|
PathBuf::from("/Library/Fonts/Arial Unicode.ttf"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
vec![
|
||||||
|
// 新版 Windows 的微软雅黑是 .ttc,旧的筛选逻辑正好漏掉它
|
||||||
|
PathBuf::from(r"C:\Windows\Fonts\msyh.ttc"),
|
||||||
|
PathBuf::from(r"C:\Windows\Fonts\msyh.ttf"),
|
||||||
|
PathBuf::from(r"C:\Windows\Fonts\simhei.ttf"),
|
||||||
|
PathBuf::from(r"C:\Windows\Fonts\Deng.ttf"),
|
||||||
|
PathBuf::from(r"C:\Windows\Fonts\simsun.ttc"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
{
|
||||||
|
vec![
|
||||||
|
PathBuf::from("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"),
|
||||||
|
PathBuf::from("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf"),
|
||||||
|
PathBuf::from("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc"),
|
||||||
|
PathBuf::from("/usr/share/fonts/opentype/source-han-sans/SourceHanSansSC-Regular.otf"),
|
||||||
|
PathBuf::from("/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc"),
|
||||||
|
PathBuf::from("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc"),
|
||||||
|
PathBuf::from("/usr/share/fonts/truetype/arphic/uming.ttc"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本机所属平台,用于 mDNS TXT 与 UI 图标。
|
||||||
|
pub const fn platform_tag() -> &'static str {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
"windows"
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
"macos"
|
||||||
|
}
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
{
|
||||||
|
"linux"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 本机能否开启 QFT Direct 临时热点。
|
||||||
|
///
|
||||||
|
/// 只有 Windows 走 WiFi Direct;macOS 无公开 API,Linux 各发行版
|
||||||
|
/// NetworkManager 行为差异过大,都不做——UI 据此隐藏入口,
|
||||||
|
/// 而不是让用户点进去再失败。
|
||||||
|
pub enum DirectApSupport {
|
||||||
|
Supported,
|
||||||
|
Unsupported(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn direct_ap_support() -> DirectApSupport {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
DirectApSupport::Supported
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
{
|
||||||
|
DirectApSupport::Unsupported("本平台不支持 QFT Direct 热点,请让两台设备连接同一个 Wi-Fi")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DirectApSupport {
|
||||||
|
pub const fn is_supported(&self) -> bool {
|
||||||
|
matches!(self, DirectApSupport::Supported)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 内部工具
|
||||||
|
|
||||||
|
fn non_empty_env(key: &str) -> Option<String> {
|
||||||
|
std::env::var(key).ok().filter(|v| !v.trim().is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn home_dir() -> Option<PathBuf> {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
if let Some(profile) = non_empty_env("USERPROFILE") {
|
||||||
|
return Some(PathBuf::from(profile));
|
||||||
|
}
|
||||||
|
let drive = non_empty_env("HOMEDRIVE")?;
|
||||||
|
let path = non_empty_env("HOMEPATH")?;
|
||||||
|
return Some(PathBuf::from(format!("{drive}{path}")));
|
||||||
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
non_empty_env("HOME").map(PathBuf::from)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析 `~/.config/user-dirs.dirs` 里形如
|
||||||
|
/// `XDG_DOWNLOAD_DIR="$HOME/下载"` 的一行。
|
||||||
|
#[cfg(all(unix, not(target_os = "macos")))]
|
||||||
|
fn xdg_user_dir(key: &str) -> Option<PathBuf> {
|
||||||
|
let home = home_dir()?;
|
||||||
|
let config = non_empty_env("XDG_CONFIG_HOME")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| home.join(".config"));
|
||||||
|
let text = std::fs::read_to_string(config.join("user-dirs.dirs")).ok()?;
|
||||||
|
for line in text.lines() {
|
||||||
|
let line = line.trim();
|
||||||
|
if line.starts_with('#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (name, value) = line.split_once('=')?;
|
||||||
|
if name.trim() != key {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let value = value.trim().trim_matches('"');
|
||||||
|
let expanded = if let Some(rest) = value.strip_prefix("$HOME/") {
|
||||||
|
home.join(rest)
|
||||||
|
} else if value == "$HOME" {
|
||||||
|
home.clone()
|
||||||
|
} else {
|
||||||
|
PathBuf::from(value)
|
||||||
|
};
|
||||||
|
if expanded.is_dir() {
|
||||||
|
return Some(expanded);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 确保目录存在,返回其路径。调用方负责处理失败。
|
||||||
|
#[allow(dead_code)] // 由 client 的下载路径使用,该路径尚未接线
|
||||||
|
pub fn ensure_dir(path: &Path) -> std::io::Result<()> {
|
||||||
|
if path.is_dir() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_dir_is_absolute_or_local_fallback() {
|
||||||
|
let dir = config_dir();
|
||||||
|
// 要么是绝对路径(拿到了环境变量),要么是约定的本地兜底
|
||||||
|
assert!(dir.is_absolute() || dir == PathBuf::from(".qft"), "{dir:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn device_name_is_never_empty_and_bounded() {
|
||||||
|
let name = device_name();
|
||||||
|
assert!(!name.is_empty());
|
||||||
|
assert!(name.chars().count() <= 64);
|
||||||
|
assert!(!name.chars().any(char::is_control));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sanitize_strips_control_chars_and_falls_back() {
|
||||||
|
assert_eq!(sanitize_device_name(" ok-name \n"), "ok-name");
|
||||||
|
assert_eq!(sanitize_device_name("a\u{0}b"), "ab");
|
||||||
|
assert_eq!(sanitize_device_name(" "), default_device_name());
|
||||||
|
assert_eq!(sanitize_device_name("\n\t"), default_device_name());
|
||||||
|
assert_eq!(sanitize_device_name(&"x".repeat(200)).chars().count(), 64);
|
||||||
|
// mDNS 后缀不该出现在设备列表里
|
||||||
|
assert_eq!(sanitize_device_name("zdeMacBook-Air.local"), "zdeMacBook-Air");
|
||||||
|
assert_eq!(sanitize_device_name("ubuntu-dev.lan"), "ubuntu-dev");
|
||||||
|
// 只去掉结尾的后缀,名字中间含 .local 的不动
|
||||||
|
assert_eq!(sanitize_device_name("my.local.pc"), "my.local.pc");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_tag_matches_direct_ap_capability() {
|
||||||
|
// Direct AP 目前只有 Windows 支持,两个常量必须保持一致
|
||||||
|
assert_eq!(
|
||||||
|
direct_ap_support().is_supported(),
|
||||||
|
platform_tag() == "windows"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -191,19 +191,7 @@ pub fn hex_sha256(bytes: &[u8; 32]) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn local_device_name() -> String {
|
pub fn local_device_name() -> String {
|
||||||
let raw = std::env::var("COMPUTERNAME")
|
crate::platform::device_name()
|
||||||
.or_else(|_| std::env::var("HOSTNAME"))
|
|
||||||
.unwrap_or_else(|_| "Windows-PC".to_owned());
|
|
||||||
let cleaned: String = raw
|
|
||||||
.chars()
|
|
||||||
.filter(|ch| !ch.is_control())
|
|
||||||
.take(64)
|
|
||||||
.collect();
|
|
||||||
if cleaned.trim().is_empty() {
|
|
||||||
"Windows-PC".to_owned()
|
|
||||||
} else {
|
|
||||||
cleaned
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
|
fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
|
||||||
@@ -3,6 +3,7 @@ use eframe::egui::ColorImage;
|
|||||||
use qrcode::{types::Color, EcLevel, QrCode};
|
use qrcode::{types::Color, EcLevel, QrCode};
|
||||||
|
|
||||||
const QUIET_MODULES: usize = 4;
|
const QUIET_MODULES: usize = 4;
|
||||||
|
const PAIR_EC_LEVEL: EcLevel = EcLevel::L;
|
||||||
|
|
||||||
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
|
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
|
||||||
/// characters, allowing the QR encoder to choose a compact alphanumeric data
|
/// characters, allowing the QR encoder to choose a compact alphanumeric data
|
||||||
@@ -16,9 +17,11 @@ pub fn render_qr_fitted(text: &str, target_side: usize) -> Result<ColorImage> {
|
|||||||
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pairing QR stays static and uses M error correction for first-scan reliability.
|
/// Pairing happens from a clean, static desktop display. QR-L keeps long
|
||||||
|
/// QFTSEND2 payloads several versions smaller than QR-M, giving the camera
|
||||||
|
/// materially more pixels per module; the full quiet zone remains intact.
|
||||||
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
||||||
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)
|
let code = QrCode::with_error_correction_level(text.as_bytes(), PAIR_EC_LEVEL)
|
||||||
.context("pair QR payload too large")?;
|
.context("pair QR payload too large")?;
|
||||||
let modules = code.width() + QUIET_MODULES * 2;
|
let modules = code.width() + QUIET_MODULES * 2;
|
||||||
let scale = (target_side / modules).max(1);
|
let scale = (target_side / modules).max(1);
|
||||||
@@ -26,6 +29,16 @@ pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
|||||||
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pairing_qr_uses_low_density_error_correction() {
|
||||||
|
assert_eq!(PAIR_EC_LEVEL, EcLevel::L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
|
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
|
||||||
let qr_width = code.width();
|
let qr_width = code.width();
|
||||||
let modules = qr_width + QUIET_MODULES * 2;
|
let modules = qr_width + QUIET_MODULES * 2;
|
||||||
@@ -10,7 +10,7 @@ use std::{
|
|||||||
net::{TcpListener, TcpStream, UdpSocket},
|
net::{TcpListener, TcpStream, UdpSocket},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::{
|
sync::{
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, AtomicU32, Ordering},
|
||||||
mpsc::Sender,
|
mpsc::Sender,
|
||||||
Arc, Mutex,
|
Arc, Mutex,
|
||||||
},
|
},
|
||||||
@@ -21,10 +21,13 @@ use std::{
|
|||||||
pub const PREFERRED_PORT: u16 = 39393;
|
pub const PREFERRED_PORT: u16 = 39393;
|
||||||
pub const DISCOVERY_PORT: u16 = 39392;
|
pub const DISCOVERY_PORT: u16 = 39392;
|
||||||
pub const PARALLEL_CHUNK_SIZE: u64 = 8 * 1024 * 1024;
|
pub const PARALLEL_CHUNK_SIZE: u64 = 8 * 1024 * 1024;
|
||||||
|
const MIN_PARALLEL_CHUNK_SIZE: u64 = 64 * 1024;
|
||||||
|
const MAX_PARALLEL_CHUNK_SIZE: u64 = 16 * 1024 * 1024;
|
||||||
const IO_BUFFER: usize = 1024 * 1024;
|
const IO_BUFFER: usize = 1024 * 1024;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum ReceiverEvent {
|
pub enum ReceiverEvent {
|
||||||
|
TransportConnected { peer: String },
|
||||||
ClientConnected { device: String },
|
ClientConnected { device: String },
|
||||||
UploadStarted { device: String, file_name: String, size: u64 },
|
UploadStarted { device: String, file_name: String, size: u64 },
|
||||||
UploadProgress { device: String, file_name: String, received: u64, size: u64 },
|
UploadProgress { device: String, file_name: String, received: u64, size: u64 },
|
||||||
@@ -57,6 +60,9 @@ struct CompletedUpload {
|
|||||||
|
|
||||||
pub struct ReceiverServer {
|
pub struct ReceiverServer {
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
|
/// PC↔PC 的配对秘密(3 字节)。UI 会把它和本机地址一起编成连接码,
|
||||||
|
/// 用户只需要念/粘贴那一串,不必再单独报 IP 和端口。
|
||||||
|
pub secret: [u8; crate::connect_code::SECRET_LEN],
|
||||||
stop: Arc<AtomicBool>,
|
stop: Arc<AtomicBool>,
|
||||||
tcp_thread: Option<JoinHandle<()>>,
|
tcp_thread: Option<JoinHandle<()>>,
|
||||||
udp_thread: Option<JoinHandle<()>>,
|
udp_thread: Option<JoinHandle<()>>,
|
||||||
@@ -74,6 +80,11 @@ impl ReceiverServer {
|
|||||||
let stop = Arc::new(AtomicBool::new(false));
|
let stop = Arc::new(AtomicBool::new(false));
|
||||||
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
|
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
|
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
// 24 bit 秘密对在线爆破仍然不够,靠严格失败计数兜底:
|
||||||
|
// 错 5 次即作废,必须重启接收重新生成。
|
||||||
|
let secret = crate::connect_code::new_secret();
|
||||||
|
let secret_hex: String = secret.iter().map(|b| format!("{b:02x}")).collect();
|
||||||
|
let pair_failures = Arc::new(AtomicU32::new(0));
|
||||||
|
|
||||||
let stop_tcp = stop.clone();
|
let stop_tcp = stop.clone();
|
||||||
let sessions_tcp = sessions.clone();
|
let sessions_tcp = sessions.clone();
|
||||||
@@ -81,17 +92,22 @@ impl ReceiverServer {
|
|||||||
let token_tcp = session_token.clone();
|
let token_tcp = session_token.clone();
|
||||||
let dir_tcp = save_dir.clone();
|
let dir_tcp = save_dir.clone();
|
||||||
let events_tcp = events.clone();
|
let events_tcp = events.clone();
|
||||||
|
let code_tcp = secret_hex.clone();
|
||||||
|
let failures_tcp = pair_failures.clone();
|
||||||
let tcp_thread = thread::spawn(move || {
|
let tcp_thread = thread::spawn(move || {
|
||||||
while !stop_tcp.load(Ordering::Relaxed) {
|
while !stop_tcp.load(Ordering::Relaxed) {
|
||||||
match listener.accept() {
|
match listener.accept() {
|
||||||
Ok((mut stream, _)) => {
|
Ok((mut stream, peer)) => {
|
||||||
|
let _ = events_tcp.send(ReceiverEvent::TransportConnected { peer: peer.to_string() });
|
||||||
let dir = dir_tcp.clone();
|
let dir = dir_tcp.clone();
|
||||||
let token = token_tcp.clone();
|
let token = token_tcp.clone();
|
||||||
let tx = events_tcp.clone();
|
let tx = events_tcp.clone();
|
||||||
let sessions = sessions_tcp.clone();
|
let sessions = sessions_tcp.clone();
|
||||||
let completed = completed_tcp.clone();
|
let completed = completed_tcp.clone();
|
||||||
|
let code = code_tcp.clone();
|
||||||
|
let failures = failures_tcp.clone();
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
if let Err(e) = handle_client(&mut stream, &dir, &token, &tx, &sessions, &completed) {
|
if let Err(e) = handle_client(&mut stream, &dir, &token, &code, &failures, &tx, &sessions, &completed) {
|
||||||
// Never turn a parse/write race into an opaque Android
|
// Never turn a parse/write race into an opaque Android
|
||||||
// `unexpected end of stream`: make a best effort to
|
// `unexpected end of stream`: make a best effort to
|
||||||
// return an HTTP status before closing the socket.
|
// return an HTTP status before closing the socket.
|
||||||
@@ -125,14 +141,31 @@ impl ReceiverServer {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
|
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
|
||||||
let expected = format!("QFTDISC2:{token_udp}");
|
|
||||||
let response = format!("QFTHERE2:{token_udp}:{port}");
|
let response = format!("QFTHERE2:{token_udp}:{port}");
|
||||||
|
// PC↔PC 的对端不知道令牌,需要先能把本机列出来
|
||||||
|
let announce = crate::discovery::browse_reply(&crate::discovery::NodeAnnounce {
|
||||||
|
n: crate::platform::device_name(),
|
||||||
|
p: crate::platform::platform_tag().to_owned(),
|
||||||
|
t: port,
|
||||||
|
r: true,
|
||||||
|
});
|
||||||
let mut buf = [0u8; 512];
|
let mut buf = [0u8; 512];
|
||||||
while !stop_udp.load(Ordering::Relaxed) {
|
while !stop_udp.load(Ordering::Relaxed) {
|
||||||
match socket.recv_from(&mut buf) {
|
match socket.recv_from(&mut buf) {
|
||||||
Ok((n, peer)) => {
|
Ok((n, peer)) => {
|
||||||
if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) {
|
match std::str::from_utf8(&buf[..n]).ok() {
|
||||||
let _ = socket.send_to(response.as_bytes(), peer);
|
Some(text) if text == crate::discovery::BROWSE_QUERY => {
|
||||||
|
let _ = socket.send_to(&announce, peer);
|
||||||
|
}
|
||||||
|
Some(text) => {
|
||||||
|
if let Some(device) = crate::pairing::discovery_device(text, &token_udp) {
|
||||||
|
if let Some(device) = device {
|
||||||
|
let _ = events.send(ReceiverEvent::ClientConnected { device });
|
||||||
|
}
|
||||||
|
let _ = socket.send_to(response.as_bytes(), peer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
|
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
|
||||||
@@ -145,6 +178,7 @@ impl ReceiverServer {
|
|||||||
port,
|
port,
|
||||||
stop,
|
stop,
|
||||||
tcp_thread: Some(tcp_thread),
|
tcp_thread: Some(tcp_thread),
|
||||||
|
secret,
|
||||||
udp_thread: Some(udp_thread),
|
udp_thread: Some(udp_thread),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -162,10 +196,64 @@ impl Drop for ReceiverServer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `POST /qft/pair`,请求头 `X-QFT-Code: 123456`。
|
||||||
|
///
|
||||||
|
/// 这是唯一不校验令牌的端点——它的作用就是用 6 位码换取令牌。
|
||||||
|
/// 6 位只有约 20 bit 熵,必须靠失败计数兜底:错 5 次即作废整个码,
|
||||||
|
/// 用户需要在电脑上重新启动接收才能拿到新码。
|
||||||
|
fn handle_pair(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
headers: &HashMap<String, String>,
|
||||||
|
token: &str,
|
||||||
|
pair_code: &str,
|
||||||
|
pair_failures: &AtomicU32,
|
||||||
|
events: &Sender<ReceiverEvent>,
|
||||||
|
) -> Result<()> {
|
||||||
|
const MAX_FAILURES: u32 = 5;
|
||||||
|
if pair_failures.load(Ordering::Relaxed) >= MAX_FAILURES {
|
||||||
|
let body = json!({
|
||||||
|
"ok": false,
|
||||||
|
"error": "配对码已因多次输入错误作废,请在电脑上重新启动接收"
|
||||||
|
}).to_string();
|
||||||
|
return write_response(stream, 429, "application/json", body.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
let supplied = headers.get("x-qft-code").map(String::as_str).unwrap_or("");
|
||||||
|
if !constant_time_eq(supplied.as_bytes(), pair_code.as_bytes()) {
|
||||||
|
let count = pair_failures.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
|
let _ = events.send(ReceiverEvent::Error(format!(
|
||||||
|
"配对码错误({count}/{MAX_FAILURES})"
|
||||||
|
)));
|
||||||
|
let body = json!({"ok": false, "remaining": MAX_FAILURES.saturating_sub(count)}).to_string();
|
||||||
|
return write_response(stream, 403, "application/json", body.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
pair_failures.store(0, Ordering::Relaxed);
|
||||||
|
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "电脑".to_owned());
|
||||||
|
let _ = events.send(ReceiverEvent::ClientConnected { device });
|
||||||
|
let body = json!({"ok": true, "token": token}).to_string();
|
||||||
|
write_response(stream, 200, "application/json", body.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 定长比较,不因首个不同字节的位置而提前返回。
|
||||||
|
/// 局域网上计时攻击并不现实,但这段代码很便宜,没有理由写成短路比较。
|
||||||
|
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||||
|
if a.len() != b.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut diff = 0u8;
|
||||||
|
for (x, y) in a.iter().zip(b.iter()) {
|
||||||
|
diff |= x ^ y;
|
||||||
|
}
|
||||||
|
diff == 0
|
||||||
|
}
|
||||||
|
|
||||||
fn handle_client(
|
fn handle_client(
|
||||||
stream: &mut TcpStream,
|
stream: &mut TcpStream,
|
||||||
save_dir: &Path,
|
save_dir: &Path,
|
||||||
token: &str,
|
token: &str,
|
||||||
|
pair_code: &str,
|
||||||
|
pair_failures: &AtomicU32,
|
||||||
events: &Sender<ReceiverEvent>,
|
events: &Sender<ReceiverEvent>,
|
||||||
sessions: &SessionMap,
|
sessions: &SessionMap,
|
||||||
completed: &CompletedMap,
|
completed: &CompletedMap,
|
||||||
@@ -200,6 +288,11 @@ fn handle_client(
|
|||||||
let method = parts.next().unwrap_or("");
|
let method = parts.next().unwrap_or("");
|
||||||
let path = parts.next().unwrap_or("");
|
let path = parts.next().unwrap_or("");
|
||||||
|
|
||||||
|
// 配对是唯一不需要令牌的端点——它的作用正是换取令牌。
|
||||||
|
if method == "POST" && path == "/qft/pair" {
|
||||||
|
return handle_pair(stream, &headers, token, pair_code, pair_failures, events);
|
||||||
|
}
|
||||||
|
|
||||||
let supplied = headers.get("x-qft-token").map(String::as_str).unwrap_or("");
|
let supplied = headers.get("x-qft-token").map(String::as_str).unwrap_or("");
|
||||||
if supplied != token {
|
if supplied != token {
|
||||||
return write_response(stream, 403, "text/plain", b"invalid session");
|
return write_response(stream, 403, "text/plain", b"invalid session");
|
||||||
@@ -250,7 +343,7 @@ fn init_parallel_upload(
|
|||||||
.parse().context("X-QFT-Size 无效")?;
|
.parse().context("X-QFT-Size 无效")?;
|
||||||
let chunk_size = headers.get("x-qft-chunk-size")
|
let chunk_size = headers.get("x-qft-chunk-size")
|
||||||
.and_then(|v| v.parse::<u64>().ok())
|
.and_then(|v| v.parse::<u64>().ok())
|
||||||
.map(|v| v.clamp(1024 * 1024, 16 * 1024 * 1024))
|
.map(|v| v.clamp(MIN_PARALLEL_CHUNK_SIZE, MAX_PARALLEL_CHUNK_SIZE))
|
||||||
.unwrap_or(PARALLEL_CHUNK_SIZE);
|
.unwrap_or(PARALLEL_CHUNK_SIZE);
|
||||||
let total_chunks_u64 = if size == 0 { 0 } else { (size + chunk_size - 1) / chunk_size };
|
let total_chunks_u64 = if size == 0 { 0 } else { (size + chunk_size - 1) / chunk_size };
|
||||||
if total_chunks_u64 > u32::MAX as u64 { bail!("文件分块数过大") }
|
if total_chunks_u64 > u32::MAX as u64 { bail!("文件分块数过大") }
|
||||||
@@ -365,7 +458,6 @@ fn receive_parallel_chunk(
|
|||||||
let mut out = OpenOptions::new().write(true).open(&part_path)?;
|
let mut out = OpenOptions::new().write(true).open(&part_path)?;
|
||||||
out.seek(SeekFrom::Start(offset))?;
|
out.seek(SeekFrom::Start(offset))?;
|
||||||
copy_exact(reader, &mut out, content_len)?;
|
copy_exact(reader, &mut out, content_len)?;
|
||||||
out.sync_data()?;
|
|
||||||
|
|
||||||
let received = {
|
let received = {
|
||||||
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
|
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
|
||||||
@@ -416,6 +508,10 @@ fn finish_parallel_upload(
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Per-chunk FlushFileBuffers serializes otherwise independent upload lanes
|
||||||
|
// and is especially costly on Windows. The in-memory session cannot resume
|
||||||
|
// across a desktop-process crash anyway, so commit once after all chunks.
|
||||||
|
OpenOptions::new().write(true).open(&part_path)?.sync_data()?;
|
||||||
let sha = hash_file(&part_path)?;
|
let sha = hash_file(&part_path)?;
|
||||||
if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") }
|
if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") }
|
||||||
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
|
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
|
||||||
@@ -639,6 +735,8 @@ mod tests {
|
|||||||
&mut stream,
|
&mut stream,
|
||||||
&dir_for_server,
|
&dir_for_server,
|
||||||
"session",
|
"session",
|
||||||
|
"000000",
|
||||||
|
&AtomicU32::new(0),
|
||||||
&events,
|
&events,
|
||||||
&sessions,
|
&sessions,
|
||||||
&completed,
|
&completed,
|
||||||
@@ -22,6 +22,7 @@ const IO_BUFFER: usize = 1024 * 1024;
|
|||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum SenderEvent {
|
pub enum SenderEvent {
|
||||||
|
TransportConnected { peer: String },
|
||||||
ClientConnected { device: String },
|
ClientConnected { device: String },
|
||||||
DownloadStarted { device: String, file_name: String, size: u64 },
|
DownloadStarted { device: String, file_name: String, size: u64 },
|
||||||
DownloadCompleted { device: String, file_name: String },
|
DownloadCompleted { device: String, file_name: String },
|
||||||
@@ -61,7 +62,8 @@ impl SenderServer {
|
|||||||
let tcp_thread = thread::spawn(move || {
|
let tcp_thread = thread::spawn(move || {
|
||||||
while !tcp_stop.load(Ordering::Relaxed) {
|
while !tcp_stop.load(Ordering::Relaxed) {
|
||||||
match listener.accept() {
|
match listener.accept() {
|
||||||
Ok((mut stream, _)) => {
|
Ok((mut stream, peer)) => {
|
||||||
|
let _ = tcp_events.send(SenderEvent::TransportConnected { peer: peer.to_string() });
|
||||||
let token = tcp_token.clone();
|
let token = tcp_token.clone();
|
||||||
let path = file_path.clone();
|
let path = file_path.clone();
|
||||||
let name = file_name.clone();
|
let name = file_name.clone();
|
||||||
@@ -93,15 +95,20 @@ impl SenderServer {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
|
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
|
||||||
let expected = format!("QFTDISC2:{session_token}");
|
|
||||||
let response = format!("QFTHERE2:{session_token}:{port}");
|
let response = format!("QFTHERE2:{session_token}:{port}");
|
||||||
let mut buf = [0u8; 512];
|
let mut buf = [0u8; 512];
|
||||||
while !udp_stop.load(Ordering::Relaxed) {
|
while !udp_stop.load(Ordering::Relaxed) {
|
||||||
match socket.recv_from(&mut buf) {
|
match socket.recv_from(&mut buf) {
|
||||||
Ok((n, peer)) if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) => {
|
Ok((n, peer)) => {
|
||||||
|
let Some(device) = std::str::from_utf8(&buf[..n])
|
||||||
|
.ok()
|
||||||
|
.and_then(|text| crate::pairing::discovery_device(text, &session_token))
|
||||||
|
else { continue };
|
||||||
|
if let Some(device) = device {
|
||||||
|
let _ = events.send(SenderEvent::ClientConnected { device });
|
||||||
|
}
|
||||||
let _ = socket.send_to(response.as_bytes(), peer);
|
let _ = socket.send_to(response.as_bytes(), peer);
|
||||||
}
|
}
|
||||||
Ok(_) => {}
|
|
||||||
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
|
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
|
||||||
Err(_) => break,
|
Err(_) => break,
|
||||||
}
|
}
|
||||||
@@ -128,19 +135,57 @@ fn handle_client(
|
|||||||
token: &str,
|
token: &str,
|
||||||
events: &Sender<SenderEvent>,
|
events: &Sender<SenderEvent>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
// The listener is non-blocking so its owner can poll for shutdown. On
|
||||||
|
// Windows an accepted socket can retain that mode, causing a large Range
|
||||||
|
// response to fail with WSAEWOULDBLOCK (10035) between write calls.
|
||||||
|
// Downloads must wait under the explicit read/write timeouts instead.
|
||||||
|
stream.set_nonblocking(false)?;
|
||||||
stream.set_nodelay(true).ok();
|
stream.set_nodelay(true).ok();
|
||||||
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
|
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
|
||||||
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
|
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
|
||||||
let cloned = stream.try_clone()?;
|
let cloned = stream.try_clone()?;
|
||||||
let mut reader = BufReader::with_capacity(32 * 1024, cloned);
|
let mut reader = BufReader::with_capacity(32 * 1024, cloned);
|
||||||
|
|
||||||
|
// 同一条连接上循环处理请求。此前每个响应都写死 Connection: close,
|
||||||
|
// 于是并行下载的每个分块都要新建一次 TCP —— 1 GB 是 64 次,
|
||||||
|
// 10 GB 是 640 次,既慢又是"短连接频繁断开"的直接来源。
|
||||||
|
loop {
|
||||||
|
match serve_one(stream, &mut reader, file_path, file_name, size, token, events)? {
|
||||||
|
KeepAlive::Continue => {}
|
||||||
|
KeepAlive::Close => return Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单个请求的处理结果:是否可以在同一条连接上继续。
|
||||||
|
enum KeepAlive {
|
||||||
|
Continue,
|
||||||
|
Close,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serve_one(
|
||||||
|
stream: &mut TcpStream,
|
||||||
|
reader: &mut BufReader<TcpStream>,
|
||||||
|
file_path: &PathBuf,
|
||||||
|
file_name: &str,
|
||||||
|
size: u64,
|
||||||
|
token: &str,
|
||||||
|
events: &Sender<SenderEvent>,
|
||||||
|
) -> Result<KeepAlive> {
|
||||||
let mut request_line = String::new();
|
let mut request_line = String::new();
|
||||||
reader.read_line(&mut request_line)?;
|
// 读到 0 字节说明对端正常关闭了连接,这是 keep-alive 下的常态,不是错误
|
||||||
|
if reader.read_line(&mut request_line)? == 0 {
|
||||||
|
return Ok(KeepAlive::Close);
|
||||||
|
}
|
||||||
|
if request_line.trim().is_empty() {
|
||||||
|
return Ok(KeepAlive::Close);
|
||||||
|
}
|
||||||
if request_line.len() > 8192 { bail!("请求行过长") }
|
if request_line.len() > 8192 { bail!("请求行过长") }
|
||||||
let mut headers = HashMap::<String, String>::new();
|
let mut headers = HashMap::<String, String>::new();
|
||||||
loop {
|
loop {
|
||||||
let mut line = String::new();
|
let mut line = String::new();
|
||||||
let n = reader.read_line(&mut line)?;
|
let n = reader.read_line(&mut line)?;
|
||||||
if n == 0 { bail!("连接在请求头前关闭") }
|
if n == 0 { return Ok(KeepAlive::Close) }
|
||||||
if line == "\r\n" || line == "\n" { break }
|
if line == "\r\n" || line == "\n" { break }
|
||||||
if line.len() > 16 * 1024 { bail!("请求头过长") }
|
if line.len() > 16 * 1024 { bail!("请求头过长") }
|
||||||
if let Some((k, v)) = line.split_once(':') {
|
if let Some((k, v)) = line.split_once(':') {
|
||||||
@@ -150,17 +195,29 @@ fn handle_client(
|
|||||||
let mut parts = request_line.split_whitespace();
|
let mut parts = request_line.split_whitespace();
|
||||||
let method = parts.next().unwrap_or("");
|
let method = parts.next().unwrap_or("");
|
||||||
let path = parts.next().unwrap_or("");
|
let path = parts.next().unwrap_or("");
|
||||||
|
let version = parts.next().unwrap_or("HTTP/1.1");
|
||||||
|
// HTTP/1.1 默认复用;客户端显式要求 close 或用 1.0 时才断开
|
||||||
|
let keep_alive = version.eq_ignore_ascii_case("HTTP/1.1")
|
||||||
|
&& !headers
|
||||||
|
.get("connection")
|
||||||
|
.map(|v| v.eq_ignore_ascii_case("close"))
|
||||||
|
.unwrap_or(false);
|
||||||
|
let connection_header = if keep_alive { "keep-alive" } else { "close" };
|
||||||
|
|
||||||
if headers.get("x-qft-token").map(String::as_str).unwrap_or("") != token {
|
if headers.get("x-qft-token").map(String::as_str).unwrap_or("") != token {
|
||||||
return write_response(stream, 403, "text/plain", b"invalid session");
|
write_response(stream, 403, "text/plain", b"invalid session")?;
|
||||||
|
return Ok(KeepAlive::Close);
|
||||||
}
|
}
|
||||||
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
|
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
|
||||||
let _ = events.send(SenderEvent::ClientConnected { device: device.clone() });
|
let _ = events.send(SenderEvent::ClientConnected { device: device.clone() });
|
||||||
if method == "GET" && path == "/qft/ping" {
|
if method == "GET" && path == "/qft/ping" {
|
||||||
let body = json!({"ok": true, "protocol": 2, "direction": "download"}).to_string();
|
let body = json!({"ok": true, "protocol": 2, "direction": "download"}).to_string();
|
||||||
return write_response(stream, 200, "application/json", body.as_bytes());
|
write_response(stream, 200, "application/json", body.as_bytes())?;
|
||||||
|
return Ok(if keep_alive { KeepAlive::Continue } else { KeepAlive::Close });
|
||||||
}
|
}
|
||||||
if method != "GET" || path != "/qft/download" {
|
if method != "GET" || path != "/qft/download" {
|
||||||
return write_response(stream, 404, "text/plain", b"not found");
|
write_response(stream, 404, "text/plain", b"not found")?;
|
||||||
|
return Ok(KeepAlive::Close);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut input = File::open(file_path)
|
let mut input = File::open(file_path)
|
||||||
@@ -175,12 +232,12 @@ fn handle_client(
|
|||||||
let _ = events.send(SenderEvent::DownloadStarted { device: device.clone(), file_name: file_name.to_owned(), size });
|
let _ = events.send(SenderEvent::DownloadStarted { device: device.clone(), file_name: file_name.to_owned(), size });
|
||||||
if headers.get("range").is_none() {
|
if headers.get("range").is_none() {
|
||||||
write!(stream,
|
write!(stream,
|
||||||
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
|
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nAccept-Ranges: bytes\r\nConnection: {connection_header}\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||||
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
||||||
)?;
|
)?;
|
||||||
} else {
|
} else {
|
||||||
write!(stream,
|
write!(stream,
|
||||||
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{end}/{}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
|
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{end}/{}\r\nAccept-Ranges: bytes\r\nConnection: {connection_header}\r\nX-QFT-Filename: {}\r\n\r\n",
|
||||||
size,
|
size,
|
||||||
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
|
||||||
)?;
|
)?;
|
||||||
@@ -192,14 +249,13 @@ fn handle_client(
|
|||||||
while left > 0 {
|
while left > 0 {
|
||||||
let want = left.min(buf.len() as u64) as usize;
|
let want = left.min(buf.len() as u64) as usize;
|
||||||
let n = input.read(&mut buf[..want])?;
|
let n = input.read(&mut buf[..want])?;
|
||||||
if n == 0 { break }
|
if n == 0 { bail!("发送文件读取提前结束:还缺 {left} 字节") }
|
||||||
stream.write_all(&buf[..n])?;
|
stream.write_all(&buf[..n])?;
|
||||||
left -= n as u64;
|
left -= n as u64;
|
||||||
}
|
}
|
||||||
if left != 0 { bail!("发送文件读取提前结束:还缺 {left} 字节") }
|
|
||||||
stream.flush()?;
|
stream.flush()?;
|
||||||
let _ = events.send(SenderEvent::DownloadCompleted { device, file_name: file_name.to_owned() });
|
let _ = events.send(SenderEvent::DownloadCompleted { device, file_name: file_name.to_owned() });
|
||||||
Ok(())
|
Ok(if keep_alive { KeepAlive::Continue } else { KeepAlive::Close })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
|
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
|
||||||
@@ -249,6 +305,7 @@ mod tests {
|
|||||||
net::{TcpListener, TcpStream},
|
net::{TcpListener, TcpStream},
|
||||||
sync::mpsc,
|
sync::mpsc,
|
||||||
thread,
|
thread,
|
||||||
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -284,18 +341,64 @@ mod tests {
|
|||||||
assert_response(&resumed, "HTTP/1.1 206 Partial Content", "cdef");
|
assert_response(&resumed, "HTTP/1.1 206 Partial Content", "cdef");
|
||||||
let header = String::from_utf8_lossy(&resumed[..header_end(&resumed)]);
|
let header = String::from_utf8_lossy(&resumed[..header_end(&resumed)]);
|
||||||
assert!(header.contains("Content-Range: bytes 2-5/6"));
|
assert!(header.contains("Content-Range: bytes 2-5/6"));
|
||||||
let bounded = request(address, Some("bytes=1-3"));
|
let bounded = request(address, Some("bytes=2-4"));
|
||||||
assert_response(&bounded, "HTTP/1.1 206 Partial Content", "bcd");
|
assert_response(&bounded, "HTTP/1.1 206 Partial Content", "cde");
|
||||||
|
let header = String::from_utf8_lossy(&bounded[..header_end(&bounded)]);
|
||||||
|
assert!(header.contains("Content-Range: bytes 2-4/6"));
|
||||||
|
|
||||||
server.join().unwrap();
|
server.join().unwrap();
|
||||||
fs::remove_file(path).unwrap();
|
fs::remove_file(path).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn large_download_waits_for_the_client_after_a_nonblocking_accept() {
|
||||||
|
let path = std::env::temp_dir().join(format!(
|
||||||
|
"qft-sender-{}-nonblocking.bin",
|
||||||
|
std::process::id(),
|
||||||
|
));
|
||||||
|
let payload = vec![0x5Au8; 2 * 1024 * 1024];
|
||||||
|
fs::write(&path, &payload).unwrap();
|
||||||
|
let file_size = payload.len() as u64;
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let (events, _receiver) = mpsc::channel::<SenderEvent>();
|
||||||
|
let path_for_server = path.clone();
|
||||||
|
let server = thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
// Reproduce the Windows mode inheritance that caused Range
|
||||||
|
// writes to fail with WSAEWOULDBLOCK (10035).
|
||||||
|
stream.set_nonblocking(true).unwrap();
|
||||||
|
handle_client(
|
||||||
|
&mut stream,
|
||||||
|
&path_for_server,
|
||||||
|
"large.bin",
|
||||||
|
file_size,
|
||||||
|
"session",
|
||||||
|
&events,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut client = TcpStream::connect(address).unwrap();
|
||||||
|
client.write_all(
|
||||||
|
b"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nConnection: close\r\n\r\n",
|
||||||
|
).unwrap();
|
||||||
|
client.flush().unwrap();
|
||||||
|
thread::sleep(Duration::from_millis(50));
|
||||||
|
let mut response = Vec::new();
|
||||||
|
client.read_to_end(&mut response).unwrap();
|
||||||
|
|
||||||
|
server.join().unwrap().unwrap();
|
||||||
|
let body_start = header_end(&response);
|
||||||
|
assert!(String::from_utf8_lossy(&response[..body_start]).starts_with("HTTP/1.1 200 OK"));
|
||||||
|
assert_eq!(&response[body_start..], payload.as_slice());
|
||||||
|
fs::remove_file(path).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
fn request(address: std::net::SocketAddr, range: Option<&str>) -> Vec<u8> {
|
fn request(address: std::net::SocketAddr, range: Option<&str>) -> Vec<u8> {
|
||||||
let mut stream = TcpStream::connect(address).unwrap();
|
let mut stream = TcpStream::connect(address).unwrap();
|
||||||
write!(
|
write!(
|
||||||
stream,
|
stream,
|
||||||
"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\n{}\r\n",
|
"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nConnection: close\r\n{}\r\n",
|
||||||
range.map(|v| format!("Range: {v}\r\n")).unwrap_or_default(),
|
range.map(|v| format!("Range: {v}\r\n")).unwrap_or_default(),
|
||||||
).unwrap();
|
).unwrap();
|
||||||
stream.flush().unwrap();
|
stream.flush().unwrap();
|
||||||
@@ -314,3 +417,85 @@ mod tests {
|
|||||||
bytes.windows(4).position(|v| v == b"\r\n\r\n").unwrap() + 4
|
bytes.windows(4).position(|v| v == b"\r\n\r\n").unwrap() + 4
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod keep_alive_tests {
|
||||||
|
use super::{handle_client, SenderEvent};
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
io::{BufRead, BufReader, Read, Write},
|
||||||
|
net::{TcpListener, TcpStream},
|
||||||
|
sync::mpsc,
|
||||||
|
thread,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 在**同一条** TCP 上连发多个 Range 请求,全部必须成功。
|
||||||
|
///
|
||||||
|
/// 此前每个响应都写死 Connection: close,并行下载的每个分块都要
|
||||||
|
/// 重建一次 TCP —— 1 GB 64 次、10 GB 640 次,既是"短连接频繁断开"
|
||||||
|
/// 的来源,也白白付出握手与慢启动的代价。
|
||||||
|
#[test]
|
||||||
|
fn serves_multiple_ranges_on_one_connection() {
|
||||||
|
let path = std::env::temp_dir().join(format!("qft-keepalive-{}.bin", std::process::id()));
|
||||||
|
let payload: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
|
||||||
|
fs::write(&path, &payload).unwrap();
|
||||||
|
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let (events, _rx) = mpsc::channel::<SenderEvent>();
|
||||||
|
let served = path.clone();
|
||||||
|
let server = thread::spawn(move || {
|
||||||
|
let (mut stream, _) = listener.accept().unwrap();
|
||||||
|
handle_client(&mut stream, &served, "p.bin", payload.len() as u64, "tok", &events)
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut stream = TcpStream::connect(address).unwrap();
|
||||||
|
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||||
|
|
||||||
|
// 三段互不重叠的 Range,全部走同一条连接
|
||||||
|
for (start, end) in [(0u64, 1023u64), (1024, 2047), (2048, 4095)] {
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"GET /qft/download HTTP/1.1\r\nHost: x\r\nX-QFT-Token: tok\r\nRange: bytes={start}-{end}\r\n\r\n"
|
||||||
|
).unwrap();
|
||||||
|
stream.flush().unwrap();
|
||||||
|
|
||||||
|
let mut status = String::new();
|
||||||
|
reader.read_line(&mut status).unwrap();
|
||||||
|
assert!(status.starts_with("HTTP/1.1 206"), "第 {start} 段状态行:{status}");
|
||||||
|
|
||||||
|
let mut length = 0usize;
|
||||||
|
let mut keep_alive = false;
|
||||||
|
loop {
|
||||||
|
let mut line = String::new();
|
||||||
|
reader.read_line(&mut line).unwrap();
|
||||||
|
if line == "\r\n" { break }
|
||||||
|
if let Some((name, value)) = line.split_once(':') {
|
||||||
|
match name.trim().to_ascii_lowercase().as_str() {
|
||||||
|
"content-length" => length = value.trim().parse().unwrap(),
|
||||||
|
"connection" => keep_alive = value.trim().eq_ignore_ascii_case("keep-alive"),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(keep_alive, "响应必须声明 keep-alive,否则客户端会关掉连接");
|
||||||
|
assert_eq!(length as u64, end - start + 1, "Content-Length 应等于该段长度");
|
||||||
|
|
||||||
|
let mut body = vec![0u8; length];
|
||||||
|
reader.read_exact(&mut body).unwrap();
|
||||||
|
let expected: Vec<u8> = (start..=end).map(|i| ((i as u32) % 251) as u8).collect();
|
||||||
|
assert_eq!(body, expected, "第 {start} 段内容不符");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显式要求关闭时应断开,服务端随之正常收尾
|
||||||
|
write!(stream, "GET /qft/ping HTTP/1.1\r\nHost: x\r\nX-QFT-Token: tok\r\nConnection: close\r\n\r\n").unwrap();
|
||||||
|
stream.flush().unwrap();
|
||||||
|
let mut rest = Vec::new();
|
||||||
|
reader.read_to_end(&mut rest).unwrap();
|
||||||
|
let text = String::from_utf8_lossy(&rest);
|
||||||
|
assert!(text.contains("Connection: close"), "显式 close 时应回 close:{text}");
|
||||||
|
|
||||||
|
server.join().unwrap().unwrap();
|
||||||
|
fs::remove_file(path).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -428,6 +428,6 @@ App 应根据实测能力自动选档,并在 UI 明示当前档位与预计耗
|
|||||||
| 兼容 | 720p | 4.0 | 30 | 128 KB/s | 最低保障 |
|
| 兼容 | 720p | 4.0 | 30 | 128 KB/s | 最低保障 |
|
||||||
|
|
||||||
### 何时不该用光学
|
### 何时不该用光学
|
||||||
仓库已有 `QFTSEND2` 扫码直传(`windows/src/sender.rs`:HTTP + Range 续传 + UDP 发现),
|
仓库已有 `QFTSEND2` 扫码直传(`desktop/src/sender.rs`:HTTP + Range 续传 + UDP 发现),
|
||||||
10 MB 在局域网下是亚秒级。光学链路应明确定位为**物理隔离场景专用**,
|
10 MB 在局域网下是亚秒级。光学链路应明确定位为**物理隔离场景专用**,
|
||||||
并在选择大文件时主动提示直传方案与两者的预计耗时对比。
|
并在选择大文件时主动提示直传方案与两者的预计耗时对比。
|
||||||
|
|||||||
+8
-11
@@ -1,4 +1,4 @@
|
|||||||
# QFT protocol notes — v0.4.6
|
# QFT protocol notes — v0.4.7
|
||||||
|
|
||||||
## 1. Windows → Android optical: QFT2
|
## 1. Windows → Android optical: QFT2
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ senderLen 2 u16 BE
|
|||||||
senderDevice N UTF-8
|
senderDevice N UTF-8
|
||||||
```
|
```
|
||||||
|
|
||||||
### Optical parameters in v0.4.6
|
### Optical parameters in v0.4.7
|
||||||
|
|
||||||
- one QR per display frame;
|
- one QR per display frame;
|
||||||
- DATA payload: **450 B**;
|
- DATA payload: **450 B**;
|
||||||
@@ -75,7 +75,7 @@ The overlay is derived from the same ROI used by the decoder, so the green/yello
|
|||||||
|
|
||||||
Discovery order includes QR hint, UDP `QFTDISC2`, gateway/direct candidates and bounded current-subnet fallback.
|
Discovery order includes QR hint, UDP `QFTDISC2`, gateway/direct candidates and bounded current-subnet fallback.
|
||||||
|
|
||||||
## 4. Android → Windows upload
|
## 4. 扫码本地直传(Android ↔ Windows)
|
||||||
|
|
||||||
Parallel v2 flow:
|
Parallel v2 flow:
|
||||||
|
|
||||||
@@ -85,19 +85,16 @@ POST /qft/upload/chunk (parallel, offset based)
|
|||||||
POST /qft/upload/finish
|
POST /qft/upload/finish
|
||||||
```
|
```
|
||||||
|
|
||||||
Windows preallocates a `.qftpart`, writes chunks at explicit offsets, verifies SHA-256, then renames to the final file. Per-file worker count is capped at 8; chunk size is selected from 4/8/16 MiB by file size.
|
Windows preallocates a `.qftpart`, writes chunks at explicit offsets, verifies SHA-256, then renames to the final file. Uploads target 8 workers per file (bounded by the usable chunks and device capacity); the requested chunk size is derived from the file size and clamped to **64 KiB–16 MiB**. Repeated `init` requests carrying the same `X-QFT-Upload-Key` resume the matching active upload session; repeated chunk and finish requests are idempotent so a lost response can be retried safely. Chunk completion is recorded only after the positioned write reaches stable storage.
|
||||||
|
|
||||||
Repeated `init` requests carrying the same `X-QFT-Upload-Key` resume the matching active upload session. The response may include a `missing` chunk-index array; the client sends only those chunks. Chunk completion is recorded only after the positioned write reaches stable storage.
|
## 5. Windows → Android download
|
||||||
|
|
||||||
## 5. Windows → Android direct download
|
The same QFTPAIR2 local session can declare the download direction. Android discovers and verifies the Windows sender, then downloads `GET /qft/download` with exact single-range requests:
|
||||||
|
|
||||||
Files of at least 32 MiB use up to 8 parallel bounded range requests:
|
|
||||||
|
|
||||||
```text
|
```text
|
||||||
GET /qft/download
|
|
||||||
Range: bytes=<start>-<end>
|
Range: bytes=<start>-<end>
|
||||||
```
|
```
|
||||||
|
|
||||||
Android preallocates an app-private `.qftpart`, writes each range at its fixed offset and persists a separate completion bitmap. A reconnect or process restart downloads only missing ranges. After every range is present, Android verifies the QR-carried SHA-256 before publishing the file to `Downloads/QFT`.
|
The sender returns `206 Partial Content`, the matching `Content-Range`, and the exact requested body length. Android splits the file toward 8 workers with **64 KiB–16 MiB** chunks, stores each completed chunk in a `.qftpart.map` ledger, and resumes only missing chunks after a reconnect. Each range retries with the currently available `Network`; the complete partial file must pass SHA-256 before it is published to `Downloads/QFT`.
|
||||||
|
|
||||||
The Android `WifiNetworkSpecifier` request remains registered for the entire transfer page. It is released when the user returns to the home page (or the Activity is destroyed); a replacement `Network` delivered after a brief radio loss is adopted by subsequent chunk/range retries.
|
For both direct-transfer directions, the Windows listener may accept connections non-blockingly for shutdown responsiveness, but each accepted file socket is switched to blocking I/O with explicit timeouts before reading or writing request bodies. This prevents `WSAEWOULDBLOCK (10035)` from turning an in-progress parallel transfer into an HTTP 500 failure.
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
# QFT v0.5 执行计划
|
||||||
|
|
||||||
|
配套设计文档:[V05_MULTIPEER_PLAN.md](V05_MULTIPEER_PLAN.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 三个默认决策(未经确认,可推翻)
|
||||||
|
|
||||||
|
设计文档结尾留了三个待定问题,为了让计划能往下排,先按以下默认执行。任一项改变都会影响排期,改之前先说。
|
||||||
|
|
||||||
|
| 问题 | 默认决策 | 理由 |
|
||||||
|
|---|---|---|
|
||||||
|
| M1 先做还是直接上 v3? | **M1 先做** | 零协议风险,做完立刻拿到真实 PC↔PC 体验;v3 的很多设计细节需要真实使用反馈才定得准 |
|
||||||
|
| 加密在哪一版做? | **放到 v3(P2),M1 维持现状明文** | TLS 与新协议一起做只需改一次握手层;分两次做要动两遍,且 M1 的目的是尽快验证对称节点模型 |
|
||||||
|
| 共享核心怎么做? | **桌面共享 Rust + 移动端原生 + `conformance/` 一致性套件** | 桌面三平台本来就是同一份代码(实测仅 3 处平台耦合),共享零成本;移动端 FFI 要等 v3 定型才划算 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 总体流程
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
P0["P0 收尾验证<br/>把半成品编译掉"] --> P1["P1 桌面跨平台 + PC↔PC<br/>走现有 v2 协议"]
|
||||||
|
P1 --> P2["P2 QFT-Stream v3<br/>目录直传 + 加密"]
|
||||||
|
P2 --> P3["P3 移动端接入 v3"]
|
||||||
|
P3 --> P4["P4 手机 ↔ 手机"]
|
||||||
|
P2 -.并行.-> P5["P5 一致性套件<br/>+ 性能回归"]
|
||||||
|
P0 -.独立并行轨.-> OPT["QFT5 光学<br/>阻塞于楔形标定"]
|
||||||
|
|
||||||
|
style P0 fill:#7a2020,color:#fff
|
||||||
|
style OPT fill:#5a4a20,color:#fff
|
||||||
|
```
|
||||||
|
|
||||||
|
**P0 是硬阻塞。** 当前有三处「写了但没验证」的代码,在其之上继续叠加会让问题定位成本指数上升。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. P0 · 收尾验证(阻塞,必须先做)
|
||||||
|
|
||||||
|
| # | 任务 | 涉及 | 验收标准 | 谁做 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| P0.1 | Android bug 修复编译 | `DownloadClient.kt` `WifiConnector.kt` `MainActivity.kt` | `./gradlew :app:assembleDebug` 通过 | **你**(我没有 Android SDK) |
|
||||||
|
| P0.2 | Android bug 修复实测 | — | 大文件传输走完全程;断网时 3 秒内报「临时网络已断开」而非等满重试;空间不足在开始前就提示 | **你**(需真机 + Windows 主机) |
|
||||||
|
| P0.3 | iOS 模拟器编译 | `ios/QFT/App/*.swift` | Xcode 选 iPhone 模拟器,⌘B 无红色错误 | **你** |
|
||||||
|
| P0.4 | `xcode-select` 指向 Xcode | — | `xcodebuild -version` 可用 | **你**(需 sudo) |
|
||||||
|
| P0.5 | 修掉 P0.1/P0.3 暴露的编译错误 | 视情况 | 同上重跑通过 | 我 |
|
||||||
|
| P0.6 | 提交并推送 | — | 工作区干净 | 我 |
|
||||||
|
|
||||||
|
**门禁:P0.1 与 P0.3 全绿才进入 P1。**
|
||||||
|
|
||||||
|
P0.4 做完之后我可以直接在命令行编译 iOS 工程,后续 Swift 改动就不再是盲写——这一项虽然可选,但会显著提升后面所有 iOS 相关工作的质量。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. P1 · 桌面跨平台 + PC↔PC
|
||||||
|
|
||||||
|
目标:**mac ↔ win、linux ↔ win 能互传单个文件**,仍走现有 v2 HTTP 协议。
|
||||||
|
|
||||||
|
| # | 任务 | 涉及 | 规模 | 验收标准 |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| P1.1 | `windows/` → `desktop/`,crate 更名 `qft-desktop` | 目录 + `Cargo.toml` + CI 脚本 + `VERIFY_WINDOWS_HOST.ps1` | S | `cargo check` 在 macOS 上通过 |
|
||||||
|
| P1.2 | 平台抽象层 `platform.rs` | 新增;改 `direct_ap.rs` `pairing.rs:148` `protocol.rs:194` | M | 三平台各自 `cargo test` 通过 |
|
||||||
|
| P1.3 | 配置/下载目录跨平台 | `pairing.rs` + 新增 | S | mac 写到 `~/Library/Application Support/QFT`,linux 写到 `$XDG_CONFIG_HOME/qft` |
|
||||||
|
| P1.4 | **桌面客户端** `client.rs` | 新增(当前完全缺失) | L | 单元测试:对本进程起的 receiver 完成一次上传 + 一次下载 |
|
||||||
|
| P1.5 | mDNS 发现 `discovery.rs` | 新增,`mdns-sd` crate | M | 两台机器互相出现在列表里;TXT 含 `v/id/name/platform/port` |
|
||||||
|
| P1.6 | 6 位配对码 | `pairing.rs` | M | 跨网段场景下输码可连;错码 3 次锁定 |
|
||||||
|
| P1.7 | UI:「附近的设备」页 + 拖拽发送 | `main.rs` | L | 拖文件到窗口即发送 |
|
||||||
|
| P1.8 | macOS / Linux 打包 | 新增 CI | M | 产出 `.app`(未签名)与 AppImage/tar.gz |
|
||||||
|
|
||||||
|
### P1 验收门
|
||||||
|
|
||||||
|
```
|
||||||
|
✅ mac → win 传 1GB 单文件,SHA-256 一致
|
||||||
|
✅ win → mac 同上
|
||||||
|
✅ linux → win 同上
|
||||||
|
✅ 三平台各自能在「附近的设备」里看到另外两台
|
||||||
|
✅ 拔网线重插后能续传(v2 的 Range 续传)
|
||||||
|
```
|
||||||
|
|
||||||
|
**这一门通过之前不进 P2。** 因为 v3 的价值全部建立在「对称节点模型成立」之上,先用最简单的协议把这个模型验证掉。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. P2 · QFT-Stream v3
|
||||||
|
|
||||||
|
目标:**目录直传可用**,先只在两台 PC 之间。
|
||||||
|
|
||||||
|
| # | 任务 | 规模 | 验收标准 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| P2.1 | 帧编解码 + 黄金测试向量 | M | 向量文件 `conformance/frames.json`,编解码往返一致 |
|
||||||
|
| P2.2 | Ed25519 身份 + 信任库 | M | 首次运行生成密钥;重启后身份不变 |
|
||||||
|
| P2.3 | TLS 1.3(`rustls`)+ 按公钥验证对端 | L | 错误公钥必须握手失败;6 位校验码两端一致 |
|
||||||
|
| P2.4 | 会话层:`SESSION_OPEN` / `INDEX_*` / `HAVE` | L | 断开重连后不重传已完成文件 |
|
||||||
|
| P2.5 | **流式并行索引** | M | 10 万文件树:首字节传输在遍历完成前就开始 |
|
||||||
|
| P2.6 | **小文件合批** | L | 见下方性能门 |
|
||||||
|
| P2.7 | 大文件分块并发 + 流控反压 | M | 接收端磁盘限速时内存不超过 `连接数 × 8MiB` |
|
||||||
|
| P2.8 | 路径安全层 | M | 见下方安全门 |
|
||||||
|
| P2.9 | 每文件 SHA-256 + 单遍哈希 | S | 单个坏文件只重传自己 |
|
||||||
|
|
||||||
|
### P2 性能门(在千兆有线上实测)
|
||||||
|
|
||||||
|
| 场景 | 目标 | 现状对照 |
|
||||||
|
|---|---|---|
|
||||||
|
| 5 万小文件 / 0.95 GB | **< 15 s** | v2 约 608 s |
|
||||||
|
| 3 千文件 / 11.7 GB | < 120 s | v2 约 138 s |
|
||||||
|
| 单文件 10 GB | < 95 s | v2 约 87 s(不得退化) |
|
||||||
|
| 峰值内存 | < 200 MB | — |
|
||||||
|
|
||||||
|
### P2 安全门(跨系统路径用例,全部必须通过)
|
||||||
|
|
||||||
|
```
|
||||||
|
linux → win : 目录含 CON.txt / aux.log / "a<b>.txt" / 结尾带空格的名字
|
||||||
|
linux → win : 同目录下 README.md 与 readme.md(大小写冲突)
|
||||||
|
linux → mac : 文件名含 "é"(NFC/NFD 归一化)
|
||||||
|
任意 → 任意 : 路径含 ../、绝对路径、指向根目录外的符号链接 → 整会话拒绝
|
||||||
|
win → 任意 : 路径长度超过 260
|
||||||
|
```
|
||||||
|
|
||||||
|
每条都要有自动化用例,不能靠手测。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. P3 · 移动端接入 v3
|
||||||
|
|
||||||
|
| # | 任务 | 端 | 规模 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| P3.1 | Android `NodeServer.kt`(ServerSocket + v3 帧) | Android | L |
|
||||||
|
| P3.2 | Android `NsdManager` 发现 | Android | M |
|
||||||
|
| P3.3 | Android 前台服务 + WakeLock | Android | M |
|
||||||
|
| P3.4 | Android 目录接收(SAF `OPEN_DOCUMENT_TREE`) | Android | M |
|
||||||
|
| P3.5 | iOS `PeerLink` 并入 v3 帧格式 | iOS | M |
|
||||||
|
| P3.6 | iOS 目录接收 + 「文件」App 导出 | iOS | M |
|
||||||
|
|
||||||
|
**门禁:手机 ↔ 电脑走 v3 传一个 5000 文件的目录成功。**
|
||||||
|
|
||||||
|
P3.3 是现有隐患的正式修复——当前只有 `FLAG_KEEP_SCREEN_ON`,息屏或切后台就有被系统掐断的风险。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. P4 · 手机 ↔ 手机
|
||||||
|
|
||||||
|
| 组合 | 任务 | 备注 |
|
||||||
|
|---|---|---|
|
||||||
|
| iOS ↔ iOS | 已实现,接 v3 即可 | `PeerLink.swift` 复用 |
|
||||||
|
| Android ↔ Android | `WifiP2pManager` 或 Local Only Hotspot,回落同 LAN | 新增 |
|
||||||
|
| Android ↔ iOS | **仅同一局域网** | UI 必须明确提示,不给假希望 |
|
||||||
|
|
||||||
|
**门禁:三种组合各传一个含子目录的相册目录成功。**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. P5 · 一致性套件(与 P2 并行)
|
||||||
|
|
||||||
|
把 `ios/CoreTests/MockPCServer.py` 的做法推广成 `conformance/`:
|
||||||
|
|
||||||
|
```
|
||||||
|
conformance/
|
||||||
|
vectors/ 黄金测试向量(帧编解码、路径规范化、合批边界)
|
||||||
|
reference_peer.py 参考对端,任一端实现都能对着它跑
|
||||||
|
run.sh 三端各自跑一遍
|
||||||
|
```
|
||||||
|
|
||||||
|
接入 `scripts/run_all_selftests.py`。**这是目前防三端协议漂移最有效的手段**,在 iOS 端已验证有效。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 验证责任分工
|
||||||
|
|
||||||
|
这个项目的返工大多来自「写完没法验证」。明确分工:
|
||||||
|
|
||||||
|
| 我能在这台 Mac 上做 | 只有你能做 |
|
||||||
|
|---|---|
|
||||||
|
| Rust `cargo check/test`(装了 Rust 之后) | Windows 上的 `cargo build --release` 与真机跑 |
|
||||||
|
| Swift 核心层编译 + 单测 | iOS 真机(相机、AWDL) |
|
||||||
|
| Swift 全量编译(**需你先做 P0.4**) | Android 编译与真机 |
|
||||||
|
| Python 工具与一致性套件 | 千兆有线上的性能实测 |
|
||||||
|
| 协议设计、黄金向量、代码审查 | 楔形标定拍照 |
|
||||||
|
|
||||||
|
**Kotlin 目前我完全无法编译**(本机无 Android SDK,装 kotlinc 会连带拉一个多余的 JDK)。所以 Android 侧改动我会尽量小步、单文件,每次都请你编译一次再继续——不要攒一大批。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 并行轨:QFT5 光学
|
||||||
|
|
||||||
|
与 v0.5 无依赖关系,可随时插入。当前**阻塞于楔形标定**:
|
||||||
|
|
||||||
|
```
|
||||||
|
你拍标定图 → 跑 wedge_analyze.py → 得到实测 px/模块
|
||||||
|
↓
|
||||||
|
≤3.2 → 按 OPTICAL_V5_PLAN 原样实施
|
||||||
|
3.2~4.0 → 目标 B 不可达,需下调指标
|
||||||
|
>4.0 → 先排查对焦/曝光,不要动协议
|
||||||
|
```
|
||||||
|
|
||||||
|
标定之前可以做的(不依赖该数值):相机帧率三级锁定、手动短曝光、关 EIS/抗闪烁、锁对焦、陀螺仪前馈。这几项**对现有 QFT2 链路也立刻有收益**(3px/模块下 33ms 自动曝光会产生 8.7px 运动模糊,等于抹掉近 3 个模块)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 回滚点与风险
|
||||||
|
|
||||||
|
| 阶段 | 回滚点 | 触发条件 |
|
||||||
|
|---|---|---|
|
||||||
|
| P1 | 保留 `windows/` 分支 tag | 跨平台抽象破坏了 Windows 行为 |
|
||||||
|
| P2 | v2 与 v3 并存,节点协商版本 | v3 性能门不达标 |
|
||||||
|
| P3 | 移动端可继续用 v2 | v3 在移动端内存/耗电不可接受 |
|
||||||
|
|
||||||
|
**每个阶段结束打一个 tag**,v3 与 v2 全程并存,任一阶段失败都不影响已发布版本可用。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 下一步
|
||||||
|
|
||||||
|
按顺序,现在只需要做三件事:
|
||||||
|
|
||||||
|
1. `cd android && ./gradlew :app:assembleDebug` —— 把 bug 修复编译掉,报错发我
|
||||||
|
2. Xcode 选模拟器 ⌘B —— iOS UI 层编译掉,报错发我
|
||||||
|
3. (可选但强烈建议)`sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`
|
||||||
|
|
||||||
|
这三件完成后我开始 P1.1。
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
# QFT v0.5 增量设计:全平台对等互传
|
||||||
|
|
||||||
|
基线 v0.4.7。三项增量需求:
|
||||||
|
|
||||||
|
1. 电脑 ↔ 电脑互传,跨平台(mac ↔ win ↔ mac,linux ↔ win ↔ mac)
|
||||||
|
2. 手机 ↔ 手机互传
|
||||||
|
3. 全量高速传输,支持目录直传,高速索引 + 稳定连接
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 现状盘点(实测,非推测)
|
||||||
|
|
||||||
|
| 项 | 现状 | 影响 |
|
||||||
|
|---|---|---|
|
||||||
|
| 桌面端角色 | **只有服务端**。`TcpStream::connect` 仅出现在 `#[cfg(test)]` 里 | PC 无法主动连接对方 → PC↔PC 完全不可用 |
|
||||||
|
| HTTP 连接 | 每个响应都写 `Connection: close`(`sender.rs:183/188/211`、`receiver.rs:531`) | 每个分块新建一次 TCP |
|
||||||
|
| 上传会话 | `UploadSession { file_name, size, chunk_size, total_chunks }` —— **单文件** | 无目录概念 |
|
||||||
|
| Windows 耦合 | 仅 3 处:`direct_ap.rs`(已 cfg 隔离)、`pairing.rs:148` 的 `LOCALAPPDATA`、`protocol.rs:194` 的 `COMPUTERNAME`。`read_at_once` 已有 unix 分支 | **跨平台成本比预期低得多** |
|
||||||
|
| 传输加密 | 无,局域网明文 HTTP | 同网段任何人可读文件内容 |
|
||||||
|
| 协议实现 | Rust 2845 行 / Kotlin 4423 行 / Swift 2053 行,同一协议三份实现 | 每加一个特性要写三遍 |
|
||||||
|
|
||||||
|
### 目录传输在现有协议下的实际代价
|
||||||
|
|
||||||
|
每个文件需要 init + chunk + finish 三次 HTTP,且每次都新建 TCP(局域网 RTT 按 2ms 计):
|
||||||
|
|
||||||
|
| 场景 | 文件数 | 总量 | 纯握手 | 数据传输(1GbE) | 合计 |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| 代码仓库 `node_modules` | 50 000 | 0.95 GB | **600 s** | 8 s | **608 s** |
|
||||||
|
| 照片目录 | 3 000 | 11.7 GB | 36 s | 102 s | 138 s |
|
||||||
|
| 单个大文件 | 1 | 10 GB | 0 s | 87 s | 87 s |
|
||||||
|
|
||||||
|
**小文件场景 98% 的时间花在握手上。** 这是本次设计的首要矛盾,不是带宽问题。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 核心设计决策:从「角色固定」到「对称节点」
|
||||||
|
|
||||||
|
现有架构把角色写死了:PC 是服务端,手机是客户端。三项需求全都被这个假设挡住。
|
||||||
|
|
||||||
|
v0.5 引入 **QFT Node** 模型——每个安装都同时具备:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────── QFT Node ───────────────────┐
|
||||||
|
│ 身份 Ed25519 密钥对(首次运行生成,持久化) │
|
||||||
|
│ 广播端 mDNS _qft._tcp + UDP 兜底 │
|
||||||
|
│ 服务端 QFT-Stream v3 监听器(接受传入会话) │
|
||||||
|
│ 客户端 QFT-Stream v3 发起器(主动连接对方) │← 桌面端当前缺失
|
||||||
|
│ 信任库 已确认过的对端公钥 │
|
||||||
|
└────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
一旦对称,三项需求退化成同一件事:**任意两个节点之间建立一条 v3 会话**。PC↔PC、手机↔手机、PC↔手机走完全相同的代码路径,差别只在链路选择。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 需求一:跨平台桌面端
|
||||||
|
|
||||||
|
### 2.1 目录改名与平台抽象
|
||||||
|
|
||||||
|
`windows/` → `desktop/`(crate 名 `qft-desktop`)。eframe/egui、rfd、rayon 本来就跨平台,实际要动的只有三处:
|
||||||
|
|
||||||
|
| 文件 | 现状 | 改法 |
|
||||||
|
|---|---|---|
|
||||||
|
| `direct_ap.rs` | Windows WiFi Direct,非 Windows 直接 `bail!` | 抽成 `trait LinkProvider`,mac/linux 返回 `Unsupported`,UI 隐藏该入口 |
|
||||||
|
| `pairing.rs:148` | `LOCALAPPDATA` | `directories` crate:win=`%LOCALAPPDATA%`,mac=`~/Library/Application Support`,linux=`$XDG_CONFIG_HOME` |
|
||||||
|
| `protocol.rs:194` | `COMPUTERNAME`/`HOSTNAME` | `hostname` crate + 各平台友好名(mac 读 `ComputerName`) |
|
||||||
|
|
||||||
|
另需新增:默认保存目录(win=`Downloads`,mac=`~/Downloads`,linux=`XDG_DOWNLOAD_DIR`)、单实例锁、开机自启(可选)。
|
||||||
|
|
||||||
|
**估算:这部分是整个方案里性价比最高的**——三个文件加一层 trait,就拿到 macOS 与 Linux。
|
||||||
|
|
||||||
|
### 2.2 桌面客户端(当前完全缺失)
|
||||||
|
|
||||||
|
新增 `desktop/src/client.rs`,实现 Node 的发起侧。UI 上新增「附近的设备」页:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─ 附近的设备 ────────────────────────────┐
|
||||||
|
│ 🖥 MacBook-Pro macOS 26 ● 已信任 │
|
||||||
|
│ 💻 DESKTOP-M7DEVQO Windows 11 ○ 未信任 │
|
||||||
|
│ 📱 iPhone 17 Pro iOS 26 ● 已信任 │
|
||||||
|
│ 🖥 ubuntu-dev Linux ○ 未信任 │
|
||||||
|
├────────────────────────────────────────┤
|
||||||
|
│ [ 拖拽文件/文件夹到此处发送 ] │
|
||||||
|
└────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
拖拽是桌面端的核心交互——这也是目录直传最自然的入口。
|
||||||
|
|
||||||
|
### 2.3 两台 PC 怎么互相发现(没有摄像头,扫不了码)
|
||||||
|
|
||||||
|
| 手段 | 适用 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| **mDNS / DNS-SD**(主) | 同一局域网 | 服务类型 `_qft._tcp`,TXT 携带 `v/id/name/platform/port/fp`。三平台都有成熟实现:桌面 `mdns-sd` crate、Android `NsdManager`、iOS `NWBrowser`(P2P 已在用) |
|
||||||
|
| UDP 广播(兜底) | mDNS 被交换机/防火墙拦时 | 沿用现有 `QFTDISC2`,升级到 v3 |
|
||||||
|
| **6 位配对码**(跨网段/兜底) | 不同子网、AP 隔离 | 接收方显示 6 位数字,发送方手输 |
|
||||||
|
| 手动 IP | 极端情况 | 直接输 `192.168.1.20:39393` |
|
||||||
|
|
||||||
|
QR 在 PC↔PC 场景不适用(对方没摄像头),所以 **6 位配对码是 PC↔PC 的必需品**,不是可选项。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 需求二:手机 ↔ 手机
|
||||||
|
|
||||||
|
| 组合 | 链路 | 状态 |
|
||||||
|
|---|---|---|
|
||||||
|
| iOS ↔ iOS | AWDL 点对点(`includePeerToPeer`)+ TLS-PSK | **已实现**(`PeerLink.swift`),并入 v3 即可 |
|
||||||
|
| Android ↔ Android | Wi-Fi Direct(`WifiP2pManager`)或 Local Only Hotspot,回落同 LAN | 需新增:Android 端 v3 服务端 |
|
||||||
|
| **Android ↔ iOS** | **只能同一局域网** | 见下 |
|
||||||
|
|
||||||
|
### 关于 Android ↔ iOS 必须说清楚的限制
|
||||||
|
|
||||||
|
无路由器直连做不到,原因是两边的点对点链路互不兼容:
|
||||||
|
|
||||||
|
- **AWDL** 是苹果私有链路,Android 无法参与
|
||||||
|
- **Wi-Fi Direct** 走 P2P GO 协商,iOS 完全不支持
|
||||||
|
- **iOS 无法用代码加入指定 Wi-Fi**(`NEHotspotConfiguration` 需付费账号 entitlement),所以「Android 开热点 + iOS 自动加入」这条路走不通;用户手动去设置里连是可行的,但体验很差
|
||||||
|
- 反方向「iOS 开个人热点 + Android 自动加入」:Android 侧可以用 `WifiNetworkSpecifier` 自动加入,但 iOS 个人热点无法由 App 开启,且多数运营商要求蜂窝套餐
|
||||||
|
|
||||||
|
**结论:Android ↔ iOS 要求两台手机连同一个 Wi-Fi。** UI 上必须直说,不能让用户在没有路由器的场合反复重试。
|
||||||
|
|
||||||
|
### Android 端要补的东西
|
||||||
|
|
||||||
|
当前 Android 只有客户端。需新增:
|
||||||
|
|
||||||
|
- `NodeServer.kt`:`ServerSocket` + v3 帧协议(不引入 HTTP 服务器依赖)
|
||||||
|
- `NsdHelper.kt`:`NsdManager` 注册与发现
|
||||||
|
- 前台服务 + `WakeLock`:长传输不被 Doze 掐断(现在只有 `FLAG_KEEP_SCREEN_ON`,息屏就危险)
|
||||||
|
- 接收侧文件写入走 MediaStore / SAF 目录树(目录传输需要 `ACTION_OPEN_DOCUMENT_TREE`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 需求三:QFT-Stream v3 —— 目录直传 + 高速索引 + 稳定连接
|
||||||
|
|
||||||
|
### 4.1 为什么必须换掉 HTTP
|
||||||
|
|
||||||
|
不是 HTTP 不好,是它的请求/响应模型表达不了这几件事:
|
||||||
|
|
||||||
|
1. **接收方主动告知「我已经有哪些」**(断点续传的前提)——HTTP 里只能靠客户端逐个 HEAD 探测
|
||||||
|
2. **一个连接上并发多个文件**——HTTP/1.1 无多路复用,HTTP/2 会引入大依赖
|
||||||
|
3. **边走目录边传**——索引和传输必须重叠,否则大目录要先干等几十秒
|
||||||
|
|
||||||
|
### 4.2 帧格式
|
||||||
|
|
||||||
|
TLS 1.3 over TCP,每会话开 N 条连接(默认 4,可调 1~8)。
|
||||||
|
|
||||||
|
```
|
||||||
|
u8 类型 | u32 长度(BE) | payload
|
||||||
|
```
|
||||||
|
|
||||||
|
| 类型 | 方向 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `HELLO` / `HELLO_ACK` | 双向 | 版本、node id、能力位 |
|
||||||
|
| `SESSION_OPEN` | 发→收 | session_id、根目录名、预估总量 |
|
||||||
|
| `INDEX_ENTRY` | 发→收 | **流式**:path / size / mtime / mode,边走目录边发 |
|
||||||
|
| `INDEX_END` | 发→收 | 总文件数、总字节数(此时才知道准确进度) |
|
||||||
|
| `HAVE` | 收→发 | 已有文件与偏移(断点续传) |
|
||||||
|
| `FILE_OPEN` / `FILE_DATA` / `FILE_END` | 发→收 | 大文件流式,`FILE_END` 带该文件 SHA-256 |
|
||||||
|
| `BATCH` | 发→收 | **小文件合批**,一帧塞多个完整小文件 |
|
||||||
|
| `ACK` | 收→发 | 字节水位,用于流控 |
|
||||||
|
| `PING` / `PONG` | 双向 | 心跳 |
|
||||||
|
| `ERROR` / `ABORT` | 双向 | |
|
||||||
|
|
||||||
|
### 4.3 高速索引:流式 + 重叠
|
||||||
|
|
||||||
|
不等目录走完就开始传。索引线程用 rayon 并行遍历目录,每发现一个文件就发一条 `INDEX_ENTRY`,同时数据通道已经在传前面发现的文件。
|
||||||
|
|
||||||
|
10 万文件的树,遍历本身 SSD 上要 2~5 秒(Windows `FindFirstFile` 更慢,机械盘或网络盘可能几十秒)。重叠之后这段时间完全被隐藏。
|
||||||
|
|
||||||
|
代价:`INDEX_END` 之前进度条只能显示「已发现 N 个 / 已传 M 个」,拿不到百分比。这是正确的取舍——先动起来比先算准重要。
|
||||||
|
|
||||||
|
### 4.4 小文件合批:本方案最大的性能杠杆
|
||||||
|
|
||||||
|
阈值:**< 1 MiB 合批,≥ 1 MiB 走 `FILE_*` 流式 + 分块并发**。
|
||||||
|
|
||||||
|
小文件打进 4 MiB 的 `BATCH` 帧,一帧内多个完整文件,接收端顺序落盘。回到开头那张表:
|
||||||
|
|
||||||
|
| 场景 | v2 | v3 | 提升 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 5 万小文件 0.95 GB | 608 s | **≈ 8 s** | **76×** |
|
||||||
|
| 3 千张照片 11.7 GB | 138 s | **≈ 102 s** | 1.35×(已接近线速) |
|
||||||
|
|
||||||
|
大文件场景本来就接近线速,提升有限;**小文件场景是数量级的差异**。
|
||||||
|
|
||||||
|
接收端配套优化:批量创建文件时避免每个文件一次 `fsync`,改为批末统一 flush;Windows 上关闭 Defender 实时扫描对目标目录的影响无法控制,但可以提示用户。
|
||||||
|
|
||||||
|
### 4.5 稳定连接
|
||||||
|
|
||||||
|
- **心跳**:每 5 s `PING`,20 s 无 `PONG` 判定断链
|
||||||
|
- **自动重连**:`session_id` 存活 10 分钟。重连后发 `HAVE`,从字节粒度续传,不重传已完成的文件
|
||||||
|
- **流控**:接收方按 `ACK` 水位反压,磁盘慢时不会把内存撑爆(现在 Android 侧 `worker × chunk` 就是内存峰值,没有反压)
|
||||||
|
- **每文件独立校验**:`FILE_END` 带 SHA-256,坏文件只重传自己,不会让一个 100 GB 的会话整体作废(现在是整份下完再校验,失败就全丢)
|
||||||
|
- **单遍哈希**:边读边算,不再像现在 Android 那样下载完再整份读一遍算 SHA-256
|
||||||
|
|
||||||
|
### 4.6 跨平台路径安全(容易被忽略但必须做)
|
||||||
|
|
||||||
|
目录传输一旦跨系统,这些全是真会踩的坑:
|
||||||
|
|
||||||
|
| 问题 | 处理 |
|
||||||
|
|---|---|
|
||||||
|
| `..`、绝对路径、空段、NUL | 一律拒绝,整会话中止 |
|
||||||
|
| Windows 保留名 `CON/PRN/AUX/NUL/COM1-9/LPT1-9` | 自动加后缀重命名,并在报告里列出 |
|
||||||
|
| Windows 非法字符 `<>:"\|?*`、结尾的点或空格 | 同上 |
|
||||||
|
| `MAX_PATH` 260 | Windows 侧统一走 `\\?\` 长路径前缀 |
|
||||||
|
| **macOS 的 NFD 归一化** | Linux 传 NFC 的「é」,macOS 存成 NFD,回传时路径对不上 → 协议层统一用 NFC,本地存储时记录原始字节 |
|
||||||
|
| **大小写冲突** | Linux 目录里的 `README.md` 与 `readme.md` 传到 Windows/macOS 会撞 → 检测并加后缀,报告给用户 |
|
||||||
|
| 符号链接 | 默认不跟随;指向根目录内则作为链接条目传输,指向外部则跳过并警告 |
|
||||||
|
| 权限位 | unix 之间保留可执行位;Windows 忽略 |
|
||||||
|
|
||||||
|
### 4.7 吞吐目标与真实瓶颈
|
||||||
|
|
||||||
|
| 链路 | 目标 |
|
||||||
|
|---|---|
|
||||||
|
| 千兆有线 | ≥ 110 MB/s(线速 118 MB/s) |
|
||||||
|
| Wi-Fi 6 (160MHz) | ≥ 40 MB/s |
|
||||||
|
| Wi-Fi 5 | ≥ 20 MB/s |
|
||||||
|
|
||||||
|
瓶颈按顺序:
|
||||||
|
|
||||||
|
1. **小文件系统调用**(最大)→ 合批解决
|
||||||
|
2. **TLS + SHA-256 CPU** → 两者都有硬件指令加速(AES-NI / SHA-NI),实测 1~3 GB/s,不是瓶颈;但**必须单遍**,做两遍就变成瓶颈了
|
||||||
|
3. **磁盘** → 大缓冲(1~4 MiB)、顺序写、批末统一 flush
|
||||||
|
4. **单条 TCP 在 Wi-Fi 上打不满** → 多连接(默认 4)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 安全模型
|
||||||
|
|
||||||
|
现状是局域网明文 HTTP + 二维码里的会话令牌。二维码作为带外信道是对的,但**内容明文**——同网段任何人抓包就能拿到文件。
|
||||||
|
|
||||||
|
v0.5:
|
||||||
|
|
||||||
|
- 每个节点首次运行生成 **Ed25519 身份密钥对**,存平台配置目录(后续可迁到 Keychain / Credential Manager / Secret Service)
|
||||||
|
- **TLS 1.3**,自签证书绑定身份公钥,**按公钥验证对端**(不走 CA 体系)
|
||||||
|
- 首次连接的信任建立分两种:
|
||||||
|
|
||||||
|
| 场景 | 方式 |
|
||||||
|
|---|---|
|
||||||
|
| 扫码(手机在场) | 二维码携带对端指纹 + 一次性 PSK,扫码动作本身即确认,**无需弹窗**(沿用现有 `QFTP2P1` 思路) |
|
||||||
|
| mDNS 发现 / 6 位码(PC↔PC) | 接收方弹「接受来自 <名字> 的传输?」,两端各显示一个由双方公钥派生的 **6 位校验码**,用户目视比对后确认 |
|
||||||
|
|
||||||
|
- 确认后写入信任库(TOFU),之后同一对端免确认
|
||||||
|
- **绝不自动接受未知对端**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 代码组织:要不要做共享核心
|
||||||
|
|
||||||
|
现状是同一协议三份实现,共 9 321 行。v3 要在三端各写一遍目录传输 + 合批 + 断点续传,是三倍工作量和三倍漂移风险。
|
||||||
|
|
||||||
|
| 方案 | 优点 | 代价 |
|
||||||
|
|---|---|---|
|
||||||
|
| A. 三端各写 | 无新工具链 | 3× 工作量,协议漂移 |
|
||||||
|
| B. 共享 Rust core + FFI | 一份实现 | NDK/cargo-ndk、uniffi、xcframework、CI 全套 |
|
||||||
|
| **C. 桌面共享 + 移动端原生 + 共用一致性测试** | 桌面三平台几乎零成本共享;移动端不引入 FFI | 移动端仍是两份 |
|
||||||
|
|
||||||
|
**推荐 C。** 理由:桌面三平台本来就是同一份 Rust 代码(实测只有 3 处平台耦合),共享是白拿的;而移动端上 FFI 的投入要等 v3 协议稳定后才划算。
|
||||||
|
|
||||||
|
配套:把现有 `ios/CoreTests/MockPCServer.py` 的做法推广成 **`conformance/` 一致性套件**——一份黄金测试向量 + 一个参考对端,三端实现都必须跑通。这是目前防漂移最有效的手段,已经在 iOS 端验证过。
|
||||||
|
|
||||||
|
若后续移动端漂移确实变痛,再切 B,届时 v3 已定型,FFI 的收益也更清楚。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 兼容与分期
|
||||||
|
|
||||||
|
v2(现有 HTTP)与 v3 并存。节点在 mDNS TXT 和 `/qft/ping` 里声明支持的版本,双方取交集。老版本 Android/iOS 装机不受影响。
|
||||||
|
|
||||||
|
| 里程碑 | 内容 | 产出 | 依赖 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **M1** | 桌面跨平台(`windows/`→`desktop/`,3 处平台抽象)+ 桌面客户端 + mDNS + 6 位码 | **PC↔PC 可用**(先走 v2 HTTP) | 无 |
|
||||||
|
| **M2** | QFT-Stream v3:帧协议、流式索引、小文件合批、断点续传、路径安全 | **目录直传可用**,先在两台 PC 之间验证 | M1 |
|
||||||
|
| **M3** | 移动端接入 v3:Android `NodeServer` + `NsdManager` + 前台服务;iOS `PeerLink` 并入 v3 | 手机 ↔ 电脑走 v3 | M2 |
|
||||||
|
| **M4** | 手机↔手机:Android Wi-Fi Direct、iOS 沿用 AWDL、跨系统走 LAN | **手机↔手机可用** | M3 |
|
||||||
|
| M5 | 一致性套件 `conformance/`、性能回归基准 | 防漂移 | M2 |
|
||||||
|
|
||||||
|
M1 最快见效且零协议风险,建议先做完 M1 拿到真实的 PC↔PC 体验,再决定 M2 的细节。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 明确不做 / 做不到
|
||||||
|
|
||||||
|
- **Android ↔ iOS 无路由器直连**:AWDL 与 Wi-Fi Direct 互不兼容,iOS 又不能用代码加入指定 Wi-Fi。只能同一局域网,UI 必须直说
|
||||||
|
- **Linux 的 Wi-Fi Direct / 热点**:各发行版 NetworkManager 行为差异过大,不做,Linux 只支持同 LAN
|
||||||
|
- **光学链路**:不在本次范围。QFT5 位阵列方案见 `OPTICAL_V5_PLAN.md`,且必须先做完楔形标定
|
||||||
|
- **公网中继 / 打洞**:QFT 的定位是本地直传,引入中继会改变整个安全模型,不做
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 主要风险
|
||||||
|
|
||||||
|
| 风险 | 影响 | 对策 |
|
||||||
|
|---|---|---|
|
||||||
|
| mDNS 在企业 Wi-Fi / AP 隔离下被拦 | 发现不到对端 | UDP 广播 + 6 位码 + 手动 IP 三重兜底 |
|
||||||
|
| 大目录索引占内存 | 10 万文件的清单常驻 | 流式索引,接收端落盘为 sqlite/紧凑二进制,不全量驻留 |
|
||||||
|
| Android 后台被杀 | 长传输中断 | 前台服务 + WakeLock + 会话可恢复(v3 断点续传) |
|
||||||
|
| 三端协议漂移 | 联调地狱 | `conformance/` 一致性套件,CI 强制 |
|
||||||
|
| TLS 引入依赖体积 | 移动端包变大 | 桌面用 `rustls`;Android 用系统 `SSLSocket`;iOS 用 Network.framework(已在用) |
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""按 windows/src/{sender,receiver}.rs 的线上语义实现的假电脑端。
|
"""按 desktop/src/{sender,receiver}.rs 的线上语义实现的假电脑端。
|
||||||
|
|
||||||
存在的意义:Swift 客户端的线格式必须和 Rust 端逐字节一致,
|
存在的意义:Swift 客户端的线格式必须和 Rust 端逐字节一致,
|
||||||
而 Rust 端在这台机器上编译不了。这个 mock 把两端的契约固定下来,
|
而 Rust 端在这台机器上编译不了。这个 mock 把两端的契约固定下来,
|
||||||
|
|||||||
@@ -194,7 +194,7 @@
|
|||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 46;
|
CURRENT_PROJECT_VERSION = 47;
|
||||||
ENABLE_PREVIEWS = YES;
|
ENABLE_PREVIEWS = YES;
|
||||||
GENERATE_INFOPLIST_FILE = NO;
|
GENERATE_INFOPLIST_FILE = NO;
|
||||||
INFOPLIST_FILE = QFT/Info.plist;
|
INFOPLIST_FILE = QFT/Info.plist;
|
||||||
@@ -203,7 +203,7 @@
|
|||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 0.4.6;
|
MARKETING_VERSION = 0.4.7;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
|
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||||
@@ -272,7 +272,7 @@
|
|||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 46;
|
CURRENT_PROJECT_VERSION = 47;
|
||||||
ENABLE_PREVIEWS = YES;
|
ENABLE_PREVIEWS = YES;
|
||||||
GENERATE_INFOPLIST_FILE = NO;
|
GENERATE_INFOPLIST_FILE = NO;
|
||||||
INFOPLIST_FILE = QFT/Info.plist;
|
INFOPLIST_FILE = QFT/Info.plist;
|
||||||
@@ -281,7 +281,7 @@
|
|||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 0.4.6;
|
MARKETING_VERSION = 0.4.7;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
|
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
# QFT iOS 客户端 v0.4.6
|
# QFT iOS 客户端 v0.4.7
|
||||||
|
|
||||||
三种传输方式:
|
三种传输方式:
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ IOS_ROOT = os.path.dirname(HERE)
|
|||||||
APP_NAME = "QFT"
|
APP_NAME = "QFT"
|
||||||
BUNDLE_ID = "com.qft.transfer"
|
BUNDLE_ID = "com.qft.transfer"
|
||||||
DEPLOYMENT_TARGET = "17.0"
|
DEPLOYMENT_TARGET = "17.0"
|
||||||
MARKETING_VERSION = "0.4.6"
|
MARKETING_VERSION = "0.4.7"
|
||||||
|
|
||||||
SOURCES = [
|
SOURCES = [
|
||||||
"QFT/App/QFTApp.swift",
|
"QFT/App/QFTApp.swift",
|
||||||
@@ -280,7 +280,7 @@ def generate():
|
|||||||
"ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon",
|
"ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon",
|
||||||
"ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor",
|
"ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor",
|
||||||
"CODE_SIGN_STYLE = Automatic",
|
"CODE_SIGN_STYLE = Automatic",
|
||||||
"CURRENT_PROJECT_VERSION = 46",
|
"CURRENT_PROJECT_VERSION = 47",
|
||||||
"ENABLE_PREVIEWS = YES",
|
"ENABLE_PREVIEWS = YES",
|
||||||
"GENERATE_INFOPLIST_FILE = NO",
|
"GENERATE_INFOPLIST_FILE = NO",
|
||||||
"INFOPLIST_FILE = QFT/Info.plist",
|
"INFOPLIST_FILE = QFT/Info.plist",
|
||||||
|
|||||||
+59
-46
@@ -1,72 +1,85 @@
|
|||||||
@echo off
|
@echo off
|
||||||
setlocal EnableExtensions
|
chcp 65001 >nul
|
||||||
|
setlocal EnableExtensions DisableDelayedExpansion
|
||||||
cd /d "%~dp0"
|
cd /d "%~dp0"
|
||||||
|
|
||||||
echo == QFT one-click package ==
|
echo == QFT 正式版中文打包 ==
|
||||||
|
|
||||||
where cargo >nul 2>nul
|
where cargo >nul 2>nul
|
||||||
if errorlevel 1 (
|
if errorlevel 1 (
|
||||||
echo ERROR: Rust cargo was not found in PATH.
|
echo 错误:PATH 中未找到 Rust cargo。
|
||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
where java >nul 2>nul
|
echo [1/4] 测试并构建 Windows 正式版...
|
||||||
if errorlevel 1 (
|
pushd desktop
|
||||||
echo ERROR: JDK 17 was not found in PATH.
|
cargo test --locked
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
|
|
||||||
if not exist "android\local.properties" if not defined ANDROID_HOME if not defined ANDROID_SDK_ROOT (
|
|
||||||
echo ERROR: Android SDK was not found. Set ANDROID_HOME or create android\local.properties with sdk.dir.
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
|
|
||||||
if not exist "android\gradle\wrapper\gradle-wrapper.jar" (
|
|
||||||
echo [1/5] Bootstrapping the Gradle wrapper...
|
|
||||||
powershell -NoProfile -ExecutionPolicy Bypass -File "android\bootstrap-wrapper.ps1"
|
|
||||||
if errorlevel 1 exit /b 1
|
|
||||||
) else (
|
|
||||||
echo [1/5] Gradle wrapper is ready.
|
|
||||||
)
|
|
||||||
|
|
||||||
echo [2/5] Testing and building the Windows release...
|
|
||||||
pushd windows
|
|
||||||
cargo test
|
|
||||||
if errorlevel 1 (popd & exit /b 1)
|
if errorlevel 1 (popd & exit /b 1)
|
||||||
cargo build --release
|
cargo build --release --locked
|
||||||
if errorlevel 1 (popd & exit /b 1)
|
if errorlevel 1 (popd & exit /b 1)
|
||||||
popd
|
popd
|
||||||
|
|
||||||
echo [3/5] Testing and building the installable Android APK...
|
for /f "tokens=3" %%V in ('findstr /R /C:"^version =" "desktop\Cargo.toml"') do set "QFT_VERSION=%%~V"
|
||||||
pushd android
|
for /f "tokens=3" %%V in ('findstr /R /C:"^[ ]*versionName =" "android\app\build.gradle.kts"') do set "QFT_ANDROID_VERSION=%%~V"
|
||||||
call gradlew.bat :app:testDebugUnitTest :app:assembleDebug --stacktrace
|
for /f "tokens=3" %%V in ('findstr /R /C:"^[ ]*versionCode =" "android\app\build.gradle.kts"') do set "QFT_ANDROID_CODE=%%V"
|
||||||
if errorlevel 1 (popd & exit /b 1)
|
|
||||||
popd
|
|
||||||
|
|
||||||
for /f "tokens=3" %%V in ('findstr /R /C:"versionName *=" "android\app\build.gradle.kts"') do set "QFT_VERSION=%%~V"
|
|
||||||
for /f "usebackq delims=" %%T in (`powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"`) do set "QFT_STAMP=%%T"
|
for /f "usebackq delims=" %%T in (`powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"`) do set "QFT_STAMP=%%T"
|
||||||
|
for /f "usebackq delims=" %%C in (`git rev-parse --short HEAD 2^>nul`) do set "QFT_RELEASE_COMMIT=%%C"
|
||||||
if not defined QFT_VERSION set "QFT_VERSION=unknown"
|
if not defined QFT_VERSION set "QFT_VERSION=unknown"
|
||||||
set "QFT_PACKAGE=QFT-%QFT_VERSION%-%QFT_STAMP%-windows"
|
if not defined QFT_ANDROID_VERSION set "QFT_ANDROID_VERSION=unknown"
|
||||||
|
if not defined QFT_ANDROID_CODE set "QFT_ANDROID_CODE=unknown"
|
||||||
|
if not defined QFT_RELEASE_COMMIT set "QFT_RELEASE_COMMIT=unknown"
|
||||||
|
if /I "%QFT_ANDROID_VERSION%"=="%QFT_VERSION%" goto versions_ok
|
||||||
|
echo 错误:PC 版本 %QFT_VERSION% 与 Android 版本 %QFT_ANDROID_VERSION% 不一致,拒绝封版。
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:versions_ok
|
||||||
|
set "QFT_PACKAGE=QFT-正式版-v%QFT_VERSION%-Windows-%QFT_STAMP%"
|
||||||
set "QFT_PACKAGE_DIR=%CD%\dist\%QFT_PACKAGE%"
|
set "QFT_PACKAGE_DIR=%CD%\dist\%QFT_PACKAGE%"
|
||||||
|
|
||||||
echo [4/5] Collecting artifacts...
|
echo [2/4] 收集正式版文件...
|
||||||
mkdir "%QFT_PACKAGE_DIR%" || exit /b 1
|
mkdir "%QFT_PACKAGE_DIR%" || exit /b 1
|
||||||
copy /y "windows\target\release\qft-windows.exe" "%QFT_PACKAGE_DIR%\QFT-Windows.exe" >nul || exit /b 1
|
copy /y "desktop\target\release\qft-desktop.exe" "%QFT_PACKAGE_DIR%\QFT超速文件传输.exe" >nul || exit /b 1
|
||||||
copy /y "android\app\build\outputs\apk\debug\app-debug.apk" "%QFT_PACKAGE_DIR%\QFT-Android-%QFT_VERSION%.apk" >nul || exit /b 1
|
copy /y "README.md" "%QFT_PACKAGE_DIR%\使用说明.md" >nul || exit /b 1
|
||||||
copy /y "README.md" "%QFT_PACKAGE_DIR%\README.md" >nul || exit /b 1
|
copy /y "TEST_REPORT.md" "%QFT_PACKAGE_DIR%\测试报告.md" >nul || exit /b 1
|
||||||
copy /y "TEST_REPORT.md" "%QFT_PACKAGE_DIR%\TEST_REPORT.md" >nul || exit /b 1
|
copy /y "docs\PROTOCOL.md" "%QFT_PACKAGE_DIR%\传输协议.md" >nul || exit /b 1
|
||||||
copy /y "docs\PROTOCOL.md" "%QFT_PACKAGE_DIR%\PROTOCOL.md" >nul || exit /b 1
|
copy /y "RELEASE_NOTES_%QFT_VERSION%.md" "%QFT_PACKAGE_DIR%\版本说明.md" >nul || exit /b 1
|
||||||
|
|
||||||
echo [5/5] Writing SHA-256 checksums and ZIP archive...
|
rem 仅收集已经由用户在 Windows 上构建好的 APK,不调用 Gradle/Android SDK。
|
||||||
|
set "QFT_APK=%QFT_ANDROID_APK%"
|
||||||
|
if defined QFT_APK goto apk_resolved
|
||||||
|
if exist "android\app\build\outputs\apk\release\app-release.apk" set "QFT_APK=android\app\build\outputs\apk\release\app-release.apk"
|
||||||
|
if defined QFT_APK goto apk_resolved
|
||||||
|
if exist "android\app\build\outputs\apk\debug\app-debug.apk" set "QFT_APK=android\app\build\outputs\apk\debug\app-debug.apk"
|
||||||
|
|
||||||
|
:apk_resolved
|
||||||
|
if not defined QFT_APK goto apk_missing
|
||||||
|
if not exist "%QFT_APK%" goto apk_missing
|
||||||
|
copy /y "%QFT_APK%" "%QFT_PACKAGE_DIR%\QFT安卓端-v%QFT_VERSION%.apk" >nul || exit /b 1
|
||||||
|
echo 已收集 Android APK:%QFT_APK%
|
||||||
|
goto apk_done
|
||||||
|
|
||||||
|
:apk_missing
|
||||||
|
echo 提示:未发现已构建 APK,本次生成 Windows 桌面端正式包。
|
||||||
|
echo 如需合并 APK,请先在 Windows 构建,或设置 QFT_ANDROID_APK 后重跑本脚本。
|
||||||
|
|
||||||
|
:apk_done
|
||||||
|
echo [3/4] 写入版本信息与 SHA-256 校验...
|
||||||
|
powershell -NoProfile -Command ^
|
||||||
|
"$dir = [IO.Path]::GetFullPath('%QFT_PACKAGE_DIR%');" ^
|
||||||
|
"$meta = @('QFT 超速文件传输 正式版', '产品版本:v%QFT_VERSION%', 'Android versionCode:%QFT_ANDROID_CODE%', '封版提交:%QFT_RELEASE_COMMIT%', '打包时间:%QFT_STAMP%', '平台:Windows x64');" ^
|
||||||
|
"[IO.File]::WriteAllLines((Join-Path $dir '版本信息.txt'), $meta, [Text.UTF8Encoding]::new($false));" ^
|
||||||
|
"$lines = Get-ChildItem -LiteralPath $dir -File ^| Where-Object Name -ne 'SHA256校验.txt' ^| Sort-Object Name ^| ForEach-Object { '{0} {1}' -f (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLower(), $_.Name };" ^
|
||||||
|
"[IO.File]::WriteAllLines((Join-Path $dir 'SHA256校验.txt'), $lines, [Text.UTF8Encoding]::new($false))"
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
echo [4/4] 创建中文 ZIP 正式包...
|
||||||
powershell -NoProfile -Command ^
|
powershell -NoProfile -Command ^
|
||||||
"$dir = [IO.Path]::GetFullPath('%QFT_PACKAGE_DIR%');" ^
|
"$dir = [IO.Path]::GetFullPath('%QFT_PACKAGE_DIR%');" ^
|
||||||
"$lines = Get-ChildItem -LiteralPath $dir -File ^| Sort-Object Name ^| ForEach-Object { '{0} {1}' -f (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLower(), $_.Name };" ^
|
|
||||||
"[IO.File]::WriteAllLines((Join-Path $dir 'SHA256SUMS.txt'), $lines, [Text.UTF8Encoding]::new($false));" ^
|
|
||||||
"Compress-Archive -LiteralPath $dir -DestinationPath ($dir + '.zip') -Force"
|
"Compress-Archive -LiteralPath $dir -DestinationPath ($dir + '.zip') -Force"
|
||||||
if errorlevel 1 exit /b 1
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo PACKAGE COMPLETE
|
echo 封版打包完成
|
||||||
echo Folder: %QFT_PACKAGE_DIR%
|
echo 文件夹:%QFT_PACKAGE_DIR%
|
||||||
echo ZIP: %QFT_PACKAGE_DIR%.zip
|
echo 压缩包:%QFT_PACKAGE_DIR%.zip
|
||||||
exit /b 0
|
exit /b 0
|
||||||
|
|||||||
+99
-39
@@ -4,67 +4,127 @@ set -eu
|
|||||||
QFT_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
QFT_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||||
cd "$QFT_ROOT"
|
cd "$QFT_ROOT"
|
||||||
|
|
||||||
echo "== QFT one-click package =="
|
echo "== QFT 正式版中文打包 =="
|
||||||
command -v cargo >/dev/null 2>&1 || { echo "ERROR: Rust cargo was not found in PATH." >&2; exit 1; }
|
if ! command -v cargo >/dev/null 2>&1; then
|
||||||
command -v java >/dev/null 2>&1 || { echo "ERROR: JDK 17 was not found in PATH." >&2; exit 1; }
|
# rustup 装在 keg-only 目录里时不会自动进 PATH,这里兜一下,
|
||||||
if [ ! -f "android/local.properties" ] && [ -z "${ANDROID_HOME:-}" ] && [ -z "${ANDROID_SDK_ROOT:-}" ]; then
|
# 避免用户明明装了工具链却被告知"没装"。
|
||||||
echo "ERROR: Android SDK was not found. Set ANDROID_HOME or create android/local.properties with sdk.dir." >&2
|
for QFT_CANDIDATE in "/opt/homebrew/opt/rustup/bin" "$HOME/.cargo/bin"; do
|
||||||
|
if [ -x "$QFT_CANDIDATE/cargo" ]; then
|
||||||
|
PATH="$QFT_CANDIDATE:$PATH"
|
||||||
|
export PATH
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
command -v cargo >/dev/null 2>&1 || {
|
||||||
|
echo "ERROR: Rust cargo was not found in PATH." >&2
|
||||||
|
echo " brew 安装:brew install rustup && rustup default stable" >&2
|
||||||
|
echo " 并把 /opt/homebrew/opt/rustup/bin 加入 PATH" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
}
|
||||||
|
|
||||||
if [ ! -f "android/gradle/wrapper/gradle-wrapper.jar" ]; then
|
echo "[1/4] 测试并构建桌面正式版..."
|
||||||
echo "[1/5] Bootstrapping the Gradle wrapper..."
|
|
||||||
sh android/bootstrap-wrapper.sh
|
|
||||||
else
|
|
||||||
echo "[1/5] Gradle wrapper is ready."
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "[2/5] Testing and building the desktop release..."
|
|
||||||
(
|
(
|
||||||
cd windows
|
cd desktop
|
||||||
cargo test
|
cargo test --locked
|
||||||
cargo build --release
|
cargo build --release --locked
|
||||||
)
|
)
|
||||||
|
|
||||||
echo "[3/5] Testing and building the installable Android APK..."
|
QFT_VERSION=$(awk -F'"' '/^\[package\]/{package=1; next} package && /^version[[:space:]]*=/{print $2; exit} /^\[/{package=0}' desktop/Cargo.toml)
|
||||||
(
|
|
||||||
cd android
|
|
||||||
sh ./gradlew :app:testDebugUnitTest :app:assembleDebug --stacktrace
|
|
||||||
)
|
|
||||||
|
|
||||||
QFT_VERSION=$(sed -n 's/.*versionName[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' android/app/build.gradle.kts | sed -n '1p')
|
|
||||||
[ -n "$QFT_VERSION" ] || QFT_VERSION=unknown
|
[ -n "$QFT_VERSION" ] || QFT_VERSION=unknown
|
||||||
QFT_STAMP=$(date '+%Y%m%d-%H%M%S')
|
QFT_STAMP=$(date '+%Y%m%d-%H%M%S')
|
||||||
QFT_PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
|
QFT_PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
|
||||||
QFT_PACKAGE="QFT-${QFT_VERSION}-${QFT_STAMP}-${QFT_PLATFORM}"
|
QFT_ARCH=$(uname -m)
|
||||||
|
QFT_PACKAGE="QFT-正式版-v${QFT_VERSION}-${QFT_PLATFORM}-${QFT_ARCH}-${QFT_STAMP}"
|
||||||
QFT_PACKAGE_DIR="$QFT_ROOT/dist/$QFT_PACKAGE"
|
QFT_PACKAGE_DIR="$QFT_ROOT/dist/$QFT_PACKAGE"
|
||||||
|
|
||||||
echo "[4/5] Collecting artifacts..."
|
ANDROID_VERSION=$(awk -F'"' '/versionName[[:space:]]*=/{print $2; exit}' android/app/build.gradle.kts)
|
||||||
|
ANDROID_VERSION_CODE=$(awk '/versionCode[[:space:]]*=/{print $3; exit}' android/app/build.gradle.kts)
|
||||||
|
[ "$ANDROID_VERSION" = "$QFT_VERSION" ] || {
|
||||||
|
echo "错误:PC 版本 $QFT_VERSION 与 Android 版本 $ANDROID_VERSION 不一致,拒绝封版。" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "[2/4] 收集正式版文件..."
|
||||||
mkdir -p "$QFT_PACKAGE_DIR"
|
mkdir -p "$QFT_PACKAGE_DIR"
|
||||||
if [ -f "windows/target/release/qft-windows.exe" ]; then
|
if [ -f "desktop/target/release/qft-desktop.exe" ]; then
|
||||||
cp "windows/target/release/qft-windows.exe" "$QFT_PACKAGE_DIR/QFT-Windows.exe"
|
cp "desktop/target/release/qft-desktop.exe" "$QFT_PACKAGE_DIR/QFT超速文件传输.exe"
|
||||||
elif [ -f "windows/target/release/qft-windows" ]; then
|
elif [ -f "desktop/target/release/qft-desktop" ]; then
|
||||||
cp "windows/target/release/qft-windows" "$QFT_PACKAGE_DIR/QFT-Desktop"
|
cp "desktop/target/release/qft-desktop" "$QFT_PACKAGE_DIR/QFT超速文件传输"
|
||||||
|
# macOS 上额外产出 .app 包。AppKit 的若干行为(其中就包括
|
||||||
|
# NSOpenPanel)依赖应用被正确注册为 GUI 程序,直接跑裸二进制时
|
||||||
|
# openPanel 会偶发返回 NULL 并导致崩溃。
|
||||||
|
if [ "$QFT_PLATFORM" = "darwin" ]; then
|
||||||
|
QFT_APP="$QFT_PACKAGE_DIR/QFT超速文件传输.app"
|
||||||
|
mkdir -p "$QFT_APP/Contents/MacOS"
|
||||||
|
cp "desktop/target/release/qft-desktop" "$QFT_APP/Contents/MacOS/QFT"
|
||||||
|
chmod +x "$QFT_APP/Contents/MacOS/QFT"
|
||||||
|
cat > "$QFT_APP/Contents/Info.plist" <<PLIST
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>CFBundleName</key><string>QFT</string>
|
||||||
|
<key>CFBundleDisplayName</key><string>QFT 超速文件传输</string>
|
||||||
|
<key>CFBundleIdentifier</key><string>com.qft.desktop</string>
|
||||||
|
<key>CFBundleExecutable</key><string>QFT</string>
|
||||||
|
<key>CFBundlePackageType</key><string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key><string>${QFT_VERSION}</string>
|
||||||
|
<key>CFBundleVersion</key><string>1</string>
|
||||||
|
<key>NSHighResolutionCapable</key><true/>
|
||||||
|
<key>LSMinimumSystemVersion</key><string>11.0</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
|
PLIST
|
||||||
|
echo " 已生成 QFT超速文件传输.app(推荐使用)"
|
||||||
|
fi
|
||||||
else
|
else
|
||||||
echo "ERROR: desktop release binary was not produced." >&2
|
echo "ERROR: desktop release binary was not produced." >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
cp "android/app/build/outputs/apk/debug/app-debug.apk" "$QFT_PACKAGE_DIR/QFT-Android-${QFT_VERSION}.apk"
|
cp README.md "$QFT_PACKAGE_DIR/使用说明.md"
|
||||||
cp README.md TEST_REPORT.md "$QFT_PACKAGE_DIR/"
|
cp TEST_REPORT.md "$QFT_PACKAGE_DIR/测试报告.md"
|
||||||
cp docs/PROTOCOL.md "$QFT_PACKAGE_DIR/PROTOCOL.md"
|
cp docs/PROTOCOL.md "$QFT_PACKAGE_DIR/传输协议.md"
|
||||||
|
cp "RELEASE_NOTES_${QFT_VERSION}.md" "$QFT_PACKAGE_DIR/版本说明.md"
|
||||||
|
|
||||||
echo "[5/5] Writing SHA-256 checksums and archive..."
|
# 只收集已经存在的 APK,不检查、下载或调用 Android SDK/Gradle。
|
||||||
|
QFT_APK=${QFT_ANDROID_APK:-}
|
||||||
|
if [ -z "$QFT_APK" ] && [ -f android/app/build/outputs/apk/release/app-release.apk ]; then
|
||||||
|
QFT_APK=android/app/build/outputs/apk/release/app-release.apk
|
||||||
|
fi
|
||||||
|
if [ -z "$QFT_APK" ] && [ -f android/app/build/outputs/apk/debug/app-debug.apk ]; then
|
||||||
|
QFT_APK=android/app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
fi
|
||||||
|
if [ -n "$QFT_APK" ] && [ -f "$QFT_APK" ]; then
|
||||||
|
cp "$QFT_APK" "$QFT_PACKAGE_DIR/QFT安卓端-v${QFT_VERSION}.apk"
|
||||||
|
echo " 已收集 Android APK:$QFT_APK"
|
||||||
|
else
|
||||||
|
echo " 提示:未发现已构建 APK,本次只生成当前桌面平台正式包。"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[3/4] 写入 SHA-256 校验..."
|
||||||
|
QFT_RELEASE_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || printf 'unknown')
|
||||||
|
{
|
||||||
|
printf '%s\n' "QFT 超速文件传输 正式版"
|
||||||
|
printf '%s\n' "产品版本:v${QFT_VERSION}"
|
||||||
|
printf '%s\n' "Android versionCode:${ANDROID_VERSION_CODE}"
|
||||||
|
printf '%s\n' "封版提交:${QFT_RELEASE_COMMIT}"
|
||||||
|
printf '%s\n' "打包时间:${QFT_STAMP}"
|
||||||
|
printf '%s\n' "平台:${QFT_PLATFORM} ${QFT_ARCH}"
|
||||||
|
} > "$QFT_PACKAGE_DIR/版本信息.txt"
|
||||||
(
|
(
|
||||||
cd "$QFT_PACKAGE_DIR"
|
cd "$QFT_PACKAGE_DIR"
|
||||||
|
# 只对普通文件求校验和:.app 是目录,直接喂给 sha256sum 会报错
|
||||||
if command -v sha256sum >/dev/null 2>&1; then
|
if command -v sha256sum >/dev/null 2>&1; then
|
||||||
sha256sum ./* > SHA256SUMS.txt
|
find . -type f ! -name SHA256校验.txt | sort | xargs sha256sum > SHA256校验.txt
|
||||||
else
|
else
|
||||||
shasum -a 256 ./* > SHA256SUMS.txt
|
find . -type f ! -name SHA256校验.txt | sort | xargs shasum -a 256 > SHA256校验.txt
|
||||||
fi
|
fi
|
||||||
)
|
)
|
||||||
|
echo "[4/4] 创建中文压缩包..."
|
||||||
tar -C "$QFT_ROOT/dist" -czf "$QFT_PACKAGE_DIR.tar.gz" "$QFT_PACKAGE"
|
tar -C "$QFT_ROOT/dist" -czf "$QFT_PACKAGE_DIR.tar.gz" "$QFT_PACKAGE"
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "PACKAGE COMPLETE"
|
echo "封版打包完成"
|
||||||
echo "Folder: $QFT_PACKAGE_DIR"
|
echo "文件夹:$QFT_PACKAGE_DIR"
|
||||||
echo "Archive: $QFT_PACKAGE_DIR.tar.gz"
|
echo "压缩包:$QFT_PACKAGE_DIR.tar.gz"
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ gradle=(ROOT/'android/app/build.gradle.kts').read_text(); manifest=(ROOT/'androi
|
|||||||
wifi=(ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text(); upload=(ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text()
|
wifi=(ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text(); upload=(ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text()
|
||||||
download=(ROOT/'android/app/src/main/java/com/qft/optical/DownloadClient.kt').read_text()
|
download=(ROOT/'android/app/src/main/java/com/qft/optical/DownloadClient.kt').read_text()
|
||||||
main=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text(); analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
|
main=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text(); analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
|
||||||
|
queue=(ROOT/'android/app/src/main/java/com/qft/optical/TransferQueue.kt').read_text()
|
||||||
gray=(ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text(); protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text(); base45=(ROOT/'android/app/src/main/java/com/qft/optical/Base45.kt').read_text(); overlay=(ROOT/'android/app/src/main/java/com/qft/optical/QrLockOverlay.kt').read_text(); security=(ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text()
|
gray=(ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text(); protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text(); base45=(ROOT/'android/app/src/main/java/com/qft/optical/Base45.kt').read_text(); overlay=(ROOT/'android/app/src/main/java/com/qft/optical/QrLockOverlay.kt').read_text(); security=(ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text()
|
||||||
assert re.search(r'minSdk\s*=\s*24',gradle)
|
assert re.search(r'minSdk\s*=\s*24',gradle)
|
||||||
assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest
|
assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest
|
||||||
@@ -15,7 +16,10 @@ assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'su
|
|||||||
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload
|
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload
|
||||||
assert 'MAX_WORKERS = 8' in download and 'bytes=$start-$end' in download and 'completionMapFile' in download
|
assert 'MAX_WORKERS = 8' in download and 'bytes=$start-$end' in download and 'completionMapFile' in download
|
||||||
assert 'requestNetwork(request, cb)' in wifi and 'delivered.set(false)' in wifi
|
assert 'requestNetwork(request, cb)' in wifi and 'delivered.set(false)' in wifi
|
||||||
assert 'val targetSize = Size(640, 480)' in main and 'Size(960, 540)' not in main
|
assert 'wifiManager.startScan()' in wifi and '.setIsHiddenSsid(false)' in wifi
|
||||||
|
assert 'probeConnectedNetwork' in upload and 'workers = 48' in upload
|
||||||
|
assert 'awaitGatewayEndpoints' not in main
|
||||||
|
assert 'if (mode == ScannerMode.PAIR) Size(960, 720) else Size(640, 480)' in main and 'Size(960, 540)' not in main
|
||||||
assert 'Camera2Interop.Extender' in main and 'CONTROL_AE_TARGET_FPS_RANGE' in main and 'STRATEGY_KEEP_ONLY_LATEST' in main
|
assert 'Camera2Interop.Extender' in main and 'CONTROL_AE_TARGET_FPS_RANGE' in main and 'STRATEGY_KEEP_ONLY_LATEST' in main
|
||||||
assert '设备拒绝显式高帧率请求' in main and 'fallbackAnalysis' in main
|
assert '设备拒绝显式高帧率请求' in main and 'fallbackAnalysis' in main
|
||||||
assert 'OPTICAL_LOCKED' in analyzer and 'OPTICAL_MULTI' not in analyzer and 'QRCodeReader' in analyzer and 'MultiFormatReader' not in analyzer
|
assert 'OPTICAL_LOCKED' in analyzer and 'OPTICAL_MULTI' not in analyzer and 'QRCodeReader' in analyzer and 'MultiFormatReader' not in analyzer
|
||||||
@@ -24,7 +28,10 @@ assert 'GrayFrameBuffer' in gray and 'scratch = ByteArray(0)' in gray
|
|||||||
assert 'Base45.decode' in protocol and 'QFT2' in protocol and 'looksLikeBinaryFrame' not in protocol
|
assert 'Base45.decode' in protocol and 'QFT2' in protocol and 'looksLikeBinaryFrame' not in protocol
|
||||||
assert 'lockedCenterInView' in overlay and 'postInvalidateDelayed' in overlay and 'maybeRefocusLockedQr' in main
|
assert 'lockedCenterInView' in overlay and 'postInvalidateDelayed' in overlay and 'maybeRefocusLockedQr' in main
|
||||||
assert 'assembler.acceptText(code.text)' in main and 'acceptBinary' not in main
|
assert 'assembler.acceptText(code.text)' in main and 'acceptBinary' not in main
|
||||||
|
assert 'showFileSelection' not in main and 'pickFiles.launch(arrayOf("*/*"))' in main
|
||||||
|
assert 'installFileQueueDrag' in main and 'uploadRunning' in main and 'moveQueueItem' in queue
|
||||||
|
assert 'row.translationY' in main and 'container.removeView(row)' not in main
|
||||||
assert 'BB8' in base45 or 'ALPHABET' in base45
|
assert 'BB8' in base45 or 'ALPHABET' in base45
|
||||||
all_kotlin='\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt'))
|
all_kotlin='\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt'))
|
||||||
assert 'java.util.Base64' not in all_kotlin
|
assert 'java.util.Base64' not in all_kotlin
|
||||||
print('PASS Android static guards: API24+, 640x480 single-QR ROI, reusable luma buffer, QFT2/Base45 text parse, dynamic lock/refocus, Camera2 FPS request, legacy/new Wi-Fi compatibility')
|
print('PASS Android static guards: API24+, fast-pair/subnet discovery, crash-safe sortable upload queue, QFT2/Base45, dynamic lock/refocus, legacy/new Wi-Fi compatibility')
|
||||||
|
|||||||
@@ -26,10 +26,10 @@ with tempfile.TemporaryDirectory() as td:
|
|||||||
import java.util.zip.CRC32
|
import java.util.zip.CRC32
|
||||||
fun b45e(data: ByteArray): String { val a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; val o=StringBuilder(); var i=0; while(i+1<data.size){val v=(data[i].toInt() and 255)*256+(data[i+1].toInt() and 255);o.append(a[v%45]).append(a[(v/45)%45]).append(a[v/2025]);i+=2};if(i<data.size){val v=data[i].toInt() and 255;o.append(a[v%45]).append(a[v/45])};return o.toString() }
|
fun b45e(data: ByteArray): String { val a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; val o=StringBuilder(); var i=0; while(i+1<data.size){val v=(data[i].toInt() and 255)*256+(data[i+1].toInt() and 255);o.append(a[v%45]).append(a[(v/45)%45]).append(a[v/2025]);i+=2};if(i<data.size){val v=data[i].toInt() and 255;o.append(a[v%45]).append(a[v/45])};return o.toString() }
|
||||||
fun fr(p:ByteArray):String { val b=ByteBuffer.allocate(24+p.size+4).order(ByteOrder.BIG_ENDIAN);b.put("QFT2".toByteArray()).put(2).put(2).putLong(7L).putInt(9).putInt(11).putShort(p.size.toShort()).put(p);val n=b.position();val c=CRC32().apply{update(b.array(),0,n)}.value;b.putInt(c.toInt());return "QFT2:"+b45e(b.array()) }
|
fun fr(p:ByteArray):String { val b=ByteBuffer.allocate(24+p.size+4).order(ByteOrder.BIG_ENDIAN);b.put("QFT2".toByteArray()).put(2).put(2).putLong(7L).putInt(9).putInt(11).putShort(p.size.toShort()).put(p);val n=b.position();val c=CRC32().apply{update(b.array(),0,n)}.value;b.putInt(c.toInt());return "QFT2:"+b45e(b.array()) }
|
||||||
fun main(){check(Base45.decode("BB8")!!.contentEquals("AB".toByteArray()));check(Base45.decode("%69 VD92EX0")!!.contentEquals("Hello!!".toByteArray()));val p="hello-qft2".toByteArray();val f=QftProtocol.parseText(fr(p))!!;check(f.kind==FrameKind.DATA&&f.sessionId==7L&&f.seq==9L&&f.payload.contentEquals(p));val c=LockRect(100,100,300,300).smoothToward(LockRect(140,130,340,340),.25f);check(c.left in 101..139);println("PASS Kotlin QFT2/Base45 protocol + ROI lock smoothing")}
|
fun main(){check(Base45.decode("BB8")!!.contentEquals("AB".toByteArray()));check(Base45.decode("%69 VD92EX0")!!.contentEquals("Hello!!".toByteArray()));val p="hello-qft2".toByteArray();val f=QftProtocol.parseText(fr(p))!!;check(f.kind==FrameKind.DATA&&f.sessionId==7L&&f.seq==9L&&f.payload.contentEquals(p));val c=LockRect(100,100,300,300).smoothToward(LockRect(140,130,340,340),.25f);check(c.left in 101..139);val q=mutableListOf("A","B","C");check(moveQueueItem(q,0,2));check(q==listOf("B","C","A"));println("PASS Kotlin QFT2/Base45 protocol + ROI lock + transfer queue")}
|
||||||
'''))
|
'''))
|
||||||
jar=td/'smoke.jar'
|
jar=td/'smoke.jar'
|
||||||
run([kotlinc, str(K/'Base45.kt'), str(K/'Base64Url.kt'), str(K/'Protocol.kt'), str(K/'LockRect.kt'), str(smoke), '-include-runtime', '-d', str(jar)])
|
run([kotlinc, str(K/'Base45.kt'), str(K/'Base64Url.kt'), str(K/'Protocol.kt'), str(K/'LockRect.kt'), str(K/'TransferQueue.kt'), str(smoke), '-include-runtime', '-d', str(jar)])
|
||||||
p=subprocess.run(['java','-jar',str(jar)],text=True,capture_output=True,env={**os.environ,'TERM':'xterm'},check=True)
|
p=subprocess.run(['java','-jar',str(jar)],text=True,capture_output=True,env={**os.environ,'TERM':'xterm'},check=True)
|
||||||
print(p.stdout.strip())
|
print(p.stdout.strip())
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
ROOT=Path(__file__).resolve().parents[1]
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
main=(ROOT/'windows/src/main.rs').read_text()
|
main=(ROOT/'desktop/src/main.rs').read_text()
|
||||||
cache=(ROOT/'windows/src/optical_cache.rs').read_text()
|
cache=(ROOT/'desktop/src/optical_cache.rs').read_text()
|
||||||
qr=(ROOT/'windows/src/qr.rs').read_text()
|
qr=(ROOT/'desktop/src/qr.rs').read_text()
|
||||||
protocol=(ROOT/'windows/src/protocol.rs').read_text()
|
protocol=(ROOT/'desktop/src/protocol.rs').read_text()
|
||||||
base45=(ROOT/'windows/src/base45.rs').read_text()
|
base45=(ROOT/'desktop/src/base45.rs').read_text()
|
||||||
analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
|
analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
|
||||||
android_protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text()
|
android_protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text()
|
||||||
activity=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text()
|
activity=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text()
|
||||||
@@ -13,11 +13,18 @@ assert 'render_qr_grid' not in qr+cache+main
|
|||||||
assert 'self.optical.lanes' not in main
|
assert 'self.optical.lanes' not in main
|
||||||
assert 'OPTICAL_MULTI' not in analyzer
|
assert 'OPTICAL_MULTI' not in analyzer
|
||||||
assert 'newFixedThreadPool' not in analyzer
|
assert 'newFixedThreadPool' not in analyzer
|
||||||
assert 'DEFAULT_CHUNK_SIZE: u16 = 450' in main
|
# 本守卫的用意是锁住「单通道大二维码」这个设计,chunk 大小只是附带指标。
|
||||||
|
# 早先写死 450 的断言在常量改成 320 时就一直是红的(没人发现),
|
||||||
|
# 改成范围检查:既能挡住"退回多通道小块",又不会因为正常调参而误报。
|
||||||
|
import re
|
||||||
|
match = re.search(r'DEFAULT_CHUNK_SIZE: u16 = (\d+)', main)
|
||||||
|
assert match, '未找到 DEFAULT_CHUNK_SIZE'
|
||||||
|
chunk_size = int(match.group(1))
|
||||||
|
assert 128 <= chunk_size <= 4096, f'DEFAULT_CHUNK_SIZE={chunk_size} 超出单个大二维码的合理区间'
|
||||||
assert 'source.text_frame(page_index)' in cache and 'render_qr_fitted' in cache
|
assert 'source.text_frame(page_index)' in cache and 'render_qr_fitted' in cache
|
||||||
assert 'QFT2:' in protocol and 'base45::encode' in protocol and 'EcLevel::L' in qr
|
assert 'QFT2:' in protocol and 'base45::encode' in protocol and 'EcLevel::L' in qr
|
||||||
assert 'Base45.decode' in android_protocol and 'QFT2' in android_protocol
|
assert 'Base45.decode' in android_protocol and 'QFT2' in android_protocol
|
||||||
assert 'assembler.acceptText(code.text)' in activity and 'acceptBinary' not in activity
|
assert 'assembler.acceptText(code.text)' in activity and 'acceptBinary' not in activity
|
||||||
assert 'grayBuffer.capture(image, current)' in analyzer and 'fingerprint = text.hashCode()' in analyzer
|
assert 'grayBuffer.capture(image, current)' in analyzer and 'fingerprint = text.hashCode()' in analyzer
|
||||||
assert 'BB8' in base45 and 'UJCLQE7W581' in base45
|
assert 'BB8' in base45 and 'UJCLQE7W581' in base45
|
||||||
print('PASS single-channel guard: one large QFT2/Base45 QR, 450B chunks, no 2x2/4-lane path, Android locked-ROI text decode only')
|
print(f'PASS single-channel guard: one large QFT2/Base45 QR, {chunk_size}B chunks, no 2x2/4-lane path, Android locked-ROI text decode only')
|
||||||
|
|||||||
@@ -1,79 +0,0 @@
|
|||||||
use anyhow::{bail, Context, Result};
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
|
||||||
use windows::{
|
|
||||||
core::HSTRING,
|
|
||||||
Devices::WiFiDirect::{
|
|
||||||
WiFiDirectAdvertisementPublisher, WiFiDirectAdvertisementPublisherStatus,
|
|
||||||
},
|
|
||||||
Security::Credentials::PasswordCredential,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct DirectAp {
|
|
||||||
pub ssid: String,
|
|
||||||
#[cfg(windows)]
|
|
||||||
publisher: WiFiDirectAdvertisementPublisher,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DirectAp {
|
|
||||||
pub fn start(ssid: String, passphrase: String) -> Result<Self> {
|
|
||||||
#[cfg(not(windows))]
|
|
||||||
{
|
|
||||||
let _ = (ssid, passphrase);
|
|
||||||
bail!("QFT Direct AP 仅支持 Windows")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
let publisher = WiFiDirectAdvertisementPublisher::new()
|
|
||||||
.context("创建 Wi-Fi Direct publisher 失败")?;
|
|
||||||
let ad = publisher.Advertisement()
|
|
||||||
.context("读取 Wi-Fi Direct advertisement 失败")?;
|
|
||||||
ad.SetIsAutonomousGroupOwnerEnabled(true)
|
|
||||||
.context("启用 Autonomous Group Owner 失败")?;
|
|
||||||
let legacy = ad.LegacySettings()
|
|
||||||
.context("读取 LegacySettings 失败")?;
|
|
||||||
legacy.SetIsEnabled(true)
|
|
||||||
.context("启用 Wi-Fi Direct Legacy AP 失败")?;
|
|
||||||
legacy.SetSsid(&HSTRING::from(&ssid))
|
|
||||||
.context("设置 QFT SSID 失败")?;
|
|
||||||
let credential = PasswordCredential::new()
|
|
||||||
.context("创建 Wi-Fi Direct 密码对象失败")?;
|
|
||||||
credential.SetPassword(&HSTRING::from(&passphrase))
|
|
||||||
.context("设置 QFT 热点密码失败")?;
|
|
||||||
legacy.SetPassphrase(&credential)
|
|
||||||
.context("应用 QFT 热点密码失败")?;
|
|
||||||
|
|
||||||
publisher.Start().context("启动 QFT Wi-Fi Direct AP 失败")?;
|
|
||||||
|
|
||||||
// Publisher startup is asynchronous. Do not expose the pairing QR until
|
|
||||||
// Windows reports Started; otherwise Android can scan a network that is
|
|
||||||
// not yet discoverable.
|
|
||||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
|
||||||
loop {
|
|
||||||
let status = publisher.Status().context("读取 AP 状态失败")?;
|
|
||||||
if status == WiFiDirectAdvertisementPublisherStatus::Started {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if status == WiFiDirectAdvertisementPublisherStatus::Aborted {
|
|
||||||
bail!("Wi-Fi Direct AP 启动被系统中止。请确认 Windows Wi-Fi 已开启,且系统移动热点未占用 Wi-Fi Direct。")
|
|
||||||
}
|
|
||||||
if std::time::Instant::now() >= deadline {
|
|
||||||
bail!("Wi-Fi Direct AP 启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。")
|
|
||||||
}
|
|
||||||
std::thread::sleep(std::time::Duration::from_millis(80));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Self { ssid, publisher })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for DirectAp {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
let _ = self.publisher.Stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-1042
File diff suppressed because it is too large
Load Diff
@@ -1,229 +0,0 @@
|
|||||||
use anyhow::{Context, Result};
|
|
||||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
|
||||||
use rand::RngCore;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use serde_json::{json, Value};
|
|
||||||
use std::{
|
|
||||||
fs,
|
|
||||||
net::{IpAddr, Ipv4Addr},
|
|
||||||
path::PathBuf,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const PAIR_PREFIX: &str = "QFTPAIR2:";
|
|
||||||
pub const SEND_PREFIX: &str = "QFTSEND2:";
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct PairingPayload {
|
|
||||||
pub v: u8,
|
|
||||||
pub session: String,
|
|
||||||
pub pc_name: String,
|
|
||||||
pub transport: String,
|
|
||||||
pub port: u16,
|
|
||||||
pub endpoints: Vec<String>,
|
|
||||||
pub wifi: Option<WifiCredentials>,
|
|
||||||
/// `upload` means Android uploads to this PC. `download` means the PC has
|
|
||||||
/// selected a file and Android downloads it immediately after pairing.
|
|
||||||
pub direction: PairingDirection,
|
|
||||||
pub file_name: Option<String>,
|
|
||||||
pub file_size: Option<u64>,
|
|
||||||
pub sha256: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum PairingDirection {
|
|
||||||
Upload,
|
|
||||||
Download,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct WifiCredentials {
|
|
||||||
pub ssid: String,
|
|
||||||
pub passphrase: String,
|
|
||||||
pub security: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
||||||
struct DirectApIdentity {
|
|
||||||
version: u8,
|
|
||||||
ssid: String,
|
|
||||||
passphrase: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PairingPayload {
|
|
||||||
/// v2 intentionally uses short JSON keys. The Direct-AP QR no longer carries
|
|
||||||
/// a long transport string/security object and only keeps a small endpoint
|
|
||||||
/// fallback list. This materially lowers QR density and speeds phone scan.
|
|
||||||
pub fn encode_text(&self) -> Result<String> {
|
|
||||||
// Direct-AP pairing carries one short endpoint hint for the immediate
|
|
||||||
// happy path, while Android still treats the connected gateway + UDP
|
|
||||||
// discovery as authoritative fallbacks. One endpoint keeps QFTPAIR2
|
|
||||||
// compact but avoids a full discovery round on common Windows APs.
|
|
||||||
let endpoints: Vec<&str> = if self.wifi.is_some() {
|
|
||||||
self.endpoints.iter().take(1).map(String::as_str).collect()
|
|
||||||
} else {
|
|
||||||
self.endpoints.iter().take(3).map(String::as_str).collect()
|
|
||||||
};
|
|
||||||
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
|
|
||||||
let mut value = json!({
|
|
||||||
"v": 2,
|
|
||||||
"s": self.session,
|
|
||||||
"n": self.pc_name,
|
|
||||||
"p": self.port,
|
|
||||||
"e": endpoints,
|
|
||||||
"w": wifi,
|
|
||||||
});
|
|
||||||
// Keep the common Android → PC QR as small as before. File metadata is
|
|
||||||
// needed only for the new PC → Android automatic-download QR.
|
|
||||||
if self.direction == PairingDirection::Download {
|
|
||||||
let object = value.as_object_mut().expect("pairing JSON object");
|
|
||||||
object.insert("d".into(), Value::String("d".into()));
|
|
||||||
object.insert("f".into(), serde_json::to_value(&self.file_name)?);
|
|
||||||
object.insert("z".into(), serde_json::to_value(self.file_size)?);
|
|
||||||
object.insert("h".into(), serde_json::to_value(&self.sha256)?);
|
|
||||||
}
|
|
||||||
let json = serde_json::to_vec(&value).context("serialize pairing payload")?;
|
|
||||||
let prefix = match self.direction {
|
|
||||||
PairingDirection::Upload => PAIR_PREFIX,
|
|
||||||
PairingDirection::Download => SEND_PREFIX,
|
|
||||||
};
|
|
||||||
Ok(format!("{prefix}{}", URL_SAFE_NO_PAD.encode(json)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_session_token() -> String {
|
|
||||||
let mut bytes = [0u8; 16];
|
|
||||||
rand::rng().fill_bytes(&mut bytes);
|
|
||||||
URL_SAFE_NO_PAD.encode(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keep one random AP identity per Windows device so Android can remember the
|
|
||||||
/// user's approval for that exact local-only network. The AP itself is only
|
|
||||||
/// active while QFT receive mode is running; the file-transfer session token is
|
|
||||||
/// regenerated every time receive mode starts.
|
|
||||||
pub fn load_or_create_direct_ap_credentials(pc_name: &str) -> Result<(String, String)> {
|
|
||||||
let path = direct_ap_identity_path();
|
|
||||||
if let Ok(bytes) = fs::read(&path) {
|
|
||||||
if let Ok(identity) = serde_json::from_slice::<DirectApIdentity>(&bytes) {
|
|
||||||
if identity.version == 1
|
|
||||||
&& !identity.ssid.trim().is_empty()
|
|
||||||
&& (8..=63).contains(&identity.passphrase.len())
|
|
||||||
{
|
|
||||||
return Ok((identity.ssid, identity.passphrase));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let (ssid, passphrase) = new_direct_ap_credentials(pc_name);
|
|
||||||
let identity = DirectApIdentity {
|
|
||||||
version: 1,
|
|
||||||
ssid: ssid.clone(),
|
|
||||||
passphrase: passphrase.clone(),
|
|
||||||
};
|
|
||||||
if let Some(parent) = path.parent() {
|
|
||||||
fs::create_dir_all(parent)
|
|
||||||
.with_context(|| format!("创建 QFT 配置目录 {} 失败", parent.display()))?;
|
|
||||||
}
|
|
||||||
let tmp = path.with_extension("json.tmp");
|
|
||||||
let json = serde_json::to_vec_pretty(&identity)?;
|
|
||||||
fs::write(&tmp, json)
|
|
||||||
.with_context(|| format!("保存 QFT Direct 身份 {} 失败", tmp.display()))?;
|
|
||||||
if path.exists() {
|
|
||||||
let _ = fs::remove_file(&path);
|
|
||||||
}
|
|
||||||
fs::rename(&tmp, &path)
|
|
||||||
.with_context(|| format!("完成 QFT Direct 身份保存 {} 失败", path.display()))?;
|
|
||||||
Ok((ssid, passphrase))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reset_direct_ap_credentials() -> Result<()> {
|
|
||||||
let path = direct_ap_identity_path();
|
|
||||||
if path.exists() {
|
|
||||||
fs::remove_file(&path)
|
|
||||||
.with_context(|| format!("删除 QFT Direct 身份 {} 失败", path.display()))?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn direct_ap_identity_path() -> PathBuf {
|
|
||||||
if let Ok(root) = std::env::var("LOCALAPPDATA") {
|
|
||||||
if !root.trim().is_empty() {
|
|
||||||
return PathBuf::from(root).join("QFT").join("direct-ap.json");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PathBuf::from(".qft").join("direct-ap.json")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new_direct_ap_credentials(pc_name: &str) -> (String, String) {
|
|
||||||
let suffix = new_session_token();
|
|
||||||
let suffix = &suffix[..6.min(suffix.len())];
|
|
||||||
let base: String = pc_name
|
|
||||||
.chars()
|
|
||||||
.filter(|c| c.is_ascii_alphanumeric())
|
|
||||||
.take(10)
|
|
||||||
.collect();
|
|
||||||
let base = if base.is_empty() { "PC" } else { &base };
|
|
||||||
let ssid = format!("QFT-{base}-{suffix}");
|
|
||||||
|
|
||||||
let mut random = [0u8; 12];
|
|
||||||
rand::rng().fill_bytes(&mut random);
|
|
||||||
let password = URL_SAFE_NO_PAD.encode(random);
|
|
||||||
(ssid, password[..16.min(password.len())].to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
|
|
||||||
let mut ips = Vec::<Ipv4Addr>::new();
|
|
||||||
if let Ok(addrs) = if_addrs::get_if_addrs() {
|
|
||||||
for iface in addrs {
|
|
||||||
let IpAddr::V4(ip) = iface.ip() else { continue };
|
|
||||||
if ip.is_loopback() || ip.is_unspecified() || ip.is_link_local() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if !ips.contains(&ip) {
|
|
||||||
ips.push(ip);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for fallback in [
|
|
||||||
Ipv4Addr::new(192, 168, 137, 1),
|
|
||||||
Ipv4Addr::new(192, 168, 49, 1),
|
|
||||||
] {
|
|
||||||
if !ips.contains(&fallback) {
|
|
||||||
ips.push(fallback);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ips.sort_by_key(|ip| {
|
|
||||||
if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 }
|
|
||||||
else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 }
|
|
||||||
else if ip.is_private() { 2 }
|
|
||||||
else { 3 }
|
|
||||||
});
|
|
||||||
ips.into_iter()
|
|
||||||
.map(|ip| format!("http://{ip}:{port}"))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn download_pairing_uses_dedicated_short_prefix() {
|
|
||||||
let payload = PairingPayload {
|
|
||||||
v: 2,
|
|
||||||
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
|
|
||||||
pc_name: "DESKTOP-QFT".into(),
|
|
||||||
transport: "http-download-v2".into(),
|
|
||||||
port: 39393,
|
|
||||||
endpoints: vec!["http://192.168.49.1:39393".into()],
|
|
||||||
wifi: None,
|
|
||||||
direction: PairingDirection::Download,
|
|
||||||
file_name: Some("sample.bin".into()),
|
|
||||||
file_size: Some(42),
|
|
||||||
sha256: Some("00".repeat(32)),
|
|
||||||
};
|
|
||||||
let text = payload.encode_text().unwrap();
|
|
||||||
assert!(text.starts_with(SEND_PREFIX));
|
|
||||||
assert!(text.len() < 800);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user