fix(desktop): 修复防火墙面板在「电脑→Android」页面是死代码,并重做 Windows 检测

上一版我说"两个页面都加了",但用户在 v0.4.9 上依然看不到。这次不猜了,
把程序真跑起来截图,看到面板确实没画出来,才找到原因:

pc_to_phone_ui 在 running 时于函数中段就 return 进了 resizable/focus 分支,
我加的那 37 行写在函数尾部,永远执行不到——代码在、grep 得到、但一个像素
都不会画。前两次自查只 grep 了"firewall_panel 在不在",没确认它在不在活的
分支上。面板已移到 pc_to_phone_running_controls(真正渲染的运行态控制区)。

为防同类缺陷复发,加了两个**真渲染**测试:在无窗口 egui 上下文里跑一帧,
把 galley 里的文字抓出来断言。grep 源码挡不住死代码,只有画一遍才行。
另外把 pc_receive_ui 里内联复制的第三份面板也收敛到 firewall_panel。

Windows 防火墙检测重做(这才是"点了放行还是连不上"的根因方向):

1. 改用 PowerShell 而非 netsh。netsh 输出的**值**会本地化(中文系统上是
   「允许/阻止/任何/是」),原先按 "Any"/"Yes" 匹配在中文 Windows 上必然
   误判;Get-NetFirewallRule 返回的枚举在任何语言下都是 Allow/Block/Any。

2. 按**程序路径**查询,不再只按规则显示名。用户在「安全警报」弹窗上点了
   取消时,Windows 会自建一条针对该 exe 的阻止规则,名字是程序名而不是
   QFT Desktop。只按显示名查完全看不见它,而 Block 在 Windows 里永远压过
   Allow——症状正是"点了放行、界面显示已放行、手机依然连不上"。
   grant() 现在会先清掉这类阻止规则再重建放行规则。

3. 检测「阻止所有传入连接,包括位于允许应用列表中的应用」
   (AllowInboundRules=False)。这项打开时加多少规则都没用,单独报为
   BlockedByPolicy,按钮相应置灰并说明要去哪里关——它属于用户的安全设置,
   程序不代劳。

4. manual_instructions 里的 -Profile Private,Domain 是个真 bug,与本模块
   自己的注释矛盾:照抄的用户会重建出一条在 Direct AP 虚拟网卡(被判为
   公用网络)上根本不适用的规则。改为 -Profile Any 并补上排查步骤。

5. grant() 成功后不再直接断言"已放行",改为触发复检——规则加上了不等于
   入站真的通了。

检测要起 PowerShell 进程(1~2 秒),移到后台线程,避免在"启动接收"的瞬间
卡住界面。解析逻辑抽成纯函数 classify_probe,配 10 个用例覆盖中文系统、
自动阻止规则、系统级封禁、防火墙整体关闭等场景——Windows 专有代码最容易
烂在没人跑的地方。已用 cargo check --target x86_64-pc-windows-gnu 验证
Windows 分支能编过。

