fix Wi-Fi Direct legacy connection acceptance

This commit is contained in:
zhy200308
2026-08-12 12:41:46 +08:00
parent 144b7d1a8e
commit d7a29e035f
4 changed files with 199 additions and 25 deletions
+110 -7
View File
@@ -9,14 +9,62 @@ use windows::{
Devices::WiFiDirect::{
WiFiDirectAdvertisementListenStateDiscoverability, WiFiDirectAdvertisementPublisher,
WiFiDirectAdvertisementPublisherStatus,
WiFiDirectAdvertisementPublisherStatusChangedEventArgs, WiFiDirectConnectionListener,
WiFiDirectConnectionRequestedEventArgs, WiFiDirectDevice,
},
Foundation::TypedEventHandler,
Security::Credentials::PasswordCredential,
};
#[cfg(windows)]
use std::sync::{Arc, Mutex};
#[cfg(windows)]
fn create_connection_listener(
connected_devices: &Arc<Mutex<Vec<WiFiDirectDevice>>>,
) -> windows::core::Result<(WiFiDirectConnectionListener, i64)> {
let callback_devices = Arc::clone(connected_devices);
let listener = WiFiDirectConnectionListener::new()?;
let handler = TypedEventHandler::<
WiFiDirectConnectionListener,
WiFiDirectConnectionRequestedEventArgs,
>::new(move |_sender, args| {
let request = args.ok()?.GetConnectionRequest()?;
let device_id = request.DeviceInformation()?.Id()?;
let operation = WiFiDirectDevice::FromIdAsync(&device_id)?;
let devices = Arc::clone(&callback_devices);
// Do not block the WinRT event thread while Windows completes the peer
// connection. `join` also keeps the async operation alive until it
// yields the device we must retain.
std::thread::spawn(move || {
if let Ok(device) = operation.join() {
if let Ok(mut devices) = devices.lock() {
devices.retain(|known| known.DeviceId().ok() != device.DeviceId().ok());
devices.push(device);
}
}
});
Ok(())
});
let token = listener.ConnectionRequested(&handler)?;
Ok((listener, token))
}
pub struct DirectAp {
pub ssid: String,
#[cfg(windows)]
publisher: WiFiDirectAdvertisementPublisher,
/// Legacy AP 只负责让普通 Wi-Fi 客户端关联和取得 DHCP 地址;Windows
/// 还要求应用接受 Wi-Fi Direct connection request,数据通道才会真正建立。
#[cfg(windows)]
connection_listener: WiFiDirectConnectionListener,
#[cfg(windows)]
connection_requested_token: i64,
/// 必须长期持有 `WiFiDirectDevice`。对象一旦被释放,Windows 会拆掉该
/// peer 的 Wi-Fi Direct 会话,表现为手机仍连着 SSID、却访问不到网关端口。
#[cfg(windows)]
connected_devices: Arc<Mutex<Vec<WiFiDirectDevice>>>,
}
impl DirectAp {
@@ -58,27 +106,74 @@ impl DirectAp {
legacy.SetPassphrase(&credential)
.context("应用 QFT 热点密码失败")?;
// Follow Microsoft's Legacy AP lifecycle exactly: install the
// connection listener from the publisher's Started callback. QFT
// keeps a stable SSID/password, so Android can auto-reassociate as
// soon as the AP appears; polling first and adding the listener
// afterwards can miss that one connection request.
type ListenerResult = std::result::Result<
(WiFiDirectConnectionListener, i64),
String,
>;
let connected_devices = Arc::new(Mutex::new(Vec::<WiFiDirectDevice>::new()));
let listener_state = Arc::new(Mutex::new(None::<ListenerResult>));
let callback_devices = Arc::clone(&connected_devices);
let callback_state = Arc::clone(&listener_state);
let status_handler = TypedEventHandler::<
WiFiDirectAdvertisementPublisher,
WiFiDirectAdvertisementPublisherStatusChangedEventArgs,
>::new(move |_sender, args| {
if args.ok()?.Status()? == WiFiDirectAdvertisementPublisherStatus::Started {
let result = create_connection_listener(&callback_devices)
.map_err(|error| error.to_string());
if let Ok(mut state) = callback_state.lock() {
if state.is_none() {
*state = Some(result);
}
}
}
Ok(())
});
let status_token = publisher
.StatusChanged(&status_handler)
.context("监听 Wi-Fi Direct AP 启动状态失败")?;
publisher.Start().context("启动 QFT Wi-Fi Direct AP 失败")?;
// Publisher startup is asynchronous. Do not expose the pairing QR until
// Windows reports Started; otherwise Android can scan a network that is
// not yet discoverable.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
let status = publisher.Status().context("读取 AP 状态失败")?;
if status == WiFiDirectAdvertisementPublisherStatus::Started {
break;
let (connection_listener, connection_requested_token) = loop {
if let Ok(mut state) = listener_state.lock() {
if let Some(result) = state.take() {
break result.map_err(anyhow::Error::msg)?;
}
}
let status = publisher.Status().context("读取 AP 状态失败")?;
if status == WiFiDirectAdvertisementPublisherStatus::Aborted {
bail!("Wi-Fi Direct AP 启动被系统中止。请确认 Windows Wi-Fi 已开启,且系统移动热点未占用 Wi-Fi Direct。")
}
if std::time::Instant::now() >= deadline {
bail!("Wi-Fi Direct AP 启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。")
bail!("Wi-Fi Direct AP 或连接监听器启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。")
}
std::thread::sleep(std::time::Duration::from_millis(80));
}
};
let _ = publisher.RemoveStatusChanged(status_token);
Ok(Self { ssid, publisher })
// This is not optional bookkeeping. Microsoft's Legacy AP sample
// creates the connection listener after the publisher reaches
// Started, accepts each request with FromIdAsync, and retains the
// resulting WiFiDirectDevice. Without these steps Android still
// associates and receives 192.168.137.x via DHCP, but TCP/UDP to
// 192.168.137.1 never reaches the desktop process.
Ok(Self {
ssid,
publisher,
connection_listener,
connection_requested_token,
connected_devices,
})
}
}
}
@@ -87,6 +182,14 @@ impl Drop for DirectAp {
fn drop(&mut self) {
#[cfg(windows)]
{
let _ = self
.connection_listener
.RemoveConnectionRequested(self.connection_requested_token);
if let Ok(mut devices) = self.connected_devices.lock() {
for device in devices.drain(..) {
let _ = device.Close();
}
}
let _ = self.publisher.Stop();
}
}
+86 -16
View File
@@ -8,8 +8,9 @@
//! 1. **只在确实缺规则时申请**。每次启动都弹 UAC 是骚扰。
//! 2. **没有放行就不宣称 Direct 已就绪**。用户明确点击“启动直传/接收”时,
//! 可以走一次标准 UAC;拒绝或复检失败就停止启动,不生成不可用二维码。
//! 3. **规则尽量窄**。只放行本程序这一个可执行文件,绝不整体关闭防火墙。
//! 但**不能按网络配置文件收窄**——见下方 `grant()` 里的说明。
//! 3. **规则尽量窄**。程序规则之外只开放 QFT 固定的 TCP/UDP 两个端口,
//! 绝不整体关闭防火墙;但**不能按网络配置文件收窄**——见下方
//! `grant()` 里的说明。
//!
//! 提权本身由操作系统的标准机制完成(Windows 的 UAC、macOS 的
//! 授权对话框),程序不接触也不存储任何凭据。
@@ -21,6 +22,14 @@ use std::path::PathBuf;
// 仅 Windows 分支使用;其余平台整段被 cfg 编译掉
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub const RULE_NAME: &str = "QFT Desktop";
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
const DIRECT_TCP_RULE: &str = "QFT-Desktop-Direct-TCP-v2";
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
const DIRECT_UDP_RULE: &str = "QFT-Desktop-Direct-UDP-v2";
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
const DIRECT_TCP_PORT: u16 = 39393;
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
const DIRECT_UDP_PORT: u16 = 39392;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FirewallStatus {
@@ -114,6 +123,11 @@ Get-NetFirewallProfile | ForEach-Object {{
Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Sort-Object -Property Name -Unique | ForEach-Object {{
"RULE|$($_.Enabled)|$($_.Direction)|$($_.Action)|$($_.Profile)|$($_.DisplayName)"
}}
Get-NetFirewallRule -Name '{DIRECT_TCP_RULE}','{DIRECT_UDP_RULE}' | ForEach-Object {{
$rule = $_
$filter = $rule | Get-NetFirewallPortFilter
"PORT|$($rule.Enabled)|$($rule.Direction)|$($rule.Action)|$($rule.Profile)|$($filter.Protocol)|$($filter.LocalPort)|$($rule.Name)"
}}
"#,
// PowerShell 单引号字符串里只需把单引号写成两个,反斜杠不转义,
// 正好适合 Windows 路径
@@ -138,6 +152,8 @@ pub fn classify_probe(probe_output: &str) -> FirewallStatus {
let mut has_block_rule = false;
let mut blocking_rules: Vec<&str> = Vec::new();
let mut has_usable_allow = false;
let mut has_direct_tcp = false;
let mut has_direct_udp = false;
for line in probe_output.lines() {
let fields: Vec<&str> = line.trim().split('|').collect();
@@ -165,6 +181,25 @@ pub fn classify_probe(probe_output: &str) -> FirewallStatus {
has_usable_allow = true;
}
}
["PORT", enabled, direction, action, profile, protocol, local_port, _name] => {
let usable = enabled.eq_ignore_ascii_case("true")
&& direction.eq_ignore_ascii_case("inbound")
&& action.eq_ignore_ascii_case("allow")
&& profile.eq_ignore_ascii_case("any");
let port = local_port.parse::<u16>().ok();
if usable
&& (protocol.eq_ignore_ascii_case("tcp") || *protocol == "6")
&& port == Some(DIRECT_TCP_PORT)
{
has_direct_tcp = true;
}
if usable
&& (protocol.eq_ignore_ascii_case("udp") || *protocol == "17")
&& port == Some(DIRECT_UDP_PORT)
{
has_direct_udp = true;
}
}
_ => {}
}
}
@@ -183,7 +218,7 @@ pub fn classify_probe(probe_output: &str) -> FirewallStatus {
return FirewallStatus::BlockedByRule(blocking_rules.join("、"));
}
// 防火墙整个关着时入站不会被拦,没必要要求存在规则
if !any_firewall_on || has_usable_allow {
if !any_firewall_on || (has_usable_allow && has_direct_tcp && has_direct_udp) {
FirewallStatus::Allowed
} else {
FirewallStatus::Missing
@@ -213,6 +248,11 @@ fn grant_script(exe: &str, marker: &str) -> String {
# (尤其是 Direct AP 虚拟网卡)默认归为公用网络。\r\n\
Remove-NetFirewallRule -DisplayName '{RULE_NAME}' -ErrorAction SilentlyContinue\r\n\
New-NetFirewallRule -DisplayName '{RULE_NAME}' -Direction Inbound -Program $exe -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
# 两条窄端口规则不依赖 exe 路径字符串的 WFP 归一化结果,专门兜住\r\n\
# Wi-Fi Direct 虚拟网卡上的 TCP/UDP 数据通道。\r\n\
Remove-NetFirewallRule -Name '{DIRECT_TCP_RULE}','{DIRECT_UDP_RULE}' -ErrorAction SilentlyContinue\r\n\
New-NetFirewallRule -Name '{DIRECT_TCP_RULE}' -DisplayName 'QFT Direct TCP' -Direction Inbound -Protocol TCP -LocalPort {DIRECT_TCP_PORT} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
New-NetFirewallRule -Name '{DIRECT_UDP_RULE}' -DisplayName 'QFT Direct UDP' -Direction Inbound -Protocol UDP -LocalPort {DIRECT_UDP_PORT} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow | Out-Null\r\n\
# 只有真的建成了才写标记,调用方据此判断成败\r\n\
Set-Content -Path $marker -Value 'ok' -Encoding ASCII\r\n"
)
@@ -402,8 +442,6 @@ pub fn manual_instructions(port: u16) -> String {
#[cfg(target_os = "windows")]
{
// 程序级规则不按端口放行,端口只在手动说明的 Linux 分支里用得上
let _ = port;
// -Profile Any 是必须的。这里早先写的是 Private,Domain,与本模块
// grant() 的注释自相矛盾,照抄的用户会重建出一条在公用网络上
// (也就是 Direct AP 虚拟网卡上)根本不适用的规则。
@@ -412,13 +450,24 @@ pub fn manual_instructions(port: u16) -> String {
// 同理绝不使用 `\` 续行——那是 bash 语法,PowerShell 用反引号;
// 一条命令就写一行,宁可长。
format!(
"# 在管理员 PowerShell 中整段粘贴执行\n\
$exe = \"{exe}\"\n\
Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} | Remove-NetFirewallRule\n\
Remove-NetFirewallRule -DisplayName \"{RULE_NAME}\" -ErrorAction SilentlyContinue\n\
New-NetFirewallRule -DisplayName \"{RULE_NAME}\" -Direction Inbound -Program $exe -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n\
Get-NetFirewallProfile | Select-Object Name,Enabled,AllowInboundRules\n\
Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Select-Object DisplayName,Enabled,Direction,Action,Profile\n"
concat!(
"# 在管理员 PowerShell 中整段粘贴执行\n",
"$exe = \"{exe}\"\n",
"Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} | Remove-NetFirewallRule\n",
"Remove-NetFirewallRule -DisplayName \"{RULE_NAME}\" -ErrorAction SilentlyContinue\n",
"New-NetFirewallRule -DisplayName \"{RULE_NAME}\" -Direction Inbound -Program $exe -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
"Remove-NetFirewallRule -Name \"{DIRECT_TCP_RULE}\",\"{DIRECT_UDP_RULE}\" -ErrorAction SilentlyContinue\n",
"New-NetFirewallRule -Name \"{DIRECT_TCP_RULE}\" -DisplayName \"QFT Direct TCP\" -Direction Inbound -Protocol TCP -LocalPort {port} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
"New-NetFirewallRule -Name \"{DIRECT_UDP_RULE}\" -DisplayName \"QFT Direct UDP\" -Direction Inbound -Protocol UDP -LocalPort {udp_port} -Action Allow -Profile Any -Enabled True -EdgeTraversalPolicy Allow\n",
"Get-NetFirewallProfile | Select-Object Name,Enabled,AllowInboundRules\n",
"Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule | Select-Object DisplayName,Enabled,Direction,Action,Profile\n",
),
exe = exe,
RULE_NAME = RULE_NAME,
DIRECT_TCP_RULE = DIRECT_TCP_RULE,
DIRECT_UDP_RULE = DIRECT_UDP_RULE,
port = port,
udp_port = port.saturating_sub(1),
)
}
#[cfg(target_os = "macos")]
@@ -489,13 +538,17 @@ mod tests {
const PROFILES_OK: &str = "PROFILE|Domain|True|Block|True\n\
PROFILE|Private|True|Block|True\n\
PROFILE|Public|True|Block|True";
const DIRECT_PORTS_OK: &str = "PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
#[test]
fn allow_rule_must_cover_any_profile() {
let only_private = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Domain, Private|QFT Desktop");
assert_eq!(classify_probe(&only_private), FirewallStatus::Missing);
let any = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop");
let any = format!(
"{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop\n{DIRECT_PORTS_OK}"
);
assert_eq!(classify_probe(&any), FirewallStatus::Allowed);
}
@@ -505,6 +558,15 @@ mod tests {
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
}
#[test]
fn legacy_program_rule_without_direct_ports_is_migrated() {
let old = format!("{PROFILES_OK}\nRULE|True|Inbound|Allow|Any|QFT Desktop");
assert_eq!(classify_probe(&old), FirewallStatus::Missing);
let only_tcp = format!("{old}\n{}", DIRECT_PORTS_OK.lines().next().unwrap());
assert_eq!(classify_probe(&only_tcp), FirewallStatus::Missing);
}
#[test]
fn outbound_rules_are_irrelevant() {
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Allow|Any|QFT Desktop");
@@ -539,7 +601,8 @@ mod tests {
let text = format!(
"{PROFILES_OK}\n\
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
RULE|False|Inbound|Block|Public|qft-desktop.exe"
RULE|False|Inbound|Block|Public|qft-desktop.exe\n\
{DIRECT_PORTS_OK}"
);
assert_eq!(classify_probe(&text), FirewallStatus::Allowed);
}
@@ -569,7 +632,9 @@ mod tests {
let text = "PROFILE|Domain|True|Block|True\n\
PROFILE|Private|True|Block|True\n\
PROFILE|Public|False|Block|False\n\
RULE|True|Inbound|Allow|Any|QFT Desktop";
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
}
@@ -584,7 +649,9 @@ mod tests {
#[test]
fn not_configured_inbound_setting_is_not_a_blanket_block() {
let text = "PROFILE|Public|True|Block|NotConfigured\n\
RULE|True|Inbound|Allow|Any|QFT Desktop";
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
PORT|True|Inbound|Allow|Any|TCP|39393|QFT-Desktop-Direct-TCP-v2\n\
PORT|True|Inbound|Allow|Any|UDP|39392|QFT-Desktop-Direct-UDP-v2";
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
}
@@ -657,6 +724,8 @@ mod tests {
assert!(script.contains("Set-Content -Path $marker"));
assert!(script.contains("-Profile Any"));
assert!(script.contains("-EdgeTraversalPolicy Allow"));
assert!(script.contains("-Protocol TCP -LocalPort 39393"));
assert!(script.contains("-Protocol UDP -LocalPort 39392"));
// 单引号要按 PowerShell 的规则翻倍转义
let tricky = grant_script("C:\\o'brien\\qft.exe", "C:\\t.ok");
assert!(tricky.contains("'C:\\o''brien\\qft.exe'"), "{tricky}");
@@ -670,6 +739,7 @@ mod tests {
!script.contains("Get-NetFirewallRule -DisplayName"),
"只按同名规则查询会把旧构建路径误判为已放行:{script}"
);
assert!(script.contains("Get-NetFirewallRule -Name 'QFT-Desktop-Direct-TCP-v2'"));
}
#[test]