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:
Generated
+1
-1
@@ -2587,7 +2587,7 @@ checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qft-desktop"
|
||||
version = "0.4.9"
|
||||
version = "0.4.10"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "qft-desktop"
|
||||
version = "0.4.9"
|
||||
version = "0.4.10"
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
|
||||
|
||||
+349
-37
@@ -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 {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
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('\'', "''"),
|
||||
)
|
||||
}
|
||||
|
||||
let output = std::process::Command::new("netsh")
|
||||
.args([
|
||||
"advfirewall",
|
||||
"firewall",
|
||||
"show",
|
||||
"rule",
|
||||
&format!("name={RULE_NAME}"),
|
||||
])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output();
|
||||
/// 解析 [`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;
|
||||
|
||||
match output {
|
||||
Ok(out) if out.status.success() => {
|
||||
// 光有同名规则还不够:规则若绑在不适用于当前网络的 profile 上,
|
||||
// 会出现「显示已启用但照样被拦」。所以要求它是 profile=any。
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let any_profile = text.contains("Any") || text.contains("任何");
|
||||
if any_profile {
|
||||
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;
|
||||
std::process::Command::new("powershell")
|
||||
.args(["-NoProfile", "-NonInteractive", "-Command", script])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
}
|
||||
|
||||
#[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);
|
||||
if text.trim().is_empty() {
|
||||
return FirewallStatus::Unknown(
|
||||
"防火墙查询没有返回任何内容,可能是 PowerShell 执行策略受限".into(),
|
||||
);
|
||||
}
|
||||
// netsh 在找不到规则时退出码非 0
|
||||
Ok(_) => FirewallStatus::Missing,
|
||||
Err(e) => FirewallStatus::Unknown(format!("无法执行 netsh:{e}")),
|
||||
classify_probe(&text)
|
||||
}
|
||||
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() {
|
||||
// 检测必须无副作用:连续调用结果一致,且不改动任何系统设置
|
||||
|
||||
+159
-79
@@ -153,6 +153,9 @@ struct PcPeerState {
|
||||
status: String,
|
||||
firewall: firewall::FirewallStatus,
|
||||
firewall_note: String,
|
||||
/// 后台探测的结果通道;探测期间为 Some
|
||||
firewall_probe: Option<mpsc::Receiver<firewall::FirewallStatus>>,
|
||||
firewall_probing: bool,
|
||||
}
|
||||
|
||||
struct QftApp {
|
||||
@@ -175,6 +178,11 @@ impl QftApp {
|
||||
Ok(path) => format!("字体:{}", path.display()),
|
||||
Err(message) => format!("字体加载失败:{message}"),
|
||||
};
|
||||
Self::bare(font_status)
|
||||
}
|
||||
|
||||
/// 不依赖 `CreationContext` 的初始状态,供 `new` 与 UI 测试共用。
|
||||
fn bare(font_status: String) -> Self {
|
||||
Self {
|
||||
screen: Screen::Home,
|
||||
font_status,
|
||||
@@ -253,6 +261,8 @@ impl QftApp {
|
||||
status: "接收方启动后会显示连接码;发送方输入该码即可传输。".into(),
|
||||
firewall: firewall::FirewallStatus::Unknown("尚未检测".into()),
|
||||
firewall_note: String::new(),
|
||||
firewall_probe: None,
|
||||
firewall_probing: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -757,43 +767,9 @@ impl QftApp {
|
||||
ui.label(&self.send.status);
|
||||
});
|
||||
|
||||
if self.send.server.is_some() {
|
||||
ui.add_space(10.0);
|
||||
ui.columns(2, |cols| {
|
||||
cols[0].group(|ui| {
|
||||
ui.heading("手机扫码 · QFTSEND2");
|
||||
// 这条路同样要接受手机的入站连接,Direct AP 的虚拟网卡
|
||||
// 更是防火墙重灾区。此前只有接收页有这个面板,
|
||||
// 用户在本页遇到「手机连上了却找不到电脑」时无处可点。
|
||||
let listen_port = self.send.server.as_ref().map(|s| s.port).unwrap_or(sender::PREFERRED_PORT);
|
||||
self.firewall_panel(ui, listen_port);
|
||||
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("手机会依次尝试这些地址;其中必须有一个与手机同网段。");
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
if let Some(texture) = &self.send.pair_texture {
|
||||
let qr_zoom = self.send.qr_zoom;
|
||||
ui.vertical_centered(|ui| {
|
||||
let side = fit_qr_side(ui, qr_zoom, 12.0);
|
||||
ui.image((texture.id(), egui::vec2(side, side)));
|
||||
});
|
||||
}
|
||||
if let Some(ap) = &self.send.direct_ap {
|
||||
ui.label(format!("临时网络:{}", ap.ssid));
|
||||
}
|
||||
});
|
||||
cols[1].group(|ui| {
|
||||
ui.heading("发送状态");
|
||||
ui.label(format!("电脑:{}", self.local_device));
|
||||
ui.label(format!("手机:{}", self.send.connected_device));
|
||||
ui.label(self.send.file.as_ref().map(|v| format!("文件:{}", v.display())).unwrap_or_default());
|
||||
ui.small("二维码只在本次直传会话有效;停止直传后立即失效。");
|
||||
});
|
||||
});
|
||||
}
|
||||
// 注意:直传一旦启动,上面第 696 行就已经 return 进 resizable/focus 分支了,
|
||||
// 所以「运行态才显示」的东西必须加在 pc_to_phone_running_controls 里,
|
||||
// 写在这个函数尾部是死代码。
|
||||
}
|
||||
|
||||
fn pc_to_phone_resizable_qr_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
|
||||
@@ -861,8 +837,28 @@ impl QftApp {
|
||||
ui.small("拖动下方分隔条可为二维码腾出更多高度;也可切换到“专注二维码”。");
|
||||
});
|
||||
|
||||
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);
|
||||
self.firewall_panel(ui, listen_port);
|
||||
|
||||
ui.add_space(6.0);
|
||||
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("手机会依次尝试这些地址;其中必须有一个与手机同网段。");
|
||||
});
|
||||
ui.label(format!("电脑:{}", self.local_device));
|
||||
ui.label(format!("手机:{}", self.send.connected_device));
|
||||
if let Some(ap) = &self.send.direct_ap {
|
||||
@@ -1302,39 +1298,10 @@ impl QftApp {
|
||||
})
|
||||
.collect();
|
||||
|
||||
{
|
||||
ui.add_space(10.0);
|
||||
ui.group(|ui| {
|
||||
let blocked = self.pc.firewall.needs_action();
|
||||
let color = if blocked {
|
||||
egui::Color32::from_rgb(220, 140, 60)
|
||||
} else {
|
||||
egui::Color32::from_rgb(80, 200, 120)
|
||||
};
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.colored_label(color, if blocked { "⚠ 系统防火墙可能拦截入站连接" } else { "● 防火墙" });
|
||||
if !self.pc.firewall_note.is_empty() {
|
||||
ui.label(&self.pc.firewall_note);
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
// 无论检测结果如何都保留入口:检测可能不准,
|
||||
// 而用户遇到「对方连不上」时需要有地方可点。
|
||||
if ui.button("放行防火墙(需要管理员授权)").clicked() {
|
||||
self.request_firewall_grant();
|
||||
}
|
||||
if ui.small_button("复制手动放行命令").clicked() {
|
||||
ui.ctx().copy_text(firewall::manual_instructions(port));
|
||||
}
|
||||
if ui.small_button("重新检测").clicked() {
|
||||
self.refresh_firewall();
|
||||
}
|
||||
});
|
||||
if !blocked {
|
||||
ui.small("检测认为入站不会被拦。若对方仍连不上,可手动放行试试。");
|
||||
}
|
||||
});
|
||||
}
|
||||
// 三个页面共用同一个面板实现。此前这里内联复制了一份,
|
||||
// 改一处忘另一处已经发生过不止一次。
|
||||
self.firewall_panel(ui, port);
|
||||
|
||||
ui.add_space(14.0);
|
||||
ui.group(|ui| {
|
||||
@@ -1496,13 +1463,17 @@ impl QftApp {
|
||||
/// 最容易被防火墙拦住的路径:ICS 虚拟网卡有自己独立的网络类型,
|
||||
/// 只覆盖专用/域网络的规则在它上面完全不生效。
|
||||
fn firewall_panel(&mut self, ui: &mut egui::Ui, port: u16) {
|
||||
let blocked = self.pc.firewall.needs_action();
|
||||
self.poll_firewall_probe(ui.ctx());
|
||||
let status = self.pc.firewall.clone();
|
||||
let blocked = status.needs_action();
|
||||
ui.group(|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if blocked {
|
||||
if self.pc.firewall_probing {
|
||||
ui.colored_label(egui::Color32::from_rgb(150, 150, 150), "◌ 正在检测防火墙…");
|
||||
} else if blocked {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(220, 140, 60),
|
||||
"⚠ 防火墙规则未覆盖当前网络类型,手机可能连不上",
|
||||
"⚠ 入站可能被系统防火墙拦截,手机会连不上",
|
||||
);
|
||||
} else {
|
||||
ui.colored_label(egui::Color32::from_rgb(80, 200, 120), "● 防火墙");
|
||||
@@ -1512,43 +1483,88 @@ impl QftApp {
|
||||
}
|
||||
});
|
||||
if blocked {
|
||||
ui.small(status.detail());
|
||||
ui.small(
|
||||
"Direct AP 会新建一块虚拟网卡,Windows 常把它归类为「公用网络」。\
|
||||
只覆盖专用/域网络的规则在这块网卡上不生效,表现就是手机连上了 Wi-Fi 却找不到电脑。",
|
||||
);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button("放行防火墙(需要管理员授权)").clicked() {
|
||||
// 检测本身可能不准,所以按钮一直保留——用户遇到「连不上」时
|
||||
// 需要有地方可点。唯一的例外是系统级封禁:那属于用户的安全设置,
|
||||
// 我们不去动,点了也不会有任何变化,所以明确禁用并说明原因。
|
||||
let policy_blocked = matches!(status, firewall::FirewallStatus::BlockedByPolicy(_));
|
||||
let grant = ui.add_enabled(
|
||||
!policy_blocked && !self.pc.firewall_probing,
|
||||
egui::Button::new("放行防火墙(需要管理员授权)"),
|
||||
);
|
||||
if policy_blocked {
|
||||
grant.on_hover_text(
|
||||
"当前是系统级的「阻止所有传入连接」,加规则无效,需要你手动关闭该选项",
|
||||
);
|
||||
} else if grant.clicked() {
|
||||
self.request_firewall_grant();
|
||||
}
|
||||
if ui.small_button("复制手动放行命令").clicked() {
|
||||
ui.ctx().copy_text(firewall::manual_instructions(port));
|
||||
}
|
||||
if ui.small_button("重新检测").clicked() {
|
||||
if ui.add_enabled(!self.pc.firewall_probing, egui::Button::new("重新检测").small()).clicked() {
|
||||
self.refresh_firewall();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// 收取后台探测结果。
|
||||
///
|
||||
/// 探测要起一个 PowerShell 进程,1~2 秒,放在 UI 线程上会让界面在
|
||||
/// 「启动接收」的瞬间明显卡一下,正好是用户盯着看的时刻。
|
||||
fn poll_firewall_probe(&mut self, ctx: &egui::Context) {
|
||||
let Some(rx) = &self.pc.firewall_probe else { return };
|
||||
match rx.try_recv() {
|
||||
Ok(status) => {
|
||||
self.pc.firewall = status;
|
||||
self.pc.firewall_probing = false;
|
||||
self.pc.firewall_probe = None;
|
||||
if !self.pc.firewall.needs_action() {
|
||||
self.pc.firewall_note.clear();
|
||||
}
|
||||
}
|
||||
Err(mpsc::TryRecvError::Empty) => {
|
||||
ctx.request_repaint_after(Duration::from_millis(150));
|
||||
}
|
||||
Err(mpsc::TryRecvError::Disconnected) => {
|
||||
self.pc.firewall_probing = false;
|
||||
self.pc.firewall_probe = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 只做**只读检测**,不申请任何权限。
|
||||
///
|
||||
/// 早先版本会在启动接收时自动弹 UAC。实际用下来这太侵入:
|
||||
/// 多数人只是想收个文件,却先被要求管理员授权。
|
||||
/// 现在提权一律由用户点按钮触发(`request_firewall_grant`)。
|
||||
fn refresh_firewall(&mut self) {
|
||||
self.pc.firewall = firewall::status();
|
||||
if !self.pc.firewall.needs_action() {
|
||||
self.pc.firewall_note.clear();
|
||||
if self.pc.firewall_probing {
|
||||
return;
|
||||
}
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.pc.firewall_probe = Some(rx);
|
||||
self.pc.firewall_probing = true;
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(firewall::status());
|
||||
});
|
||||
}
|
||||
|
||||
/// 用户显式点击后才提权。
|
||||
fn request_firewall_grant(&mut self) {
|
||||
match firewall::grant() {
|
||||
Ok(()) => {
|
||||
self.pc.firewall = firewall::status();
|
||||
self.pc.firewall_note = "已放行系统防火墙。".into();
|
||||
// 不要在这里直接断言"已放行"。规则加上了不等于入站真的通了:
|
||||
// 系统级的「阻止所有传入连接」照样会拦。以复检结果为准。
|
||||
self.pc.firewall_note = "已提交放行规则,正在复检…".into();
|
||||
self.refresh_firewall();
|
||||
}
|
||||
Err(e) => self.pc.firewall_note = format!("{e}"),
|
||||
}
|
||||
@@ -1972,6 +1988,70 @@ mod font_tests {
|
||||
assert!(!is_font_file(Path::new("/no/such/file")), "不存在的路径不应通过");
|
||||
}
|
||||
|
||||
/// 在无窗口环境里跑一帧,把这一帧真正绘制出来的所有文字收集起来。
|
||||
///
|
||||
/// 之所以要走真渲染而不是 grep 源码:防火墙面板的代码曾经确实存在于
|
||||
/// `pc_to_phone_ui` 里,却因为运行态在函数更靠前的位置就 `return` 了,
|
||||
/// 整段是死代码,界面上一个字都没有。只有把像素画一遍才能发现这种缺陷。
|
||||
fn rendered_text(build: impl Fn(&mut egui::Ui)) -> String {
|
||||
fn collect(shape: &egui::epaint::Shape, out: &mut String) {
|
||||
match shape {
|
||||
egui::epaint::Shape::Text(text) => {
|
||||
out.push_str(text.galley.text());
|
||||
out.push('\n');
|
||||
}
|
||||
egui::epaint::Shape::Vec(shapes) => {
|
||||
for shape in shapes {
|
||||
collect(shape, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
let mut text = String::new();
|
||||
// 首帧字体图集尚未就绪,取第二帧的结果
|
||||
for _ in 0..2 {
|
||||
text.clear();
|
||||
let output = ctx.run_ui(egui::RawInput::default(), |ui| build(ui));
|
||||
for clipped in &output.shapes {
|
||||
collect(&clipped.shape, &mut text);
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// 直传运行态的控制区必须包含防火墙放行入口。
|
||||
#[test]
|
||||
fn running_send_controls_render_the_firewall_panel() {
|
||||
let drawn = rendered_text(|ui| {
|
||||
let mut app = QftApp::bare(String::new());
|
||||
app.screen = Screen::PcToPhone;
|
||||
app.pc.firewall = firewall::FirewallStatus::Missing;
|
||||
app.pc_to_phone_running_controls(ui);
|
||||
});
|
||||
assert!(
|
||||
drawn.contains("放行防火墙"),
|
||||
"电脑→Android 直传运行态没有画出防火墙放行按钮,实际绘制的文字:\n{drawn}"
|
||||
);
|
||||
assert!(
|
||||
drawn.contains("二维码广播的地址"),
|
||||
"运行态没有画出二维码地址清单,实际绘制的文字:\n{drawn}"
|
||||
);
|
||||
}
|
||||
|
||||
/// 接收页运行态(非专注模式)同样必须有防火墙入口。
|
||||
#[test]
|
||||
fn receive_running_page_renders_the_firewall_panel() {
|
||||
let drawn = rendered_text(|ui| {
|
||||
let mut app = QftApp::bare(String::new());
|
||||
app.pc.firewall = firewall::FirewallStatus::Missing;
|
||||
app.firewall_panel(ui, receiver::PREFERRED_PORT);
|
||||
});
|
||||
assert!(drawn.contains("放行防火墙"), "实际绘制:\n{drawn}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_usable_cjk_font_exists_on_this_platform() {
|
||||
let found = find_ttf_font();
|
||||
|
||||
Reference in New Issue
Block a user