版本号 0.4.9 → 0.4.10,便于确认拿到的是新构建。
This commit is contained in:
zhy200308
2026-08-12 09:55:12 +08:00
parent 4c294d4270
commit 2bb6ce63ae
4 changed files with 511 additions and 119 deletions
+349 -37
View File
@@ -28,6 +28,20 @@ pub enum FirewallStatus {
Allowed,
/// 缺少放行规则,入站很可能被拦
Missing,
/// 规则本身没问题,但系统层面的策略让任何放行规则都不生效。
///
/// 对应 Windows 的「阻止所有传入连接,包括位于允许应用列表中的应用」
/// (`BlockInboundAlways`)。这一项打开时,用户点多少次「放行防火墙」
/// 都不会有任何变化——必须先把它关掉,所以要单独报出来。
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
BlockedByPolicy(String),
/// 存在针对本程序的「阻止」入站规则,压过了我们的放行规则。
///
/// 通常是用户在 Windows「安全警报」弹窗上点了取消后系统自动建的,
/// 规则名是程序名而非 `QFT Desktop`。这一类提权后可以自动清掉,
/// 所以和 [`BlockedByPolicy`](Self::BlockedByPolicy) 分开表示。
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
BlockedByRule(String),
/// 查不出来(命令不可用、输出无法解析等),不要据此吓唬用户
Unknown(String),
/// 本平台不做自动放行(目前只有 Linux 会返回)
@@ -37,7 +51,32 @@ pub enum FirewallStatus {
impl FirewallStatus {
pub fn needs_action(&self) -> bool {
matches!(self, Self::Missing)
matches!(
self,
Self::Missing | Self::BlockedByPolicy(_) | Self::BlockedByRule(_)
)
}
/// 提权后加/删规则能否解决。
///
/// `BlockedByPolicy` 是系统级开关,我们不去动它——那属于用户的安全设置,
/// 只做提示,由用户自己决定是否关闭。
pub fn fixable_by_grant(&self) -> bool {
matches!(self, Self::Missing | Self::BlockedByRule(_))
}
/// 给界面用的一句话说明。
pub fn detail(&self) -> String {
match self {
Self::Allowed => "入站已放行".into(),
Self::Missing => "缺少放行规则,手机可能连不上".into(),
Self::BlockedByPolicy(reason) | Self::Unknown(reason) => reason.clone(),
Self::BlockedByRule(names) => format!(
"存在阻止本程序入站的规则({names}),它的优先级高于放行规则。\
点「放行防火墙」会连同这些阻止规则一起清掉。"
),
Self::Unsupported(reason) => (*reason).to_owned(),
}
}
}
@@ -47,37 +86,138 @@ fn current_exe() -> Result<PathBuf> {
// ---------------------------------------------------------------- Windows
/// 探测脚本。刻意用 PowerShell 而不是 netsh:
///
/// `netsh advfirewall show` 的**值**也会跟随系统语言本地化(中文 Windows 上
/// 是「允许 / 阻止 / 任何 / 是」),按英文关键字匹配在中文系统上必然误判;
/// 而 `Get-NetFirewallRule` 返回的是枚举,`Allow`/`Block`/`Any`/`True`
/// 在任何语言下都是这几个字面量。
///
/// 输出被压成一行一条的管道分隔记录,便于用纯函数解析、也便于在非 Windows
/// 上对解析逻辑写测试。
/// 注意查询是**按程序路径**做的,不是只按规则显示名。
///
/// 用户在 Windows 弹出「安全警报」时点了「取消」,系统会自己建一条针对该
/// 可执行文件的**阻止**规则,名字是程序名而不是我们的 `QFT Desktop`。
/// 只按显示名查完全看不到它,却又是它压着我们的放行规则——
/// 表现就是「点了放行、界面显示已放行,手机依然连不上」。
#[cfg(target_os = "windows")]
pub fn status() -> FirewallStatus {
fn probe_script(exe: &str) -> String {
format!(
r#"
$ErrorActionPreference='SilentlyContinue'
$exe = '{exe}'
Get-NetFirewallProfile | ForEach-Object {{
"PROFILE|$($_.Name)|$($_.Enabled)|$($_.DefaultInboundAction)|$($_.AllowInboundRules)"
}}
$byName = Get-NetFirewallRule -DisplayName '{RULE_NAME}'
$byPath = Get-NetFirewallApplicationFilter -Program $exe | Get-NetFirewallRule
@($byName) + @($byPath) | Where-Object {{ $_ }} | Sort-Object -Property Name -Unique | ForEach-Object {{
"RULE|$($_.Enabled)|$($_.Direction)|$($_.Action)|$($_.Profile)|$($_.DisplayName)"
}}
"#,
// PowerShell 单引号字符串里只需把单引号写成两个,反斜杠不转义,
// 正好适合 Windows 路径
exe = exe.replace('\'', "''"),
)
}
/// 解析 [`PROBE_SCRIPT`] 的输出。放在这里而不是内联,是为了能在任意平台
/// 上用真实样本做测试——Windows 专有逻辑最容易腐烂在没人跑的地方。
///
/// 判定顺序是有讲究的:
/// 1. **先看系统级策略**。`AllowInboundRules=False` 对应「阻止所有传入连接,
/// 包括位于允许应用列表中的应用」。这项打开时用户点多少次放行都没有
/// 任何变化,必须先报出来,否则会得出「规则已就绪」的错误结论。
/// 2. **再看有没有阻止规则**。Windows 里 Block 永远压过 Allow,旧版本残留
/// 的阻止规则会让新加的放行规则彻底失效,而界面上两条都显示「已启用」。
/// 3. **最后才看放行规则**,且必须是 `Any` profile——手机连的那块 Direct AP
/// 虚拟网卡会被判为「公用网络」,只覆盖专用/域的规则在它上面不适用。
pub fn classify_probe(probe_output: &str) -> FirewallStatus {
let mut any_firewall_on = false;
let mut blanket_block: Vec<&str> = Vec::new();
let mut has_block_rule = false;
let mut blocking_rules: Vec<&str> = Vec::new();
let mut has_usable_allow = false;
for line in probe_output.lines() {
let fields: Vec<&str> = line.trim().split('|').collect();
match fields.as_slice() {
["PROFILE", name, enabled, _default_inbound, allow_inbound] => {
let on = enabled.eq_ignore_ascii_case("true");
any_firewall_on |= on;
// AllowInboundRules 还可能是 NotConfigured,那不算封禁
if on && allow_inbound.eq_ignore_ascii_case("false") {
blanket_block.push(name);
}
}
["RULE", enabled, direction, action, profile, display_name] => {
if !direction.eq_ignore_ascii_case("inbound") {
continue;
}
// 只有启用中的阻止规则才真正生效
if action.eq_ignore_ascii_case("block") && enabled.eq_ignore_ascii_case("true") {
has_block_rule = true;
blocking_rules.push(*display_name);
} else if enabled.eq_ignore_ascii_case("true")
&& action.eq_ignore_ascii_case("allow")
&& profile.eq_ignore_ascii_case("any")
{
has_usable_allow = true;
}
}
_ => {}
}
}
if !blanket_block.is_empty() {
return FirewallStatus::BlockedByPolicy(format!(
"{} 配置文件启用了「阻止所有传入连接,包括位于允许应用列表中的应用」。\
这一项打开时,放行规则不起任何作用,必须先在\
「Windows 安全中心 → 防火墙和网络保护」里把它关掉。",
blanket_block.join("、")
));
}
if has_block_rule {
// 这类规则多半是用户在「安全警报」弹窗上点了取消后由系统自动建的,
// 名字五花八门,所以把实际名字列出来,用户手动排查时才有的放矢。
return FirewallStatus::BlockedByRule(blocking_rules.join("、"));
}
// 防火墙整个关着时入站不会被拦,没必要要求存在规则
if !any_firewall_on || has_usable_allow {
FirewallStatus::Allowed
} else {
FirewallStatus::Missing
}
}
#[cfg(target_os = "windows")]
fn run_powershell(script: &str) -> std::io::Result<std::process::Output> {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let output = std::process::Command::new("netsh")
.args([
"advfirewall",
"firewall",
"show",
"rule",
&format!("name={RULE_NAME}"),
])
std::process::Command::new("powershell")
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.creation_flags(CREATE_NO_WINDOW)
.output();
.output()
}
match output {
Ok(out) if out.status.success() => {
// 光有同名规则还不够:规则若绑在不适用于当前网络的 profile 上,
// 会出现「显示已启用但照样被拦」。所以要求它是 profile=any。
#[cfg(target_os = "windows")]
pub fn status() -> FirewallStatus {
let exe = match current_exe() {
Ok(path) => path.display().to_string(),
Err(e) => return FirewallStatus::Unknown(format!("{e}")),
};
match run_powershell(&probe_script(&exe)) {
Ok(out) => {
let text = String::from_utf8_lossy(&out.stdout);
let any_profile = text.contains("Any") || text.contains("任何");
if any_profile {
FirewallStatus::Allowed
} else {
FirewallStatus::Missing
if text.trim().is_empty() {
return FirewallStatus::Unknown(
"防火墙查询没有返回任何内容,可能是 PowerShell 执行策略受限".into(),
);
}
classify_probe(&text)
}
// netsh 在找不到规则时退出码非 0
Ok(_) => FirewallStatus::Missing,
Err(e) => FirewallStatus::Unknown(format!("无法执行 netsh:{e}")),
Err(e) => FirewallStatus::Unknown(format!("无法执行 PowerShell:{e}")),
}
}
@@ -98,13 +238,25 @@ pub fn grant() -> Result<()> {
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let exe = current_exe()?;
let script = std::env::temp_dir().join(format!("qft-firewall-{}.bat", std::process::id()));
let exe_literal = exe.display().to_string().replace('\'', "''");
let script = std::env::temp_dir().join(format!("qft-firewall-{}.ps1", std::process::id()));
// 写成 .ps1 文件而不是把命令塞进 -ArgumentList:程序路径里带空格时,
// 经过 PowerShell 再到子进程会被重新分词,引号层层嵌套极易出错。
// 脚本文件里的单引号字符串不会被二次解析。
let content = format!(
"@echo off\r\n\
netsh advfirewall firewall delete rule name=\"{RULE_NAME}\" >nul 2>&1\r\n\
netsh advfirewall firewall add rule name=\"{RULE_NAME}\" dir=in action=allow \
program=\"{}\" enable=yes profile=any\r\n",
exe.display()
"$ErrorActionPreference='Stop'\r\n\
$exe = '{exe_literal}'\r\n\
# 先清掉一切针对本程序的入站阻止规则。Windows 在用户点掉「安全警报」\r\n\
# 弹窗时会自动建这种规则,名字是程序名,且优先级高于任何放行规则。\r\n\
Get-NetFirewallApplicationFilter -Program $exe -ErrorAction SilentlyContinue |\r\n\
\x20 Get-NetFirewallRule -ErrorAction SilentlyContinue |\r\n\
\x20 Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} |\r\n\
\x20 Remove-NetFirewallRule -ErrorAction SilentlyContinue\r\n\
# 重建放行规则。profile=any 是刻意的:Windows 把没见过的网络\r\n\
# (尤其是 Direct AP 虚拟网卡)默认归为公用网络。\r\n\
Remove-NetFirewallRule -DisplayName '{RULE_NAME}' -ErrorAction SilentlyContinue\r\n\
New-NetFirewallRule -DisplayName '{RULE_NAME}' -Direction Inbound -Program $exe \\\r\n\
\x20 -Action Allow -Profile Any -Enabled True | Out-Null\r\n"
);
std::fs::write(&script, content).context("写入临时放行脚本失败")?;
@@ -115,7 +267,7 @@ pub fn grant() -> Result<()> {
"Hidden",
"-Command",
&format!(
"Start-Process -FilePath cmd -ArgumentList '/c','\"{}\"' -Verb RunAs -WindowStyle Hidden -Wait",
"Start-Process -FilePath powershell -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','\"{}\"' -Verb RunAs -WindowStyle Hidden -Wait",
script.display()
),
])
@@ -222,11 +374,27 @@ pub fn manual_instructions(port: u16) -> String {
#[cfg(target_os = "windows")]
{
// 程序级规则不按端口放行,端口只在手动说明的 Linux 分支里用得上
let _ = port;
// -Profile Any 是必须的。这里早先写的是 Private,Domain,与本模块
// grant() 的注释自相矛盾,照抄的用户会重建出一条在公用网络上
// (也就是 Direct AP 虚拟网卡上)根本不适用的规则。
format!(
"以管理员身份打开 PowerShell,执行:\n\n\
"以管理员身份打开 PowerShell,依次执行:\n\n\
# 1. 清掉系统自动创建的阻止规则(它优先级高于放行规则)\n\
Get-NetFirewallApplicationFilter -Program \"{exe}\" |\n\
\x20 Get-NetFirewallRule |\n\
\x20 Where-Object {{ $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }} |\n\
\x20 Remove-NetFirewallRule\n\n\
# 2. 建立覆盖所有网络类型的放行规则\n\
Remove-NetFirewallRule -DisplayName \"{RULE_NAME}\" -ErrorAction SilentlyContinue\n\
New-NetFirewallRule -DisplayName \"{RULE_NAME}\" -Direction Inbound \\\n\
\x20 -Program \"{exe}\" -Action Allow -Profile Private,Domain\n\n\
或在「允许应用通过 Windows Defender 防火墙」里勾选该程序的专用网络。"
\x20 -Program \"{exe}\" -Action Allow -Profile Any\n\n\
# 3. 确认没有开启「阻止所有传入连接」\n\
Get-NetFirewallProfile | Select-Object Name,Enabled,AllowInboundRules\n\n\
第 3 步里 AllowInboundRules 若为 False,需要到\n\
「Windows 安全中心 → 防火墙和网络保护 → 对应网络」里\n\
取消勾选「阻止所有传入连接」,否则前两步都不会起作用。"
)
}
#[cfg(target_os = "macos")]
@@ -263,12 +431,21 @@ mod tests {
FirewallStatus::Allowed
| FirewallStatus::Missing
| FirewallStatus::Unsupported(_) => {}
FirewallStatus::Unknown(reason) => assert!(!reason.is_empty(), "未知原因不能为空"),
FirewallStatus::Unknown(reason)
| FirewallStatus::BlockedByPolicy(reason)
| FirewallStatus::BlockedByRule(reason) => {
assert!(!reason.is_empty(), "原因说明不能为空")
}
}
// 只有 Missing 才该触发后续动作
// Allowed / Unknown / Unsupported 都不该催促用户去点按钮
assert_eq!(
value.needs_action(),
matches!(value, FirewallStatus::Missing)
matches!(
value,
FirewallStatus::Missing
| FirewallStatus::BlockedByPolicy(_)
| FirewallStatus::BlockedByRule(_)
)
);
}
@@ -283,6 +460,141 @@ mod tests {
);
}
// 探测脚本的输出形状是固定的,解析逻辑在任何平台上都能测。
// Windows 专有代码最容易腐烂在没人跑的地方,这几个用例就是防这个的。
const PROFILES_OK: &str = "PROFILE|Domain|True|Block|True\n\
PROFILE|Private|True|Block|True\n\
PROFILE|Public|True|Block|True";
#[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");
assert_eq!(classify_probe(&any), FirewallStatus::Allowed);
}
#[test]
fn disabled_allow_rule_does_not_count() {
let text = format!("{PROFILES_OK}\nRULE|False|Inbound|Allow|Any|QFT Desktop");
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
}
#[test]
fn outbound_rules_are_irrelevant() {
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Allow|Any|QFT Desktop");
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
// 出站的阻止规则同样不该被误判成入站被拦
let text = format!("{PROFILES_OK}\nRULE|True|Outbound|Block|Any|随便什么");
assert_eq!(classify_probe(&text), FirewallStatus::Missing);
}
/// 这是「点了放行还是连不上」最常见的成因:用户在安全警报弹窗上点了取消,
/// 系统按程序路径建了一条阻止规则,名字和我们的规则完全不同。
#[test]
fn auto_created_block_rule_beats_our_allow_rule() {
let text = format!(
"{PROFILES_OK}\n\
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
RULE|True|Inbound|Block|Public|qft-desktop.exe"
);
match classify_probe(&text) {
FirewallStatus::BlockedByRule(names) => {
assert!(names.contains("qft-desktop.exe"), "要报出实际规则名:{names}");
}
other => panic!("阻止规则必须压过放行规则,实际判定为 {other:?}"),
}
// 这一类是可以靠提权自动清掉的
assert!(classify_probe(&text).fixable_by_grant());
assert!(classify_probe(&text).needs_action());
}
#[test]
fn disabled_block_rule_is_harmless() {
let text = format!(
"{PROFILES_OK}\n\
RULE|True|Inbound|Allow|Any|QFT Desktop\n\
RULE|False|Inbound|Block|Public|qft-desktop.exe"
);
assert_eq!(classify_probe(&text), FirewallStatus::Allowed);
}
/// 「阻止所有传入连接」打开时,加多少放行规则都没用,
/// 必须报成另一种状态,否则用户会一直点那个不起作用的按钮。
#[test]
fn blanket_inbound_block_is_reported_separately() {
let text = "PROFILE|Domain|True|Block|True\n\
PROFILE|Private|True|Block|True\n\
PROFILE|Public|True|Block|False\n\
RULE|True|Inbound|Allow|Any|QFT Desktop";
match classify_probe(text) {
FirewallStatus::BlockedByPolicy(reason) => {
assert!(reason.contains("Public"), "要指出是哪个配置文件:{reason}");
}
other => panic!("应报告系统级封禁,实际为 {other:?}"),
}
// 这一类我们不去动,属于用户的安全设置
assert!(!classify_probe(text).fixable_by_grant());
assert!(classify_probe(text).needs_action());
}
#[test]
fn blanket_block_on_a_disabled_profile_is_ignored() {
// 防火墙本身关着的配置文件,AllowInboundRules 是什么都无所谓
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";
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
}
#[test]
fn firewall_entirely_off_needs_no_rule() {
let text = "PROFILE|Domain|False|Block|True\n\
PROFILE|Private|False|Block|True\n\
PROFILE|Public|False|Block|True";
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
}
#[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";
assert_eq!(classify_probe(text), FirewallStatus::Allowed);
}
#[test]
fn every_status_has_a_non_empty_detail() {
for value in [
FirewallStatus::Allowed,
FirewallStatus::Missing,
FirewallStatus::BlockedByPolicy("策略".into()),
FirewallStatus::BlockedByRule("规则名".into()),
FirewallStatus::Unknown("原因".into()),
FirewallStatus::Unsupported("不支持"),
] {
assert!(!value.detail().trim().is_empty(), "{value:?} 缺少说明文案");
}
}
#[test]
fn manual_instructions_never_recreate_the_profile_bug() {
let text = manual_instructions(39393);
#[cfg(target_os = "windows")]
{
assert!(
text.contains("-Profile Any"),
"手动命令必须覆盖所有网络类型,否则在公用网络上无效:{text}"
);
assert!(
!text.contains("Private,Domain"),
"照抄这条命令会重建出在 Direct AP 网卡上不适用的规则:{text}"
);
}
let _ = text;
}
#[test]
fn status_is_read_only_and_repeatable() {
// 检测必须无副作用:连续调用结果一致,且不改动任何系统设置