feat(desktop): PC↔PC 改用连接码,一串搞定,不再单独输 IP

此前发送方要分别念/输三样东西:IP、端口、6 位配对码。现在合成一串
可口述的连接码,**地址就编在码里**,所以拿到码即可直连——不需要广播、
不需要在同一网段,只要 IP 层路由可达即可(同一路由器下的不同 VLAN /
网段正属于这种情况)。

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

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

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

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

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

验证:cargo test 30/30,含连接码往返(全部地址类型)、容错输入、
单字符输错拦截率统计、以及走完整连接码链路的端到端传输
(编码 → 解码 → 换令牌 → 9MB 并发上传 → SHA-256 比对)。
This commit is contained in:
zhy200308
2026-08-11 17:29:00 +08:00
parent d2669fb2e4
commit 84643bff5e
5 changed files with 559 additions and 109 deletions
+78 -81
View File
@@ -1,5 +1,6 @@
mod base45;
mod client;
mod connect_code;
mod direct_ap;
mod discovery;
mod optical_cache;
@@ -128,8 +129,6 @@ struct PcPeerState {
server: Option<ReceiverServer>,
// 发送侧
peers: Vec<discovery::Peer>,
selected_peer: Option<usize>,
manual_address: String,
code_input: String,
token: Option<String>,
connected_base: Option<String>,
@@ -223,8 +222,6 @@ impl QftApp {
save_dir: Some(platform::default_download_dir()),
server: None,
peers: Vec::new(),
selected_peer: None,
manual_address: String::new(),
code_input: String::new(),
token: None,
connected_base: None,
@@ -1044,29 +1041,43 @@ impl QftApp {
let Some(server) = self.pc.server.as_ref() else { return };
let port = server.port;
let code = server.pair_code.clone();
let secret = server.secret;
// 每个网卡各生成一个连接码:对方在哪个网段,就用哪一个。
// 地址已经编在码里,所以对方不需要再单独输入 IP。
let codes: Vec<(std::net::IpAddr, String)> = pairing::local_ipv4_addresses()
.into_iter()
.map(|address| {
let code = connect_code::ConnectCode::new(std::net::IpAddr::V4(address), port, secret);
(std::net::IpAddr::V4(address), code.encode())
})
.collect();
ui.add_space(14.0);
ui.group(|ui| {
ui.heading("把这两项告诉发送方");
ui.add_space(6.0);
ui.horizontal_wrapped(|ui| {
ui.label("配对码:");
ui.heading(egui::RichText::new(&code).monospace().strong());
if ui.small_button("复制").clicked() {
ui.ctx().copy_text(code.clone());
}
});
ui.small("输错 5 次该码即作废,需要重新启动接收。");
ui.heading("把连接码告诉发送方");
ui.small("码里已经包含地址,对方只需输入这一串,不用再报 IP 和端口。");
ui.add_space(8.0);
ui.label("本机地址(发现不到时可让对方手动输入其中一个):");
for endpoint in pairing::local_ipv4_endpoints(port) {
if codes.is_empty() {
ui.colored_label(egui::Color32::from_rgb(220, 120, 60), "没有可用的局域网地址,请检查网络连接。");
}
for (index, (address, code)) in codes.iter().enumerate() {
ui.horizontal(|ui| {
ui.monospace(&endpoint);
if ui.small_button("复制").clicked() {
ui.ctx().copy_text(endpoint.clone());
if index == 0 {
ui.heading(egui::RichText::new(code).monospace().strong());
} else {
ui.monospace(egui::RichText::new(code).strong());
}
if ui.small_button("复制").clicked() {
ui.ctx().copy_text(code.clone());
}
ui.weak(format!("({address})"));
});
}
ui.add_space(6.0);
ui.small("输错 5 次该码即作废,需要重新启动接收。");
if codes.len() > 1 {
ui.small("本机有多个网卡:对方在哪个网段就用对应的那一串。");
}
});
ui.add_space(14.0);
@@ -1088,52 +1099,59 @@ impl QftApp {
fn pc_send_ui(&mut self, ui: &mut egui::Ui) {
ui.group(|ui| {
ui.heading("1 · 找到对方");
ui.heading("1 · 输入对方的连接码");
ui.horizontal_wrapped(|ui| {
if ui.add_enabled(!self.pc.busy, egui::Button::new("搜索附近的电脑")).clicked() {
self.browse_pc_peers();
}
ui.label("或手动输入:");
ui.add(egui::TextEdit::singleline(&mut self.pc.manual_address)
.hint_text("192.168.1.20:39393")
.desired_width(190.0));
});
ui.small("UDP 广播只覆盖同一个网段。跨网段或开了 AP 隔离的 Wi-Fi 上搜不到,请手动输入地址。");
ui.add_space(6.0);
for (index, peer) in self.pc.peers.iter().enumerate() {
let label = format!("{} · {} · {}", peer.name, peer.platform, peer.base_url());
if ui.selectable_label(self.pc.selected_peer == Some(index), label).clicked() {
self.pc.selected_peer = Some(index);
}
}
if self.pc.peers.is_empty() {
ui.weak("尚未搜索到设备。请确认对方已在「我要接收」里启动接收。");
}
});
ui.add_space(12.0);
ui.group(|ui| {
ui.heading("2 · 输入对方屏幕上的 6 位配对码");
ui.horizontal_wrapped(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.pc.code_input)
.hint_text("123456")
.desired_width(110.0));
let can_pair = !self.pc.busy
&& self.pc.code_input.trim().len() == 6
&& (self.pc.selected_peer.is_some() || !self.pc.manual_address.trim().is_empty());
if ui.add_enabled(can_pair, egui::Button::new("连接")).clicked() {
let response = ui.add(
egui::TextEdit::singleline(&mut self.pc.code_input)
.hint_text("K7M2-9X4P-QR3T")
.desired_width(240.0)
.font(egui::TextStyle::Monospace),
);
let submitted = response.lost_focus()
&& ui.input(|i| i.key_pressed(egui::Key::Enter));
let parsed = connect_code::ConnectCode::decode(&self.pc.code_input);
let can_connect = !self.pc.busy && parsed.is_ok();
if (ui.add_enabled(can_connect, egui::Button::new("连接")).clicked()
|| (submitted && can_connect))
{
self.pair_pc_peer();
}
if self.pc.token.is_some() {
ui.colored_label(egui::Color32::from_rgb(80, 200, 120), "● 已连接");
}
});
// 边打边校验:CRC 能在连接之前就发现输错,不用等超时
if !self.pc.code_input.trim().is_empty() {
match connect_code::ConnectCode::decode(&self.pc.code_input) {
Ok(code) => ui.weak(format!("将连接 {}", code.base_url())),
Err(e) => ui.colored_label(egui::Color32::from_rgb(220, 120, 60), e.to_string()),
};
}
ui.add_space(4.0);
ui.small("连接码里已包含对方地址,不需要在同一网段——只要网络能路由到对方即可。");
});
ui.add_space(12.0);
ui.collapsing("搜索同网段的设备(可选)", |ui| {
ui.small("同一网段时可以免输码。跨网段、或 Wi-Fi 开了客户端隔离时搜不到,请改用连接码。");
if ui.add_enabled(!self.pc.busy, egui::Button::new("搜索")).clicked() {
self.browse_pc_peers();
}
for peer in &self.pc.peers {
if ui.button(format!("{} · {} · {}", peer.name, peer.platform, peer.base_url())).clicked() {
// 直接把对端地址填进码输入框还不够——秘密只有对方屏幕上有,
// 所以这里只做地址提示,仍需用户补齐连接码
self.pc.status = format!("请输入 {} 屏幕上显示的连接码", peer.name);
}
}
if self.pc.peers.is_empty() {
ui.weak("尚未搜索到设备。");
}
});
ui.add_space(12.0);
ui.group(|ui| {
ui.heading("3 · 选择文件并发送");
ui.heading("2 · 选择文件并发送");
ui.horizontal_wrapped(|ui| {
if ui.button("选择文件").clicked() {
if let Some(files) = rfd::FileDialog::new().pick_files() {
@@ -1174,8 +1192,7 @@ impl QftApp {
let (tx, rx) = mpsc::channel();
match ReceiverServer::start(dir, token, tx) {
Ok(server) => {
self.pc.status = format!(
"接收中。把配对码 {} 告诉发送方即可。", server.pair_code);
self.pc.status = "接收中。把下面的连接码告诉发送方即可。".into();
self.pc.server = Some(server);
self.receive.events = Some(rx);
self.receive.connected_device = "等待对方连接".into();
@@ -1201,36 +1218,17 @@ impl QftApp {
});
}
/// 选中的对端,或手动输入的地址。手动输入允许省略 http:// 与端口。
fn pc_target_base_url(&self) -> Option<String> {
if let Some(index) = self.pc.selected_peer {
if let Some(peer) = self.pc.peers.get(index) {
return Some(peer.base_url());
}
}
let raw = self.pc.manual_address.trim();
if raw.is_empty() {
return None;
}
let raw = raw.trim_start_matches("http://").trim_end_matches('/');
let with_port = if raw.contains(':') {
raw.to_string()
} else {
format!("{raw}:{}", receiver::PREFERRED_PORT)
};
Some(format!("http://{with_port}"))
}
fn pair_pc_peer(&mut self) {
let Some(base_url) = self.pc_target_base_url() else { return };
let code = self.pc.code_input.trim().to_string();
let Ok(code) = connect_code::ConnectCode::decode(&self.pc.code_input) else { return };
let base_url = code.base_url();
let secret = code.secret_hex();
let device = self.local_device.clone();
let (tx, rx) = mpsc::channel();
self.pc.events = Some(rx);
self.pc.busy = true;
self.pc.status = format!("正在连接 {base_url}…");
std::thread::spawn(move || {
let _ = match client::PeerClient::pair(&base_url, &code, &device) {
let _ = match client::PeerClient::pair(&base_url, &secret, &device) {
Ok(token) => tx.send(PcEvent::Paired { base_url, token }),
Err(e) => tx.send(PcEvent::Failed(format!("{e:#}"))),
};
@@ -1300,7 +1298,6 @@ impl QftApp {
format!("搜索到 {} 台设备。", peers.len())
};
self.pc.peers = peers;
self.pc.selected_peer = None;
self.pc.busy = false;
}
PcEvent::Paired { base_url, token } => {