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:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user