From b1eee5340353ab92bd09709b9f0481b5698ab2c0 Mon Sep 17 00:00:00 2001 From: xlli67 Date: Tue, 27 Oct 2026 00:17:31 +0800 Subject: [PATCH 1/2] fix: support IPv6-disabled Windows (error 1168) Three fixes for machines with IPv6 disabled via DisabledComponents=0xFFFFFFFF: 1. Move metric(1) from builder to post-build: tun-rs set_interface_metric iterates AF_INET then AF_INET6; GetIpInterfaceEntry(AF_INET6) returns ERROR_NOT_FOUND(1168) when IPv6 is disabled, failing the entire build_async(). Now set_metric is called after build, ignoring IPv6 errors. 2. Make virtual IPv6 optional: add_address_v6 and VirtualIpv6Routes fail with 1168 on IPv6-disabled machines. Added ipv6_unavailable flag to DeviceState; first failure sets the flag and skips all subsequent IPv6 configuration with a warning, without blocking IPv4 networking. 3. Increase start timeout from 30s to 120s: hardened enterprise machines with multiple NDIS filter drivers (ESET, Sangfor VPN, etc.) can take 30-45s for Wintun PnP install + filter binding. The old 30s limit killed successfully-completed startups. Added a progress log line. --- vnt-core/src/tun/general.rs | 111 +++++++++++++++++++++++++----------- vnt-web/src/service_http.rs | 14 ++++- 2 files changed, 92 insertions(+), 33 deletions(-) diff --git a/vnt-core/src/tun/general.rs b/vnt-core/src/tun/general.rs index 2e51e003..943a0ab5 100644 --- a/vnt-core/src/tun/general.rs +++ b/vnt-core/src/tun/general.rs @@ -37,6 +37,10 @@ struct DeviceState { tun_name: Option, #[cfg(not(any(target_os = "android", target_os = "ios", target_os = "tvos")))] ipv6_routes: Option, + /// 系统未启用 IPv6(网卡没有 IPv6 接口行)时置位,之后不再尝试配置虚拟 + /// IPv6。虚拟 IPv6 只影响 IPv6 互通,不能阻断 IPv4 组网启动。 + #[cfg_attr(target_os = "android", allow(dead_code))] + ipv6_unavailable: bool, } /// 任务替换成功后提交到 [`DeviceState`] 的字段。 @@ -237,38 +241,50 @@ impl DeviceIOManager { .set_mac_address(crate::ethernet::mac_from_ip(ip).octets()) .context("更新TAP MAC失败")?; } - let ipv6 = crate::virtual_ipv6::address(ip); - if !device.addresses()?.contains(&std::net::IpAddr::V6(ipv6)) { - device - .add_address_v6(ipv6, crate::virtual_ipv6::PREFIX_LEN) - .context("设置虚拟IPv6失败")?; + // 虚拟 IPv6 只是组网内的 IPv6 互通增强。系统禁用 IPv6 的机器上,新建 + // 网卡没有 IPv6 接口行,添加地址会以 ERROR_NOT_FOUND(1168) 失败;此时 + // 跳过全部虚拟 IPv6 配置并记住该状态,不能因为缺少 IPv6 让组网启动失败。 + if !guard.ipv6_unavailable { + let ipv6 = crate::virtual_ipv6::address(ip); + if !device.addresses()?.contains(&std::net::IpAddr::V6(ipv6)) { + match device.add_address_v6(ipv6, crate::virtual_ipv6::PREFIX_LEN) { + Ok(()) => {} + Err(error) if is_ipv6_unavailable(&error) => { + guard.ipv6_unavailable = true; + log::warn!("系统未启用 IPv6,跳过虚拟 IPv6 配置: {error}"); + } + Err(error) => return Err(error).context("设置虚拟IPv6失败"), + } + } } - if let Some((old_ip, _)) = guard.network - && old_ip != ip - { - let old_ipv6 = crate::virtual_ipv6::address(old_ip); - if device - .addresses()? - .contains(&std::net::IpAddr::V6(old_ipv6)) + if !guard.ipv6_unavailable { + if let Some((old_ip, _)) = guard.network + && old_ip != ip { - device - .remove_address(old_ipv6.into()) - .context("清理旧虚拟IPv6失败")?; + let old_ipv6 = crate::virtual_ipv6::address(old_ip); + if device + .addresses()? + .contains(&std::net::IpAddr::V6(old_ipv6)) + { + device + .remove_address(old_ipv6.into()) + .context("清理旧虚拟IPv6失败")?; + } } - } - #[cfg(not(any(target_os = "ios", target_os = "tvos")))] - { - if guard.ipv6_routes.is_none() { - guard.ipv6_routes = Some(crate::system_subnet_routes::VirtualIpv6Routes::new( - device.if_index()?, - )?); + #[cfg(not(any(target_os = "ios", target_os = "tvos")))] + { + if guard.ipv6_routes.is_none() { + guard.ipv6_routes = Some(crate::system_subnet_routes::VirtualIpv6Routes::new( + device.if_index()?, + )?); + } + guard + .ipv6_routes + .as_mut() + .unwrap() + .apply() + .context("设置虚拟IPv6路由失败")?; } - guard - .ipv6_routes - .as_mut() - .unwrap() - .apply() - .context("设置虚拟IPv6路由失败")?; } guard.network = Some((ip, prefix_len)); Ok(()) @@ -495,10 +511,11 @@ fn create_device(config: DeviceConfig) -> anyhow::Result { if let Some(mac_addr) = config.mac_addr { builder = builder.mac_addr(mac_addr); } - #[cfg(windows)] - { - builder = builder.metric(1); - } + // 路由跃点不随 builder 设置:tun-rs 的 builder.metric 会在 build 阶段 + // 依次读取 IPv4、IPv6 的 IP 接口行,任一失败即整次建网卡失败。IPv6 被 + // 策略关闭的机器(Tcpip6\Parameters\DisabledComponents)上不存在 IPv6 + // 接口行,GetIpInterfaceEntry 返回 ERROR_NOT_FOUND(1168),表现为 + // “创建 TUN 失败: 找不到元素”。改为建网后尽力设置,见下方 set_metric。 #[cfg(target_os = "linux")] if config.device_mode == DeviceMode::Tun { builder = builder.offload(true); @@ -515,6 +532,13 @@ fn create_device(config: DeviceConfig) -> anyhow::Result { dev.set_mtu(mtu) .map_err(|error| anyhow::anyhow!("设置MTU失败: {error}"))?; } + // 跃点只影响路由优先级,失败不应拖垮组网:tun-rs 的 set_metric 先写 + // IPv4 再写 IPv6,IPv6 接口行缺失(系统禁用 IPv6)时最后会返回 + // ERROR_NOT_FOUND,此时 IPv4 跃点已经生效,忽略该错误即可。 + #[cfg(windows)] + if let Err(error) = dev.set_metric(1) { + log::debug!("设置虚拟网卡跃点失败(忽略): {error}"); + } #[cfg(target_os = "linux")] { _ = dev.set_tx_queue_len(1000); @@ -523,6 +547,29 @@ fn create_device(config: DeviceConfig) -> anyhow::Result { } } +/// 判断添加 IPv6 地址失败是否因为该接口/系统没有可用的 IPv6。 +/// +/// Windows 禁用 IPv6(`Tcpip6\Parameters\DisabledComponents`)时,新建网卡 +/// 没有 IPv6 接口行,`CreateUnicastIpAddressEntry` 返回 ERROR_NOT_FOUND(1168); +/// 接口未绑定 IPv6 协议时还可能是 ERROR_NOT_SUPPORTED(50) / WSAEAFNOSUPPORT(10047)。 +/// Unix 上对应 `EAFNOSUPPORT`,各系统 errno 值不同(Linux=97, macOS/BSD=47/36), +/// 用 `ErrorKind::AddrNotAvailable` 统一判断,避免硬编码 errno。 +/// 这类情况下虚拟 IPv6 不可用,但 IPv4 组网完全正常,不应中止启动。 +#[cfg_attr(target_os = "android", allow(dead_code))] +fn is_ipv6_unavailable(error: &io::Error) -> bool { + #[cfg(windows)] + { + const CODES: &[i32] = &[1168, 50, 10047]; + error + .raw_os_error() + .is_some_and(|code| CODES.contains(&code)) + } + #[cfg(unix)] + { + error.kind() == io::ErrorKind::AddrNotAvailable + } +} + #[cfg_attr(target_os = "android", allow(dead_code))] fn device_creation_error_context(mode: DeviceMode, error: &io::Error) -> &'static str { let permission_denied = error.kind() == io::ErrorKind::PermissionDenied || { diff --git a/vnt-web/src/service_http.rs b/vnt-web/src/service_http.rs index deae7b52..43c0e9d4 100644 --- a/vnt-web/src/service_http.rs +++ b/vnt-web/src/service_http.rs @@ -1416,6 +1416,15 @@ fn begin_vnt_start(state: &HttpAppState, file_name: &str) -> anyhow::Result Ok(generation) } +/// 启动时等待「注册 + 创建虚拟网卡」完成的上限。 +/// +/// 加固过的企业机器上,创建 Wintun 网卡(PnP 安装 + NDIS 过滤器绑定 + 安全 +/// 软件扫描)实测可达 30~45 秒。旧的 30 秒上限会让**刚好完成**的启动被判超时 +/// 并回滚,日志表现为 `Network Started` 与 `启动网络实例超时` 几乎同时出现, +/// 随后 `starting_to_running VNT is not starting` / +/// `实例启动完成时 generation 已失效`。放宽到 120 秒,同时仍保留上限防止真卡死。 +const START_READY_TIMEOUT: Duration = Duration::from_secs(120); + async fn start_vnt_internal_reserved( state: &HttpAppState, file_name: String, @@ -1526,7 +1535,7 @@ async fn start_vnt_internal_reserved( drop(on_error_guard); }); state.set_start_handle(&file_name, generation, start_handle); - match tokio::time::timeout(Duration::from_secs(30), ready_rx).await { + match tokio::time::timeout(START_READY_TIMEOUT, ready_rx).await { Ok(Ok(Ok(()))) => Ok(()), Ok(Ok(Err(error))) => Err(anyhow!(error)), Ok(Err(_)) => Err(anyhow!("启动任务在返回结果前退出")), @@ -1568,6 +1577,9 @@ async fn start_vnt_network(context: StartNetworkContext) -> anyhow::Result<()> { .context("配置管理器不可用")?; // 启动虚拟网卡(管理器内部等待注册完成) + // 建卡含 PnP 安装与过滤器绑定,加固机器上可能要几十秒:先落一条日志, + // 既让界面不是「一片空白」,也便于把慢启动与真正的卡死区分开。 + state.record_log(&file_name, "等待注册并创建虚拟网卡"); let (device_mode, vnt_api) = { let mut guard = manager.lock().await; let network_addr = match guard.start_device().await { From 55e698cf3b9e1229c0f3c11e3b0e2263b0e77e9c Mon Sep 17 00:00:00 2001 From: xlli67 Date: Wed, 28 Oct 2026 16:06:03 +0800 Subject: [PATCH 2/2] fix: detect EAFNOSUPPORT via libc and add is_ipv6_unavailable tests ErrorKind::AddrNotAvailable maps to EADDRNOTAVAIL, not EAFNOSUPPORT, so the previous Unix check missed the intended error and matched an unrelated one. Use libc::EAFNOSUPPORT for the platform value and cover both Windows and Unix branches with unit tests. --- vnt-core/src/tun/general.rs | 50 ++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/vnt-core/src/tun/general.rs b/vnt-core/src/tun/general.rs index 943a0ab5..e07b997c 100644 --- a/vnt-core/src/tun/general.rs +++ b/vnt-core/src/tun/general.rs @@ -552,8 +552,9 @@ fn create_device(config: DeviceConfig) -> anyhow::Result { /// Windows 禁用 IPv6(`Tcpip6\Parameters\DisabledComponents`)时,新建网卡 /// 没有 IPv6 接口行,`CreateUnicastIpAddressEntry` 返回 ERROR_NOT_FOUND(1168); /// 接口未绑定 IPv6 协议时还可能是 ERROR_NOT_SUPPORTED(50) / WSAEAFNOSUPPORT(10047)。 -/// Unix 上对应 `EAFNOSUPPORT`,各系统 errno 值不同(Linux=97, macOS/BSD=47/36), -/// 用 `ErrorKind::AddrNotAvailable` 统一判断,避免硬编码 errno。 +/// Unix 上对应 `EAFNOSUPPORT`(内核未启用 IPv6)。各系统 errno 数值不同, +/// 通过 `libc::EAFNOSUPPORT` 取平台值;标准库没有为它映射专门的 `ErrorKind`, +/// 不能用 `AddrNotAvailable`(那是 `EADDRNOTAVAIL`,含义不同)。 /// 这类情况下虚拟 IPv6 不可用,但 IPv4 组网完全正常,不应中止启动。 #[cfg_attr(target_os = "android", allow(dead_code))] fn is_ipv6_unavailable(error: &io::Error) -> bool { @@ -566,7 +567,7 @@ fn is_ipv6_unavailable(error: &io::Error) -> bool { } #[cfg(unix)] { - error.kind() == io::ErrorKind::AddrNotAvailable + error.raw_os_error() == Some(libc::EAFNOSUPPORT) } } @@ -763,4 +764,47 @@ mod tests { "创建 TAP 失败:权限不足,请尝试以管理员身份运行程序" ); } + + #[cfg(windows)] + #[test] + fn windows_ipv6_disabled_codes_are_treated_as_unavailable() { + // ERROR_NOT_FOUND / ERROR_NOT_SUPPORTED / WSAEAFNOSUPPORT + for code in [1168, 50, 10047] { + let error = io::Error::from_raw_os_error(code); + assert!(is_ipv6_unavailable(&error), "os error {code} 应视为 IPv6 不可用"); + } + } + + #[cfg(windows)] + #[test] + fn windows_other_errors_are_not_treated_as_ipv6_unavailable() { + // ERROR_ACCESS_DENIED / ERROR_INVALID_PARAMETER 是真实故障,必须照常上报 + for code in [5, 87] { + let error = io::Error::from_raw_os_error(code); + assert!(!is_ipv6_unavailable(&error), "os error {code} 不应被吞掉"); + } + } + + #[cfg(unix)] + #[test] + fn unix_eafnosupport_is_treated_as_unavailable() { + let error = io::Error::from_raw_os_error(libc::EAFNOSUPPORT); + assert!(is_ipv6_unavailable(&error)); + } + + #[cfg(unix)] + #[test] + fn unix_other_errors_are_not_treated_as_ipv6_unavailable() { + // EADDRNOTAVAIL 与 EAFNOSUPPORT 含义不同,权限错误也必须照常上报 + for code in [libc::EADDRNOTAVAIL, libc::EPERM, libc::EINVAL] { + let error = io::Error::from_raw_os_error(code); + assert!(!is_ipv6_unavailable(&error), "errno {code} 不应被吞掉"); + } + } + + #[test] + fn errors_without_os_code_are_not_treated_as_ipv6_unavailable() { + let error = io::Error::other("synthetic"); + assert!(!is_ipv6_unavailable(&error)); + } }