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)
This commit is contained in:
zhy200308
2026-08-11 16:36:33 +08:00
parent a960ad91d8
commit 376ffba96e
26 changed files with 2139 additions and 44 deletions
+34
View File
@@ -0,0 +1,34 @@
# Windows v0.2.0 build / test
```powershell
cd E:\tools\qft_win_android_mvp\windows
cargo check
cargo run --release
```
新增:
- `windows = 0.62.2` / `Devices_WiFiDirect` / `Security_Credentials`
- `serde` / `serde_json`
- `if-addrs`
QFT Direct 真机要求:
- Windows 10/11
- Wi-Fi 已开启
- 适配器/驱动支持 Wi-Fi Direct
- Windows Mobile Hotspot 没有占用 Wi-Fi Direct group-owner 资源
首次使用会在 `%LOCALAPPDATA%\QFT\direct-ap.json` 创建随机 QFT Direct SSID/密码。它用于让 Android 记住同一台电脑的网络身份;每次“启动接收”仍会生成不同的 session token。
如果 QFT Direct 启动失败:
1. 关闭 Windows“移动热点”。
2. 确认 Wi-Fi 开启。
3. 再试一次。
4. 仍失败则在 QFT UI 切到 `当前局域网(备用)`。
如果 Android 已显示连接 QFT Wi-Fi、但无法找到 Windows:
- 允许 qft-windows.exe 通过 Windows Defender Firewall 的**专用网络**。
- Android v0.2.0 会优先探测 QFT Wi-Fi 返回的 gateway,不再依赖固定 Windows IP。
+21
View File
@@ -0,0 +1,21 @@
# Windows build fix v0.1.2
This patch updates the Windows sender for `eframe = 0.35.0` / `egui = 0.35.0`.
Changes:
- `eframe::App::update(ctx, frame)` -> `eframe::App::ui(ui, frame)`
- clone `egui::Context` from `ui.ctx()` for texture/repaint operations
- `egui::TopBottomPanel::top(...)` -> `egui::Panel::top(...)`
- `CentralPanel::show(ctx, ...)` -> `CentralPanel::show(ui, ...)`
- project `rust-version` corrected to `1.95` for egui/eframe 0.35 compatibility
No QFT protocol, QR framing, file chunking, or Android code was changed.
Verify on Windows:
```powershell
cd windows
cargo check
cargo run --release
```
+56
View File
@@ -0,0 +1,56 @@
# Windows UI / device identity update — v0.1.3
## 1. Chinese UI font
The Windows sender no longer relies on egui's default font for Chinese text.
It loads a TrueType font (`.ttf`) at runtime and installs it as the first
Proportional and Monospace font fallback.
Lookup order:
1. `QFT_FONT_PATH`
2. `qft-ui.ttf` next to the executable
3. `assets/qft-ui.ttf` next to the executable
4. `./assets/qft-ui.ttf` from the current working directory
5. common Windows Chinese `.ttf` files
For development, the most deterministic setup is to put your own Chinese-capable
TTF at:
```text
windows/assets/qft-ui.ttf
```
No font file is bundled by this project.
## 2. Device display
The Windows sender now displays:
```text
本机设备:DESKTOP-XXXX
传输设备:DESKTOP-XXXX → Android 光学接收端 · 正在传输
```
The MANIFEST payload now appends:
```text
sender_device_len: u16
sender_device_utf8: bytes
```
The Android app displays both endpoints, for example:
```text
传输设备:DESKTOP-XXXX → Xiaomi 15
```
The field is appended to the end of the old MANIFEST payload, so the new Android
parser remains compatible with v0.1/v0.1.2 manifests.
## Important limitation
Windows -> Android is intentionally a one-way optical channel. The Android phone
does not send any ACK or identity back to Windows, so the Windows sender cannot
automatically know the exact receiving phone model. The Android side can show
both the sender PC name and its own local device model.
+20
View File
@@ -0,0 +1,20 @@
# QFT Windows v0.2.2 build fix
This patch fixes the five `cargo check` errors reported against eframe/egui 0.35.0.
## Fixed
1. Added semicolons after `ui.small(...)` calls that were used as the final expression of `if/else` blocks. `ui.small()` returns `egui::Response`, while those blocks must evaluate to `()`.
2. Removed the obsolete `Context::style()` and `Context::set_style()` calls. Those APIs are not available in egui 0.35.
3. Preserved the intended spacing by applying it through `Ui::spacing_mut()` inside `eframe::App::ui`.
4. Bumped Windows application/package version to 0.2.2.
## Verify on Windows
```powershell
cd E:\tools\qft_win_android_mvp\windows
cargo check
cargo run --release
```
The Android/Windows transfer protocol, Wi-Fi Direct pairing flow, receiver service and optical transport are unchanged by this patch.
+4585
View File
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "qft-desktop"
version = "0.5.0-m1"
edition = "2024"
rust-version = "1.95"
[dependencies]
eframe = "0.35.0"
rfd = "0.17.2"
qrcode = { version = "0.14.1", default-features = false }
base64 = "0.22.1"
crc32fast = "1.5.0"
sha2 = "0.10.9"
rand = "0.9.2"
anyhow = "1.0.99"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.143"
if-addrs = "0.13.4"
rayon = "1.11.0"
# 跨平台取本机名:macOS 上 HOSTNAME 环境变量通常不存在,
# Linux 上默认也不导出,只靠 env 会退化成占位名。
whoami = "1.6"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62.2", features = [
"Devices_WiFiDirect",
"Security_Credentials",
] }
+17
View File
@@ -0,0 +1,17 @@
QFT Windows UI font
Place a Chinese-capable TrueType font here and name it:
qft-ui.ttf
The application loads TTF at runtime. It does not embed/distribute font files.
Lookup order:
1. QFT_FONT_PATH environment variable
2. qft-ui.ttf beside the executable
3. assets/qft-ui.ttf beside the executable
4. ./assets/qft-ui.ttf from the current working directory
5. common Windows CJK .ttf files (for example C:\Windows\Fonts\simhei.ttf)
Example PowerShell:
$env:QFT_FONT_PATH = 'D:\fonts\my-cjk-font.ttf'
cargo run --release
+37
View File
@@ -0,0 +1,37 @@
const ALPHABET: &[u8; 45] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
/// RFC 9285 Base45. Its alphabet is fully supported by QR alphanumeric mode,
/// so the QR encoder can use fewer modules than Base64 text for the same
/// binary QFT frame while still giving Android a normal Result.text string.
pub fn encode(input: &[u8]) -> String {
if input.is_empty() {
return String::new();
}
let mut out = String::with_capacity((input.len() * 3 + 1) / 2);
let mut i = 0usize;
while i + 1 < input.len() {
let value = input[i] as usize * 256 + input[i + 1] as usize;
out.push(ALPHABET[value % 45] as char);
out.push(ALPHABET[(value / 45) % 45] as char);
out.push(ALPHABET[value / (45 * 45)] as char);
i += 2;
}
if i < input.len() {
let value = input[i] as usize;
out.push(ALPHABET[value % 45] as char);
out.push(ALPHABET[value / 45] as char);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_vectors() {
assert_eq!(encode(b"AB"), "BB8");
assert_eq!(encode(b"Hello!!"), "%69 VD92EX0");
assert_eq!(encode(b"base-45"), "UJCLQE7W581");
}
}
+575
View File
@@ -0,0 +1,575 @@
//! 桌面端的**发起侧**。
//!
//! 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,
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」。
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(&[]),
Duration::from_secs(10),
)?;
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 塞进多个线程
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.fetch_add(length as u64, Ordering::Relaxed);
}
}));
}
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: sent.load(Ordering::Relaxed),
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]) -> Result<()> {
let path = format!("/qft/upload/chunk/{upload_id}/{index}");
// 接收端对重复分块是幂等的,因此重试安全。
// 局域网上首次连接常被 Windows 防火墙首包丢弃,一次重试就能救回来。
let mut last = None;
for attempt in 0..3 {
match send_request(
address,
"POST",
&path,
&self.auth_headers(),
Some(body),
Duration::from_secs(60),
) {
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 起点。
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
}
}
fn platform_ensure_dir(path: &Path) -> Result<()> {
crate::platform::ensure_dir(path)
.with_context(|| format!("创建目录 {} 失败", path.display()))
}
// ---------------------------------------------------------------- 极简 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> {
let stream = TcpStream::connect_timeout(&address, timeout.min(Duration::from_secs(10)))
.with_context(|| format!("连接 {address} 失败"))?;
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 {
if !body.is_empty() {
writer.write_all(body)?;
}
}
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);
// 错误配对码必须被拒
assert!(PeerClient::pair(&base_url, "000000", "tester").is_err()
|| server.pair_code == "000000");
let paired = PeerClient::pair(&base_url, &server.pair_code, "tester").unwrap();
assert_eq!(paired, token, "配对应返回真实会话令牌");
let client = PeerClient::new(base_url, paired, "tester");
let mut last = Progress { done: 0, total: 0 };
let sha = client.upload_file(&source, |p| last = p).unwrap();
assert_eq!(last.done, payload.len() as u64, "进度应抵达文件全长");
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);
}
}
+82
View File
@@ -0,0 +1,82 @@
use anyhow::{bail, Result};
// Context 只在 Windows 的 WiFiDirect 分支里用;非 Windows 上整段被编译掉。
#[cfg(windows)]
use anyhow::Context;
#[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();
}
}
}
+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");
}
}
+1469
View File
File diff suppressed because it is too large Load Diff
+122
View File
@@ -0,0 +1,122 @@
use crate::{protocol::TransferSource, qr};
use eframe::egui::ColorImage;
use rayon::prelude::*;
use std::{
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, Receiver, TryRecvError, TrySendError},
Arc,
},
thread::{self, JoinHandle},
time::Duration,
};
/// Managed pre-render cache stays below the requested whole-process ceiling.
pub const HARD_PROCESS_BUDGET_MIB: usize = 1100;
pub const MAX_MANAGED_CACHE_MIB: usize = 768;
const MIN_CACHE_MIB: usize = 64;
const MAX_CACHE_PAGES: usize = 192;
const PREENCODE_BATCH: usize = 12;
pub struct EncodedPage {
pub page_index: u32,
pub round: u64,
pub image: ColorImage,
}
pub struct OpticalPrefetcher {
rx: Receiver<EncodedPage>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
pub capacity_pages: usize,
pub cache_mib: usize,
pub estimated_page_mib: f64,
}
impl OpticalPrefetcher {
pub fn start(
source: Arc<TransferSource>,
canvas_side: usize,
requested_cache_mib: usize,
) -> Self {
let cache_mib = requested_cache_mib.clamp(MIN_CACHE_MIB, MAX_MANAGED_CACHE_MIB);
let bytes_per_page = canvas_side.saturating_mul(canvas_side).saturating_mul(4).max(1);
let budget_bytes = cache_mib.saturating_mul(1024 * 1024);
let capacity_pages = (budget_bytes / bytes_per_page).clamp(4, MAX_CACHE_PAGES);
let estimated_page_mib = bytes_per_page as f64 / (1024.0 * 1024.0);
let (tx, rx) = mpsc::sync_channel::<EncodedPage>(capacity_pages);
let stop = Arc::new(AtomicBool::new(false));
let stop_worker = stop.clone();
// Single QR on screen, but multiple *future frames* are encoded in
// parallel so the display thread can still target 60 Hz.
let thread = thread::spawn(move || {
let total_pages = source.total_playlist_frames().max(1);
let mut next_page = 0u32;
let mut next_round = 0u64;
while !stop_worker.load(Ordering::Relaxed) {
let mut plan = Vec::with_capacity(PREENCODE_BATCH);
for order in 0..PREENCODE_BATCH {
plan.push((order, next_page, next_round));
next_page += 1;
if next_page >= total_pages {
next_page = 0;
next_round = next_round.saturating_add(1);
}
}
let mut rendered: Vec<(usize, EncodedPage)> = plan
.into_par_iter()
.filter_map(|(order, page_index, round)| {
if stop_worker.load(Ordering::Relaxed) { return None; }
let text = source.text_frame(page_index).ok()?;
let image = qr::render_qr_fitted(&text, canvas_side).ok()?;
Some((order, EncodedPage { page_index, round, image }))
})
.collect();
rendered.sort_unstable_by_key(|(order, _)| *order);
if rendered.is_empty() {
thread::sleep(Duration::from_millis(3));
continue;
}
for (_, mut item) in rendered {
loop {
match tx.try_send(item) {
Ok(()) => break,
Err(TrySendError::Full(returned)) => {
item = returned;
if stop_worker.load(Ordering::Relaxed) { return; }
thread::sleep(Duration::from_millis(1));
}
Err(TrySendError::Disconnected(_)) => return,
}
}
}
}
});
Self {
rx,
stop,
thread: Some(thread),
capacity_pages,
cache_mib,
estimated_page_mib,
}
}
pub fn try_next(&self) -> Result<EncodedPage, TryRecvError> {
self.rx.try_recv()
}
}
impl Drop for OpticalPrefetcher {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.thread.take() {
let _ = handle.join();
}
}
}
+240
View File
@@ -0,0 +1,240 @@
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)))
}
}
/// 6 位数字配对码,供 PC↔PC 使用。
///
/// 桌面端之间没有摄像头,二维码用不上,用户只能目视或口头传递这 6 位。
/// 用拒绝采样避免取模偏置——虽然此处偏置只有约 1e-5,但没必要留下这种脏细节。
pub fn new_pair_code() -> String {
let mut bytes = [0u8; 4];
loop {
rand::rng().fill_bytes(&mut bytes);
let value = u32::from_be_bytes(bytes);
// 4_294_000_000 是 1_000_000 的整数倍中不超过 u32::MAX 的最大值
if value < 4_294_000_000 {
return format!("{:06}", value % 1_000_000);
}
}
}
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 {
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())
}
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);
}
}
+238
View File
@@ -0,0 +1,238 @@
//! 平台差异的唯一收敛点。
//!
//! 约定:除本文件与 `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,必须去掉控制字符并限长。
pub fn sanitize_device_name(raw: &str) -> String {
let cleaned: String = raw
.chars()
.filter(|ch| !ch.is_control())
.take(64)
.collect();
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"
}
}
/// 本机所属平台,用于 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
}
/// 确保目录存在,返回其路径。调用方负责处理失败。
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);
}
#[test]
fn platform_tag_matches_direct_ap_capability() {
// Direct AP 目前只有 Windows 支持,两个常量必须保持一致
assert_eq!(
direct_ap_support().is_supported(),
platform_tag() == "windows"
);
}
}
+242
View File
@@ -0,0 +1,242 @@
use crate::base45;
use anyhow::{bail, Context, Result};
use crc32fast::hash as crc32;
use rand::RngCore;
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::Read,
path::{Path, PathBuf},
};
pub const PREFIX: &str = "QFT2:";
pub const VERSION: u8 = 2;
#[derive(Clone, Copy, Debug)]
#[repr(u8)]
pub enum FrameKind {
Manifest = 1,
Data = 2,
End = 3,
}
#[derive(Clone, Debug)]
pub struct Manifest {
pub session_id: u64,
pub sender_device: String,
pub file_name: String,
pub file_size: u64,
pub chunk_size: u16,
pub total_chunks: u32,
pub sha256: [u8; 32],
}
pub struct TransferSource {
path: PathBuf,
file: File,
pub manifest: Manifest,
}
impl TransferSource {
pub fn open(path: impl AsRef<Path>, chunk_size: u16) -> Result<Self> {
if chunk_size == 0 {
bail!("chunk_size must be > 0");
}
let path = path.as_ref().to_path_buf();
let file = File::open(&path).context("open input file")?;
let file_size = file.metadata()?.len();
let total_chunks_u64 = if file_size == 0 {
0
} else {
(file_size + chunk_size as u64 - 1) / chunk_size as u64
};
if total_chunks_u64 > u32::MAX as u64 {
bail!("file requires too many chunks");
}
let sha256 = hash_file_streaming(&file)?;
let mut rng = rand::rng();
let session_id = rng.next_u64();
let file_name = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("qft.bin")
.to_owned();
let sender_device = local_device_name();
Ok(Self {
path,
file,
manifest: Manifest {
session_id,
sender_device,
file_name,
file_size,
chunk_size,
total_chunks: total_chunks_u64 as u32,
sha256,
},
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn total_playlist_frames(&self) -> u32 {
self.manifest.total_chunks.saturating_add(2)
}
/// playlist_index: 0=manifest, 1..=N=data, N+1=end
pub fn binary_frame(&self, playlist_index: u32) -> Result<Vec<u8>> {
let n = self.manifest.total_chunks;
if playlist_index == 0 {
return Ok(encode_manifest_binary(&self.manifest));
}
if playlist_index >= 1 && playlist_index <= n {
return self.encode_data_binary(playlist_index - 1);
}
if playlist_index == n + 1 {
return Ok(encode_frame_binary(
FrameKind::End,
self.manifest.session_id,
0,
n,
&[],
));
}
bail!("playlist index out of range")
}
/// QFT2 uses Base45 because the whole alphabet is legal in QR alphanumeric
/// mode. This is close to raw byte efficiency without relying on ZXing's
/// rawBytes interpretation, and Android can consume Result.text directly.
pub fn text_frame(&self, playlist_index: u32) -> Result<String> {
let binary = self.binary_frame(playlist_index)?;
Ok(format!("{PREFIX}{}", base45::encode(&binary)))
}
fn encode_data_binary(&self, seq: u32) -> Result<Vec<u8>> {
let offset = seq as u64 * self.manifest.chunk_size as u64;
let remaining = self.manifest.file_size.saturating_sub(offset);
let len = remaining.min(self.manifest.chunk_size as u64) as usize;
let mut payload = vec![0u8; len];
if len > 0 {
read_exact_at(&self.file, &mut payload, offset)?;
}
Ok(encode_frame_binary(
FrameKind::Data,
self.manifest.session_id,
seq,
self.manifest.total_chunks,
&payload,
))
}
}
fn encode_manifest_binary(m: &Manifest) -> Vec<u8> {
let name = m.file_name.as_bytes();
let name_len = name.len().min(u16::MAX as usize) as u16;
let device = m.sender_device.as_bytes();
let device_len = device.len().min(u16::MAX as usize) as u16;
let mut payload = Vec::with_capacity(
8 + 2 + 32 + 2 + name_len as usize + 2 + device_len as usize,
);
payload.extend_from_slice(&m.file_size.to_be_bytes());
payload.extend_from_slice(&m.chunk_size.to_be_bytes());
payload.extend_from_slice(&m.sha256);
payload.extend_from_slice(&name_len.to_be_bytes());
payload.extend_from_slice(&name[..name_len as usize]);
payload.extend_from_slice(&device_len.to_be_bytes());
payload.extend_from_slice(&device[..device_len as usize]);
encode_frame_binary(
FrameKind::Manifest,
m.session_id,
0,
m.total_chunks,
&payload,
)
}
pub fn encode_frame_binary(
kind: FrameKind,
session_id: u64,
seq: u32,
total_chunks: u32,
payload: &[u8],
) -> Vec<u8> {
assert!(payload.len() <= u16::MAX as usize);
let mut binary = Vec::with_capacity(28 + payload.len());
binary.extend_from_slice(b"QFT2");
binary.push(VERSION);
binary.push(kind as u8);
binary.extend_from_slice(&session_id.to_be_bytes());
binary.extend_from_slice(&seq.to_be_bytes());
binary.extend_from_slice(&total_chunks.to_be_bytes());
binary.extend_from_slice(&(payload.len() as u16).to_be_bytes());
binary.extend_from_slice(payload);
let crc = crc32(&binary);
binary.extend_from_slice(&crc.to_be_bytes());
binary
}
pub fn hex_sha256(bytes: &[u8; 32]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(64);
for &b in bytes {
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
}
out
}
pub fn local_device_name() -> String {
crate::platform::device_name()
}
fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
let mut input = file.try_clone().context("clone input for sha256")?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 4 * 1024 * 1024];
loop {
let n = input.read(&mut buf).context("read input for sha256")?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hasher.finalize().into())
}
fn read_exact_at(file: &File, mut out: &mut [u8], mut offset: u64) -> Result<()> {
while !out.is_empty() {
let n = read_at_once(file, out, offset)?;
if n == 0 {
bail!("unexpected EOF at offset {offset}");
}
offset = offset.saturating_add(n as u64);
let (_, rest) = out.split_at_mut(n);
out = rest;
}
Ok(())
}
#[cfg(windows)]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::windows::fs::FileExt;
file.seek_read(out, offset)
}
#[cfg(unix)]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::unix::fs::FileExt;
file.read_at(out, offset)
}
#[cfg(not(any(windows, unix)))]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::io::{Seek, SeekFrom};
let mut cloned = file.try_clone()?;
cloned.seek(SeekFrom::Start(offset))?;
cloned.read(out)
}
+47
View File
@@ -0,0 +1,47 @@
use anyhow::{Context, Result};
use eframe::egui::ColorImage;
use qrcode::{types::Color, EcLevel, QrCode};
const QUIET_MODULES: usize = 4;
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
/// characters, allowing the QR encoder to choose a compact alphanumeric data
/// mode. Exact integer module pixels + full quiet zone maximize camera clarity.
pub fn render_qr_fitted(text: &str, target_side: usize) -> Result<ColorImage> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L)
.context("QR payload too large")?;
let modules = code.width() + QUIET_MODULES * 2;
let scale = (target_side / modules).max(1);
let side = modules * scale;
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
}
/// Pairing QR stays static and uses M error correction for first-scan reliability.
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)
.context("pair QR payload too large")?;
let modules = code.width() + QUIET_MODULES * 2;
let scale = (target_side / modules).max(1);
let side = modules * scale;
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
}
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
let qr_width = code.width();
let modules = qr_width + QUIET_MODULES * 2;
let scale = (side / modules).max(1);
let actual_side = modules * scale;
let mut gray = vec![255u8; actual_side * actual_side];
for y in 0..qr_width {
for x in 0..qr_width {
if code[(x, y)] != Color::Dark { continue; }
let px0 = (x + QUIET_MODULES) * scale;
let py0 = (y + QUIET_MODULES) * scale;
for py in py0..py0 + scale {
let row = py * actual_side;
gray[row + px0..row + px0 + scale].fill(0);
}
}
}
gray
}
+754
View File
@@ -0,0 +1,754 @@
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::RngCore;
use serde_json::json;
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::{self, File, OpenOptions},
io::{BufRead, BufReader, Read, Seek, SeekFrom, Write},
net::{TcpListener, TcpStream, UdpSocket},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::Sender,
Arc, Mutex,
},
thread::{self, JoinHandle},
time::{Duration, Instant},
};
pub const PREFERRED_PORT: u16 = 39393;
pub const DISCOVERY_PORT: u16 = 39392;
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;
#[derive(Clone, Debug)]
pub enum ReceiverEvent {
ClientConnected { device: String },
UploadStarted { device: String, file_name: String, size: u64 },
UploadProgress { device: String, file_name: String, received: u64, size: u64 },
UploadCompleted { device: String, file_name: String, saved_path: PathBuf, sha256: String },
Error(String),
}
#[derive(Debug)]
struct UploadSession {
upload_key: Option<String>,
device: String,
file_name: String,
size: u64,
chunk_size: u64,
total_chunks: u32,
part_path: PathBuf,
final_path: PathBuf,
received: Vec<bool>,
received_bytes: u64,
}
type SessionMap = Arc<Mutex<HashMap<String, Arc<Mutex<UploadSession>>>>>;
type CompletedMap = Arc<Mutex<HashMap<String, CompletedUpload>>>;
#[derive(Clone, Debug)]
struct CompletedUpload {
sha256: String,
size: u64,
}
pub struct ReceiverServer {
pub port: u16,
/// PC↔PC 用的 6 位配对码:对端没有摄像头,扫不了二维码,
/// 只能靠用户口头/目视传递这 6 位数字来换取会话令牌。
pub pair_code: String,
stop: Arc<AtomicBool>,
tcp_thread: Option<JoinHandle<()>>,
udp_thread: Option<JoinHandle<()>>,
}
impl ReceiverServer {
pub fn start(save_dir: PathBuf, session_token: String, events: Sender<ReceiverEvent>) -> Result<Self> {
fs::create_dir_all(&save_dir).context("创建接收目录失败")?;
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 sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
let completed: CompletedMap = Arc::new(Mutex::new(HashMap::new()));
// 6 位数字只有约 20 bit 熵,单靠它不足以抵抗在线爆破,
// 因此配一个严格的失败计数:错 5 次即作废,必须重启接收重新生成。
let pair_code = crate::pairing::new_pair_code();
let pair_failures = Arc::new(AtomicU32::new(0));
let stop_tcp = stop.clone();
let sessions_tcp = sessions.clone();
let completed_tcp = completed.clone();
let token_tcp = session_token.clone();
let dir_tcp = save_dir.clone();
let events_tcp = events.clone();
let code_tcp = pair_code.clone();
let failures_tcp = pair_failures.clone();
let tcp_thread = thread::spawn(move || {
while !stop_tcp.load(Ordering::Relaxed) {
match listener.accept() {
Ok((mut stream, _)) => {
let dir = dir_tcp.clone();
let token = token_tcp.clone();
let tx = events_tcp.clone();
let sessions = sessions_tcp.clone();
let completed = completed_tcp.clone();
let code = code_tcp.clone();
let failures = failures_tcp.clone();
thread::spawn(move || {
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
// `unexpected end of stream`: make a best effort to
// return an HTTP status before closing the socket.
let message = format!("接收失败:{e:#}");
let _ = write_response(&mut stream, 500, "text/plain", message.as_bytes());
let _ = tx.send(ReceiverEvent::Error(message));
}
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(12));
}
Err(e) => {
let _ = events_tcp.send(ReceiverEvent::Error(format!("监听端口失败:{e}")));
break;
}
}
}
});
let stop_udp = stop.clone();
let token_udp = session_token;
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(ReceiverEvent::Error(format!(
"快速发现端口 {DISCOVERY_PORT} 不可用:{e}。仍可使用网关/IP 探测。"
)));
return;
}
};
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
let expected = format!("QFTDISC2:{token_udp}");
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];
while !stop_udp.load(Ordering::Relaxed) {
match socket.recv_from(&mut buf) {
Ok((n, peer)) => {
match std::str::from_utf8(&buf[..n]).ok() {
Some(text) if text == expected => {
let _ = socket.send_to(response.as_bytes(), peer);
}
Some(text) if text == crate::discovery::BROWSE_QUERY => {
let _ = socket.send_to(&announce, 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),
pair_code,
udp_thread: Some(udp_thread),
})
}
}
impl Drop for ReceiverServer {
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();
}
}
}
/// `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(
stream: &mut TcpStream,
save_dir: &Path,
token: &str,
pair_code: &str,
pair_failures: &AtomicU32,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
completed: &CompletedMap,
) -> 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_read_timeout(Some(Duration::from_secs(120)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
let cloned = stream.try_clone()?;
let mut reader = BufReader::with_capacity(64 * 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 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("");
if supplied != 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(ReceiverEvent::ClientConnected { device: device.clone() });
if method == "GET" && path == "/qft/ping" {
let body = json!({"ok": true, "protocol": 2, "parallel": true}).to_string();
return write_response(stream, 200, "application/json", body.as_bytes());
}
if method == "POST" && path == "/qft/upload/init" {
return init_parallel_upload(stream, save_dir, &headers, &device, events, sessions);
}
if method == "POST" && path.starts_with("/qft/upload/chunk/") {
return receive_parallel_chunk(stream, &mut reader, path, &headers, events, sessions);
}
if method == "POST" && path.starts_with("/qft/upload/finish/") {
return finish_parallel_upload(stream, path, events, sessions, completed);
}
// Compatibility path for old clients and content providers that cannot seek.
if method == "POST" && path == "/qft/upload" {
return receive_legacy_stream(stream, &mut reader, save_dir, &headers, &device, events);
}
write_response(stream, 404, "text/plain", b"not found")
}
fn init_parallel_upload(
stream: &mut TcpStream,
save_dir: &Path,
headers: &HashMap<String, String>,
device: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let file_name = decode_header(headers.get("x-qft-filename"))
.map(sanitize_file_name)
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "qft-upload.bin".to_owned());
let size: u64 = headers.get("x-qft-size")
.context("缺少 X-QFT-Size")?
.parse().context("X-QFT-Size 无效")?;
let chunk_size = headers.get("x-qft-chunk-size")
.and_then(|v| v.parse::<u64>().ok())
.map(|v| v.clamp(MIN_PARALLEL_CHUNK_SIZE, MAX_PARALLEL_CHUNK_SIZE))
.unwrap_or(PARALLEL_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!("文件分块数过大") }
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 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 part_path = final_path.with_file_name(format!("{final_name}.{upload_id}.qftpart"));
let part = File::create(&part_path)
.with_context(|| format!("创建临时文件 {}", part_path.display()))?;
part.set_len(size)?;
drop(part);
let session = UploadSession {
upload_key,
device: device.to_owned(),
file_name: file_name.clone(),
size,
chunk_size,
total_chunks,
part_path,
final_path,
received: vec![false; total_chunks as usize],
received_bytes: 0,
};
map.insert(upload_id.clone(), Arc::new(Mutex::new(session)));
drop(map);
let _ = events.send(ReceiverEvent::UploadStarted {
device: device.to_owned(),
file_name,
size,
});
let body = json!({
"ok": true,
"upload_id": upload_id,
"chunk_size": chunk_size,
"total_chunks": total_chunks,
}).to_string();
write_response(stream, 200, "application/json", body.as_bytes())
}
fn receive_parallel_chunk(
stream: &mut TcpStream,
reader: &mut BufReader<TcpStream>,
path: &str,
headers: &HashMap<String, String>,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let suffix = path.trim_start_matches("/qft/upload/chunk/");
let (upload_id, index_text) = suffix.split_once('/').context("chunk 路径无效")?;
let index: u32 = index_text.parse().context("chunk index 无效")?;
let content_len: u64 = headers.get("content-length")
.context("缺少 Content-Length")?
.parse().context("Content-Length 无效")?;
let session_arc = {
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.get(upload_id).cloned().context("上传会话不存在或已完成")?
};
let (part_path, offset, expected_len, device, file_name, size, already) = {
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if index >= session.total_chunks { bail!("chunk index 越界") }
let offset = index as u64 * session.chunk_size;
let expected = (session.size - offset).min(session.chunk_size);
(
session.part_path.clone(),
offset,
expected,
session.device.clone(),
session.file_name.clone(),
session.size,
session.received[index as usize],
)
};
if content_len != expected_len { bail!("chunk 长度不匹配:{content_len} != {expected_len}") }
if already {
drain_exact(reader, content_len)?;
return write_response(stream, 200, "application/json", b"{\"ok\":true,\"duplicate\":true}");
}
let mut out = OpenOptions::new().write(true).open(&part_path)?;
out.seek(SeekFrom::Start(offset))?;
copy_exact(reader, &mut out, content_len)?;
out.sync_data()?;
let received = {
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if !session.received[index as usize] {
session.received[index as usize] = true;
session.received_bytes = session.received_bytes.saturating_add(content_len);
}
session.received_bytes
};
let _ = events.send(ReceiverEvent::UploadProgress { device, file_name, received, size });
write_response(stream, 200, "application/json", b"{\"ok\":true}")
}
fn finish_parallel_upload(
stream: &mut TcpStream,
path: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
completed: &CompletedMap,
) -> Result<()> {
let upload_id = path.trim_start_matches("/qft/upload/finish/");
let session_arc = {
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.get(upload_id).cloned()
};
if session_arc.is_none() {
// The client may lose the TCP response after the file was safely
// renamed. Finish is idempotent so its retry reports that committed
// result instead of surfacing an opaque connection/404 failure.
if let Some(done) = completed.lock().ok().and_then(|v| v.get(upload_id).cloned()) {
let body = json!({"ok": true, "sha256": done.sha256, "size": done.size, "duplicate": true}).to_string();
return write_response(stream, 200, "application/json", body.as_bytes());
}
bail!("上传会话不存在或已完成")
}
let session_arc = session_arc.expect("checked above");
let (device, file_name, size, part_path, final_path) = {
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if session.received.iter().any(|v| !*v) {
let missing = session.received.iter().filter(|v| !**v).count();
let body = json!({"ok": false, "missing": missing}).to_string();
return write_response(stream, 409, "application/json", body.as_bytes());
}
(
session.device.clone(), session.file_name.clone(), session.size,
session.part_path.clone(), session.final_path.clone(),
)
};
let sha = hash_file(&part_path)?;
if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") }
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
{
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.remove(upload_id);
}
if let Ok(mut finished) = completed.lock() {
// A QFT receive session is short-lived. Keep a bounded completion cache
// only for retrying a lost finish response.
if finished.len() >= 64 { finished.clear(); }
finished.insert(upload_id.to_owned(), CompletedUpload { sha256: sha.clone(), size });
}
let _ = events.send(ReceiverEvent::UploadCompleted {
device, file_name, saved_path: final_path, sha256: sha.clone(),
});
let body = json!({"ok": true, "sha256": sha, "size": size}).to_string();
write_response(stream, 200, "application/json", body.as_bytes())
}
fn receive_legacy_stream(
stream: &mut TcpStream,
reader: &mut BufReader<TcpStream>,
save_dir: &Path,
headers: &HashMap<String, String>,
device: &str,
events: &Sender<ReceiverEvent>,
) -> Result<()> {
let file_name = decode_header(headers.get("x-qft-filename"))
.map(sanitize_file_name)
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "qft-upload.bin".to_owned());
let size: u64 = headers.get("content-length")
.context("缺少 Content-Length")?
.parse().context("Content-Length 无效")?;
let declared_size = headers.get("x-qft-size")
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(size);
if declared_size != size { bail!("文件大小头与 Content-Length 不一致") }
let final_path = unique_path(save_dir, &file_name);
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}.qftpart"));
let mut out = File::create(&part_path).with_context(|| format!("创建临时文件 {}", part_path.display()))?;
let _ = events.send(ReceiverEvent::UploadStarted { device: device.to_owned(), file_name: file_name.clone(), size });
let mut remaining = size;
let mut received = 0u64;
let mut buf = vec![0u8; IO_BUFFER];
let mut hasher = Sha256::new();
let mut last_report = Instant::now();
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
let n = reader.read(&mut buf[..want])?;
if n == 0 { bail!("上传中连接提前关闭:{received}/{size}") }
out.write_all(&buf[..n])?;
hasher.update(&buf[..n]);
received += n as u64;
remaining -= n as u64;
if last_report.elapsed() >= Duration::from_millis(100) || remaining == 0 {
let _ = events.send(ReceiverEvent::UploadProgress {
device: device.to_owned(), file_name: file_name.clone(), received, size,
});
last_report = Instant::now();
}
}
out.sync_all()?;
drop(out);
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
let sha = hex(&hasher.finalize());
let _ = events.send(ReceiverEvent::UploadCompleted {
device: device.to_owned(), file_name, saved_path: final_path, sha256: sha,
});
write_response(stream, 200, "application/json", b"{\"ok\":true,\"legacy\":true}")
}
fn copy_exact(reader: &mut impl Read, writer: &mut impl Write, mut remaining: u64) -> Result<()> {
let mut buf = vec![0u8; IO_BUFFER];
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
let n = reader.read(&mut buf[..want])?;
if n == 0 { bail!("chunk 上传中连接提前关闭") }
writer.write_all(&buf[..n])?;
remaining -= n as u64;
}
Ok(())
}
fn drain_exact(reader: &mut impl Read, remaining: u64) -> Result<()> {
copy_exact(reader, &mut std::io::sink(), remaining)
}
fn hash_file(path: &Path) -> Result<String> {
let mut input = File::open(path)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 4 * 1024 * 1024];
loop {
let n = input.read(&mut buf)?;
if n == 0 { break }
hasher.update(&buf[..n]);
}
Ok(hex(&hasher.finalize()))
}
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
let reason = match code {
200 => "OK", 400 => "Bad Request", 403 => "Forbidden", 404 => "Not Found",
409 => "Conflict", _ => "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 raw = value?;
let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?;
String::from_utf8(bytes).ok()
}
fn sanitize_file_name(name: String) -> String {
let cleaned: String = name.chars()
.map(|c| if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') { '_' } else { c })
.collect();
cleaned.trim().trim_matches('.').chars().take(180).collect()
}
fn unique_path(dir: &Path, name: &str) -> PathBuf {
let base = Path::new(name);
let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload");
let ext = base.extension().and_then(|s| s.to_str());
let mut candidate = dir.join(name);
let mut n = 1;
while candidate.exists() {
let next = match ext {
Some(ext) => format!("{stem} ({n}).{ext}"),
None => format!("{stem} ({n})"),
};
candidate = dir.join(next);
n += 1;
}
candidate
}
fn unique_path_reserved<'a>(
dir: &Path,
name: &str,
sessions: impl Iterator<Item = &'a Arc<Mutex<UploadSession>>>,
) -> PathBuf {
let reserved: Vec<PathBuf> = sessions
.filter_map(|s| s.lock().ok().map(|v| v.final_path.clone()))
.collect();
let base = Path::new(name);
let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload");
let ext = base.extension().and_then(|s| s.to_str());
let mut n = 0u32;
loop {
let next_name = if n == 0 {
name.to_owned()
} else {
match ext {
Some(ext) => format!("{stem} ({n}).{ext}"),
None => format!("{stem} ({n})"),
}
};
let candidate = dir.join(next_name);
if !candidate.exists() && !reserved.contains(&candidate) {
return candidate;
}
n += 1;
}
}
fn random_id() -> String {
let mut bytes = [0u8; 12];
rand::rng().fill_bytes(&mut bytes);
URL_SAFE_NO_PAD.encode(bytes)
}
fn hex(bytes: &[u8]) -> String {
const H: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
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);
}
}
+367
View File
@@ -0,0 +1,367 @@
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<()> {
// 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);
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 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: 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}-{end}/{}\r\nAccept-Ranges: bytes\r\nConnection: close\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(())
}
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\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\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
}
}