45 Commits

Author SHA1 Message Date
zhy200308 f248deac17 release: 封版 v0.4.16 中文正式版 2026-08-12 14:48:09 +08:00
zhy200308 1c5e015285 fix direct connection startup and drag stability 2026-08-12 14:28:49 +08:00
zhy200308 8b3f5c0216 optimize direct transfer UI and Android queue 2026-08-12 14:06:03 +08:00
zhy200308 d7a29e035f fix Wi-Fi Direct legacy connection acceptance 2026-08-12 12:41:59 +08:00
zhy 144b7d1a8e fix(android): enable BuildConfig generation 2026-08-12 12:27:24 +08:00
zhy200308 c1a4dbbd7a fix Windows Direct service reachability 2026-08-12 12:11:15 +08:00
zhy200308 65223dafe4 enforce dedicated Wi-Fi for direct QR pairing 2026-08-12 11:46:59 +08:00
zhy200308 eccd93266e fix direct pairing probe timeout and speed up QR scanning 2026-08-12 11:26:59 +08:00
zhy200308 f9e25819ee fix: improve QR direct connection reliability and speed 2026-08-12 11:14:34 +08:00
zhy200308 9c16cc1690 fix(desktop): 提权脚本用了 bash 的 \ 续行导致放行必然失败,且失败被误报为成功
用户的终端输出把我上一版的 bug 直接暴露了出来:手动放行命令里
`New-NetFirewallRule ... -Direction Inbound \` 后面接换行——`\` 是 bash 的
续行语法,PowerShell 用反引号,于是命令被拆成两条,两条都报错。

同一个 `\` 也写在了 grant() 生成的提权脚本里,所以「放行防火墙」按钮在
Windows 上是**必然失败**的。更糟的是它还误报成功:Start-Process -Wait
返回的是启动器的退出码,不是被提权进程的,脚本语法错误照样得到 0。
用户看到的「已提交放行规则,正在复检…」+ 复检仍显示缺少规则,就是这么来的。

三处修复:

1. 脚本一律一条命令一行,绝不使用任何续行。新增测试逐行断言不以 `\` 结尾。
2. 提权脚本跑完必须写一个成功标记文件,grant() 以标记存在与否判定成败,
   不再相信外层退出码。拿不到标记时给出明确提示而不是假装成功。
3. 「复制手动放行命令」现在只放命令,不再夹杂中文说明。用户是整段粘进
   PowerShell 的,混在里面的散文会被逐行当成 cmdlet 报错,把真正的错误
   淹没掉——用户的终端输出里满屏都是这个。加测试断言每一行都是命令或注释。

另外 APP_VERSION 是 main.rs 里的手写常量,上一版我只改了 Cargo.toml,
界面仍显示 v0.4.9,用户无法判断自己跑的是不是新构建。改为
env!("CARGO_PKG_VERSION"),从此只有一个版本号来源。

用户机器上的诊断结果排除了另外两种成因:三个配置文件的 AllowInboundRules
都是 NotConfigured(没有开启「阻止所有传入连接」),按程序路径也查不到任何
阻止规则。所以剩下的就是放行规则本身没建成——正是本次修复的这个 bug。

版本号 0.4.10 → 0.4.11。
2026-08-12 10:54:05 +08:00
zhy200308 2bb6ce63ae fix(desktop): 修复防火墙面板在「电脑→Android」页面是死代码,并重做 Windows 检测
上一版我说"两个页面都加了",但用户在 v0.4.9 上依然看不到。这次不猜了,
把程序真跑起来截图,看到面板确实没画出来,才找到原因:

pc_to_phone_ui 在 running 时于函数中段就 return 进了 resizable/focus 分支,
我加的那 37 行写在函数尾部,永远执行不到——代码在、grep 得到、但一个像素
都不会画。前两次自查只 grep 了"firewall_panel 在不在",没确认它在不在活的
分支上。面板已移到 pc_to_phone_running_controls(真正渲染的运行态控制区)。

为防同类缺陷复发,加了两个**真渲染**测试:在无窗口 egui 上下文里跑一帧,
把 galley 里的文字抓出来断言。grep 源码挡不住死代码,只有画一遍才行。
另外把 pc_receive_ui 里内联复制的第三份面板也收敛到 firewall_panel。

Windows 防火墙检测重做(这才是"点了放行还是连不上"的根因方向):

1. 改用 PowerShell 而非 netsh。netsh 输出的**值**会本地化(中文系统上是
   「允许/阻止/任何/是」),原先按 "Any"/"Yes" 匹配在中文 Windows 上必然
   误判;Get-NetFirewallRule 返回的枚举在任何语言下都是 Allow/Block/Any。

2. 按**程序路径**查询,不再只按规则显示名。用户在「安全警报」弹窗上点了
   取消时,Windows 会自建一条针对该 exe 的阻止规则,名字是程序名而不是
   QFT Desktop。只按显示名查完全看不见它,而 Block 在 Windows 里永远压过
   Allow——症状正是"点了放行、界面显示已放行、手机依然连不上"。
   grant() 现在会先清掉这类阻止规则再重建放行规则。

3. 检测「阻止所有传入连接,包括位于允许应用列表中的应用」
   (AllowInboundRules=False)。这项打开时加多少规则都没用,单独报为
   BlockedByPolicy,按钮相应置灰并说明要去哪里关——它属于用户的安全设置,
   程序不代劳。

4. manual_instructions 里的 -Profile Private,Domain 是个真 bug,与本模块
   自己的注释矛盾:照抄的用户会重建出一条在 Direct AP 虚拟网卡(被判为
   公用网络)上根本不适用的规则。改为 -Profile Any 并补上排查步骤。

5. grant() 成功后不再直接断言"已放行",改为触发复检——规则加上了不等于
   入站真的通了。

检测要起 PowerShell 进程(1~2 秒),移到后台线程,避免在"启动接收"的瞬间
卡住界面。解析逻辑抽成纯函数 classify_probe,配 10 个用例覆盖中文系统、
自动阻止规则、系统级封禁、防火墙整体关闭等场景——Windows 专有代码最容易
烂在没人跑的地方。已用 cargo check --target x86_64-pc-windows-gnu 验证
Windows 分支能编过。

版本号 0.4.9 → 0.4.10,便于确认拿到的是新构建。
2026-08-12 09:55:12 +08:00
zhy200308 4c294d4270 feat: Direct AP 直连提速 + 剔除虚拟网卡 + 版本号提到 0.4.9 便于确认构建
三项一起处理。

1. 所有 PC→手机的二维码页面都有防火墙放行
   「Android → 电脑」页在 dec132c 已加,「电脑 → Android」页在 7b18c6a
   补上,两处都是「防火墙面板 + 二维码广播的地址」并在启动时自动检测。
   本次把版本号从 0.4.8 提到 0.4.9:此前用户反馈"看不到防火墙功能",
   实为未拉取新提交,而界面上没有任何可据以判断构建新旧的标识。

2. Direct AP 下先直连网关,UDP 发现退为兜底
   Direct AP 场景里网关必然就是那台电脑——手机的 IP 正是它的 DHCP 发的。
   此前却把阻塞式 UDP 发现排在最前,白白等掉一两秒才开始真正能成功的
   那一步。现在配网一就绪立刻并发探测「网关 + 二维码携带的地址」
   (400ms 连接 / 600ms 读取),不通才回落到 UDP 广播与子网扫描。

3. Direct AP 下彻底剔除虚拟网卡地址
   二维码只放得下 4 个地址,而实测机器上有 192.168.30.1、192.168.31.1、
   172.21.96.1 三个 VMware/Hyper-V/WSL 地址。上一版只做降权,名额紧张时
   救不了场。Direct AP 启用时改为直接剔除——此刻手机连的是 AP 网段,
   这些地址永远到不了,占着名额纯属浪费。
   新增 is_virtual_endpoint(),对解析不了的字符串一律不判为虚拟,
   避免误删真实地址。

cargo test 51/51。Kotlin 侧本机无法编译,仅结构检查。
2026-08-12 09:22:24 +08:00
zhy200308 7b18c6a661 fix(desktop): 电脑→Android 页也加防火墙面板与地址列表
二维码端点的修复已经验证生效:手机端诊断显示码里第一个地址就是
192.168.137.1,49.1 紧随其后,虚拟网卡 192.168.30.1 被压到末尾,
顺序完全符合预期。

但连接仍然失败,且手机明确探测过 192.168.137.1:39393 无应答——
问题彻底收敛到「Windows 没有在 Wi-Fi Direct 虚拟网卡上接受连接」,
也就是防火墙规则没有覆盖该网卡的网络类型(通常被归类为公用网络)。

而我上一版只把防火墙面板加到了接收页,本页(电脑→Android)没有,
用户在这里遇到问题时界面上无处可点。补上:
- 面板 + 「二维码广播的地址」折叠项,与接收页一致
- 启动直传时自动重新检测(AP 网卡类型与主网卡往往不同,缓存会误导)

cargo test 49/49。
2026-08-12 09:08:20 +08:00
zhy200308 b2edb3048a fix(desktop): 非 Windows 平台禁用 Direct AP 选项,不再把做不到的事列为「推荐」
Direct AP 只有 Windows 有实现(direct_ap.rs 在其余平台直接 bail),
但两个页面的「连接方式」都把它写成「QFT Direct(推荐)」并默认选中。
macOS/Linux 用户点了之后才发现失败,白白浪费一次尝试。

platform::direct_ap_support() 早就写好了,只是一直没接线(还挂着
allow(dead_code))。现在:
- 两个页面的 Direct AP 单选项在不支持的平台上禁用,并在下方说明原因
- 默认值改为随平台决定,非 Windows 上直接落在「当前局域网」
- 移除 platform.rs 里相应的 allow(dead_code)

cargo test 49/49。
2026-08-12 09:03:09 +08:00
zhy200308 13624d9747 fix(pairing): Direct AP 网关地址被挤出二维码,修复我上一版引入的回退
上一版号称把 AP 网关置顶,实测二维码里依然没有 192.168.137.1,
而手机连上 AP 后网关正是它。两个独立原因叠在一起:

1. 判断条件读了还没赋值的字段
   start_receiver 里 direct_ap 是局部变量,要到函数末尾才写回
   self.receive.direct_ap;而生成二维码那行读的正是 self.receive.direct_ap,
   此刻永远是 None,于是 direct_ap_active 恒为 false,置顶逻辑从未触发。
   改为直接用局部变量。发送端同一处问题一并修正。

2. 虚拟网卡把名额占满了
   实测机器上有 192.168.30.1、192.168.31.1、172.21.96.1 三个
   VMware / Hyper-V / WSL 的地址。它们是真实网卡、排序里与普通局域网
   同级,正好填满二维码仅有的 4 个名额,把 AP 网关顶了出去。手机
   永远到不了这些地址,却要为它们付出探测时间。
   新增 is_likely_virtual():按各家虚拟化产品的默认网段 + 以 .1 结尾
   (宿主机在虚拟网络里通常是网关)判断,只降权不丢弃——万一某台机器
   真用这些网段做局域网,仍能兜底。

新增三项用例:实测遇到的三个虚拟地址必须被识别;192.168.0.1 /
192.168.1.1 / 192.168.8.1 / 10.0.0.1 这些家用网关不得误伤;
只有 .1 结尾才参与判断,普通主机地址一律不降权。

cargo test 49/49。
2026-08-12 08:59:07 +08:00
zhy200308 6abd932872 fix(desktop): 配对二维码按窗口自适应 + 接收页加专注模式;修复 Direct AP 地址被挤出二维码
两个问题,后者是我上一版引入的真实回退。

一、二维码显示不全
接收页与发送页的配对码此前只按 available_width() 计算边长,并硬性保底
260 点,完全不看可用高度。窗口一矮,码就溢出到可视区外——用户看到的是
被截掉下半截、根本扫不了的码。

- 新增 fit_qr_side():同时受宽高约束,宁可让码变小也不越界;
  并对退化输入(布局初帧可能给出 0 或负的可用空间)保证边长为正
- 接收页(QFTPAIR2)新增专注模式与占比滑条。扫码时用户会把手机凑近
  屏幕,界面上的按钮和状态此刻毫无用处,反而在小窗口里抢走空间。
  发送页原本就有专注模式,本次统一了两页的行为
- 退出接收/返回首页时重置专注状态

二、Direct AP 网关地址被挤出二维码
实测诊断显示二维码给出的是 192.168.8.68、192.168.30.1、192.168.31.1,
唯独没有 192.168.137.1——而手机连上 AP 后网关恰恰是它。

根因是上一版把「猜测性兜底地址」挪到列表末尾后,二维码只取前 3 个,
192.168.137.1 被截断了。它在生成二维码的瞬间往往还不是真实网卡地址
(ICS 虚拟网卡尚未分配 IP),因此不会出现在 get_if_addrs 结果里。
表现为「手机连上了临时 Wi-Fi、拿到了 IP 和网关,却找不到电脑」——
从现象几乎无法反推到这里。

- 新增 pairing::qr_endpoints(port, direct_ap_active):Direct AP 启用时
  把两个 ICS 网关地址置顶
- 二维码端点数从 3 提到 4,容纳 AP 地址与常规局域网地址
- Windows 界面新增「二维码广播的地址」折叠项,把码里的地址摊开显示,
  不必等手机端报错就能确认

cargo test 46/46,含二维码尺寸的三项回归(不越界、缩放夹取、退化输入)
与 Direct AP 地址置顶的三项。
2026-08-11 22:08:44 +08:00
zhy200308 f62fe8d23b fix(pairing): Direct AP 网关地址被挤出二维码,修复我上一版引入的回退
手机端诊断给出了决定性证据。二维码广播的三个地址是:
  192.168.8.68、192.168.30.1、192.168.31.1
而手机连上 Direct AP 后拿到的是 192.168.137.200/24、网关 192.168.137.1
——**码里根本没有它能到达的那个地址**。

回退是我造成的。上一版为了让真实网卡优先,把 192.168.137.1 / 192.168.49.1
这两个猜测性兜底地址挪到了列表末尾;而二维码只取前 3 个。二维码是在
点「启动接收」的瞬间生成的,此时 ICS 虚拟网卡往往还没拿到 IP,因此
不会出现在 get_if_addrs 里,只能靠那两个兜底地址补位——一挪到末尾就被
截断掉了。表现是"Wi-Fi 已连接但找不到电脑",从现象几乎无法反推到这里。

改动
- 新增 pairing::qr_endpoints(port, direct_ap_active):Direct AP 启用时
  把 ICS 网关地址强制放到最前,未启用时维持真实网卡优先
- 二维码端点上限 3 → 4,以便同时容纳 AP 网关与常规局域网地址
- Windows 接收页新增可展开的「二维码广播的地址」列表。手机报"找不到
  电脑"时,第一件要确认的就是码里有没有它能到达的地址——现在一眼可见,
  不必等手机端诊断

测试:新增三项,分别锁住「AP 网关必须排第一」「即使网卡很多也不能被
长度上限截断」「未开 AP 时不该让猜测地址占位」。cargo test 43/43。

注意:本次修复的是"地址没进二维码"。手机此前也直接探测过网关
192.168.137.1:39393 并且失败,说明 Windows 在 ICS 虚拟网卡上仍未接受
连接——那是防火墙配置文件的问题,需要在接收页点「放行防火墙」
(规则会以 profile=any 重建,覆盖该网卡的网络类型)。
2026-08-11 22:03:19 +08:00
zhy200308 ae2c36fa54 perf(android): 传输期间持 Wi-Fi 高性能锁;汇总带上链路协商速率
实测 1.01 GB 的分段数据推翻了此前的判断:

  接收  1分1秒 · 17.06 MB/s   ← 97% 的时间
  校验  1秒   · 1.05 GB/s
  保存  2秒   · 731 MB/s
  合计  1分3秒 · 16.44 MB/s

保存只花 2 秒,此前估计的 15 秒完全错误——那次 MediaStore 拷贝根本不值得
优化,也不构成 10 GB 的阻塞(按此速率 10 GB 约 14 秒)。全部瓶颈都在
网络传输本身。

改动

1. Wi-Fi 高性能锁
   Android 默认让 Wi-Fi 芯片在包间隙进入省电休眠,代价是额外唤醒延迟,
   对持续大流量传输会明显压低吞吐。这是 Android 上最常见也最容易被忽略的
   一项限速。传输期间持锁(API 29+ 用 WIFI_MODE_FULL_LOW_LATENCY,
   以下用 WIFI_MODE_FULL_HIGH_PERF),下载与上传两条路径都覆盖,
   并在 finally 与返回首页时释放——否则 Wi-Fi 会一直停在高功耗模式。
   Manifest 补 WAKE_LOCK 权限。

2. 汇总带上链路协商速率
   新增 WifiConnector.describeLink(),在完成汇总里附上
   「链路 x Mbps · 频段 · 信号 y dBm」。判断"传输慢"到底是软件问题还是
   链路本身的上限,这两个数字是唯一依据:协商 866 Mbps 却只跑到
   136 Mbps 说明有优化空间;协商本来就只有 150 Mbps 则已接近满速,
   再改代码也没有意义。下一步该往哪走,取决于这个数。

Kotlin 本机无法编译,仅做结构检查。
2026-08-11 21:52:52 +08:00
zhy200308 dec132cf3e fix(desktop): 手机接收页也显示防火墙检测,Direct AP 才是最需要它的地方
防火墙面板此前只在「电脑 ↔ 电脑」页有,而 Direct AP 恰恰是最容易被
拦住的路径:它会新建一块 ICS 虚拟网卡,Windows 通常把这块网卡归类为
「公用网络」,与主网卡的类型不同。只覆盖专用/域网络的规则在它上面
完全不生效——表现就是手机连上了临时 Wi-Fi、拿到了 IP 和网关、
二维码地址也正确,却怎么都找不到电脑。用户不可能自己想到这一层。

改动
- 把面板抽成 firewall_panel(ui, port) 供两处共用
- 放在手机接收页的二维码旁边:用户在这里停留最久,也正是在这一步失败
- 被拦时额外解释「Direct AP 是独立网卡、可能被归类为公用网络」这一因果
- 启动接收时自动重新检测,而不是沿用上次结果——AP 网卡的类型与主网卡
  往往不同,缓存的结论会误导

cargo test 40/40。
2026-08-11 21:42:12 +08:00
zhy200308 22c7d7f22d fix: 扫码后先在当前网络直连,不再无条件切 Direct AP
实测诊断给出了决定性信息:手机成功连上 Direct AP、拿到
192.168.137.200/24、网关 192.168.137.1,二维码也正确指向
192.168.137.1:39393,但那个地址上的 39393 不应答,整个 /24 扫了
253 个地址也没有。也就是说手机侧全对,是 Windows 没有在 ICS 虚拟
网卡上接受连接。

而这次切换本来就没有必要——两台设备当时已经在同一个 192.168.8.0/24
局域网里,且实测 192.168.8.68:39393 是通的。切到 Direct AP 反而引入了
ICS 虚拟网卡、该网卡独立的防火墙配置,以及实测一两分钟的配网等待。

改动

1. 二维码始终携带局域网地址(pairing.rs)
   此前开 Direct AP 时只放一个 AP 地址,手机因此**必须**切网才能连。
   现在无论是否开 AP 都带上常规局域网地址,多两个短地址对二维码密度
   的影响可以忽略。

2. 端点顺序修正(pairing.rs)
   此前无条件把 192.168.137.1 / 192.168.49.1 排在最前,即使本机根本
   没有这两块网卡——手机于是先去探测两个不存在的地址,真正可用的
   局域网地址被挤到后面。改为真实网卡优先、猜测性兜底地址殿后。

3. 先试当前网络(MainActivity)
   扫到带 Wi-Fi 凭据的码时,先用系统默认网络并发探测二维码里的地址
   (700ms 连接 / 900ms 读取)。通了就直接开始传输,完全跳过配网弹窗
   与虚拟网卡;不通才切 Direct AP。新增 UploadClient.probeEndpoints。

4. 配网请求复用加时间上限(WifiConnector)
   上一版为了避免「系统选网弹窗还开着就 unregister」而改成复用挂起的
   请求,但没有上限。系统偶尔会让请求既不回 onAvailable 也不回
   onUnavailable 地一直挂着,于是每次「重试连接」都只是再等一次那个
   死掉的请求——这正是本次「配网越来越慢、至少两分钟」的由来。
   超过 20 秒即推倒重来。

5. 网关探测过滤 0.0.0.0(WifiConnector)
   诊断截图里出现了 http://0.0.0.0:39393,来自默认路由的空网关,
   永远连不上却占着探测预算。回环与组播地址一并过滤。

Rust 侧 cargo test 40/40,含两项新用例:端点顺序、以及开 Direct AP 时
二维码仍携带局域网地址。Kotlin 侧本机无法编译,仅做结构检查。
2026-08-11 21:39:46 +08:00
zhy200308 b5d124abe5 fix(android): 网关探测过滤 0.0.0.0 等无效地址
实测诊断截图里出现了 http://0.0.0.0:39393 这个候选。它来自默认路由的
空网关(直连链路无下一跳),永远不可能连上,白白占用探测预算并把真正
的候选挤到后面。回环与组播地址同理,一并过滤。
2026-08-11 21:26:06 +08:00
zhy200308 0281382c39 feat(android): 分阶段速率记账 + 连接失败时输出网络诊断
两件都是为了让"到底哪里慢/哪里断"能被看见,而不是继续靠猜。

分阶段速率
下载分传输、校验、保存三段,三者速率含义完全不同,混在一起平均出来的
数字毫无意义——这也是"传输不到 10 MB/s"这个观察难以定位的原因:
1 GB 若传输 50 s、校验 5 s、保存 15 s,看起来就成了 14 MB/s。
现在逐段记账,完成后一并列出:

  接收完成:已保存到 Downloads/QFT/xxx
  接收  52.3s · 19.6 MB/s
  校验  6.1s · 168 MB/s
  保存  14.8s · 69 MB/s
  合计  73.2s · 14.0 MB/s

并行下载的进度回调来自多个 worker 线程(DownloadClient 里 pool.submit
的闭包),因此记账用 AtomicLong 与 synchronizedList,不能用普通 var。

连接失败的诊断
"未找到 QFT 接收服务"这句话无法区分:手机在别的网段?没拿到网关?
还是对端根本没开。现在报错里直接带上手机侧的实际网络状况——
本机地址/掩码、网关、SSID——以及二维码给出的地址、探测过的网关、
子网扫描范围,并列出三条对照检查项。
新增 WifiConnector.describeNetwork()。

注意:Kotlin 在本机无法编译,以上改动仅做过结构检查,需要实测编译。
2026-08-11 21:14:22 +08:00
zhy200308 ae41267221 perf(sender): 下载服务支持 HTTP keep-alive,消除每分块重建 TCP
Android 的并行下载在每个 Range 请求里都写了 Connection: keep-alive,
但服务端每个响应都写死 Connection: close —— 复用是单方面的,实际上
每个 16 MiB 分块都要新建一条 TCP。1 GB 是 64 次,10 GB 是 640 次。
这正是"短连接不稳定、很快断开"的直接来源。

改动
- handle_client 拆出 serve_one,在同一条连接上循环处理请求
- 按 HTTP/1.1 语义决定是否复用:客户端显式 Connection: close 或
  使用 HTTP/1.0 时才断开,否则响应回 Connection: keep-alive
- 读到 0 字节视为对端正常关闭,这是 keep-alive 下的常态而非错误,
  不再当作 "连接在请求头前关闭" 报错

测试
新增 serves_multiple_ranges_on_one_connection:在同一条 TCP 上连发三段
互不重叠的 Range,逐段校验状态行、Content-Length、Connection 头与内容
字节,最后再用一个显式 Connection: close 的请求确认服务端会正常收尾。
两个既有用例同步补上 Connection: close —— 它们只发一个请求就读到 EOF,
在 keep-alive 下会一直等下一个请求直到读超时。

cargo test 38/38。
2026-08-11 21:02:01 +08:00
zhy 90800b9a21 Merge branch 'main' of https://git.xskjhy.top/kmcc/QFT 2026-08-11 20:52:54 +08:00
zhy 32b58d121a 优化UI,电脑传手机二维码配网可拖动区域大小 2026-08-11 20:44:43 +08:00
zhy200308 99be46acf7 release: v0.4.8 跨端 PC 互传封版;修复发送端进度直到结束才更新
实测 1.01 GB / 23.11 MB/s 传输成功,但发送端进度条全程 0%、
最后才跳到 100%,接收端却是实时的。两处原因,都已修复。

1. 请求体一次性写出
   16 MiB 的分块用单次 write_all 送出,中途没有任何可上报的点。
   改为 256 KiB 一片:足够小让进度看起来连续,又足够大不拖慢吞吐。
   put_chunk 逐片累加共享计数;失败重试时把本次尝试已计的字节扣回去,
   否则重试会让进度虚高甚至越过 100%。

2. on_progress 只在所有 worker 结束后调用一次
   主线程改为在 worker 运行期间轮询上报(40 ms 一次,对 UI 足够,
   代价可忽略),而不是等 thread::scope 返回。

测试拆成两层
- 确定性单测 body_progress_is_reported_incrementally:5 片请求体必须
  上报 5 次、总量吻合。回环速度太快时集成测试采样不到中间进度,
  只有这一层能稳定拦住回归
- 集成测试改为断言稳健性质:进度单调不减、且不超过文件总长
  (后者正是重试重复计数会破坏的)
- 配套的 mock 服务端按 Content-Length 精确读取。此前用 read_to_end
  会一直等客户端关闭写端,而客户端在等响应,两边互等直接死锁

封版
- 版本 0.5.0-m1 → 0.4.8,接续既有编号
- 界面与 README 里残留的「6 位配对码」文案更新为连接码

本版可用范围:mac / win / linux 桌面端互传,连接码内含地址,
不要求同一网段,只要 IP 层可路由到达即可。
2026-08-11 19:37:21 +08:00
zhy200308 375ae8a956 fix(desktop): 选择文件不再让程序崩溃;新增拖拽;macOS 产出 .app
macOS 上点「选择文件」直接退出:

  panicked at objc2-app-kit-0.3.2/.../NSOpenPanel.rs:127:
  unexpected NULL returned from +[NSOpenPanel openPanel]

rfd 在 openPanel 返回 NULL 时直接 panic,整个进程随之结束——用户只是
想选个文件,窗口就没了。三层处理,从"不该崩"到"不该发生":

1. 不该崩:pick_files/pick_folder/pick_file 全部包进 catch_unwind。
   文件对话框失败是可以恢复的情况,不该终止程序;失败时在状态栏说明
   并提示改用拖拽。

2. 提供不依赖对话框的路径:支持把文件直接拖进窗口。拖拽不经过
   NSOpenPanel,对话框失效时照样能用,而且本来就是桌面端更顺手的交互。
   悬停时给出"松手即可加入待发送列表"的提示。

3. 消除诱因:package.sh 在 macOS 上额外产出 QFT.app。AppKit 的若干行为
   依赖应用被正确注册为 GUI 程序,直接跑裸二进制正是这个 NULL 的高发场景。
   Info.plist 含 NSHighResolutionCapable,Retina 下不会被拉伸。

顺带修复 package.sh 的校验和步骤:此前 `sha256sum ./*` 会把 .app 目录
一起喂进去并报错,改为 find -type f 只处理普通文件。

验证:cargo test 35/35;package.sh 完整跑通并实际 open 了生成的 .app,
确认能启动存活;plutil 校验 Info.plist 通过。
2026-08-11 18:56:17 +08:00
zhy200308 bcadcf0b53 fix(firewall): 规则必须用 profile=any,否则在公用网络下完全不生效
实测发现的真 bug。用户机器上的规则列表:

  qft-windows  Allow Inbound Public           (旧版,能用)
  QFT Desktop  Allow Inbound Domain, Private  (新加,不生效)

Windows 对没见过的 Wi-Fi 默认归类为「公用网络」。规则只覆盖
Private,Domain 时,Get-NetFirewallRule 照样显示 Enabled: True,
但对当前网络根本不适用,连接依旧被拦——这种「配置看起来是对的却没有
效果」的失败最难排查。旧版之所以一直能用,是因为当初点系统安全警报的
「允许」时,Windows 按当时的 Public 配置自动建了规则。

改动
- grant() 生成的 netsh 规则改为 profile=any
- status() 不再只看「有没有同名规则」,还要求它是 any profile,
  否则同样报 Missing。避免出现「检测说已放行、实际仍被拦」
- README 补充排查步骤:先看 NetworkCategory 与规则的 Profile 两列,
  以及 Block 规则优先于 Allow 这个常见坑

关于收窄 profile 的取舍:限定到 private 并不能带来实际安全收益。
QFT 的入站真正靠的是连接码里的秘密加失败计数,没有秘密的连接一律被拒;
而按 profile 收窄只会在最常见的家用/公共 Wi-Fi 场景下静默失效。

验证:cargo test 35/35。Windows 分支仍无法在本机执行,
netsh 与 UAC 那条路径需要在 Windows 上实测。
2026-08-11 18:48:41 +08:00
zhy200308 0f0dbaef47 fix(desktop): 防火墙提权改为手动触发;构建前检测占用;清理警告
三个问题一起处理。

1. 提权改为手动
上一版会在点「启动接收」时自动弹 UAC。实际用下来太侵入——多数人
只是想收个文件,却先被要求管理员授权。现在:
- 检测保持自动,但**只读**,无任何副作用
- 提权只在用户点「放行防火墙(需要管理员授权)」时发生
- 按钮无条件保留,不再只在"检测到被拦"时出现:检测可能不准,
  而用户遇到「对方连不上」时需要有地方可点
- 同时移除了拒绝标记的持久化——提权已不自动发生,无需记忆

2. Windows 构建报 os error 5
  error: failed to remove file `...\target\release\qft-desktop.exe`
  Caused by: 拒绝访问。 (os error 5)
原因是 QFT 窗口还开着,运行中的 exe 锁住了产物文件,而 cargo 的报错
完全看不出这一层。VERIFY_WINDOWS_HOST.ps1 现在会在构建前检测
qft-desktop 进程,列出 PID 并询问是否结束;README 也补了说明
(含 Defender 扫描导致的偶发同类报错)。

3. 构建警告 15 → 5
长期堆积的警告会训练人忽略所有警告,所以逐条处理:
- 真实问题:if 条件多余的括号,已修
- 为后续里程碑准备但尚未接线的 API(client::ping、download_file、
  platform::direct_ap_support/ensure_dir),加 #[allow(dead_code)]
  并注明将在哪个阶段使用
- 仅特定平台构造的项(firewall::RULE_NAME 只用于 Windows,
  FirewallStatus::Unsupported 只在 Linux 返回),改用
  #[cfg_attr(not(...), allow(dead_code))],避免无条件放行
剩余 5 个均为本次改动之前既有(cache_mib、v/transport、security、
path),不属本次范围,未改动。

验证:cargo test 35/35,release 构建 5 个警告且全部是既有的。
2026-08-11 18:28:43 +08:00
zhy200308 bdb822233f feat(desktop): 启动接收时自动检测并申请防火墙放行
上一次实测卡在「连接码解析正确但连不上」,根因是对端 Windows 防火墙
拦截入站,而用户几乎不可能自己联想到这一层。新增 firewall.rs,
在点「启动接收」时自动检测,缺规则就申请一次放行。

三条设计约束
1. 只在确实缺规则时申请。每次启动都弹 UAC 属于骚扰。
2. 被拒绝就记住。写标记文件到配置目录,之后只在界面留一个手动按钮,
   不再自动弹窗;用户点「放行防火墙」会清除标记重新申请。
3. 规则尽量窄。只放行本程序、只放行专用/域网络,不碰公用网络,
   更不整体关闭防火墙。

提权全部交给操作系统的标准机制(Windows UAC、macOS 授权对话框),
程序不接触也不存储任何凭据。

各平台
- Windows:netsh 查规则;添加时把命令写进临时批处理再用
  Start-Process -Verb RunAs 提权执行。不把参数塞进 PowerShell 的
  -ArgumentList —— 程序路径含空格时会被二次分词,引号层层嵌套极易出错,
  批处理里的引号由我们自己写死,不再被重新解析
- macOS:先查 socketfilterfw 全局状态,防火墙没开就直接判定无需处理;
  否则查本程序是否被拦,需要时用 osascript 的管理员授权添加。
  路径含引号或反斜杠时拒绝拼接命令,改为提示手动操作
- Linux:只检测与给出 ufw / firewalld 的命令,不自动改规则。
  各发行版防火墙前端差异过大,自动修改风险高于收益

界面
接收页在检测到可能被拦时显示橙色提示,附「放行防火墙」与
「复制手动放行命令」两个按钮。已放行或防火墙未开启时不显示任何东西。

验证:cargo test 35/35。防火墙相关 3 项均为只读,不改动任何系统设置:
状态查询不 panic 且分类正确、手动说明包含可操作信息、拒绝标记可持久化
往返。本机实测返回 Allowed(防火墙未开启),符合预期。

未验证:Windows 与 Linux 分支在这台 Mac 上无法执行,
netsh/UAC 那条路径需要在 Windows 上实测。
2026-08-11 18:07:53 +08:00
zhy200308 3e4d5861aa fix(desktop): 连接失败给出可执行的排查方向,并分离配对与传输状态
实测中出现「连接码解析正确但连不上」。诊断结果不是代码问题:两台机器
同在 192.168.8.0/24,ARP 能解析对方 MAC(二层通),但 ICMP 100% 丢包、
TCP 39393 连接超时——典型的对端主机丢包,即 Windows 防火墙拦截入站。

顺带暴露的连带影响:二进制从 qft-windows.exe 改名为 qft-desktop.exe 后,
此前给旧名字放行的防火墙规则对新程序不生效,用户不会想到这一层。
README 已补充放行步骤与排查顺序。

代码侧的三个真实缺陷

1. 连接失败只说「失败」,等于什么都没说。现按 io::ErrorKind 分类:
   - TimedOut  → 包发出去没回应:防火墙 / AP 客户端隔离 / 对方已关闭
   - ConnectionRefused → 主机在线但端口没人监听:对方没点「启动接收」
   - Host/NetworkUnreachable → 本机没有到该地址的路由
   三者成因完全不同,给的建议也必须不同。

2. 配对超时从 10 秒缩到 4 秒。配对只是一次极小的请求,拖到 10 秒
   只会让用户以为程序卡死。

3. 配对阶段就显示「正在发送 0%」。此前用 busy 兼作「正在传输」,
   导致刚点连接就出现发送进度条。新增独立的 transferring 标志,
   进度块只在真正推送文件时出现;配对期间改为显示 spinner 与
   「正在建立连接…最多等 4 秒」。

验证:cargo test 32/32。新增两项针对错误分类的用例——
用 RFC 5737 文档网段 192.0.2.1 触发超时路径,用刚释放的本地端口
触发拒绝路径,分别断言提示里包含对应的排查方向。
2026-08-11 17:39:53 +08:00
zhy200308 84643bff5e feat(desktop): PC↔PC 改用连接码,一串搞定,不再单独输 IP
此前发送方要分别念/输三样东西:IP、端口、6 位配对码。现在合成一串
可口述的连接码,**地址就编在码里**,所以拿到码即可直连——不需要广播、
不需要在同一网段,只要 IP 层路由可达即可(同一路由器下的不同 VLAN /
网段正属于这种情况)。

新增 connect_code.rs
- 编码:version(3) | kind(3) | 默认端口位 | 地址 | [端口] | 24bit 秘密 | CRC-8
- 按网段压缩地址:192.168.a.b 只需 2 字节,10./172.16-31. 三字节,
  其余四字节,IPv6 十六字节
- Crockford Base32(去掉易混的 I/L/O/U),分组显示
- 典型 192.168.a.b:39393 → **12 个字符**,如 4849-3WT1-3ZS0
- 输入容错:大小写、分隔符、空格随意;I/L 归一为 1、O 归一为 0

接收侧
- 6 位配对码 → 3 字节秘密;UI 为**每个网卡各生成一个连接码**,
  对方在哪个网段就用哪一串(虚拟网卡排后面)
- 新增 pairing::local_ipv4_addresses(),按「最可能被对方看到」排序

发送侧
- 三个输入框(设备列表 / 手动 IP / 配对码)合并为**一个连接码输入框**
- 边打边校验:CRC 在连接之前就能发现输错,并实时显示「将连接 http://x.x.x.x:port」
- 广播搜索降级为可选的折叠项——同网段免输码是锦上添花,不再是主路径

一个被测试抓出来的真问题
最初单字符输错的拦截率只有 96%。原因是 12 个 Base32 字符携带 60 bit
而实际只用 56 bit,末尾 4 个填充位被解码器直接丢弃,改动最后一个字符
有 1/16 概率解出完全相同的字节,CRC 根本没机会发现。加上填充位必须为 0
的校验后拦截率 >99%。

必须说清的边界
连接码解决的是「找不到对方」和「输入太繁琐」,不能凭空制造可达性。
若两台机器在 IP 层互不可达(Wi-Fi 客户端隔离、各自在不同物理网络),
任何客户端侧协议都无法建立连接,只能换链路或引入第三方中转——
后者与 QFT「不经过外网」的定位冲突,本版不做。

验证:cargo test 30/30,含连接码往返(全部地址类型)、容错输入、
单字符输错拦截率统计、以及走完整连接码链路的端到端传输
(编码 → 解码 → 换令牌 → 9MB 并发上传 → SHA-256 比对)。
2026-08-11 17:29:00 +08:00
zhy200308 d2669fb2e4 fix(desktop): 修复 macOS/Linux 上的中文豆腐块与 HiDPI 缩放
macOS 首次构建暴露的两个独立问题。

中文全是豆腐块
- is_ttf_file 只按 `.ttf` 扩展名筛选,而 macOS 的中文字体清一色是
  .ttc 字体集合(PingFang/Hiragino/STHeiti),Linux 的 NotoSansCJK
  与新版 Windows 的 msyh 也是 .ttc —— 全部被拒。改为按文件魔数识别
  (ttcf / OTTO / 0x00010000 / true),同时支持 ttf、otf、ttc
- 候选路径此前只有三条 Windows 的,非 Windows 平台根本没有兜底。
  新增 platform::system_font_candidates(),三平台各自列出系统中文字体
- 报错信息里的 windows/assets 路径跟进为 desktop/assets

HiDPI 下整个界面缩成一半
- set_pixels_per_point(1.0) 写死了缩放。Retina 屏 ppp=2.0,
  强制 1.0 会让所有控件和文字按一半尺寸渲染,界面挤在窗口左上角。
  改为交给 eframe 从系统取
- 原先写死 1.0 应是为了让二维码纹理与物理像素 1:1。改用
  snap_to_physical() 在绘制时把尺寸吸附到物理像素整数上达到同样目的:
  NEAREST 采样下若落在半个物理像素,相邻模块占的像素数会一宽一窄,
  边缘产生锯齿,反而更难被手机解码

顺带
- 设备名去掉 mDNS 的 .local/.lan 后缀。这个名字会出现在对方的设备
  列表里,zdeMacBook-Air.local 既长又没有信息量

验证(macOS,Retina 2880x1864)
- cargo test 21/21,其中新增 4 项:
  * 系统字体候选中存在的文件必须被 is_font_file 接受
  * 本平台至少能找到一个中文字体
  * **把找到的字体真正装进 egui 并渲染 '中'**,断言字形宽度非零且
    宽于 'A' —— 只检查文件存在是不够的,.ttc 解析失败时宽度会是 0
  * snap_to_physical 在 ppp=1/1.5/2/3 下都落在整数物理像素上
- release 构建后实际启动截图确认:中文正常显示(Hiragino Sans GB),
  界面按 Retina 正确缩放
2026-08-11 16:51:50 +08:00
zhy200308 92237ff76f fix(package): package.sh 跟进 desktop/ 改名,并在 keg-only 安装下自动找到 cargo
上一个提交把 windows/ 改成 desktop/ 时漏掉了 package.sh —— 当时的
grep 只覆盖 .md/.py/.ps1/.toml/.yml,没有扫 .sh,导致打包脚本仍然
cd windows 并寻找 qft-windows 二进制。

- 路径与二进制名跟进 desktop/ 与 qft-desktop
- cargo 检测增加兜底:brew 的 rustup 是 keg-only,
  /opt/homebrew/opt/rustup/bin 不会自动进 PATH,此前会出现
  "明明装了工具链却报 cargo 未找到"。现在先在常见位置探一次,
  仍找不到时给出可直接执行的修复命令而不是一句干巴巴的报错
- .gitignore 忽略 /dist 打包产物(release 二进制 14 MB,不应入库)

已在 macOS 上完整跑通 ./package.sh:cargo test 17/17 通过、
release 构建成功、产出 QFT-Rust-0.5.0-m1-<时间戳>-darwin 目录与
tar.gz,内含 14 MB 的 Mach-O arm64 可执行文件与 SHA256SUMS.txt。
2026-08-11 16:43:55 +08:00
zhy200308 376ffba96e feat(desktop): 跨平台桌面端 + 电脑↔电脑互传(v0.5.0-m1)
对应 V05_EXECUTION_PLAN 的 P1。核心改动是把「PC 只能当服务端」
这个写死的角色拆开——此前 TcpStream::connect 只出现在测试里,
桌面端根本无法主动连接另一台桌面端,PC↔PC 因此完全不可用。

跨平台
- windows/ → desktop/,crate 更名 qft-desktop
- 新增 platform.rs 收敛全部平台差异:配置目录(LOCALAPPDATA /
  Application Support / XDG)、下载目录(含 Linux 本地化的 ~/下载)、
  设备名、Direct AP 能力。约定:其余模块不得再出现 #[cfg(target_os)]
- direct_ap.rs 的 Context 导入按平台条件化,非 Windows 上不再告警
- macOS 上已实测编译并链接出可执行文件(65 MB Mach-O arm64),
  这是本仓库首次在非 Windows 平台构建成功

电脑 ↔ 电脑
- 新增 client.rs:桌面端发起侧。手写 HTTP,不引入客户端依赖——
  服务端本来就是手写的,两边同一套解析更容易与 Android/iOS 对齐。
  含并发分块上传(自适应 4/8/16 MiB、最多 8 worker)与 Range 断点续传
- 新增 discovery.rs:UDP 广播 QFTBROWSE3 浏览局域网节点。
  既有的 QFTDISC2 是「已知令牌找机器」,用于扫码之后;
  PC 没有摄像头,必须先能列出附近有谁
- receiver.rs 新增 POST /qft/pair:用 6 位配对码换会话令牌。
  这是唯一不校验令牌的端点。6 位仅约 20 bit 熵,配严格失败计数兜底——
  错 5 次即作废,需重启接收;比较用定长实现,不做短路返回
- 新增「电脑 ↔ 电脑」界面:接收方显示配对码与本机地址;
  发送方搜索/手动输入地址 → 输码连接 → 多选文件 → 带进度发送

验证(macOS,Rust 1.97.1)
- cargo check 0 错误,cargo test 17/17 通过
- 新增端到端用例:真实起接收服务 → 配对(含错误码必须被拒)→
  9 MB 跨多分块并发上传 → 校验落盘内容逐字节一致且 SHA-256 与
  接收端返回值相同。这就是 PC↔PC 的完整链路
- 11 项 Python 自检全部通过

顺带修复
- single_channel_guard_selftest 长期为红:它断言
  DEFAULT_CHUNK_SIZE = 450,而代码早已改为 320。改名前即存在,
  已用 git stash 验证与本次无关。改为范围检查(128~4096)并在
  PASS 信息里打印实际值,既挡住"退回多通道小块"又不会因调参误报

已知限制
- UDP 广播只覆盖同一广播域。跨网段或 AP 隔离的 Wi-Fi 上搜索不到,
  需手动输入对方 IP(界面已说明)。mDNS 留待后续
- 本阶段仍走 v2 明文 HTTP,加密随 QFT-Stream v3 一起做(见 P2)
2026-08-11 16:36:33 +08:00
zhy a960ad91d8 合并 0.4.7 双向并发传输封版
# Conflicts:
#	README.md
#	android/app/src/main/java/com/qft/optical/DownloadClient.kt
#	android/app/src/main/java/com/qft/optical/UploadClient.kt
#	docs/PROTOCOL.md
#	windows/src/sender.rs
2026-08-11 14:27:30 +08:00
zhy 20ac4dc6c7 发布 0.4.7 双向并发传输封版 2026-08-11 13:49:27 +08:00
zhy200308 cb92397300 修正为仅打包Rust桌面端 2026-08-11 11:48:09 +08:00
zhy200308 dffee5365d Merge remote-tracking branch 'origin/main' 2026-08-11 11:31:44 +08:00
zhy200308 a4edf734b6 优化大文件稳定并发传输与打包流程 2026-08-11 11:27:40 +08:00
zhy e326611c82 发布 0.4.6 封版 2026-08-11 10:53:59 +08:00
kmcc f260ff4266 Merge pull request 'New test' (#1) from new-test into main
Reviewed-on: #1
2026-08-11 10:44:48 +08:00
zhy 34b8fdf050 合并直传接收与文件选择优化 2026-08-11 10:21:45 +08:00
zhy e9e51a4941 修复直传接收并优化文件选择提示 2026-08-11 10:21:37 +08:00
zhy200308 b444a39a63 修复传输问题 2026-08-11 09:44:26 +08:00
63 changed files with 9272 additions and 1993 deletions
+4
View File
@@ -1,6 +1,8 @@
# Rust # Rust
/target /target
**/target **/target
windows/target-*/
**/__pycache__/
# Android # Android
.gradle/ .gradle/
**/build/ **/build/
@@ -17,3 +19,5 @@ ios/**/xcuserdata/
ios/**/*.xcworkspace/xcuserdata/ ios/**/*.xcworkspace/xcuserdata/
ios/build/ ios/build/
DerivedData/ DerivedData/
# package.sh 打包产物
/dist
+16 -2
View File
@@ -1,4 +1,4 @@
# QFT v0.4.0-rc2 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)
+138 -11
View File
@@ -1,13 +1,125 @@
# QFT · 超速二维码文件传输 v0.4.0-rc2 # 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/网关/子网探测定位电脑,并按二维码指定方向自动进入选文件上传或接收下载;文件数据不经过外网。
> rc2 已完成协议、图像合成解码、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 的稳定性优化继续保留:
@@ -103,8 +215,11 @@ v0.3 的稳定性优化继续保留:
- 扫码连接后 UDP `QFTDISC2` 快速发现; - 扫码连接后 UDP `QFTDISC2` 快速发现;
- gateway / endpoint / 当前子网 fallback; - gateway / endpoint / 当前子网 fallback;
- HTTP 请求明确绑定扫码建立的 `Network`; - HTTP 请求明确绑定扫码建立的 `Network`;
- 单文件最高 8 worker 并行; - 配网请求在传输页持续持有,仅返回首页时释放;短暂网络波动会自动接入新的 `Network`;
- 4/8/16 MiB 自适应上传块; - 手机上传和电脑下发均以 8 路为目标并发数;
- 64 KiB–16 MiB 自适应分块;
- 电脑下发使用精确 Range 响应,手机以 `.qftpart` + 位图断点续传;
- 手机上传使用定位写入和幂等完成确认;
- Windows positioned writes + `.qftpart` + SHA-256 + 最终 rename。 - Windows positioned writes + `.qftpart` + SHA-256 + 最终 rename。
## Android 版本 ## Android 版本
@@ -119,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
@@ -139,9 +254,21 @@ APK:
`android/app/build/outputs/apk/debug/app-debug.apk` `android/app/build/outputs/apk/debug/app-debug.apk`
## 一键打包
脚本执行锁定依赖的 Rust 测试和正式构建,随后把桌面程序、中文说明、协议及 SHA-256 校验收集到带时间戳的 `dist/QFT-正式版-*` 目录。脚本不会安装、下载或调用 Android SDK、Java、Gradle;如果已经在 Windows 上构建好 APK,则会自动将它收集进同一个中文正式包:
```bat
package.bat
```
```bash
./package.sh
```
## 字体 ## 字体
Windows UI 优先读取 `windows/assets/qft-ui.ttf`,也可用 `QFT_FONT_PATH` 指向你自己的中文 TTF。仓库不附带第三方字体文件。 桌面端 UI 优先读取 `desktop/assets/qft-ui.ttf`,也可用 `QFT_FONT_PATH` 指向你自己的中文 TTF。仓库不附带第三方字体文件。
## 自动验证 ## 自动验证
+35
View File
@@ -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
View File
@@ -1,12 +1,12 @@
# QFT v0.4.0-rc2 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 rc2 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 rc2 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 rc2 ## 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. rc2 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 rc2. 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
View File
@@ -1,5 +1,11 @@
QFT v0.4.0-rc2 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
View File
@@ -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.0-rc2 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."
+7 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.qft.optical" applicationId = "com.qft.optical"
minSdk = 24 minSdk = 24
targetSdk = 35 targetSdk = 35
versionCode = 16 versionCode = 23
versionName = "0.4.0-rc8" versionName = "0.4.16"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
@@ -36,10 +36,15 @@ android {
kotlinOptions { kotlinOptions {
jvmTarget = "17" jvmTarget = "17"
} }
buildFeatures {
buildConfig = true
}
} }
dependencies { dependencies {
implementation("androidx.activity:activity-ktx:1.10.1") implementation("androidx.activity:activity-ktx:1.10.1")
implementation("androidx.core:core-ktx:1.15.0")
implementation("androidx.camera:camera-core:1.4.2") implementation("androidx.camera:camera-core:1.4.2")
implementation("androidx.camera:camera-camera2:1.4.2") implementation("androidx.camera:camera-camera2:1.4.2")
implementation("androidx.camera:camera-lifecycle:1.4.2") implementation("androidx.camera:camera-lifecycle:1.4.2")
+11
View File
@@ -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" />
@@ -19,6 +21,15 @@
android:label="QFT" android:label="QFT"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/QftTheme"> android:theme="@style/QftTheme">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/qft_file_paths" />
</provider>
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
@@ -13,9 +13,14 @@ import java.io.File
import java.io.FileInputStream import java.io.FileInputStream
import java.io.FileOutputStream import java.io.FileOutputStream
import java.io.OutputStream import java.io.OutputStream
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.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
data class DownloadedFile(val name: String, val size: Long, val uri: Uri?) data class DownloadedFile(val name: String, val size: Long, val uri: Uri?)
@@ -24,15 +29,121 @@ data class DownloadedFile(val name: String, val size: Long, val uri: Uri?)
object DownloadClient { 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 ATTEMPTS = 5 private const val SERIAL_ATTEMPTS = 3
// 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_CHUNK_SIZE = 16L * 1024L * 1024L
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 不匹配(缓存已损坏)时才会用到第二轮。 */
private const val VERIFY_ROUNDS = 2
/** 落盘阶段的失败与「下载失败」是两回事,用独立异常类型区分。 */
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,
network: Network?, networkProvider: () -> Network?,
baseUrl: String, baseUrl: String,
pairing: PairingPayload, pairing: PairingPayload,
deviceName: String, deviceName: String,
/** 返回非 null 表示应立刻中止(例如 QFT 临时网络已断开),并以该原因报错。 */
abortReason: () -> String? = { null },
/** 阶段提示。传输完成后还有校验与落盘两步,必须让 UI 有反馈,
* 否则用户看到的就是「进度条停在 100% 然后报错」。 */
onPhase: (String) -> Unit = {},
onProgress: (received: Long, total: Long) -> Unit, onProgress: (received: Long, total: Long) -> Unit,
): DownloadedFile { ): DownloadedFile {
require(pairing.direction == TransferDirection.DOWNLOAD_TO_PHONE) require(pairing.direction == TransferDirection.DOWNLOAD_TO_PHONE)
@@ -41,27 +152,78 @@ 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) partial.delete() if (partial.length() > expectedSize) discardTransferState(partial)
// 落盘时缓存文件与目标文件同时存在,需要约 2 倍空间。
// 不预检的话,这里会在下载 100% 之后才失败,用户看到的是「快结束时失败」。
ensureSpaceForTransfer(partial, expectedSize)
repeat(VERIFY_ROUNDS) { round ->
receiveUntilComplete(networkProvider, baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
onPhase("正在校验文件完整性…")
val actual = sha256(partial, onProgress)
if (actual.equals(expectedSha, ignoreCase = true)) {
onPhase("正在保存到 Downloads/QFT…")
ensureSpaceForSave(partial, expectedSize)
val result = try {
saveToDownloads(resolver, partial, expectedName, expectedSize, onProgress)
} catch (e: Exception) {
// 这一步失败与网络无关,重下多少次都没用,直接如实报错
throw SaveFailure("文件已完整收到,但保存到 Downloads/QFT 失败:${failureDetail(e)}", e)
}
discardTransferState(partial)
Log.i(TAG, "completed size=$expectedSize")
return result
}
Log.w(TAG, "sha mismatch round=${round + 1}/$VERIFY_ROUNDS expected=$expectedSha actual=$actual")
discardTransferState(partial)
if (round + 1 >= VERIFY_ROUNDS) {
error("文件校验失败:重新完整下载后 SHA-256 仍不匹配,请让电脑重新生成二维码")
}
onPhase("校验未通过,正在重新完整下载…")
}
error("下载未能完成")
}
/** 传输阶段:断点续传 + 有限重试。只有这一段的失败才算「下载失败」。 */
@Suppress("unused")
private fun receiveSequentialCompatibility(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
if (expectedSize >= PARALLEL_MIN_FILE_SIZE && expectedSize > 0L) {
receiveParallel(networkProvider, baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
return
}
var last: Exception? = null var last: Exception? = null
repeat(ATTEMPTS) { attempt -> repeat(SERIAL_ATTEMPTS) { attempt ->
abortReason()?.let { throw IllegalStateException(it, last) }
try { try {
Log.i(TAG, "attempt=${attempt + 1}/$ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl") Log.i(TAG, "serial attempt=${attempt + 1}/$SERIAL_ATTEMPTS partial=${partial.length()}/$expectedSize endpoint=$baseUrl")
if (partial.length() < expectedSize) { if (partial.length() < expectedSize) {
receiveAttempt(network, baseUrl, pairing, deviceName, partial, expectedSize, onProgress) receiveAttempt(networkProvider(), baseUrl, pairing, deviceName, partial,
expectedSize, abortReason, onProgress)
} }
if (partial.length() != expectedSize) { if (partial.length() != expectedSize) {
error("下载提前结束:${partial.length()}/$expectedSize") error("下载提前结束:${partial.length()}/$expectedSize")
} }
verifySha256(partial, expectedSha) return
val result = saveToDownloads(resolver, partial, expectedName, expectedSize)
partial.delete()
Log.i(TAG, "completed size=$expectedSize")
return result
} catch (e: Exception) { } catch (e: Exception) {
last = e last = e
Log.w(TAG, "attempt=${attempt + 1}/$ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e) Log.w(TAG, "serial attempt=${attempt + 1}/$SERIAL_ATTEMPTS failed partial=${partial.length()}/$expectedSize: ${failureDetail(e)}", e)
if (attempt + 1 < ATTEMPTS) { abortReason()?.let { throw IllegalStateException(it, e) }
if (attempt + 1 < SERIAL_ATTEMPTS) {
try { try {
Thread.sleep(250L * (attempt + 1)) Thread.sleep(250L * (attempt + 1))
} catch (interrupted: InterruptedException) { } catch (interrupted: InterruptedException) {
@@ -71,7 +233,226 @@ object DownloadClient {
} }
} }
} }
throw IllegalStateException("从电脑下载失败,已重试 $ATTEMPTS 次:${failureDetail(last)}", last) val progressed = partial.length()
throw IllegalStateException(
"从电脑下载失败(断点 ${progressed}/$expectedSize 字节):${failureDetail(last)}",
last,
)
}
/**
* 大文件并行直传。每个 worker 请求一个有界 HTTP Range,并写入预分配文件的
* 固定 offset。完成位图单独落盘,所以应用进程或某条 TCP 流中断后只补缺块,
* 不会把 1 GB 文件从头再传一遍。
*/
private fun receiveParallel(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
partial: File,
expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit,
) {
val totalChunks = ((expectedSize + PARALLEL_CHUNK_SIZE - 1L) / PARALLEL_CHUNK_SIZE).toInt()
val mapFile = completionMapFile(partial)
val completed = loadCompletionMap(mapFile, totalChunks)
// A partial from the old sequential downloader has no bitmap. Preserve
// only complete chunks; an incomplete tail is safely downloaded again.
val oldLength = partial.length()
if (!mapFile.exists() && oldLength in 1 until expectedSize) {
for (index in completed.indices) {
val endExclusive = minOf(expectedSize, (index + 1L) * PARALLEL_CHUNK_SIZE)
if (endExclusive <= oldLength) completed[index] = true
}
}
RandomAccessFile(partial, "rw").use { it.setLength(expectedSize) }
persistCompletionMap(mapFile, completed)
val initialBytes = completed.indices.sumOf { index ->
if (completed[index]) chunkLength(index, expectedSize) else 0L
}
val received = AtomicLong(initialBytes)
val lastReport = AtomicLong(0L)
val next = AtomicInteger(0)
onProgress(initialBytes, expectedSize)
val workers = totalChunks.coerceAtMost(
Runtime.getRuntime().availableProcessors().coerceIn(2, MAX_WORKERS)
).coerceAtLeast(1)
Log.i(TAG, "parallel download chunks=$totalChunks workers=$workers completed=$initialBytes/$expectedSize")
val pool = Executors.newFixedThreadPool(workers)
val futures = (0 until workers).map {
pool.submit {
RandomAccessFile(partial, "rw").use { output ->
while (!Thread.currentThread().isInterrupted) {
abortReason()?.let { error(it) }
val index = next.getAndIncrement()
if (index >= totalChunks) break
if (completed[index]) continue
val start = index.toLong() * PARALLEL_CHUNK_SIZE
val length = chunkLength(index, expectedSize)
receiveRangeWithRetry(
networkProvider, baseUrl, pairing, deviceName,
output, index, start, length, expectedSize, abortReason,
)
// Data reaches stable storage before its completion bit.
// A crash can therefore only cause a harmless re-download.
output.fd.sync()
synchronized(completed) {
completed[index] = true
persistCompletionMap(mapFile, completed)
}
val done = received.addAndGet(length)
val now = android.os.SystemClock.elapsedRealtime()
val previous = lastReport.get()
if (now - previous >= 80L && lastReport.compareAndSet(previous, now)) {
onProgress(done.coerceAtMost(expectedSize), expectedSize)
}
}
}
}
}
val failures = mutableListOf<Throwable>()
try {
futures.forEach { future ->
try { future.get() } catch (e: Exception) { failures += (e.cause ?: e) }
}
} finally {
pool.shutdownNow()
}
if (failures.isNotEmpty()) throw IllegalStateException(
"并行直传中断,已完成 ${received.get()}/$expectedSize 字节;下次将只补传缺块:${failureDetail(failures.first())}",
failures.first(),
)
if (completed.any { !it }) error("并行直传结束但仍有缺块")
onProgress(expectedSize, expectedSize)
}
private fun receiveRangeWithRetry(
networkProvider: () -> Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
output: RandomAccessFile,
index: Int,
start: Long,
length: Long,
expectedSize: Long,
abortReason: () -> String?,
) {
var last: Exception? = null
repeat(RANGE_ATTEMPTS) { attempt ->
abortReason()?.let { error(it) }
try {
receiveRange(
networkProvider(), baseUrl, pairing, deviceName, output,
start, length, expectedSize, abortReason,
)
return
} catch (e: Exception) {
last = e
Log.w(TAG, "range=$index attempt=${attempt + 1}/$RANGE_ATTEMPTS failed: ${failureDetail(e)}")
if (attempt + 1 < RANGE_ATTEMPTS) {
try { Thread.sleep((200L shl attempt).coerceAtMost(3_000L)) }
catch (_: InterruptedException) {
Thread.currentThread().interrupt()
throw e
}
}
}
}
throw IllegalStateException("区段 $index 传输失败:${failureDetail(last)}", last)
}
private fun receiveRange(
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
output: RandomAccessFile,
start: Long,
length: Long,
expectedSize: Long,
abortReason: () -> String?,
) {
val end = start + length - 1L
val conn = open(network, URL("$baseUrl/qft/download"))
try {
conn.requestMethod = "GET"
conn.connectTimeout = 8_000
conn.readTimeout = 90_000
conn.useCaches = false
conn.setRequestProperty("Connection", "keep-alive")
conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8)))
conn.setRequestProperty("Range", "bytes=$start-$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 contentRange = conn.getHeaderField("Content-Range").orEmpty()
if (contentRange != "bytes $start-$end/$expectedSize") {
error("下载服务返回了无效区段:$contentRange")
}
if (conn.contentLengthLong >= 0L && conn.contentLengthLong != length) {
error("区段长度不匹配:${conn.contentLengthLong} != $length")
}
output.seek(start)
var remaining = length
conn.inputStream.use { input ->
val buffer = ByteArray(BUFFER_SIZE)
while (remaining > 0L) {
abortReason()?.let { error(it) }
val n = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
if (n < 0) error("区段提前结束:还缺 $remaining 字节")
if (n == 0) continue
output.write(buffer, 0, n)
remaining -= n.toLong()
}
}
} finally {
conn.disconnect()
}
}
private fun chunkLength(index: Int, total: Long): Long =
minOf(PARALLEL_CHUNK_SIZE, total - index.toLong() * PARALLEL_CHUNK_SIZE)
private fun completionMapFile(partial: File): File = File(partial.parentFile, partial.name + ".map")
private fun loadCompletionMap(file: File, count: Int): BooleanArray {
val result = BooleanArray(count)
val bytes = try { if (file.exists()) file.readBytes() else ByteArray(0) } catch (_: Exception) { ByteArray(0) }
if (bytes.size == count) bytes.indices.forEach { result[it] = bytes[it].toInt() == 1 }
return result
}
private fun persistCompletionMap(file: File, completed: BooleanArray) {
FileOutputStream(file, false).use { output ->
output.write(ByteArray(completed.size) { if (completed[it]) 1 else 0 })
output.fd.sync()
}
}
/** 传输 + 落盘阶段合计需要的可用空间。 */
private fun ensureSpaceForTransfer(partial: File, expectedSize: Long) {
val root = partial.parentFile ?: return
val needed = (expectedSize - partial.length()).coerceAtLeast(0L) + expectedSize
val usable = root.usableSpace
if (usable in 1 until needed) {
error("存储空间不足:本次接收约需 ${needed / 1024 / 1024} MB(含保存时的临时副本),当前可用 ${usable / 1024 / 1024} MB")
}
}
private fun ensureSpaceForSave(partial: File, expectedSize: Long) {
val usable = partial.parentFile?.usableSpace ?: return
if (usable in 1 until expectedSize) {
error("存储空间不足:保存副本还需 ${expectedSize / 1024 / 1024} MB,当前可用 ${usable / 1024 / 1024} MB")
}
} }
private fun receiveAttempt( private fun receiveAttempt(
@@ -81,6 +462,7 @@ object DownloadClient {
deviceName: String, deviceName: String,
partial: File, partial: File,
expectedSize: Long, expectedSize: Long,
abortReason: () -> String?,
onProgress: (received: Long, total: Long) -> Unit, onProgress: (received: Long, total: Long) -> Unit,
) { ) {
val requestedOffset = partial.length().coerceIn(0L, expectedSize) val requestedOffset = partial.length().coerceIn(0L, expectedSize)
@@ -88,13 +470,9 @@ object DownloadClient {
try { try {
conn.requestMethod = "GET" conn.requestMethod = "GET"
conn.connectTimeout = 5_000 conn.connectTimeout = 5_000
// A QFT LAN transfer should start immediately. The old 120-second conn.readTimeout = 60_000
// read timeout let Huawei tear down a local-only Wi-Fi request
// before a retry could occur. A short timeout safely resumes from
// the persisted Range offset and finishes all retries sooner.
conn.readTimeout = 12_000
conn.useCaches = false conn.useCaches = false
conn.setRequestProperty("Connection", "close") conn.setRequestProperty("Connection", "keep-alive")
conn.setRequestProperty("X-QFT-Token", pairing.session) conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8))) conn.setRequestProperty("X-QFT-Device", Base64Url.encode(deviceName.toByteArray(Charsets.UTF_8)))
if (requestedOffset > 0L) conn.setRequestProperty("Range", "bytes=$requestedOffset-") if (requestedOffset > 0L) conn.setRequestProperty("Range", "bytes=$requestedOffset-")
@@ -132,6 +510,8 @@ object DownloadClient {
FileOutputStream(partial, offset > 0L).use { output -> FileOutputStream(partial, offset > 0L).use { output ->
val buffer = ByteArray(BUFFER_SIZE) val buffer = ByteArray(BUFFER_SIZE)
while (true) { while (true) {
// 用户明确返回首页时才中止;普通 TCP 波动由 Range 续传恢复。
abortReason()?.let { error(it) }
val n = input.read(buffer) val n = input.read(buffer)
if (n < 0) break if (n < 0) break
if (n == 0) continue if (n == 0) continue
@@ -154,28 +534,221 @@ object DownloadClient {
} }
} }
private fun verifySha256(file: File, expectedSha: String) { /** 校验也要报进度:大文件读一整遍是好几秒,静默的话看起来就是卡在 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 {
val digest = MessageDigest.getInstance("SHA-256") val digest = MessageDigest.getInstance("SHA-256")
val total = file.length()
var done = 0L
var lastReport = 0L
FileInputStream(file).use { input -> FileInputStream(file).use { input ->
val buffer = ByteArray(BUFFER_SIZE) val buffer = ByteArray(BUFFER_SIZE)
while (true) { while (true) {
val n = input.read(buffer) val n = input.read(buffer)
if (n < 0) break if (n < 0) break
if (n > 0) digest.update(buffer, 0, n) if (n > 0) {
digest.update(buffer, 0, n)
done += n.toLong()
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 80L) {
onProgress(done, total)
lastReport = now
} }
} }
val actual = digest.digest().toHex()
if (!actual.equals(expectedSha, ignoreCase = true)) {
file.delete()
error("文件校验失败,已清除不完整缓存;请重试")
} }
} }
onProgress(total, total)
return digest.digest().toHex()
}
private fun saveToDownloads( private fun saveToDownloads(
resolver: ContentResolver, resolver: ContentResolver,
partial: File, partial: File,
expectedName: String, expectedName: String,
expectedSize: Long, expectedSize: Long,
onProgress: (Long, Long) -> Unit,
): DownloadedFile { ): DownloadedFile {
var target: DownloadTarget? = null var target: DownloadTarget? = null
try { try {
@@ -185,12 +758,18 @@ object DownloadClient {
createdTarget.output.use { output -> createdTarget.output.use { output ->
val buffer = ByteArray(BUFFER_SIZE) val buffer = ByteArray(BUFFER_SIZE)
var copied = 0L var copied = 0L
var lastReport = 0L
while (true) { while (true) {
val n = input.read(buffer) val n = input.read(buffer)
if (n < 0) break if (n < 0) break
if (n == 0) continue if (n == 0) continue
output.write(buffer, 0, n) output.write(buffer, 0, n)
copied += n.toLong() copied += n.toLong()
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 80L) {
onProgress(copied, expectedSize)
lastReport = now
}
} }
output.flush() output.flush()
if (copied != expectedSize) error("保存下载文件时大小发生变化") if (copied != expectedSize) error("保存下载文件时大小发生变化")
@@ -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
@@ -76,16 +77,23 @@ class MainActivity : ComponentActivity() {
private lateinit var progress: ProgressBar private lateinit var progress: ProgressBar
private var pendingPair: PairingPayload? = null private var pendingPair: PairingPayload? = null
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 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 临时网络断开等)。
* 下载线程每读一个缓冲区就检查一次,避免在 readTimeout 上白等。 */
@Volatile private var transferAbortReason: String? = null
@Volatile private var pairConnectionAttempt = 0L @Volatile private var pairConnectionAttempt = 0L
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
@@ -112,11 +120,14 @@ class MainActivity : ComponentActivity() {
} }
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
selectedFiles.clear() 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 += file else unknown++ if (file != null && selectedFiles.none { it.uri == file.uri }) selectedFiles += file else if (file == null) unknown++
} }
renderSelectedFiles() renderSelectedFiles()
if (unknown > 0) { if (unknown > 0) {
@@ -136,10 +147,12 @@ class MainActivity : ComponentActivity() {
} }
private fun showHome(message: String? = null) { private fun showHome(message: String? = null) {
transferAbortReason = "已返回首页,传输已停止"
pairConnectionAttempt++ pairConnectionAttempt++
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
@@ -147,6 +160,14 @@ class MainActivity : ComponentActivity() {
downloadRunning = false downloadRunning = false
downloadStatusText = null downloadStatusText = null
selectedFiles.clear() selectedFiles.clear()
uploadRunning = false
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))
@@ -172,9 +193,16 @@ class MainActivity : ComponentActivity() {
body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。", body = "扫描电脑二维码后自动连接 QFT 本地网络:接收二维码会进入手机选文件上传;下发二维码会自动下载并保存到 Downloads/QFT。",
buttonLabel = "扫描电脑二维码", buttonLabel = "扫描电脑二维码",
) { requestScanner(ScannerMode.PAIR) }) ) { requestScanner(ScannerMode.PAIR) })
root.addView(space(16))
root.addView(modeCard(
title = "接收文件柜",
badge = "Downloads/QFT · 图片/视频/PDF/Office/压缩包等",
body = "查看 QFT 已接收的文件;点击后将使用手机中可用的阅读器或播放器打开。",
buttonLabel = "打开文件柜",
) { 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.0-rc2 · 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) })
} }
@@ -289,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)
@@ -583,6 +611,15 @@ class MainActivity : ComponentActivity() {
private fun connectPair(pair: PairingPayload) { private fun connectPair(pair: PairingPayload) {
val attempt = ++pairConnectionAttempt val attempt = ++pairConnectionAttempt
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,
@@ -592,30 +629,85 @@ class MainActivity : ComponentActivity() {
onAvailable = available@{ network -> onAvailable = available@{ network ->
if (attempt != pairConnectionAttempt) return@available if (attempt != pairConnectionAttempt) return@available
connectedNetwork = network connectedNetwork = network
// A retained WifiNetworkSpecifier request may deliver a fresh
// Network after a brief radio fluctuation. Do not restart the
// page or transfer; chunk retries will use this new handle.
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)
val routedEndpoints = if (dedicatedWifi) emptyList() else {
wifiConnector.endpointsOnNetwork(network, pair.endpoints, pair.port)
}
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 {
updateConnectingStatus(
if (dedicatedWifi) "专用 Wi-Fi 已连接 · 正在并行认证网关和电脑…"
else "网络已就绪 · 正在连接同网段电脑…"
)
}
val direct = if (dedicatedWifi) {
UploadClient.probeConnectedNetwork(
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 {
updateConnectingStatus(
if (dedicatedWifi) "专用网关正在初始化 · 仅在 QFT 子网内自动发现…"
else "同网段地址未应答 · 正在 UDP 快速发现电脑…"
)
}
discovered = UploadClient.discoverUdp(
network = network, network = network,
pairing = pair, pairing = pair,
hosts = wifiConnector.discoveryHosts(network), 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 { runOnUiThread {
updateConnectingStatus( updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…" if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
else "UDP 未响应 · 正在并行探测网关与本地 IP…" else "仅在当前连接的 QFT 子网内并行查找电脑…"
) )
} }
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
val subnet = wifiConnector.subnetEndpoints(network, pair.port)
if (discovered == null) {
runOnUiThread {
updateConnectingStatus("正在并行探测网关;必要时自动扫描当前 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,
@@ -623,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) {
@@ -638,11 +753,11 @@ class MainActivity : ComponentActivity() {
}, },
onUnavailable = { message -> runOnUiThread { onUnavailable = { message -> runOnUiThread {
if (attempt != pairConnectionAttempt) return@runOnUiThread if (attempt != pairConnectionAttempt) return@runOnUiThread
// Huawei can report onLost while a bound local-only HTTP // onLost is recovered inside WifiConnector. onUnavailable is
// socket is unwinding. Let DownloadClient surface its precise // terminal (system/user rejected the retained request), so it
// HTTP/timeout cause instead of replacing it with this generic // is the only network callback that aborts an active transfer.
// message mid-retry.
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) { if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE && downloadRunning) {
transferAbortReason = message
downloadStatusText?.apply { downloadStatusText?.apply {
text = "QFT 本地网络已断开,正在结束当前下载请求…" text = "QFT 本地网络已断开,正在结束当前下载请求…"
setTextColor(WARNING) setTextColor(WARNING)
@@ -682,8 +797,8 @@ class MainActivity : ComponentActivity() {
private fun showPairError(pair: PairingPayload?, message: String) { private fun showPairError(pair: PairingPayload?, message: String) {
// Do not unregister here: Android may still be displaying its // Do not unregister here: Android may still be displaying its
// Wi-Fi-selection sheet, and unregistering at that moment produces // Wi-Fi-selection sheet, and unregistering at that moment produces
// "the app cancelled the device selection request". The next attempt // "the app cancelled the device selection request". A retry reuses
// (or returning home) releases the previous request safely. // this retained request; returning home is what explicitly releases it.
pairConnectionAttempt++ pairConnectionAttempt++
connectedNetwork = null connectedNetwork = null
connectedBaseUrl = null connectedBaseUrl = null
@@ -695,7 +810,7 @@ class MainActivity : ComponentActivity() {
root.addView(button("重试连接").apply { setOnClickListener { ensureWifiPermissionThenConnect(pair) } }) root.addView(button("重试连接").apply { setOnClickListener { ensureWifiPermissionThenConnect(pair) } })
root.addView(space(10)) root.addView(space(10))
} }
root.addView(button("重新扫码").apply { setOnClickListener { requestScanner(ScannerMode.PAIR) } }) root.addView(button("返回首页重新扫码").apply { setOnClickListener { showHome() } })
root.addView(space(10)) root.addView(space(10))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } }) root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) }) setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
@@ -709,29 +824,53 @@ 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, MUTED) sendFilesText = text("请先选择需要传输的文件", 14f, WARNING)
addView(sendFilesText, matchWrap(top = 8)) addView(sendFilesText, matchWrap(top = 8))
addView(button("选择文件(可多选)").apply { sendFilesContainer = LinearLayout(this@MainActivity).apply {
orientation = LinearLayout.VERTICAL
}
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("*/*")) } setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
}, matchWrap(top = 12)) }
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 {
addView(text("传输进度", 17f, Color.WHITE, true)) addView(text("传输进度", 17f, Color.WHITE, true))
sendStatusText = text("选择文件后点击开始传输", 14f, MUTED) sendStatusText = text("请先选择需要传输的文件,再点击“开始传输”", 14f, WARNING)
addView(sendStatusText, matchWrap(top = 8)) addView(sendStatusText, matchWrap(top = 8))
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 = selectedFiles.isNotEmpty() isEnabled = false
setOnClickListener { startUploads(pair, baseUrl) } setOnClickListener {
startUploads(pair, baseUrl)
}
} }
addView(sendButton, matchWrap(top = 14)) addView(sendButton, matchWrap(top = 14))
}) })
@@ -750,7 +889,13 @@ class MainActivity : ComponentActivity() {
root.addView(space(18)) root.addView(space(18))
root.addView(card().apply { root.addView(card().apply {
addView(text("扫码配置已完成", 17f, SUCCESS, true)) addView(text("扫码配置已完成", 17f, SUCCESS, true))
addView(text("电脑已自动确认会话,正在通过本地网络直接传输。", 14f, MUTED), matchWrap(top = 8)) addView(text(
if (total >= 32L * 1024L * 1024L)
"连接将保持到返回首页;正在通过本地网络进行最高 8 路并行直传。"
else
"连接将保持到返回首页;正在通过本地网络直接传输。",
14f, MUTED,
), matchWrap(top = 8))
addView(text(fileName, 15f, Color.WHITE), matchWrap(top = 12)) addView(text(fileName, 15f, Color.WHITE), matchWrap(top = 12))
addView(text(humanBytes(total), 13f, MUTED), matchWrap(top = 4)) addView(text(humanBytes(total), 13f, MUTED), matchWrap(top = 4))
}) })
@@ -765,59 +910,266 @@ class MainActivity : ComponentActivity() {
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) }) setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
downloadRunning = true downloadRunning = true
transferAbortReason = null
// 传输期间阻止 Wi-Fi 进入省电休眠。Android 默认会在包间隙让
// Wi-Fi 芯片休眠,对持续大流量传输会明显压低吞吐。
wifiConnector.acquireHighPerfLock()
val linkAtStart = wifiConnector.describeLink()
transferExecutor.execute { transferExecutor.execute {
// 「传输 / 校验 / 保存」三个阶段各自的速率含义完全不同,混在一起
// 平均出来的数字毫无意义。逐段记账,结束后一并列出——
// 这样"到底是哪一段慢"一眼就能看出来,不必再靠猜。
val phases = java.util.Collections.synchronizedList(
mutableListOf<Triple<String, Long, Long>>() // 名称、毫秒、字节
)
var phaseLabel = "接收"
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 startedAt = android.os.SystemClock.elapsedRealtime()
val saved = DownloadClient.download( val saved = DownloadClient.download(
context = this@MainActivity, context = this@MainActivity,
resolver = contentResolver, resolver = contentResolver,
network = connectedNetwork, networkProvider = { connectedNetwork },
baseUrl = baseUrl, baseUrl = baseUrl,
pairing = pair, pairing = pair,
deviceName = receiverDeviceLabel, deviceName = receiverDeviceLabel,
abortReason = { transferAbortReason },
onPhase = { label ->
closePhase()
// 去掉文案里的修饰,只留阶段名,汇总表才对得齐
phaseLabel = label.removePrefix("正在").removeSuffix("…")
.substringBefore("到 ").substringBefore("文件完整性").ifBlank { label }
phaseStartedAt = android.os.SystemClock.elapsedRealtime()
phaseFirstBytes.set(-1L)
phaseLastBytes.set(0L)
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() - startedAt).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 = "${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 {
downloadRunning = false downloadRunning = false
showPairError(pair, "从电脑接收失败:${e.message}") // 落盘失败时文件其实已经完整收到了,别再说「接收失败」误导用户
val prefix = if (e is DownloadClient.SaveFailure) "保存失败" else "从电脑接收失败"
showPairError(pair, "$prefix:${e.message}")
} }
} finally { } finally {
downloadRunning = false downloadRunning = false
// 无论成功失败都要释放,否则 Wi-Fi 会一直停留在高功耗模式
wifiConnector.releaseHighPerfLock()
} }
} }
} }
private fun showReceivedFiles(message: String? = null) {
val root = pageColumn()
root.addView(text("接收文件柜", 28f, Color.WHITE, true))
root.addView(text("QFT 已保存到 Downloads/QFT 的文件", 14f, MUTED))
message?.let { root.addView(text(it, 13f, WARNING), matchWrap(top = 10)) }
root.addView(space(16))
val files = try {
ReceivedFileCabinet.list(this)
} catch (e: Exception) {
emptyList()
}
if (files.isEmpty()) {
root.addView(card().apply {
addView(text("文件柜为空", 17f, Color.WHITE, true))
addView(text("完成电脑下发或光学接收后,文件会自动出现在这里。", 14f, MUTED), matchWrap(top = 8))
})
} else {
root.addView(text("共 ${files.size} 个文件", 13f, ACCENT, true))
files.forEach { file ->
val entry = card()
entry.addView(text(file.name, 16f, Color.WHITE, true))
entry.addView(
text("${humanBytes(file.size)} · ${file.mimeType.ifBlank { "未知格式" }}", 12f, MUTED),
matchWrap(top = 5),
)
entry.addView(button("打开文件").apply {
setOnClickListener {
try {
ReceivedFileCabinet.open(this@MainActivity, file)
} catch (e: Exception) {
showReceivedFiles("无法打开 ${file.name}:请安装支持该格式的阅读器。")
}
}
}, matchWrap(top = 10))
root.addView(entry, matchWrap(bottom = 10))
}
}
root.addView(space(12))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
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?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null
} }
private fun startUploads(pair: PairingPayload, baseUrl: String) { private fun startUploads(pair: PairingPayload, baseUrl: String) {
if (selectedFiles.isEmpty()) return if (uploadRunning) return
if (selectedFiles.isEmpty()) {
sendStatusText?.setTextColor(WARNING)
sendStatusText?.text = "请先选择需要传输的文件"
pickFiles.launch(arrayOf("*/*"))
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 ->
@@ -828,11 +1180,12 @@ class MainActivity : ComponentActivity() {
} }
UploadClient.upload( UploadClient.upload(
resolver = contentResolver, resolver = contentResolver,
network = connectedNetwork, networkProvider = { connectedNetwork },
baseUrl = baseUrl, baseUrl = baseUrl,
pairing = pair, pairing = pair,
deviceName = receiverDeviceLabel, deviceName = receiverDeviceLabel,
file = file, file = file,
abortReason = { transferAbortReason },
) { sent, total -> ) { sent, total ->
runOnUiThread { runOnUiThread {
val p = if (total == 0L) 1000 else ((sent.toDouble() / total) * 1000).toInt().coerceIn(0, 1000) val p = if (total == 0L) 1000 else ((sent.toDouble() / total) * 1000).toInt().coerceIn(0, 1000)
@@ -851,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 ->
updatePairRegion(result, centered)
return result
}
if (frameCounter % 3L == 0L) {
decodeDense(centered, hybrid = true)?.let { result -> decodeDense(centered, hybrid = true)?.let { result ->
updatePairRegion(result, centered) updatePairRegion(result, centered)
return result return result
} }
// Global thresholding remains a cheap fallback for very clean displays,
// 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)
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,102 @@
package com.qft.optical
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import java.io.File
data class ReceivedFile(
val uri: Uri,
val name: String,
val size: Long,
val mimeType: String,
val modifiedAtSeconds: Long,
)
/** Lists only the files QFT has finished writing to Downloads/QFT. */
object ReceivedFileCabinet {
private const val RELATIVE_QFT_PATH = "Download/QFT/"
fun list(context: Context): List<ReceivedFile> =
if (Build.VERSION.SDK_INT >= 29) listModern(context.contentResolver) else listLegacy(context)
fun open(context: Context, file: ReceivedFile) {
val resolvedMime = mimeFor(file.name, file.mimeType)
val intent = Intent(Intent.ACTION_VIEW)
.setDataAndType(file.uri, resolvedMime)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(Intent.createChooser(intent, "打开 ${file.name}"))
}
private fun listModern(resolver: ContentResolver): List<ReceivedFile> {
val projection = arrayOf(
MediaStore.Downloads._ID,
MediaStore.Downloads.DISPLAY_NAME,
MediaStore.Downloads.SIZE,
MediaStore.Downloads.MIME_TYPE,
MediaStore.Downloads.DATE_MODIFIED,
)
val out = mutableListOf<ReceivedFile>()
resolver.query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
projection,
"${MediaStore.Downloads.RELATIVE_PATH}=? AND ${MediaStore.Downloads.IS_PENDING}=0",
arrayOf(RELATIVE_QFT_PATH),
"${MediaStore.Downloads.DATE_MODIFIED} DESC",
)?.use { cursor ->
val idIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID)
val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.SIZE)
val mimeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.MIME_TYPE)
val timeIndex = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DATE_MODIFIED)
while (cursor.moveToNext()) {
val id = cursor.getLong(idIndex)
val name = cursor.getString(nameIndex).orEmpty().ifBlank { "未命名文件" }
out += ReceivedFile(
uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, id),
name = name,
size = cursor.getLong(sizeIndex).coerceAtLeast(0L),
mimeType = cursor.getString(mimeIndex).orEmpty(),
modifiedAtSeconds = cursor.getLong(timeIndex),
)
}
}
return out
}
@Suppress("DEPRECATION")
private fun listLegacy(context: Context): List<ReceivedFile> {
val directory = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"QFT",
)
return directory.listFiles()
?.asSequence()
?.filter { it.isFile }
?.sortedByDescending { it.lastModified() }
?.map { file ->
ReceivedFile(
uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file),
name = file.name,
size = file.length().coerceAtLeast(0L),
mimeType = mimeFor(file.name, ""),
modifiedAtSeconds = file.lastModified() / 1000L,
)
}
?.toList()
.orEmpty()
}
private fun mimeFor(name: String, supplied: String): String {
if (supplied.isNotBlank() && supplied != "application/octet-stream") return supplied
val extension = name.substringAfterLast('.', "").lowercase()
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
}
}
@@ -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
}
@@ -5,6 +5,7 @@ import android.database.Cursor
import android.net.Network import android.net.Network
import android.net.Uri import android.net.Uri
import android.provider.OpenableColumns import android.provider.OpenableColumns
import android.util.Log
import org.json.JSONObject import org.json.JSONObject
import java.io.FileInputStream import java.io.FileInputStream
import java.net.DatagramPacket import java.net.DatagramPacket
@@ -19,25 +20,58 @@ import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicLong
import java.util.UUID
data class SelectedFile( data class SelectedFile(
val uri: Uri, val uri: Uri,
val name: String, val name: String,
val size: Long, val size: Long,
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 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
// 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.
private const val LOCAL_REQUEST_ATTEMPTS = 3 private const val LOCAL_REQUEST_ATTEMPTS = 8
fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? { fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? {
var name = "qft-upload.bin" var name = "qft-upload.bin"
@@ -66,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()
@@ -73,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) {
@@ -114,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 }
@@ -135,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 }
@@ -156,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,
@@ -176,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 {
@@ -215,16 +316,17 @@ object UploadClient {
fun upload( fun upload(
resolver: ContentResolver, resolver: ContentResolver,
network: Network?, networkProvider: () -> Network?,
baseUrl: String, baseUrl: String,
pairing: PairingPayload, pairing: PairingPayload,
deviceName: String, deviceName: String,
file: SelectedFile, file: SelectedFile,
abortReason: () -> String? = { null },
onProgress: (sent: Long, total: Long) -> Unit, onProgress: (sent: Long, total: Long) -> Unit,
) { ) {
if (pairing.version >= 2 && isSeekable(resolver, file)) { if (pairing.version >= 2 && isSeekable(resolver, file)) {
try { try {
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress) uploadParallel(resolver, networkProvider, baseUrl, pairing, deviceName, file, abortReason, onProgress)
return return
} catch (e: Exception) { } catch (e: Exception) {
// Never mask a transient v2 failure by immediately switching to a // Never mask a transient v2 failure by immediately switching to a
@@ -236,50 +338,90 @@ object UploadClient {
if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e if (!message.contains("HTTP 404") && !message.contains("HTTP 501")) throw e
} }
} }
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress) Log.i(TAG, "using compatibility single-stream upload: size=${file.size}, endpoint=$baseUrl")
uploadLegacy(resolver, networkProvider(), baseUrl, pairing, deviceName, file, abortReason, onProgress)
} }
private data class InitReply(val uploadId: String, val chunkSize: Long, val totalChunks: Int) private data class InitReply(
val uploadId: String,
val chunkSize: Long,
val totalChunks: Int,
val pendingChunks: IntArray,
)
private fun <T> retryLocalRequest(label: String, block: () -> T): T { private fun <T> retryLocalRequest(label: String, abortReason: () -> String?, block: () -> T): T {
var last: Throwable? = null var last: Throwable? = null
repeat(LOCAL_REQUEST_ATTEMPTS) { attempt -> repeat(LOCAL_REQUEST_ATTEMPTS) { attempt ->
abortReason()?.let { throw IllegalStateException(it, last) }
try { try {
return block() return block()
} catch (e: Throwable) { } catch (e: Throwable) {
last = e last = e
Log.w(
TAG,
"$label: attempt=${attempt + 1}/$LOCAL_REQUEST_ATTEMPTS, ${failureSummary(e)}",
e,
)
if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) { if (attempt + 1 < LOCAL_REQUEST_ATTEMPTS) {
try { Thread.sleep(120L * (attempt + 1)) } catch (_: InterruptedException) { try { Thread.sleep((250L shl attempt).coerceAtMost(3_000L)) } catch (_: InterruptedException) {
Thread.currentThread().interrupt() Thread.currentThread().interrupt()
throw e throw e
} }
} }
} }
} }
throw IllegalStateException("$label after $LOCAL_REQUEST_ATTEMPTS attempts", last) val failure = last ?: IllegalStateException("unknown local request failure")
throw IllegalStateException(
"$label,已重试 $LOCAL_REQUEST_ATTEMPTS 次:${failureSummary(failure)}",
failure,
)
}
private fun failureSummary(error: Throwable): String {
val chain = ArrayList<String>(3)
var current: Throwable? = error
while (current != null && chain.size < 3) {
val type = current.javaClass.simpleName.ifBlank { current.javaClass.name }
val detail = current.message?.replace(Regex("\\s+"), " ")?.take(240)
chain += if (detail.isNullOrBlank()) type else "$type: $detail"
current = current.cause
}
return chain.joinToString(" <- ")
} }
private fun uploadParallel( private fun uploadParallel(
resolver: ContentResolver, resolver: ContentResolver,
network: Network?, networkProvider: () -> Network?,
baseUrl: String, baseUrl: String,
pairing: PairingPayload, pairing: PairingPayload,
deviceName: String, deviceName: String,
file: SelectedFile, file: SelectedFile,
abortReason: () -> String?,
onProgress: (sent: Long, total: Long) -> Unit, onProgress: (sent: Long, total: Long) -> Unit,
) { ) {
val init = initUpload(network, baseUrl, pairing, deviceName, file) Log.i(TAG, "parallel init: size=${file.size}, endpoint=$baseUrl")
val init = initUpload(networkProvider, baseUrl, pairing, deviceName, file, file.uploadKey, abortReason)
Log.i(TAG, "parallel init complete: chunks=${init.totalChunks}, pending=${init.pendingChunks.size}, chunkSize=${init.chunkSize}")
if (init.totalChunks == 0) { if (init.totalChunks == 0) {
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId) finishUpload(networkProvider, baseUrl, pairing, deviceName, init.uploadId, abortReason)
onProgress(0, 0) onProgress(0, 0)
return return
} }
val cpuWorkers = Runtime.getRuntime().availableProcessors().coerceIn(2, MAX_WORKERS) // Upload workers are network/disk bound, not CPU bound. Large files
val workerCount = init.totalChunks.coerceAtMost(cpuWorkers).coerceAtLeast(1) // therefore use all eight lanes even on a 4-core phone.
if (init.pendingChunks.isEmpty()) {
finishUpload(networkProvider, baseUrl, pairing, deviceName, init.uploadId, abortReason)
onProgress(file.size, file.size)
return
}
val workerCount = init.pendingChunks.size.coerceAtMost(MAX_WORKERS).coerceAtLeast(1)
val pool = Executors.newFixedThreadPool(workerCount) val pool = Executors.newFixedThreadPool(workerCount)
val next = AtomicInteger(0) val next = AtomicInteger(0)
val sent = AtomicLong(0) val pendingBytes = init.pendingChunks.sumOf { index ->
minOf(init.chunkSize, file.size - index.toLong() * init.chunkSize)
}
val sent = AtomicLong((file.size - pendingBytes).coerceAtLeast(0L))
val lastReport = AtomicLong(0) val lastReport = AtomicLong(0)
val failures = mutableListOf<Throwable>() val failures = mutableListOf<Throwable>()
val futures = (0 until workerCount).map { val futures = (0 until workerCount).map {
@@ -289,13 +431,15 @@ object UploadClient {
val channel = input.channel val channel = input.channel
val buffer = ByteBuffer.allocate(STREAM_BUFFER) val buffer = ByteBuffer.allocate(STREAM_BUFFER)
while (!Thread.currentThread().isInterrupted) { while (!Thread.currentThread().isInterrupted) {
val index = next.getAndIncrement() abortReason()?.let { error(it) }
if (index >= init.totalChunks) break val pendingIndex = next.getAndIncrement()
if (pendingIndex >= init.pendingChunks.size) break
val index = init.pendingChunks[pendingIndex]
val offset = index.toLong() * init.chunkSize val offset = index.toLong() * init.chunkSize
val length = minOf(init.chunkSize, file.size - offset) val length = minOf(init.chunkSize, file.size - offset)
sendChunk( sendChunk(
network, baseUrl, pairing, deviceName, networkProvider, baseUrl, pairing, deviceName,
init.uploadId, index, channel, offset, length, buffer, init.uploadId, index, channel, offset, length, buffer, abortReason,
) )
val totalSent = sent.addAndGet(length) val totalSent = sent.addAndGet(length)
val now = android.os.SystemClock.elapsedRealtime() val now = android.os.SystemClock.elapsedRealtime()
@@ -316,22 +460,25 @@ object UploadClient {
pool.shutdownNow() pool.shutdownNow()
} }
if (failures.isNotEmpty()) throw failures.first() if (failures.isNotEmpty()) throw failures.first()
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId) finishUpload(networkProvider, baseUrl, pairing, deviceName, init.uploadId, abortReason)
onProgress(file.size, file.size) onProgress(file.size, file.size)
} }
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(
network: Network?, baseUrl: String, pairing: PairingPayload, networkProvider: () -> Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, file: SelectedFile, deviceName: String, file: SelectedFile, requestKey: String, abortReason: () -> String?,
): InitReply = retryLocalRequest("本地上传初始化失败") { ): InitReply = retryLocalRequest("本地上传初始化失败", abortReason) {
val conn = open(network, URL("$baseUrl/qft/upload/init")) val conn = open(networkProvider(), URL("$baseUrl/qft/upload/init"))
try { try {
conn.requestMethod = "POST" conn.requestMethod = "POST"
conn.doOutput = true conn.doOutput = true
@@ -342,15 +489,27 @@ object UploadClient {
conn.setRequestProperty("X-QFT-Filename", b64(file.name)) conn.setRequestProperty("X-QFT-Filename", b64(file.name))
conn.setRequestProperty("X-QFT-Size", file.size.toString()) conn.setRequestProperty("X-QFT-Size", file.size.toString())
conn.setRequestProperty("X-QFT-Chunk-Size", desiredChunkSize(file.size).toString()) conn.setRequestProperty("X-QFT-Chunk-Size", desiredChunkSize(file.size).toString())
conn.setRequestProperty("X-QFT-Upload-Key", requestKey)
conn.outputStream.close() conn.outputStream.close()
val code = conn.responseCode val code = conn.responseCode
if (code != 200) error("初始化并行上传失败 HTTP $code") if (code != 200) error("初始化并行上传失败 HTTP $code")
val body = conn.inputStream.bufferedReader().use { it.readText() } val body = conn.inputStream.bufferedReader().use { it.readText() }
val obj = JSONObject(body) val obj = JSONObject(body)
val totalChunks = obj.getInt("total_chunks")
val missing = obj.optJSONArray("missing")
val pending = if (missing == null) {
IntArray(totalChunks) { it }
} else {
IntArray(missing.length()) { missing.getInt(it) }
}
if (pending.any { it !in 0 until totalChunks } || pending.distinct().size != pending.size) {
error("电脑返回了无效的缺块列表")
}
InitReply( InitReply(
uploadId = obj.getString("upload_id"), uploadId = obj.getString("upload_id"),
chunkSize = obj.getLong("chunk_size"), chunkSize = obj.getLong("chunk_size"),
totalChunks = obj.getInt("total_chunks"), totalChunks = totalChunks,
pendingChunks = pending,
) )
} finally { } finally {
conn.disconnect() conn.disconnect()
@@ -358,16 +517,17 @@ object UploadClient {
} }
private fun sendChunk( private fun sendChunk(
network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String, networkProvider: () -> Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long, uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
buffer: ByteBuffer, buffer: ByteBuffer, abortReason: () -> String?,
) = retryLocalRequest("分块 $index 上传失败") { ) = retryLocalRequest("分块 $index 上传失败", abortReason) {
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index")) Log.d(TAG, "chunk start: index=$index, bytes=$length, endpoint=$baseUrl")
val conn = open(networkProvider(), URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
try { try {
conn.requestMethod = "POST" conn.requestMethod = "POST"
conn.doOutput = true conn.doOutput = true
conn.connectTimeout = 4_000 conn.connectTimeout = 8_000
conn.readTimeout = 15_000 conn.readTimeout = 90_000
conn.setFixedLengthStreamingMode(length) conn.setFixedLengthStreamingMode(length)
conn.setRequestProperty("Content-Type", "application/octet-stream") conn.setRequestProperty("Content-Type", "application/octet-stream")
commonHeaders(conn, pairing, deviceName) commonHeaders(conn, pairing, deviceName)
@@ -376,6 +536,7 @@ object UploadClient {
var remaining = length var remaining = length
val array = buffer.array() val array = buffer.array()
while (remaining > 0) { while (remaining > 0) {
abortReason()?.let { error(it) }
buffer.clear() buffer.clear()
buffer.limit(minOf(array.size.toLong(), remaining).toInt()) buffer.limit(minOf(array.size.toLong(), remaining).toInt())
val n = channel.read(buffer) val n = channel.read(buffer)
@@ -391,16 +552,17 @@ object UploadClient {
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}") error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
} }
try { conn.inputStream.close() } catch (_: Exception) {} try { conn.inputStream.close() } catch (_: Exception) {}
Log.d(TAG, "chunk complete: index=$index, bytes=$length")
} finally { } finally {
conn.disconnect() conn.disconnect()
} }
} }
private fun finishUpload( private fun finishUpload(
network: Network?, baseUrl: String, pairing: PairingPayload, networkProvider: () -> Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, uploadId: String, deviceName: String, uploadId: String, abortReason: () -> String?,
) = retryLocalRequest("本地上传完成确认失败") { ) = retryLocalRequest("本地上传完成确认失败", abortReason) {
val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId")) val conn = open(networkProvider(), URL("$baseUrl/qft/upload/finish/$uploadId"))
try { try {
conn.requestMethod = "POST" conn.requestMethod = "POST"
conn.doOutput = true conn.doOutput = true
@@ -427,6 +589,7 @@ object UploadClient {
pairing: PairingPayload, pairing: PairingPayload,
deviceName: String, deviceName: String,
file: SelectedFile, file: SelectedFile,
abortReason: () -> String?,
onProgress: (sent: Long, total: Long) -> Unit, onProgress: (sent: Long, total: Long) -> Unit,
) { ) {
val conn = open(network, URL("$baseUrl/qft/upload")) val conn = open(network, URL("$baseUrl/qft/upload"))
@@ -447,6 +610,7 @@ object UploadClient {
var sent = 0L var sent = 0L
var lastReport = 0L var lastReport = 0L
while (true) { while (true) {
abortReason()?.let { error(it) }
val n = input.read(buf) val n = input.read(buf)
if (n <= 0) break if (n <= 0) break
output.write(buf, 0, n) output.write(buf, 0, n)
@@ -489,7 +653,7 @@ object UploadClient {
private fun commonHeaders(conn: HttpURLConnection, pairing: PairingPayload, deviceName: String) { private fun commonHeaders(conn: HttpURLConnection, pairing: PairingPayload, deviceName: String) {
conn.useCaches = false conn.useCaches = false
conn.setRequestProperty("Connection", "close") conn.setRequestProperty("Connection", "keep-alive")
conn.setRequestProperty("X-QFT-Token", pairing.session) conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", b64(deviceName)) conn.setRequestProperty("X-QFT-Device", b64(deviceName))
} }
@@ -20,59 +20,118 @@ 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
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
private var callback: ConnectivityManager.NetworkCallback? = null private var callback: ConnectivityManager.NetworkCallback? = null
@Volatile private var currentNetwork: Network? = null
private var generation = 0 private var generation = 0
private var legacyPreviousNetworkId: Int? = null private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null private var legacyTargetNetworkId: Int? = null
/**
* 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。
* 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的
* WifiNetworkSpecifier 请求,不必 unregister —— 在系统选网弹窗还开着的
* 时候 unregister,Android 会弹「该应用已取消选择设备的请求」。
*/
private class Listener(
val onStatus: (String) -> Unit,
val onAvailable: (Network?) -> Unit,
val onUnavailable: (String) -> Unit,
)
private var listener: Listener? = null
private var pendingSsid: String? = null
private var pendingDelivered: AtomicBoolean? = null
private var pendingTerminal: AtomicBoolean? = null
private var pendingStartedAt = 0L
// 所有对外回调都只走这三个入口。直接调用捕获来的闭包会在「复用挂起请求」
// 时通知到上一次的界面,是很难查的一类 bug。
private fun notifyStatus(message: String) { listener?.onStatus?.invoke(message) }
private fun notifyAvailable(network: Network?) { listener?.onAvailable?.invoke(network) }
private fun notifyUnavailable(message: String) { listener?.onUnavailable?.invoke(message) }
fun connect( fun connect(
pairing: PairingPayload, pairing: PairingPayload,
onStatus: (String) -> Unit, onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit, onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit, onUnavailable: (String) -> Unit,
) { ) {
val wifi = pairing.wifi
// 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可,
// 千万不要 unregister 再重新 requestNetwork。
// 复用必须有时间上限。系统偶尔会让一个 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) {
Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}")
listener = Listener(onStatus, onAvailable, onUnavailable)
val active = currentNetwork
if (active != null) {
notifyStatus("QFT 本地网络仍保持连接")
notifyAvailable(active)
} else {
notifyStatus("系统配网请求仍在进行中,正在自动恢复连接…")
scheduleWaitHints(generation, wifi.ssid)
}
return
}
release(restoreLegacy = false) release(restoreLegacy = false)
generation++ generation++
val run = generation val run = generation
val wifi = pairing.wifi listener = Listener(onStatus, onAvailable, onUnavailable)
if (wifi == null) { if (wifi == null) {
onStatus("正在使用当前局域网发现电脑…") notifyStatus("正在使用当前局域网发现电脑…")
val wifiNetwork = bestWifiNetwork() val wifiNetwork = bestWifiNetwork()
onAvailable(wifiNetwork ?: connectivity.activeNetwork) currentNetwork = wifiNetwork ?: connectivity.activeNetwork
notifyAvailable(currentNetwork)
return return
} }
if (Build.VERSION.SDK_INT >= 29) { if (Build.VERSION.SDK_INT >= 29) {
connectModern(run, wifi, onStatus, onAvailable, onUnavailable) connectModern(run, wifi)
} else { } else {
connectLegacy(run, wifi, onStatus, onAvailable, onUnavailable) connectLegacy(run, wifi)
} }
} }
@RequiresApi(29) @RequiresApi(29)
@Suppress("MissingPermission") @Suppress("MissingPermission")
private fun connectModern( private fun connectModern(run: Int, wifi: WifiCredentials) {
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("正在请求连接 ${wifi.ssid}…")
Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}") Log.i(TAG, "attempt=$run request SSID=${wifi.ssid}")
onStatus("正在等待 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) {
onUnavailable("配网参数无效:${e.message}") notifyUnavailable("配网参数无效:${e.message}")
return return
} }
val request = NetworkRequest.Builder() val request = NetworkRequest.Builder()
@@ -86,39 +145,66 @@ class WifiConnector(context: Context) {
// launching a duplicate probe/download for the same Wi-Fi connection. // launching a duplicate probe/download for the same Wi-Fi connection.
val delivered = AtomicBoolean(false) val delivered = AtomicBoolean(false)
val terminal = AtomicBoolean(false) val terminal = AtomicBoolean(false)
pendingSsid = wifi.ssid
pendingDelivered = delivered
pendingTerminal = terminal
pendingStartedAt = SystemClock.elapsedRealtime()
val startedAt = pendingStartedAt
val cb = object : ConnectivityManager.NetworkCallback() { val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) { override fun onAvailable(network: Network) {
if (run != generation || terminal.get()) return if (run != generation || terminal.get()) return
currentNetwork = network
Log.i(TAG, "attempt=$run framework onAvailable network=$network") Log.i(TAG, "attempt=$run framework onAvailable network=$network")
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…") notifyStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, onStatus) { waitUntilUsable(run, network, ::notifyStatus) {
if (run == generation && !terminal.get() && delivered.compareAndSet(false, true)) { if (run == generation && !terminal.get() && currentNetwork == network &&
delivered.compareAndSet(false, true)) {
Log.i(TAG, "attempt=$run route ready network=$network") Log.i(TAG, "attempt=$run route ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…") notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network) notifyAvailable(network)
} }
} }
} }
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) { override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
if (run != generation || terminal.get() || delivered.get()) return if (run != generation || terminal.get() || delivered.get() || currentNetwork != network) return
if (hasIpv4(linkProperties) && delivered.compareAndSet(false, true)) { if (hasIpv4(linkProperties) && delivered.compareAndSet(false, true)) {
currentNetwork = network
Log.i(TAG, "attempt=$run IPv4 ready network=$network") Log.i(TAG, "attempt=$run IPv4 ready network=$network")
onStatus("QFT 本地网络已就绪,正在快速发现电脑…") notifyStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network) notifyAvailable(network)
} }
} }
override fun onUnavailable() { override fun onUnavailable() {
if (run != generation || !terminal.compareAndSet(false, true)) return if (run != generation || !terminal.compareAndSet(false, true)) return
Log.w(TAG, "attempt=$run framework onUnavailable") currentNetwork = null
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。") val waited = SystemClock.elapsedRealtime() - startedAt
Log.w(TAG, "attempt=$run framework onUnavailable after ${waited}ms")
// Android 不区分「用户点了取消」和「始终没扫到这个热点」,
// 只能用等待时长推断,给出真正能指导用户下一步的提示。
notifyUnavailable(
if (waited < 4_000L) {
"已取消系统配网。请重新点击「重试连接」,并在系统弹窗里选择 ${wifi.ssid} 后点连接。"
} else {
"系统始终没有搜索到热点 ${wifi.ssid}。请确认:" +
"① 电脑上 QFT 接收页仍开着且显示 Direct 已启动;" +
"② 手机 Wi-Fi 列表里能看到这个名字;" +
"③ 电脑与手机距离不要太远。"
}
)
} }
override fun onLost(network: Network) { override fun onLost(network: Network) {
if (run != generation || !delivered.get() || !terminal.compareAndSet(false, true)) return if (run != generation || terminal.get() || currentNetwork != network) return
Log.w(TAG, "attempt=$run network lost network=$network") Log.w(TAG, "attempt=$run network lost network=$network")
if (run == generation && delivered.get()) onUnavailable("QFT 临时网络已断开") currentNetwork = null
delivered.set(false)
// requestNetwork stays registered. Android can therefore
// deliver a replacement Network without another system picker;
// range/chunk retries wait for and then use that new handle.
notifyStatus("QFT 网络短暂波动,正在保持会话并自动恢复…")
} }
} }
callback = cb callback = cb
@@ -130,26 +216,37 @@ class WifiConnector(context: Context) {
// system sheet; otherwise keep this request alive while our page // system sheet; otherwise keep this request alive while our page
// continues to show connection progress. // continues to show connection progress.
connectivity.requestNetwork(request, cb) connectivity.requestNetwork(request, cb)
handler.postDelayed({ scheduleWaitHints(run, wifi.ssid)
if (run == generation && !terminal.get() && !delivered.get()) {
onStatus("仍在等待系统完成配网…")
}
}, 8_000)
} catch (e: Exception) { } catch (e: Exception) {
callback = null callback = null
onUnavailable("系统配网请求失败:${e.message}") pendingSsid = null
notifyUnavailable("系统配网请求失败:${e.message}")
} }
} }
/**
* 弹窗久久不出结果时逐级给出更具体的提示。
* 截图里那种「弹窗一直转圈」的情况,光说「仍在等待系统完成配网」
* 完全没有指导意义——真正的原因通常是电脑侧热点没起来。
*/
private fun scheduleWaitHints(run: Int, ssid: String) {
fun pending(): Boolean =
run == generation && pendingTerminal?.get() == false && pendingDelivered?.get() == false
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke("仍在等待系统完成配网…")
}, 4_000)
handler.postDelayed({
if (pending()) listener?.onStatus?.invoke(
"系统仍在搜索 $ssid。若弹窗里一直没出现这个名字," +
"多半是电脑侧热点没启动——请检查 Windows 上 QFT 接收页是否显示 Direct 已就绪。"
)
}, 20_000)
}
@Suppress("DEPRECATION", "MissingPermission") @Suppress("DEPRECATION", "MissingPermission")
private fun connectLegacy( private fun connectLegacy(run: Int, wifi: WifiCredentials) {
run: Int, notifyStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
try { try {
if (!wifiManager.isWifiEnabled) { if (!wifiManager.isWifiEnabled) {
wifiManager.isWifiEnabled = true wifiManager.isWifiEnabled = true
@@ -168,13 +265,13 @@ class WifiConnector(context: Context) {
wifiManager.addNetwork(config) wifiManager.addNetwork(config)
} }
if (targetId < 0) { if (targetId < 0) {
onUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。") notifyUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
return return
} }
legacyTargetNetworkId = targetId legacyTargetNetworkId = targetId
wifiManager.disconnect() wifiManager.disconnect()
if (!wifiManager.enableNetwork(targetId, true)) { if (!wifiManager.enableNetwork(targetId, true)) {
onUnavailable("系统拒绝启用 QFT Wi-Fi 网络") notifyUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
return return
} }
wifiManager.reconnect() wifiManager.reconnect()
@@ -186,20 +283,21 @@ class WifiConnector(context: Context) {
if (matches) { if (matches) {
val network = bestWifiNetwork() val network = bestWifiNetwork()
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) { if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
onStatus("QFT Wi-Fi 已连接,正在快速发现电脑…") notifyStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
onAvailable(network) currentNetwork = network
notifyAvailable(network)
return return
} }
} }
if (SystemClock.elapsedRealtime() - started > 15_000) { if (SystemClock.elapsedRealtime() - started > 15_000) {
onUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。") notifyUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
} else { } else {
handler.postDelayed({ poll() }, 250) handler.postDelayed({ poll() }, 250)
} }
} }
handler.postDelayed({ poll() }, 250) handler.postDelayed({ poll() }, 250)
} catch (e: Exception) { } catch (e: Exception) {
onUnavailable("Android 7~9 配网失败:${e.message}") notifyUnavailable("Android 7~9 配网失败:${e.message}")
} }
} }
@@ -229,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) {
@@ -316,6 +530,11 @@ class WifiConnector(context: Context) {
try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {} try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {}
} }
callback = null callback = null
currentNetwork = null
listener = null
pendingSsid = null
pendingDelivered = null
pendingTerminal = null
handler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
if (restoreLegacy && Build.VERSION.SDK_INT < 29) { if (restoreLegacy && Build.VERSION.SDK_INT < 29) {
val previous = legacyPreviousNetworkId val previous = legacyPreviousNetworkId
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="qft_downloads" path="Download/QFT/" />
</paths>
@@ -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)
}
}
Binary file not shown.
+1 -1
View File
@@ -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
+20 -2
View File
@@ -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.0-rc6" 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"
+6 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "qft-windows" name = "qft-desktop"
version = "0.4.0-rc6" 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",
] } ] }
+798
View File
@@ -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);
}
}
+425
View File
@@ -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, "每次生成的秘密必须不同");
}
}
+196
View File
@@ -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();
}
}
}
+201
View File
@@ -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");
}
}
+750
View File
@@ -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
View File
File diff suppressed because it is too large Load Diff
+424
View File
@@ -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()));
}
}
+293
View File
@@ -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]> {
+15 -2
View File
@@ -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 },
@@ -34,6 +37,7 @@ pub enum ReceiverEvent {
#[derive(Debug)] #[derive(Debug)]
struct UploadSession { struct UploadSession {
upload_key: Option<String>,
device: String, device: String,
file_name: String, file_name: String,
size: u64, size: u64,
@@ -56,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<()>>,
@@ -73,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();
@@ -80,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.
@@ -124,16 +141,33 @@ 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() {
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); 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) => {}
Err(_) => break, Err(_) => break,
} }
@@ -144,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),
}) })
} }
@@ -161,14 +196,73 @@ 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,
) -> Result<()> { ) -> Result<()> {
// The listener is non-blocking so the UI can poll for shutdown. On
// Windows an accepted socket may retain that mode, which made a body read
// race the next Wi-Fi Direct packet and fail with WSAEWOULDBLOCK (10035).
// File requests must instead wait under the explicit socket timeouts.
stream.set_nonblocking(false)?;
stream.set_nodelay(true).ok(); stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_secs(120)))?; stream.set_read_timeout(Some(Duration::from_secs(120)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?; stream.set_write_timeout(Some(Duration::from_secs(120)))?;
@@ -194,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");
@@ -244,14 +343,39 @@ 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!("文件分块数过大") }
let total_chunks = total_chunks_u64 as u32; let total_chunks = total_chunks_u64 as u32;
let upload_key = headers.get("x-qft-upload-key")
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty() && value.len() <= 128);
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
// init is idempotent: if the response packet was lost, the Android client
// may repeat init. Return the existing session so already received chunks
// and the preallocated file are preserved instead of leaking a second part.
for (existing_id, existing) in map.iter() {
if let Ok(session) = existing.lock() {
if upload_key.is_some() && session.upload_key == upload_key {
let missing: Vec<usize> = session.received.iter().enumerate()
.filter_map(|(index, received)| if *received { None } else { Some(index) })
.collect();
let body = json!({
"ok": true,
"upload_id": existing_id,
"chunk_size": session.chunk_size,
"total_chunks": session.total_chunks,
"resumed": true,
"missing": missing,
}).to_string();
return write_response(stream, 200, "application/json", body.as_bytes());
}
}
}
let upload_id = random_id(); let upload_id = random_id();
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
let final_path = unique_path_reserved(save_dir, &file_name, map.values()); let final_path = unique_path_reserved(save_dir, &file_name, map.values());
let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin"); let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin");
let part_path = final_path.with_file_name(format!("{final_name}.{upload_id}.qftpart")); let part_path = final_path.with_file_name(format!("{final_name}.{upload_id}.qftpart"));
@@ -261,6 +385,7 @@ fn init_parallel_upload(
drop(part); drop(part);
let session = UploadSession { let session = UploadSession {
upload_key,
device: device.to_owned(), device: device.to_owned(),
file_name: file_name.clone(), file_name: file_name.clone(),
size, size,
@@ -333,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.flush()?;
let received = { let received = {
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?; let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
@@ -384,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("完成文件重命名失败")?;
@@ -572,3 +700,65 @@ fn hex(bytes: &[u8]) -> String {
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); } for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
out out
} }
#[cfg(test)]
mod tests {
use super::*;
use std::{
io::{Read, Write},
net::TcpListener,
sync::mpsc,
time::{SystemTime, UNIX_EPOCH},
};
#[test]
fn legacy_upload_waits_for_a_delayed_body_on_a_nonblocking_accepted_socket() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let dir = std::env::temp_dir().join(format!(
"qft-receiver-test-{}-{}",
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(),
));
fs::create_dir_all(&dir).unwrap();
let dir_for_server = dir.clone();
let (events, _updates) = mpsc::channel();
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
// This matches the Windows mode inheritance that previously made
// the body read return WSAEWOULDBLOCK between TCP packets.
stream.set_nonblocking(true).unwrap();
handle_client(
&mut stream,
&dir_for_server,
"session",
"000000",
&AtomicU32::new(0),
&events,
&sessions,
&completed,
)
});
let mut client = TcpStream::connect(address).unwrap();
client
.write_all(
b"POST /qft/upload HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\nContent-Length: 4\r\nX-QFT-Size: 4\r\n\r\n",
)
.unwrap();
client.flush().unwrap();
thread::sleep(Duration::from_millis(50));
client.write_all(b"qft!").unwrap();
client.flush().unwrap();
let mut response = String::new();
client.read_to_string(&mut response).unwrap();
server.join().unwrap().unwrap();
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
assert_eq!(fs::read(dir.join("qft-upload.bin")).unwrap(), b"qft!");
let _ = fs::remove_dir_all(dir);
}
}
+501
View File
@@ -0,0 +1,501 @@
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use serde_json::json;
use std::{
collections::HashMap,
fs::File,
io::{BufRead, BufReader, Read, Write},
net::{TcpListener, TcpStream, UdpSocket},
path::PathBuf,
sync::{
atomic::{AtomicBool, Ordering},
mpsc::Sender,
Arc,
},
thread::{self, JoinHandle},
time::Duration,
};
pub const PREFERRED_PORT: u16 = 39393;
pub const DISCOVERY_PORT: u16 = 39392;
const IO_BUFFER: usize = 1024 * 1024;
#[derive(Clone, Debug)]
pub enum SenderEvent {
TransportConnected { peer: String },
ClientConnected { device: String },
DownloadStarted { device: String, file_name: String, size: u64 },
DownloadCompleted { device: String, file_name: String },
Error(String),
}
/// A short-lived, token-protected local HTTP server for PC → Android transfer.
/// The actual file remains on disk and is streamed only after a phone scans the
/// QFTSEND2 QR, joins the advertised local network, and presents that token.
pub struct SenderServer {
pub port: u16,
stop: Arc<AtomicBool>,
tcp_thread: Option<JoinHandle<()>>,
udp_thread: Option<JoinHandle<()>>,
}
impl SenderServer {
pub fn start(file_path: PathBuf, session_token: String, events: Sender<SenderEvent>) -> Result<Self> {
let file_name = file_path.file_name()
.and_then(|v| v.to_str())
.filter(|v| !v.is_empty())
.unwrap_or("qft-download.bin")
.to_owned();
let size = std::fs::metadata(&file_path)
.with_context(|| format!("读取发送文件 {} 失败", file_path.display()))?
.len();
let listener = TcpListener::bind(("0.0.0.0", PREFERRED_PORT))
.or_else(|_| TcpListener::bind(("0.0.0.0", 0)))
.context("启动本地发送端口失败")?;
let port = listener.local_addr()?.port();
listener.set_nonblocking(true)?;
let stop = Arc::new(AtomicBool::new(false));
let tcp_stop = stop.clone();
let tcp_token = session_token.clone();
let tcp_events = events.clone();
let tcp_thread = thread::spawn(move || {
while !tcp_stop.load(Ordering::Relaxed) {
match listener.accept() {
Ok((mut stream, peer)) => {
let _ = tcp_events.send(SenderEvent::TransportConnected { peer: peer.to_string() });
let token = tcp_token.clone();
let path = file_path.clone();
let name = file_name.clone();
let tx = tcp_events.clone();
thread::spawn(move || {
if let Err(e) = handle_client(&mut stream, &path, &name, size, &token, &tx) {
let message = format!("向手机发送失败:{e:#}");
let _ = write_response(&mut stream, 500, "text/plain", message.as_bytes());
let _ = tx.send(SenderEvent::Error(message));
}
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(12)),
Err(e) => {
let _ = tcp_events.send(SenderEvent::Error(format!("发送端口监听失败:{e}")));
break;
}
}
}
});
let udp_stop = stop.clone();
let udp_thread = thread::spawn(move || {
let socket = match UdpSocket::bind(("0.0.0.0", DISCOVERY_PORT)) {
Ok(v) => v,
Err(e) => {
let _ = events.send(SenderEvent::Error(format!("快速发现端口 {DISCOVERY_PORT} 不可用:{e}")));
return;
}
};
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
let response = format!("QFTHERE2:{session_token}:{port}");
let mut buf = [0u8; 512];
while !udp_stop.load(Ordering::Relaxed) {
match socket.recv_from(&mut buf) {
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);
}
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
Err(_) => break,
}
}
});
Ok(Self { port, stop, tcp_thread: Some(tcp_thread), udp_thread: Some(udp_thread) })
}
}
impl Drop for SenderServer {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.tcp_thread.take() { let _ = handle.join(); }
if let Some(handle) = self.udp_thread.take() { let _ = handle.join(); }
}
}
fn handle_client(
stream: &mut TcpStream,
file_path: &PathBuf,
file_name: &str,
size: u64,
token: &str,
events: &Sender<SenderEvent>,
) -> 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_read_timeout(Some(Duration::from_secs(20)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
let cloned = stream.try_clone()?;
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();
// 读到 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!("请求行过长") }
let mut headers = HashMap::<String, String>::new();
loop {
let mut line = String::new();
let n = reader.read_line(&mut line)?;
if n == 0 { return Ok(KeepAlive::Close) }
if line == "\r\n" || line == "\n" { break }
if line.len() > 16 * 1024 { bail!("请求头过长") }
if let Some((k, v)) = line.split_once(':') {
headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned());
}
}
let mut parts = request_line.split_whitespace();
let method = 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 {
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 _ = events.send(SenderEvent::ClientConnected { device: device.clone() });
if method == "GET" && path == "/qft/ping" {
let body = json!({"ok": true, "protocol": 2, "direction": "download"}).to_string();
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" {
write_response(stream, 404, "text/plain", b"not found")?;
return Ok(KeepAlive::Close);
}
let mut input = File::open(file_path)
.with_context(|| format!("发送文件已不可读取:{}", file_path.display()))?;
if input.metadata()?.len() != size {
bail!("发送文件在二维码生成后发生变化,请重新选择文件并生成二维码")
}
let range = parse_range(headers.get("range"), size)?;
let offset = range.start;
let end = range.end;
let remaining = if size == 0 { 0 } else { end.saturating_sub(offset).saturating_add(1) };
let _ = events.send(SenderEvent::DownloadStarted { device: device.clone(), file_name: file_name.to_owned(), size });
if headers.get("range").is_none() {
write!(stream,
"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()),
)?;
} else {
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: {connection_header}\r\nX-QFT-Filename: {}\r\n\r\n",
size,
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
)?;
}
use std::io::{Seek, SeekFrom};
input.seek(SeekFrom::Start(offset))?;
let mut buf = vec![0u8; IO_BUFFER];
let mut left = remaining;
while left > 0 {
let want = left.min(buf.len() as u64) as usize;
let n = input.read(&mut buf[..want])?;
if n == 0 { bail!("发送文件读取提前结束:还缺 {left} 字节") }
stream.write_all(&buf[..n])?;
left -= n as u64;
}
stream.flush()?;
let _ = events.send(SenderEvent::DownloadCompleted { device, file_name: file_name.to_owned() });
Ok(if keep_alive { KeepAlive::Continue } else { KeepAlive::Close })
}
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
let reason = match code { 200 => "OK", 403 => "Forbidden", 404 => "Not Found", _ => "Error" };
write!(stream, "HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len())?;
stream.write_all(body)?;
stream.flush()?;
Ok(())
}
fn decode_header(value: Option<&String>) -> Option<String> {
let bytes = URL_SAFE_NO_PAD.decode(value?).ok()?;
String::from_utf8(bytes).ok()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ByteRange {
start: u64,
end: u64,
}
fn parse_range(value: Option<&String>, size: u64) -> Result<ByteRange> {
if size == 0 {
if value.is_some() { bail!("空文件没有可下载的字节范围") }
return Ok(ByteRange { start: 0, end: 0 });
}
let Some(value) = value else { return Ok(ByteRange { start: 0, end: size - 1 }) };
let suffix = value.trim().strip_prefix("bytes=").context("Range 格式无效")?;
let (start_text, end_text) = suffix.split_once('-').context("Range 格式无效")?;
if start_text.is_empty() { bail!("不支持后缀 Range") }
let start = start_text.parse::<u64>().context("Range 起点无效")?;
let end = if end_text.is_empty() {
size - 1
} else {
end_text.parse::<u64>().context("Range 终点无效")?
};
if start >= size || end >= size || end < start { bail!("Range 超出文件范围") }
Ok(ByteRange { start, end })
}
#[cfg(test)]
mod tests {
use super::{handle_client, parse_range, ByteRange, SenderEvent};
use std::{
fs,
io::{Read, Write},
net::{TcpListener, TcpStream},
sync::mpsc,
thread,
time::Duration,
};
#[test]
fn accepts_open_and_bounded_byte_ranges() {
assert_eq!(parse_range(None, 10).unwrap(), ByteRange { start: 0, end: 9 });
assert_eq!(parse_range(None, 0).unwrap(), ByteRange { start: 0, end: 0 });
assert_eq!(parse_range(Some(&"bytes=4-".to_owned()), 10).unwrap(), ByteRange { start: 4, end: 9 });
assert_eq!(parse_range(Some(&"bytes=2-6".to_owned()), 10).unwrap(), ByteRange { start: 2, end: 6 });
assert!(parse_range(Some(&"bytes=10-".to_owned()), 10).is_err());
assert!(parse_range(Some(&"bytes=6-2".to_owned()), 10).is_err());
assert!(parse_range(Some(&"bytes=-4".to_owned()), 10).is_err());
assert!(parse_range(Some(&"items=4-".to_owned()), 10).is_err());
}
#[test]
fn download_endpoint_returns_the_requested_range() {
let path = std::env::temp_dir().join(format!("qft-sender-{}-range.bin", std::process::id()));
fs::write(&path, b"abcdef").unwrap();
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 || {
for _ in 0..3 {
let (mut stream, _) = listener.accept().unwrap();
handle_client(&mut stream, &path_for_server, "range.bin", 6, "session", &events).unwrap();
}
});
let full = request(address, None);
assert_response(&full, "HTTP/1.1 200 OK", "abcdef");
let resumed = request(address, Some("bytes=2-"));
assert_response(&resumed, "HTTP/1.1 206 Partial Content", "cdef");
let header = String::from_utf8_lossy(&resumed[..header_end(&resumed)]);
assert!(header.contains("Content-Range: bytes 2-5/6"));
let bounded = request(address, Some("bytes=2-4"));
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();
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> {
let mut stream = TcpStream::connect(address).unwrap();
write!(
stream,
"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(),
).unwrap();
stream.flush().unwrap();
let mut bytes = Vec::new();
stream.read_to_end(&mut bytes).unwrap();
bytes
}
fn assert_response(response: &[u8], status: &str, body: &str) {
let end = header_end(response);
assert!(String::from_utf8_lossy(&response[..end]).starts_with(status));
assert_eq!(&response[end..], body.as_bytes());
}
fn header_end(bytes: &[u8]) -> usize {
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();
}
}
+1 -1
View File
@@ -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 在局域网下是亚秒级。光学链路应明确定位为**物理隔离场景专用**,
并在选择大文件时主动提示直传方案与两者的预计耗时对比。 并在选择大文件时主动提示直传方案与两者的预计耗时对比。
+16 -4
View File
@@ -1,4 +1,4 @@
# QFT protocol notes — v0.4.0-rc2 # 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 rc2 ### 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,4 +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.
## 5. Windows → Android 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:
```text
Range: bytes=<start>-<end>
```
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`.
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.
+219
View File
@@ -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。
+297
View File
@@ -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 -1
View File
@@ -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 把两端的契约固定下来,
+76 -64
View File
@@ -7,35 +7,35 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */; };
38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5459D124A555B0E4121361E5 /* PairingProtocol.swift */; };
4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */; };
554512A1FC8A6F66E2784787 /* QFTApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 453B172D654B3AEDE4E36D1E /* QFTApp.swift */; }; 554512A1FC8A6F66E2784787 /* QFTApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 453B172D654B3AEDE4E36D1E /* QFTApp.swift */; };
6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */; };
78FD5CF5E04D7E2483B90BAA /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */; }; 78FD5CF5E04D7E2483B90BAA /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */; };
978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA81C375609633BD8DB42F3 /* DownloadClient.swift */; };
A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD16686BB19417EDC0B611A /* PeerLink.swift */; };
BDCF0D82F0BD0328770A8ABD /* ScannerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3B15455554D7647B44D5038 /* ScannerView.swift */; }; BDCF0D82F0BD0328770A8ABD /* ScannerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3B15455554D7647B44D5038 /* ScannerView.swift */; };
C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C628A05E9C83375781E165EB /* Assets.xcassets */; };
E26487D1146FDF6DD5F92D80 /* TransferModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3017489412A6FCAE8995B32E /* TransferModel.swift */; }; E26487D1146FDF6DD5F92D80 /* TransferModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3017489412A6FCAE8995B32E /* TransferModel.swift */; };
EE5510DAC5BBB7F9D41A8F26 /* Base64URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848334DC6B2D30622C7E2A45 /* Base64URL.swift */; }; EE5510DAC5BBB7F9D41A8F26 /* Base64URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848334DC6B2D30622C7E2A45 /* Base64URL.swift */; };
38E462342111ACFA8775D17B /* PairingProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5459D124A555B0E4121361E5 /* PairingProtocol.swift */; };
6B2EB3BCEDA4855168DB4ACE /* HostDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */; };
978F01FFFFF69591E44C8528 /* DownloadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAA81C375609633BD8DB42F3 /* DownloadClient.swift */; };
0469B1106E6746B3BE56007D /* UploadClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */; };
4D2B05655C76F69F32349834 /* PeerPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */; };
A80B2E7BF8035E27D115EF59 /* PeerLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DD16686BB19417EDC0B611A /* PeerLink.swift */; };
C0C0B5440A627CE758643A9F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C628A05E9C83375781E165EB /* Assets.xcassets */; };
/* End PBXBuildFile section */ /* End PBXBuildFile section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
928818DCDA72C62B2D8288D5 /* QFT.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QFT.app; sourceTree = BUILT_PRODUCTS_DIR; };
453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = "<group>"; };
0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = "<group>"; };
3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = "<group>"; };
848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = "<group>"; };
5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = "<group>"; };
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = "<group>"; };
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = "<group>"; };
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadClient.swift; sourceTree = "<group>"; };
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerPairing.swift; sourceTree = "<group>"; }; 06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerPairing.swift; sourceTree = "<group>"; };
8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = "<group>"; }; 0B6863D13BC7270D7FCE21E7 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; }; 3017489412A6FCAE8995B32E /* TransferModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransferModel.swift; sourceTree = "<group>"; };
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDiscovery.swift; sourceTree = "<group>"; };
453B172D654B3AEDE4E36D1E /* QFTApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QFTApp.swift; sourceTree = "<group>"; };
5459D124A555B0E4121361E5 /* PairingProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingProtocol.swift; sourceTree = "<group>"; };
7E4A60F8CA5D515103446ED3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 7E4A60F8CA5D515103446ED3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
848334DC6B2D30622C7E2A45 /* Base64URL.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Base64URL.swift; sourceTree = "<group>"; };
8DD16686BB19417EDC0B611A /* PeerLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeerLink.swift; sourceTree = "<group>"; };
928818DCDA72C62B2D8288D5 /* QFT.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = QFT.app; sourceTree = BUILT_PRODUCTS_DIR; };
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadClient.swift; sourceTree = "<group>"; };
C628A05E9C83375781E165EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadClient.swift; sourceTree = "<group>"; };
F3B15455554D7647B44D5038 /* ScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScannerView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */ /* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */ /* Begin PBXFrameworksBuildPhase section */
@@ -60,20 +60,6 @@
path = App; path = App;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EC599E8CF455428A5E3179CE /* Core */ = {
isa = PBXGroup;
children = (
848334DC6B2D30622C7E2A45 /* Base64URL.swift */,
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */,
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */,
5459D124A555B0E4121361E5 /* PairingProtocol.swift */,
8DD16686BB19417EDC0B611A /* PeerLink.swift */,
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */,
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */,
);
path = Core;
sourceTree = "<group>";
};
36EDFB66685EBD501D3910CE /* QFT */ = { 36EDFB66685EBD501D3910CE /* QFT */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
@@ -101,12 +87,26 @@
name = Products; name = Products;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
EC599E8CF455428A5E3179CE /* Core */ = {
isa = PBXGroup;
children = (
848334DC6B2D30622C7E2A45 /* Base64URL.swift */,
EAA81C375609633BD8DB42F3 /* DownloadClient.swift */,
3776FFCC2817EF6BF3EEC4FD /* HostDiscovery.swift */,
5459D124A555B0E4121361E5 /* PairingProtocol.swift */,
8DD16686BB19417EDC0B611A /* PeerLink.swift */,
06E1A38EC22BBFED928C8EB6 /* PeerPairing.swift */,
B8FB8A4A9482DB8F1234AE39 /* UploadClient.swift */,
);
path = Core;
sourceTree = "<group>";
};
/* End PBXGroup section */ /* End PBXGroup section */
/* Begin PBXNativeTarget section */ /* Begin PBXNativeTarget section */
497CBF7ECF21FFA362230876 /* QFT */ = { 497CBF7ECF21FFA362230876 /* QFT */ = {
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = A886B50DF087AEF7B87CDC65; buildConfigurationList = A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */;
buildPhases = ( buildPhases = (
C2511B36F0F0E810A9E46328 /* Sources */, C2511B36F0F0E810A9E46328 /* Sources */,
019BAB185F97B56993A7087D /* Frameworks */, 019BAB185F97B56993A7087D /* Frameworks */,
@@ -136,7 +136,7 @@
}; };
}; };
}; };
buildConfigurationList = 26E84C2B3712F7DFAC8AD93F; buildConfigurationList = 26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */;
compatibilityVersion = "Xcode 14.0"; compatibilityVersion = "Xcode 14.0";
developmentRegion = en; developmentRegion = en;
hasScannedForEncodings = 0; hasScannedForEncodings = 0;
@@ -188,6 +188,29 @@
/* End PBXSourcesBuildPhase section */ /* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */ /* Begin XCBuildConfiguration section */
032222C0BAA33BC7119DFAF1 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 47;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.4.7;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
70DCC1EB255A5F3C8D9ED349 /* Debug */ = { 70DCC1EB255A5F3C8D9ED349 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
@@ -203,8 +226,11 @@
ENABLE_TESTABILITY = YES; ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES; GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0; GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1 $(inherited)"; GCC_PREPROCESSOR_DEFINITIONS = (
IPHONEOS_DEPLOYMENT_TARGET = 17.0; "DEBUG=1",
"$(inherited)",
);
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
@@ -215,25 +241,6 @@
}; };
name = Debug; name = Debug;
}; };
DB189EBE9D4E38495C3C7EF5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = QFT/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
MARKETING_VERSION = 0.1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.qft.transfer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
C3DCEEC1E0EB17A5583B8E94 /* Release */ = { C3DCEEC1E0EB17A5583B8E94 /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
@@ -248,9 +255,10 @@
ENABLE_NS_ASSERTIONS = NO; ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_NO_COMMON_BLOCKS = YES; GCC_NO_COMMON_BLOCKS = YES;
IPHONEOS_DEPLOYMENT_TARGET = 17.0; IPHONEOS_DEPLOYMENT_TARGET = 18.6;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos; SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule; SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
@@ -258,29 +266,33 @@
}; };
name = Release; name = Release;
}; };
032222C0BAA33BC7119DFAF1 /* Release */ = { DB189EBE9D4E38495C3C7EF5 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
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 = 1; 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;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 18.6;
MARKETING_VERSION = 0.1.0; LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
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;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
}; };
name = Release; name = Debug;
}; };
/* End XCBuildConfiguration section */ /* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */ /* Begin XCConfigurationList section */
26E84C2B3712F7DFAC8AD93F = { 26E84C2B3712F7DFAC8AD93F /* Build configuration list for PBXProject "QFT" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
70DCC1EB255A5F3C8D9ED349 /* Debug */, 70DCC1EB255A5F3C8D9ED349 /* Debug */,
@@ -289,7 +301,7 @@
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
A886B50DF087AEF7B87CDC65 = { A886B50DF087AEF7B87CDC65 /* Build configuration list for PBXNativeTarget "QFT" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
DB189EBE9D4E38495C3C7EF5 /* Debug */, DB189EBE9D4E38495C3C7EF5 /* Debug */,
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
+1 -1
View File
@@ -1,4 +1,4 @@
# QFT iOS 客户端 v0.1.0 # QFT iOS 客户端 v0.4.7
三种传输方式: 三种传输方式:
+2 -2
View File
@@ -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.1.0" 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 = 1", "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",
+85
View File
@@ -0,0 +1,85 @@
@echo off
chcp 65001 >nul
setlocal EnableExtensions DisableDelayedExpansion
cd /d "%~dp0"
echo == QFT 正式版中文打包 ==
where cargo >nul 2>nul
if errorlevel 1 (
echo 错误:PATH 中未找到 Rust cargo。
exit /b 1
)
echo [1/4] 测试并构建 Windows 正式版...
pushd desktop
cargo test --locked
if errorlevel 1 (popd & exit /b 1)
cargo build --release --locked
if errorlevel 1 (popd & exit /b 1)
popd
for /f "tokens=3" %%V in ('findstr /R /C:"^version =" "desktop\Cargo.toml"') do set "QFT_VERSION=%%~V"
for /f "tokens=3" %%V in ('findstr /R /C:"^[ ]*versionName =" "android\app\build.gradle.kts"') do set "QFT_ANDROID_VERSION=%%~V"
for /f "tokens=3" %%V in ('findstr /R /C:"^[ ]*versionCode =" "android\app\build.gradle.kts"') do set "QFT_ANDROID_CODE=%%V"
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_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%"
echo [2/4] 收集正式版文件...
mkdir "%QFT_PACKAGE_DIR%" || exit /b 1
copy /y "desktop\target\release\qft-desktop.exe" "%QFT_PACKAGE_DIR%\QFT超速文件传输.exe" >nul || exit /b 1
copy /y "README.md" "%QFT_PACKAGE_DIR%\使用说明.md" >nul || exit /b 1
copy /y "TEST_REPORT.md" "%QFT_PACKAGE_DIR%\测试报告.md" >nul || exit /b 1
copy /y "docs\PROTOCOL.md" "%QFT_PACKAGE_DIR%\传输协议.md" >nul || exit /b 1
copy /y "RELEASE_NOTES_%QFT_VERSION%.md" "%QFT_PACKAGE_DIR%\版本说明.md" >nul || exit /b 1
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 ^
"$dir = [IO.Path]::GetFullPath('%QFT_PACKAGE_DIR%');" ^
"Compress-Archive -LiteralPath $dir -DestinationPath ($dir + '.zip') -Force"
if errorlevel 1 exit /b 1
echo.
echo 封版打包完成
echo 文件夹:%QFT_PACKAGE_DIR%
echo 压缩包:%QFT_PACKAGE_DIR%.zip
exit /b 0
Executable
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env sh
set -eu
QFT_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$QFT_ROOT"
echo "== QFT 正式版中文打包 =="
if ! command -v cargo >/dev/null 2>&1; then
# rustup 装在 keg-only 目录里时不会自动进 PATH,这里兜一下,
# 避免用户明明装了工具链却被告知"没装"。
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
}
echo "[1/4] 测试并构建桌面正式版..."
(
cd desktop
cargo test --locked
cargo build --release --locked
)
QFT_VERSION=$(awk -F'"' '/^\[package\]/{package=1; next} package && /^version[[:space:]]*=/{print $2; exit} /^\[/{package=0}' desktop/Cargo.toml)
[ -n "$QFT_VERSION" ] || QFT_VERSION=unknown
QFT_STAMP=$(date '+%Y%m%d-%H%M%S')
QFT_PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
QFT_ARCH=$(uname -m)
QFT_PACKAGE="QFT-正式版-v${QFT_VERSION}-${QFT_PLATFORM}-${QFT_ARCH}-${QFT_STAMP}"
QFT_PACKAGE_DIR="$QFT_ROOT/dist/$QFT_PACKAGE"
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"
if [ -f "desktop/target/release/qft-desktop.exe" ]; then
cp "desktop/target/release/qft-desktop.exe" "$QFT_PACKAGE_DIR/QFT超速文件传输.exe"
elif [ -f "desktop/target/release/qft-desktop" ]; then
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
echo "ERROR: desktop release binary was not produced." >&2
exit 1
fi
cp README.md "$QFT_PACKAGE_DIR/使用说明.md"
cp TEST_REPORT.md "$QFT_PACKAGE_DIR/测试报告.md"
cp docs/PROTOCOL.md "$QFT_PACKAGE_DIR/传输协议.md"
cp "RELEASE_NOTES_${QFT_VERSION}.md" "$QFT_PACKAGE_DIR/版本说明.md"
# 只收集已经存在的 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"
# 只对普通文件求校验和:.app 是目录,直接喂给 sha256sum 会报错
if command -v sha256sum >/dev/null 2>&1; then
find . -type f ! -name SHA256校验.txt | sort | xargs sha256sum > SHA256校验.txt
else
find . -type f ! -name SHA256校验.txt | sort | xargs shasum -a 256 > SHA256校验.txt
fi
)
echo "[4/4] 创建中文压缩包..."
tar -C "$QFT_ROOT/dist" -czf "$QFT_PACKAGE_DIR.tar.gz" "$QFT_PACKAGE"
echo
echo "封版打包完成"
echo "文件夹:$QFT_PACKAGE_DIR"
echo "压缩包:$QFT_PACKAGE_DIR.tar.gz"
+12 -2
View File
@@ -4,7 +4,9 @@ import re
ROOT=Path(__file__).resolve().parents[1] ROOT=Path(__file__).resolve().parents[1]
gradle=(ROOT/'android/app/build.gradle.kts').read_text(); manifest=(ROOT/'android/app/src/main/AndroidManifest.xml').read_text() gradle=(ROOT/'android/app/build.gradle.kts').read_text(); manifest=(ROOT/'android/app/src/main/AndroidManifest.xml').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() 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()
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
@@ -12,7 +14,12 @@ assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest and 'NEARB
assert 'networkSecurityConfig="@xml/network_security_config"' in manifest and 'cleartextTrafficPermitted="true"' in security assert 'networkSecurityConfig="@xml/network_security_config"' in manifest and 'cleartextTrafficPermitted="true"' in security
assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload
assert 'val targetSize = Size(640, 480)' in main and 'Size(960, 540)' not in main 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 '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
@@ -21,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')
+2 -2
View File
@@ -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())
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Bounded Range + retry + out-of-order positioned-write download self-test."""
import hashlib
import http.client
import random
import tempfile
import threading
from concurrent.futures import ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
SIZE = 64 * 1024 * 1024 + 12345
CHUNK = 16 * 1024 * 1024
WORKERS = 8
TOKEN = "parallel_download_test"
def digest(path):
value = hashlib.sha256()
with open(path, "rb", buffering=0) as stream:
while block := stream.read(4 * 1024 * 1024):
value.update(block)
return value.hexdigest()
def main():
assert (1024 * 1024 * 1024 + CHUNK - 1) // CHUNK == 64
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
source = root / "source.bin"
target = root / "target.qftpart"
pattern = bytes((index * 73 + 19) & 0xFF for index in range(1024 * 1024))
with source.open("wb", buffering=0) as stream:
remaining = SIZE
while remaining:
block = pattern[:min(len(pattern), remaining)]
stream.write(block)
remaining -= len(block)
with target.open("wb") as stream:
stream.truncate(SIZE)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
if self.path != "/qft/download" or self.headers.get("X-QFT-Token") != TOKEN:
self.send_error(403)
return
value = self.headers.get("Range", "")
assert value.startswith("bytes=") and "-" in value
start_text, end_text = value[6:].split("-", 1)
start, end = int(start_text), int(end_text)
assert 0 <= start <= end < SIZE
length = end - start + 1
self.send_response(206)
self.send_header("Content-Length", str(length))
self.send_header("Content-Range", f"bytes {start}-{end}/{SIZE}")
self.end_headers()
with source.open("rb", buffering=0) as stream:
stream.seek(start)
remaining = length
while remaining:
block = stream.read(min(1024 * 1024, remaining))
assert block
self.wfile.write(block)
remaining -= len(block)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
host, port = server.server_address
indices = list(range((SIZE + CHUNK - 1) // CHUNK))
random.Random(42).shuffle(indices)
def receive(index):
start = index * CHUNK
end = min(SIZE, start + CHUNK) - 1
connection = http.client.HTTPConnection(host, port, timeout=10)
connection.request("GET", "/qft/download", headers={
"X-QFT-Token": TOKEN,
"Range": f"bytes={start}-{end}",
})
response = connection.getresponse()
assert response.status == 206
assert response.getheader("Content-Range") == f"bytes {start}-{end}/{SIZE}"
offset = start
with target.open("r+b", buffering=0) as output:
output.seek(start)
while block := response.read(1024 * 1024):
assert output.write(block) == len(block)
offset += len(block)
connection.close()
assert offset == end + 1
try:
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
list(pool.map(receive, indices))
finally:
server.shutdown()
server.server_close()
assert digest(source) == digest(target)
print(f"PASS parallel download: {SIZE} bytes, 16 MiB bounded ranges, {WORKERS} workers, SHA-256 identical; 1 GiB maps to 64 resumable ranges")
if __name__ == "__main__":
main()
+1
View File
@@ -7,6 +7,7 @@ scripts = [
'optical_image_decode_selftest.py', 'optical_image_decode_selftest.py',
'pairing_selftest.py', 'pairing_selftest.py',
'parallel_upload_selftest.py', 'parallel_upload_selftest.py',
'parallel_download_selftest.py',
'udp_discovery_selftest.py', 'udp_discovery_selftest.py',
'local_transfer_integration_selftest.py', 'local_transfer_integration_selftest.py',
'memory_budget_selftest.py', 'memory_budget_selftest.py',
+14 -7
View File
@@ -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')
-79
View File
@@ -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
View File
File diff suppressed because it is too large Load Diff
-229
View File
@@ -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);
}
}
-290
View File
@@ -1,290 +0,0 @@
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use serde_json::json;
use std::{
collections::HashMap,
fs::File,
io::{BufRead, BufReader, Read, Write},
net::{TcpListener, TcpStream, UdpSocket},
path::PathBuf,
sync::{
atomic::{AtomicBool, Ordering},
mpsc::Sender,
Arc,
},
thread::{self, JoinHandle},
time::Duration,
};
pub const PREFERRED_PORT: u16 = 39393;
pub const DISCOVERY_PORT: u16 = 39392;
const IO_BUFFER: usize = 1024 * 1024;
#[derive(Clone, Debug)]
pub enum SenderEvent {
ClientConnected { device: String },
DownloadStarted { device: String, file_name: String, size: u64 },
DownloadCompleted { device: String, file_name: String },
Error(String),
}
/// A short-lived, token-protected local HTTP server for PC → Android transfer.
/// The actual file remains on disk and is streamed only after a phone scans the
/// QFTSEND2 QR, joins the advertised local network, and presents that token.
pub struct SenderServer {
pub port: u16,
stop: Arc<AtomicBool>,
tcp_thread: Option<JoinHandle<()>>,
udp_thread: Option<JoinHandle<()>>,
}
impl SenderServer {
pub fn start(file_path: PathBuf, session_token: String, events: Sender<SenderEvent>) -> Result<Self> {
let file_name = file_path.file_name()
.and_then(|v| v.to_str())
.filter(|v| !v.is_empty())
.unwrap_or("qft-download.bin")
.to_owned();
let size = std::fs::metadata(&file_path)
.with_context(|| format!("读取发送文件 {} 失败", file_path.display()))?
.len();
let listener = TcpListener::bind(("0.0.0.0", PREFERRED_PORT))
.or_else(|_| TcpListener::bind(("0.0.0.0", 0)))
.context("启动本地发送端口失败")?;
let port = listener.local_addr()?.port();
listener.set_nonblocking(true)?;
let stop = Arc::new(AtomicBool::new(false));
let tcp_stop = stop.clone();
let tcp_token = session_token.clone();
let tcp_events = events.clone();
let tcp_thread = thread::spawn(move || {
while !tcp_stop.load(Ordering::Relaxed) {
match listener.accept() {
Ok((mut stream, _)) => {
let token = tcp_token.clone();
let path = file_path.clone();
let name = file_name.clone();
let tx = tcp_events.clone();
thread::spawn(move || {
if let Err(e) = handle_client(&mut stream, &path, &name, size, &token, &tx) {
let message = format!("向手机发送失败:{e:#}");
let _ = write_response(&mut stream, 500, "text/plain", message.as_bytes());
let _ = tx.send(SenderEvent::Error(message));
}
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(12)),
Err(e) => {
let _ = tcp_events.send(SenderEvent::Error(format!("发送端口监听失败:{e}")));
break;
}
}
}
});
let udp_stop = stop.clone();
let udp_thread = thread::spawn(move || {
let socket = match UdpSocket::bind(("0.0.0.0", DISCOVERY_PORT)) {
Ok(v) => v,
Err(e) => {
let _ = events.send(SenderEvent::Error(format!("快速发现端口 {DISCOVERY_PORT} 不可用:{e}")));
return;
}
};
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
let expected = format!("QFTDISC2:{session_token}");
let response = format!("QFTHERE2:{session_token}:{port}");
let mut buf = [0u8; 512];
while !udp_stop.load(Ordering::Relaxed) {
match socket.recv_from(&mut buf) {
Ok((n, peer)) if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) => {
let _ = socket.send_to(response.as_bytes(), peer);
}
Ok(_) => {}
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
Err(_) => break,
}
}
});
Ok(Self { port, stop, tcp_thread: Some(tcp_thread), udp_thread: Some(udp_thread) })
}
}
impl Drop for SenderServer {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.tcp_thread.take() { let _ = handle.join(); }
if let Some(handle) = self.udp_thread.take() { let _ = handle.join(); }
}
}
fn handle_client(
stream: &mut TcpStream,
file_path: &PathBuf,
file_name: &str,
size: u64,
token: &str,
events: &Sender<SenderEvent>,
) -> Result<()> {
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_secs(20)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
let cloned = stream.try_clone()?;
let mut reader = BufReader::with_capacity(32 * 1024, cloned);
let mut request_line = String::new();
reader.read_line(&mut request_line)?;
if request_line.len() > 8192 { bail!("请求行过长") }
let mut headers = HashMap::<String, String>::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 line.len() > 16 * 1024 { bail!("请求头过长") }
if let Some((k, v)) = line.split_once(':') {
headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned());
}
}
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("");
let path = parts.next().unwrap_or("");
if headers.get("x-qft-token").map(String::as_str).unwrap_or("") != token {
return write_response(stream, 403, "text/plain", b"invalid session");
}
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
let _ = events.send(SenderEvent::ClientConnected { device: device.clone() });
if method == "GET" && path == "/qft/ping" {
let body = json!({"ok": true, "protocol": 2, "direction": "download"}).to_string();
return write_response(stream, 200, "application/json", body.as_bytes());
}
if method != "GET" || path != "/qft/download" {
return write_response(stream, 404, "text/plain", b"not found");
}
let mut input = File::open(file_path)
.with_context(|| format!("发送文件已不可读取:{}", file_path.display()))?;
if input.metadata()?.len() != size {
bail!("发送文件在二维码生成后发生变化,请重新选择文件并生成二维码")
}
let offset = parse_range_start(headers.get("range"), size)?;
let remaining = size.saturating_sub(offset);
let _ = events.send(SenderEvent::DownloadStarted { device: device.clone(), file_name: file_name.to_owned(), size });
if offset == 0 {
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",
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
)?;
} else {
write!(stream,
"HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {remaining}\r\nContent-Range: bytes {offset}-{}/{}\r\nAccept-Ranges: bytes\r\nConnection: close\r\nX-QFT-Filename: {}\r\n\r\n",
size - 1,
size,
URL_SAFE_NO_PAD.encode(file_name.as_bytes()),
)?;
}
use std::io::{Seek, SeekFrom};
input.seek(SeekFrom::Start(offset))?;
let mut buf = vec![0u8; IO_BUFFER];
loop {
let n = input.read(&mut buf)?;
if n == 0 { break }
stream.write_all(&buf[..n])?;
}
stream.flush()?;
let _ = events.send(SenderEvent::DownloadCompleted { device, file_name: file_name.to_owned() });
Ok(())
}
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
let reason = match code { 200 => "OK", 403 => "Forbidden", 404 => "Not Found", _ => "Error" };
write!(stream, "HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len())?;
stream.write_all(body)?;
stream.flush()?;
Ok(())
}
fn decode_header(value: Option<&String>) -> Option<String> {
let bytes = URL_SAFE_NO_PAD.decode(value?).ok()?;
String::from_utf8(bytes).ok()
}
fn parse_range_start(value: Option<&String>, size: u64) -> Result<u64> {
let Some(value) = value else { return Ok(0) };
let suffix = value.trim().strip_prefix("bytes=").context("Range 格式无效")?;
let start = suffix.strip_suffix('-').context("只支持单段 Range")?
.parse::<u64>().context("Range 起点无效")?;
if start >= size { bail!("Range 超出文件范围") }
Ok(start)
}
#[cfg(test)]
mod tests {
use super::{handle_client, parse_range_start, SenderEvent};
use std::{
fs,
io::{Read, Write},
net::{TcpListener, TcpStream},
sync::mpsc,
thread,
};
#[test]
fn accepts_only_a_valid_resumable_byte_range() {
assert_eq!(parse_range_start(None, 10).unwrap(), 0);
assert_eq!(parse_range_start(Some(&"bytes=4-".to_owned()), 10).unwrap(), 4);
assert!(parse_range_start(Some(&"bytes=10-".to_owned()), 10).is_err());
assert!(parse_range_start(Some(&"bytes=-4".to_owned()), 10).is_err());
assert!(parse_range_start(Some(&"items=4-".to_owned()), 10).is_err());
}
#[test]
fn download_endpoint_returns_the_requested_range() {
let path = std::env::temp_dir().join(format!("qft-sender-{}-range.bin", std::process::id()));
fs::write(&path, b"abcdef").unwrap();
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 || {
for _ in 0..2 {
let (mut stream, _) = listener.accept().unwrap();
handle_client(&mut stream, &path_for_server, "range.bin", 6, "session", &events).unwrap();
}
});
let full = request(address, None);
assert_response(&full, "HTTP/1.1 200 OK", "abcdef");
let resumed = request(address, Some("bytes=2-"));
assert_response(&resumed, "HTTP/1.1 206 Partial Content", "cdef");
let header = String::from_utf8_lossy(&resumed[..header_end(&resumed)]);
assert!(header.contains("Content-Range: bytes 2-5/6"));
server.join().unwrap();
fs::remove_file(path).unwrap();
}
fn request(address: std::net::SocketAddr, range: Option<&str>) -> Vec<u8> {
let mut stream = TcpStream::connect(address).unwrap();
write!(
stream,
"GET /qft/download HTTP/1.1\r\nHost: localhost\r\nX-QFT-Token: session\r\n{}\r\n",
range.map(|v| format!("Range: {v}\r\n")).unwrap_or_default(),
).unwrap();
stream.flush().unwrap();
let mut bytes = Vec::new();
stream.read_to_end(&mut bytes).unwrap();
bytes
}
fn assert_response(response: &[u8], status: &str, body: &str) {
let end = header_end(response);
assert!(String::from_utf8_lossy(&response[..end]).starts_with(status));
assert_eq!(&response[end..], body.as_bytes());
}
fn header_end(bytes: &[u8]) -> usize {
bytes.windows(4).position(|v| v == b"\r\n\r\n").unwrap() + 4
}
}