enforce dedicated Wi-Fi for direct QR pairing

This commit is contained in:
zhy200308
2026-08-12 11:46:59 +08:00
parent eccd93266e
commit 65223dafe4
10 changed files with 345 additions and 306 deletions
+1 -1
View File
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qft-desktop"
version = "0.4.11"
version = "0.4.12"
dependencies = [
"anyhow",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "qft-desktop"
version = "0.4.11"
version = "0.4.12"
edition = "2024"
rust-version = "1.95"
+118 -42
View File
@@ -647,15 +647,19 @@ impl QftApp {
ui.image((texture.id(), egui::vec2(side, side)));
});
}
// 把二维码实际广播的地址摊开显示。手机报"找不到电脑"时,
// 第一件要确认的就是码里到底有没有它能到达的那个地址——
// 在这里一眼可见,不必等手机端的诊断。
ui.collapsing("二维码广播的地址", |ui| {
for endpoint in pairing::qr_endpoints(listen_port, self.receive.direct_ap.is_some()).iter().take(4) {
ui.monospace(endpoint);
}
ui.small("手机连上后会依次尝试这些地址;其中必须有一个与手机同网段。");
});
if self.receive.direct_ap.is_some() {
ui.collapsing("QFT 专用 Wi-Fi 路由", |ui| {
ui.label("二维码不广播电脑现有网卡地址。");
ui.small("Android 先连接专用网络,再读取该连接的实际网关;只在专用子网内发现接收服务。");
});
} else {
ui.collapsing("二维码广播的地址", |ui| {
for endpoint in pairing::qr_endpoints(listen_port, false).iter().take(4) {
ui.monospace(endpoint);
}
ui.small("当前局域网备用模式:手机只尝试与自身同网段的地址。");
});
}
if let Some(ap) = &self.receive.direct_ap {
ui.label(format!("临时网络:{}", ap.ssid));
ui.small("网络身份会在这台电脑上复用以减少重复确认;每次接收仍会生成新的会话 Token。");
@@ -695,7 +699,11 @@ impl QftApp {
ui.horizontal_wrapped(|ui| {
ui.heading("电脑 → Android · 扫码自动直传");
ui.separator();
ui.label("QFTSEND2 · 自动连接本地 Wi-Fi · 扫码后立即下载");
ui.label(if self.send.use_direct_ap {
"QFTSEND2 · 自动连接 QFT 专用 Wi-Fi · 扫码后立即下载"
} else {
"QFTSEND2 · 当前局域网备用模式 · 扫码后立即下载"
});
if ui.add_enabled(
running,
egui::Button::new(if self.send.qr_focus { "退出专注二维码" } else { "专注二维码" }),
@@ -823,6 +831,31 @@ impl QftApp {
}
fn pc_to_phone_running_controls(&mut self, ui: &mut egui::Ui) {
let listen_port = self
.send
.server
.as_ref()
.map(|server| server.port)
.unwrap_or(sender::PREFERRED_PORT);
// 宽屏时让连接信息从控制区顶部开始,而不是先走完整个左侧控制区
// 后才进入第二行 columns。此前右侧面板因此被整体推低,形成截图中
// “广播地址上面一大片空白”的布局。
if ui.available_width() >= 860.0 {
ui.columns(2, |cols| {
self.send_control_and_firewall_column(&mut cols[0], listen_port);
self.send_connection_panel(&mut cols[1], listen_port);
});
} else {
self.send_control_panel(ui);
ui.add_space(6.0);
self.send_connection_panel(ui, listen_port);
ui.add_space(6.0);
self.firewall_panel(ui, listen_port);
}
}
fn send_control_panel(&mut self, ui: &mut egui::Ui) {
ui.group(|ui| {
ui.heading("直传控制");
ui.horizontal_wrapped(|ui| {
@@ -838,46 +871,38 @@ impl QftApp {
ui.label(&self.send.status);
ui.small("拖动下方分隔条可为二维码腾出更多高度;也可切换到“专注二维码”。");
});
}
fn send_control_and_firewall_column(&mut self, ui: &mut egui::Ui, listen_port: u16) {
self.send_control_panel(ui);
ui.add_space(6.0);
// 这条路同样要接受手机的入站连接,Direct AP 的虚拟网卡更是防火墙重灾区。
// 面板必须放在运行态控制区里——直传启动后 pc_to_phone_ui 已经提前 return,
// 那个函数尾部的任何 UI 都画不出来。
let listen_port = self
.send
.server
.as_ref()
.map(|server| server.port)
.unwrap_or(sender::PREFERRED_PORT);
// 宽屏下把连接信息放到防火墙右侧:这两块都是扫码失败时要一起核对的
// 诊断信息,并排后不必在控制区里上下寻找。最小窗口下仍改回纵向,
// 给防火墙按钮和较长的 endpoint 留出足够宽度。
if ui.available_width() >= 860.0 {
ui.columns(2, |cols| {
self.firewall_panel(&mut cols[0], listen_port);
self.send_connection_panel(&mut cols[1], listen_port);
});
} else {
self.firewall_panel(ui, listen_port);
ui.add_space(6.0);
self.send_connection_panel(ui, listen_port);
}
// 直传同样接受手机入站连接;Direct AP 虚拟网卡尤其需要明确放行。
self.firewall_panel(ui, listen_port);
}
fn send_connection_panel(&mut self, ui: &mut egui::Ui, listen_port: u16) {
ui.group(|ui| {
ui.collapsing("二维码广播的地址", |ui| {
for endpoint in
pairing::qr_endpoints(listen_port, self.send.direct_ap.is_some()).iter().take(4)
{
ui.monospace(endpoint);
}
ui.small("手机会依次尝试这些地址;其中必须有一个与手机同网段。");
});
if self.send.direct_ap.is_some() {
ui.collapsing("QFT 专用 Wi-Fi 路由", |ui| {
ui.label("二维码不广播电脑现有网卡地址。");
ui.small("Android 会先连接下方专用网络,再读取该连接的实际网关并完成会话认证;只在这个专用子网内发现电脑。");
});
} else {
ui.collapsing("二维码广播的地址", |ui| {
for endpoint in pairing::qr_endpoints(listen_port, false).iter().take(4) {
ui.monospace(endpoint);
}
ui.small("当前局域网备用模式:手机只尝试与自身同网段的地址。");
});
}
ui.label(format!("电脑:{}", self.local_device));
ui.label(format!("手机:{}", self.send.connected_device));
if let Some(ap) = &self.send.direct_ap {
ui.label(format!("临时网络:{}", ap.ssid));
ui.label(format!("专用网络:{}", ap.ssid));
if !self.send.session_token.is_empty() {
let short = &self.send.session_token[..10.min(self.send.session_token.len())];
ui.small(format!("专用 Wi-Fi + 临时会话 {short}… · 停止直传后失效"));
}
}
});
}
@@ -885,7 +910,6 @@ impl QftApp {
fn pc_to_phone_qr_focus_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
if ctx.input(|input| input.key_pressed(egui::Key::Escape)) {
self.send.qr_focus = false;
self.receive.focus_qr = false;
return;
}
@@ -2043,6 +2067,36 @@ mod font_tests {
text
}
fn rendered_text_positions(build: impl Fn(&mut egui::Ui)) -> Vec<(String, f32)> {
fn collect(shape: &egui::epaint::Shape, out: &mut Vec<(String, f32)>) {
match shape {
egui::epaint::Shape::Text(text) => {
out.push((text.galley.text().to_owned(), text.pos.y));
}
egui::epaint::Shape::Vec(shapes) => {
for shape in shapes {
collect(shape, out);
}
}
_ => {}
}
}
let ctx = egui::Context::default();
let mut positions = Vec::new();
for _ in 0..2 {
positions.clear();
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
ui.set_width(1_200.0);
build(ui);
});
for clipped in &output.shapes {
collect(&clipped.shape, &mut positions);
}
}
positions
}
/// 直传运行态的控制区必须包含防火墙放行入口。
#[test]
fn running_send_controls_render_the_firewall_panel() {
@@ -2062,6 +2116,28 @@ mod font_tests {
);
}
#[test]
fn running_send_connection_panel_starts_beside_the_top_controls() {
let positions = rendered_text_positions(|ui| {
let mut app = QftApp::bare(String::new());
app.pc_to_phone_running_controls(ui);
});
let control_y = positions
.iter()
.find(|(text, _)| text.contains("直传控制"))
.map(|(_, y)| *y)
.expect("应绘制直传控制标题");
let connection_y = positions
.iter()
.find(|(text, _)| text.contains("二维码广播的地址"))
.map(|(_, y)| *y)
.expect("应绘制连接信息标题");
assert!(
(control_y - connection_y).abs() <= 8.0,
"连接信息应与顶部控制区并排,实际 y={connection_y},控制区 y={control_y}"
);
}
/// 接收页运行态(非专注模式)同样必须有防火墙入口。
#[test]
fn receive_running_page_renders_the_firewall_panel() {
+50 -171
View File
@@ -50,25 +50,17 @@ struct DirectApIdentity {
}
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.
/// v2 intentionally uses short JSON keys. A Direct-AP QR carries only the
/// dedicated Wi-Fi identity, session and port: Android must join that Wi-Fi
/// and obtain the desktop gateway from the resulting route table. Existing
/// LAN/virtual-adapter addresses are deliberately excluded so they cannot
/// bypass or delay dedicated pairing.
pub fn encode_text(&self) -> Result<String> {
// 开了 Direct AP 时,此前只放一个 AP 地址进二维码,手机因此**必须**
// 切到那张虚拟网卡才能连上。可两台设备本来常常已经在同一个局域网里,
// 切过去反而引入了 ICS 网卡、独立防火墙配置和几十秒的配网等待。
//
// 现在无论是否开 Direct AP,都把常规局域网地址一并带上,
// 手机可以先在当前网络直连,连不上再切 AP。多两个短地址对
// 二维码密度的影响可以忽略。
// 取 4 个:Direct AP 场景要同时容纳 AP 网关地址与常规局域网地址,
// 只取 3 个时前者会被挤掉——手机于是连上了 AP 却找不到电脑。
let endpoints: Vec<&str> = self
.endpoints
.iter()
.take(4)
.map(String::as_str)
.collect();
let endpoints: Vec<&str> = if self.wifi.is_some() {
Vec::new()
} else {
self.endpoints.iter().take(4).map(String::as_str).collect()
};
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
let mut value = json!({
"v": 2,
@@ -193,9 +185,10 @@ pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
}
ips.sort_by_key(|ip| {
let o = ip.octets();
if is_likely_virtual(*ip) {
return 4;
}
match (o[0], o[1]) {
// Windows 的 ICS / Wi-Fi Direct 固定网段,最可能是 QFT 自己拉起来的
(192, 168) if o[2] == 137 || o[2] == 49 => 0,
(192, 168) => 1,
(10, _) => 2,
(172, 16..=31) => 3,
@@ -207,40 +200,14 @@ pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
/// 供二维码使用的端点列表。
///
/// `direct_ap_active` 为真时,把 ICS/Wi-Fi Direct 的固定网关地址放在最前。
/// 这一步不能省:二维码是在启动接收的瞬间生成的,而那块虚拟网卡往往
/// **还没拿到 IP**,因此它不会出现在 get_if_addrs 的结果里。可手机连上
/// AP 之后,网关恰恰就是这个地址——漏掉它,手机就会连上了 Wi-Fi 却
/// 找不到电脑。
/// Direct AP 模式不广播任何电脑现有网卡地址。手机必须先加入二维码中的
/// 专用 Wi-Fi,再从 Android 为该连接提供的实际路由表读取网关。这样不会
/// 猜测 192.168.137.1/49.1,也不会误连 LAN、VPN、WSL 或虚拟机网卡。
pub fn qr_endpoints(port: u16, direct_ap_active: bool) -> Vec<String> {
let mut endpoints = local_ipv4_endpoints(port);
if direct_ap_active {
// Direct AP 场景下二维码名额尤其紧张(只放得下 4 个),而手机此刻
// 连的是 AP 网段,虚拟网卡地址永远到不了,却会挤掉真正可用的地址。
// 这里直接剔除而不只是降权——降权在名额少时救不了场。
endpoints.retain(|endpoint| !is_virtual_endpoint(endpoint));
for ap in [
format!("http://192.168.137.1:{port}"),
format!("http://192.168.49.1:{port}"),
].into_iter().rev() {
endpoints.retain(|e| *e != ap);
endpoints.insert(0, ap);
}
return Vec::new();
}
endpoints
}
/// 判断地址是否多半来自虚拟网卡。
///
/// 依据的是各家虚拟化产品的默认网段,且都以 `.1` 结尾(宿主机在虚拟网络里
/// 通常是网关)。这只是启发式,因此调用方只降权、不丢弃。
/// 判断 `http://IP:port` 形式的端点是否指向虚拟网卡。
fn is_virtual_endpoint(endpoint: &str) -> bool {
endpoint
.strip_prefix("http://")
.and_then(|rest| rest.split(':').next())
.and_then(|host| host.parse::<Ipv4Addr>().ok())
.is_some_and(is_likely_virtual)
local_ipv4_endpoints(port)
}
fn is_likely_virtual(ip: Ipv4Addr) -> bool {
@@ -259,43 +226,9 @@ fn is_likely_virtual(ip: Ipv4Addr) -> bool {
}
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);
}
}
}
// 真实存在的网卡地址排在前面,其中 Direct AP 常用的两个网段优先;
// 随后才补上猜测性的兜底地址。此前无条件把 192.168.137.1 / 49.1 排在
// 最前,即使本机根本没有这两块网卡——手机于是先去探测两个不存在的
// 地址,真正可用的局域网地址反而被挤到后面。
ips.sort_by_key(|ip| {
if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 }
else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 }
// 虚拟网卡(VMware / Hyper-V / WSL / Docker)的地址手机永远到不了,
// 却会占满二维码里有限的名额,把真正可达的地址挤出去——实测中
// 192.168.30.1、192.168.31.1、172.21.96.1 就是这样把 AP 网关顶掉的。
// 不删除,只降权:万一某台机器真用这些网段做局域网,仍能兜底。
else if is_likely_virtual(*ip) { 4 }
else if ip.is_private() { 2 }
else { 3 }
});
for fallback in [
Ipv4Addr::new(192, 168, 137, 1),
Ipv4Addr::new(192, 168, 49, 1),
] {
if !ips.contains(&fallback) {
ips.push(fallback);
}
}
ips.into_iter()
// 备用 LAN 模式也只广播系统中真实存在的私有地址,不再追加
// 192.168.137.1/49.1 等猜测值。Android 随后还会按实际子网过滤。
local_ipv4_addresses().into_iter()
.map(|ip| format!("http://{ip}:{port}"))
.collect()
}
@@ -329,34 +262,19 @@ mod tests {
mod endpoint_order_tests {
use super::*;
/// 二维码里的地址顺序直接决定手机先探测谁。真实网卡必须排在
/// 猜测性兜底地址之前,否则手机会先去连两个根本不存在的地址。
#[test]
fn real_interfaces_come_before_guessed_fallbacks() {
fn current_lan_endpoints_are_all_real_private_interfaces() {
let endpoints = local_ipv4_endpoints(39393);
assert!(!endpoints.is_empty(), "至少应有兜底地址");
let real: Vec<Ipv4Addr> = local_ipv4_addresses();
let guessed = ["http://192.168.137.1:39393", "http://192.168.49.1:39393"];
for address in &real {
let endpoint = format!("http://{address}:39393");
let Some(position) = endpoints.iter().position(|e| *e == endpoint) else { continue };
for guess in guessed {
// 若某个兜底地址并非本机真实网卡,它必须排在真实网卡之后
if real.iter().any(|ip| format!("http://{ip}:39393") == guess) { continue }
if let Some(guess_position) = endpoints.iter().position(|e| e == guess) {
assert!(
position < guess_position,
"真实地址 {endpoint} 应排在猜测地址 {guess} 之前:{endpoints:?}"
);
}
}
}
let expected: Vec<String> = real
.iter()
.map(|address| format!("http://{address}:39393"))
.collect();
assert_eq!(endpoints, expected);
}
#[test]
fn download_pairing_carries_lan_endpoints_even_with_direct_ap() {
// 开了 Direct AP 也要带上局域网地址,否则手机必须切网才能连
fn direct_pairing_excludes_every_preexisting_computer_address() {
let payload = PairingPayload {
v: 2,
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
@@ -383,8 +301,10 @@ mod endpoint_order_tests {
.decode(text.trim_start_matches(PAIR_PREFIX))
.unwrap(),
).unwrap();
assert!(json.contains("192.168.8.68"), "局域网地址必须进二维码:{json}");
assert!(json.contains("192.168.137.1"), "Direct AP 地址也应保留:{json}");
assert!(!json.contains("192.168.8.68"), "Direct 二维码不得携带 LAN 地址:{json}");
assert!(!json.contains("192.168.137.1"), "Direct 二维码不得猜测 AP 网关:{json}");
assert!(json.contains("\"e\":[]"), "Direct 二维码端点必须为空:{json}");
assert!(json.contains("QFT-PC-abc"), "专用 Wi-Fi 身份必须保留:{json}");
}
}
@@ -392,36 +312,24 @@ mod endpoint_order_tests {
mod qr_endpoint_tests {
use super::*;
/// Direct AP 的网关地址必须出现在二维码里,且排在最前。
///
/// 这是一个真实发生过的回退:把"猜测性兜底地址"挪到列表末尾后,
/// 二维码只取前 3 个,192.168.137.1 被挤了出去。手机连上了 AP、
/// 拿到了 192.168.137.200/24,却在二维码里找不到 192.168.137.1,
/// 表现为"Wi-Fi 已连接但找不到电脑"——从现象几乎无法反推到这里。
#[test]
fn direct_ap_gateway_is_always_advertised_first() {
fn direct_ap_never_advertises_guessed_or_local_addresses() {
let endpoints = qr_endpoints(39393, true);
assert_eq!(
endpoints.first().map(String::as_str),
Some("http://192.168.137.1:39393"),
"Direct AP 网关必须排第一:{endpoints:?}"
);
assert!(
endpoints.iter().any(|e| e == "http://192.168.49.1:39393"),
"Wi-Fi Direct 的另一个常用网段也应保留:{endpoints:?}"
);
assert!(endpoints.is_empty(), "Direct 模式只能由手机读取实际网关:{endpoints:?}");
}
#[test]
fn direct_ap_addresses_survive_the_qr_length_cap() {
// 即使本机有很多张网卡,AP 地址也不能被截断掉
fn direct_ap_encoding_stays_address_free_even_with_input_endpoints() {
let payload = PairingPayload {
v: 2,
session: "abcdefghijklmnopqrstuvwxyz012345".into(),
pc_name: "PC".into(),
transport: "http-parallel-v2".into(),
port: 39393,
endpoints: qr_endpoints(39393, true),
endpoints: vec![
"http://192.168.137.1:39393".into(),
"http://10.20.30.40:39393".into(),
],
wifi: Some(WifiCredentials {
ssid: "QFT-PC-abc".into(),
passphrase: "0123456789ab".into(),
@@ -438,19 +346,21 @@ mod qr_endpoint_tests {
.decode(text.trim_start_matches(PAIR_PREFIX))
.unwrap(),
).unwrap();
assert!(json.contains("192.168.137.1"), "AP 网关必须进二维码:{json}");
assert!(!json.contains("192.168.137.1"), "不得携带猜测网关:{json}");
assert!(!json.contains("10.20.30.40"), "不得携带本地网卡:{json}");
}
#[test]
fn without_direct_ap_the_guessed_addresses_stay_at_the_back() {
fn without_direct_ap_no_guessed_addresses_are_added() {
let endpoints = qr_endpoints(39393, false);
// 没开 AP 时不该把两个猜测地址顶到前面去占位
if endpoints.len() > 2 {
assert_ne!(
endpoints.first().map(String::as_str),
Some("http://192.168.137.1:39393"),
"未开 Direct AP 时不应优先猜测地址:{endpoints:?}"
);
let real = local_ipv4_addresses();
for guessed in ["192.168.137.1", "192.168.49.1"] {
if !real.iter().any(|ip| ip.to_string() == guessed) {
assert!(
!endpoints.iter().any(|endpoint| endpoint.contains(guessed)),
"不存在的地址不得加入二维码:{endpoints:?}"
);
}
}
}
}
@@ -482,34 +392,3 @@ mod virtual_adapter_tests {
assert!(!is_likely_virtual("172.21.96.200".parse().unwrap()));
}
}
#[cfg(test)]
mod direct_ap_filter_tests {
use super::*;
#[test]
fn virtual_endpoints_are_dropped_when_direct_ap_is_on() {
let endpoints = qr_endpoints(39393, true);
for endpoint in &endpoints {
assert!(
!is_virtual_endpoint(endpoint),
"Direct AP 下不应出现虚拟网卡端点:{endpoint}(完整列表 {endpoints:?})"
);
}
// 剔除之后 AP 网关仍须在最前
assert_eq!(
endpoints.first().map(String::as_str),
Some("http://192.168.137.1:39393")
);
}
#[test]
fn endpoint_parser_handles_malformed_input() {
assert!(is_virtual_endpoint("http://192.168.30.1:39393"));
assert!(!is_virtual_endpoint("http://192.168.8.68:39393"));
// 解析不了的一律不当作虚拟网卡,避免误删真实地址
assert!(!is_virtual_endpoint("garbage"));
assert!(!is_virtual_endpoint("http://:39393"));
assert!(!is_virtual_endpoint(""));
}
}