Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 308d71021e | |||
| 54a3433b81 |
@@ -1,11 +1,11 @@
|
|||||||
# 纵横家开源源码
|
# 纵横家开源源码
|
||||||
|
|
||||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.7、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.20、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||||
|
|
||||||
| 目录 | 内容与状态 |
|
| 目录 | 内容与状态 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| windows/ | Windows Forms / .NET 8 源码;公开导出删除许可来源不明的可选登录插图,保留原创山水 fallback |
|
| windows/ | Windows Forms / .NET 8 源码;0.3.20 加入动态 DERP 旁路、业务故障切换、后台学习和有界日志修复 |
|
||||||
| backend/ | Django 后台源码与迁移;不含生产数据库、运行配置或凭据 |
|
| backend/ | Django 后台源码与迁移;公开入口默认值已迁移到 `vpn.ucvl.cn`,不含生产数据库、运行配置或凭据 |
|
||||||
| ios/ | iPhone/iPad Swift / Packet Tunnel 源码;未提供 IPA,未声称 Xcode/签名/实机验收通过 |
|
| ios/ | iPhone/iPad Swift / Packet Tunnel 源码;未提供 IPA,未声称 Xcode/签名/实机验收通过 |
|
||||||
| android/ | 原 GPL-3.0 公开源码及固定候选提交链接 |
|
| android/ | 原 GPL-3.0 公开源码及固定候选提交链接 |
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
# 纵横家 Django 后台开源源码
|
# 纵横家 Django 后台开源源码
|
||||||
|
|
||||||
|
## 2026-11-27 配置更新
|
||||||
|
|
||||||
|
源码默认公开域名、允许主机、CSRF 来源及客户端网关统一为 `vpn.ucvl.cn`,默认青岛公网入口为 `47.104.134.190`。部署环境可继续通过 `DJANGO_ALLOWED_HOSTS`、`DJANGO_CSRF_TRUSTED_ORIGINS`、`VPN_PUBLIC_BASE_URL`、`VPN_PUBLIC_GATEWAY_HOST` 和 `VPN_PUBLIC_GATEWAY_IPV4` 覆盖;生产密钥、数据库和企业微信凭据仍必须由服务器环境注入。
|
||||||
|
|
||||||
|
新增生产默认值和环境覆盖测试。完整 Django 测试集通过只代表源码候选通过隔离验证,不等同于生产容器已经部署。
|
||||||
|
|
||||||
来源为固定的 phone-20261010 源码 freeze(含 0001–0015 迁移),不是生产部署或正式迁移验收。公司自有代码按 MIT 开源,依赖保持原许可证;不含数据库、用户信息、环境变量、SSH/代理/企业微信/支付凭据、生产镜像或私有 Git 历史。
|
来源为固定的 phone-20261010 源码 freeze(含 0001–0015 迁移),不是生产部署或正式迁移验收。公司自有代码按 MIT 开源,依赖保持原许可证;不含数据库、用户信息、环境变量、SSH/代理/企业微信/支付凭据、生产镜像或私有 Git 历史。
|
||||||
|
|
||||||
使用隔离的 Python 虚拟环境和 requirements.txt 安装依赖,按 toplc_vpn/settings.py 的环境变量入口提供自己的 Django secret、数据库、主机与代理配置。先审查配置与迁移,在自己的非生产数据库测试后再部署。不要直接接入现有生产数据或使用示例节点值。本仓库未提供一键安全生产部署承诺。
|
使用隔离的 Python 虚拟环境和 requirements.txt 安装依赖,按 toplc_vpn/settings.py 的环境变量入口提供自己的 Django secret、数据库、主机与代理配置。先审查配置与迁移,在自己的非生产数据库测试后再部署。不要直接接入现有生产数据或使用示例节点值。本仓库未提供一键安全生产部署承诺。
|
||||||
|
|||||||
@@ -92,12 +92,12 @@ class DispatchTests(TestCase):
|
|||||||
self.assertEqual(choose_node(self.session)[0], self.nodes[0])
|
self.assertEqual(choose_node(self.session)[0], self.nodes[0])
|
||||||
self.assertIsNone(next(n for n in build_dispatch_snapshot()["nodes"] if n["id"] == self.nodes[1].pk)["rate_bps"])
|
self.assertIsNone(next(n for n in build_dispatch_snapshot()["nodes"] if n["id"] == self.nodes[1].pk)["rate_bps"])
|
||||||
|
|
||||||
@override_settings(VPN_PUBLIC_GATEWAY_HOST="vpn.toplc.cn", VPN_PUBLIC_GATEWAY_IPV4="192.0.2.1")
|
@override_settings(VPN_PUBLIC_GATEWAY_HOST="vpn.toplc.cn", VPN_PUBLIC_GATEWAY_IPV4="47.104.134.190")
|
||||||
def test_config_auto_returns_actual_domain_and_node(self):
|
def test_config_auto_returns_actual_domain_and_node(self):
|
||||||
response = self.client.get("/api/v1/client/config/?node=auto&route=smart", HTTP_AUTHORIZATION=f"Bearer {self.token}")
|
response = self.client.get("/api/v1/client/config/?node=auto&route=smart", HTTP_AUTHORIZATION=f"Bearer {self.token}")
|
||||||
self.assertEqual(response.status_code, 200, response.content)
|
self.assertEqual(response.status_code, 200, response.content)
|
||||||
self.assertEqual(response.json()["config_contract"], 2)
|
self.assertEqual(response.json()["config_contract"], 2)
|
||||||
self.assertEqual(response.json()["gateway"], {"host": "vpn.toplc.cn", "ipv4": "192.0.2.1"})
|
self.assertEqual(response.json()["gateway"], {"host": "vpn.toplc.cn", "ipv4": "47.104.134.190"})
|
||||||
self.assertEqual(response.json()["node"]["slug"], self.nodes[1].slug)
|
self.assertEqual(response.json()["node"]["slug"], self.nodes[1].slug)
|
||||||
self.assertEqual(response.json()["config"]["outbounds"][0]["settings"]["vnext"][0]["address"], self.nodes[1].server)
|
self.assertEqual(response.json()["config"]["outbounds"][0]["settings"]["vnext"][0]["address"], self.nodes[1].server)
|
||||||
|
|
||||||
|
|||||||
@@ -347,7 +347,7 @@ def client_profile(request):
|
|||||||
|
|
||||||
def _client_gateway_payload():
|
def _client_gateway_payload():
|
||||||
"""Return the stable public NPM entrypoint without exposing private overlay IPs."""
|
"""Return the stable public NPM entrypoint without exposing private overlay IPs."""
|
||||||
host = str(getattr(settings, "VPN_PUBLIC_GATEWAY_HOST", "vpn.toplc.cn") or "vpn.toplc.cn").strip()
|
host = str(getattr(settings, "VPN_PUBLIC_GATEWAY_HOST", "vpn.ucvl.cn") or "vpn.ucvl.cn").strip()
|
||||||
configured_ipv4 = str(getattr(settings, "VPN_PUBLIC_GATEWAY_IPV4", "") or "").strip()
|
configured_ipv4 = str(getattr(settings, "VPN_PUBLIC_GATEWAY_IPV4", "") or "").strip()
|
||||||
public_ipv4 = None
|
public_ipv4 = None
|
||||||
if configured_ipv4:
|
if configured_ipv4:
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ if not SECRET_KEY:
|
|||||||
else:
|
else:
|
||||||
raise RuntimeError("DJANGO_SECRET_KEY is required when DJANGO_DEBUG is false")
|
raise RuntimeError("DJANGO_SECRET_KEY is required when DJANGO_DEBUG is false")
|
||||||
|
|
||||||
ALLOWED_HOSTS = env_list("DJANGO_ALLOWED_HOSTS", "vpn.toplc.cn,localhost,127.0.0.1")
|
ALLOWED_HOSTS = env_list("DJANGO_ALLOWED_HOSTS", "vpn.ucvl.cn,localhost,127.0.0.1")
|
||||||
CSRF_TRUSTED_ORIGINS = env_list("DJANGO_CSRF_TRUSTED_ORIGINS", "https://vpn.toplc.cn")
|
CSRF_TRUSTED_ORIGINS = env_list("DJANGO_CSRF_TRUSTED_ORIGINS", "https://vpn.ucvl.cn")
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
"django.contrib.admin",
|
"django.contrib.admin",
|
||||||
@@ -110,14 +110,14 @@ STORAGES = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||||
PUBLIC_BASE_URL = os.getenv("VPN_PUBLIC_BASE_URL", "https://vpn.toplc.cn").rstrip("/")
|
PUBLIC_BASE_URL = os.getenv("VPN_PUBLIC_BASE_URL", "https://vpn.ucvl.cn").rstrip("/")
|
||||||
# Credentials are injected server-side; no admin form or browser receives the secret.
|
# Credentials are injected server-side; no admin form or browser receives the secret.
|
||||||
WECOM_ENABLED = env_bool("WECOM_ENABLED", False)
|
WECOM_ENABLED = env_bool("WECOM_ENABLED", False)
|
||||||
WECOM_CORP_ID = os.getenv("WECOM_CORP_ID", "").strip()
|
WECOM_CORP_ID = os.getenv("WECOM_CORP_ID", "").strip()
|
||||||
WECOM_AGENT_ID = os.getenv("WECOM_AGENT_ID", "").strip()
|
WECOM_AGENT_ID = os.getenv("WECOM_AGENT_ID", "").strip()
|
||||||
WECOM_SECRET = os.getenv("WECOM_SECRET", "").strip()
|
WECOM_SECRET = os.getenv("WECOM_SECRET", "").strip()
|
||||||
VPN_PUBLIC_GATEWAY_HOST = os.getenv("VPN_PUBLIC_GATEWAY_HOST", "vpn.toplc.cn").strip()
|
VPN_PUBLIC_GATEWAY_HOST = os.getenv("VPN_PUBLIC_GATEWAY_HOST", "vpn.ucvl.cn").strip()
|
||||||
VPN_PUBLIC_GATEWAY_IPV4 = os.getenv("VPN_PUBLIC_GATEWAY_IPV4", "").strip()
|
VPN_PUBLIC_GATEWAY_IPV4 = os.getenv("VPN_PUBLIC_GATEWAY_IPV4", "47.104.134.190").strip()
|
||||||
# Optional employee-only same-node transport hint. Enabling also requires the
|
# Optional employee-only same-node transport hint. Enabling also requires the
|
||||||
# node/Tailnet firewall to explicitly authorize client sources; sharing is not login.
|
# node/Tailnet firewall to explicitly authorize client sources; sharing is not login.
|
||||||
VPN_TAILSCALE_ENDPOINT_ENABLED = env_bool("VPN_TAILSCALE_ENDPOINT_ENABLED", False)
|
VPN_TAILSCALE_ENDPOINT_ENABLED = env_bool("VPN_TAILSCALE_ENDPOINT_ENABLED", False)
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import os
|
||||||
|
import runpy
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
|
||||||
|
class ProductionDefaultSettingsTests(unittest.TestCase):
|
||||||
|
def load_defaults(self):
|
||||||
|
settings_path = Path(__file__).with_name("settings.py")
|
||||||
|
with patch.dict(os.environ, {"DJANGO_DEBUG": "1"}, clear=True):
|
||||||
|
return runpy.run_path(str(settings_path))
|
||||||
|
|
||||||
|
def test_current_public_domain_is_the_only_default_identity(self):
|
||||||
|
settings = self.load_defaults()
|
||||||
|
self.assertEqual(settings["ALLOWED_HOSTS"], ["vpn.ucvl.cn", "localhost", "127.0.0.1"])
|
||||||
|
self.assertEqual(settings["CSRF_TRUSTED_ORIGINS"], ["https://vpn.ucvl.cn"])
|
||||||
|
self.assertEqual(settings["PUBLIC_BASE_URL"], "https://vpn.ucvl.cn")
|
||||||
|
self.assertEqual(settings["VPN_PUBLIC_GATEWAY_HOST"], "vpn.ucvl.cn")
|
||||||
|
self.assertEqual(settings["VPN_PUBLIC_GATEWAY_IPV4"], "47.104.134.190")
|
||||||
|
|
||||||
|
def test_environment_still_overrides_every_public_default(self):
|
||||||
|
settings_path = Path(__file__).with_name("settings.py")
|
||||||
|
environment = {
|
||||||
|
"DJANGO_DEBUG": "1",
|
||||||
|
"DJANGO_ALLOWED_HOSTS": "fixture.example,localhost",
|
||||||
|
"DJANGO_CSRF_TRUSTED_ORIGINS": "https://fixture.example",
|
||||||
|
"VPN_PUBLIC_BASE_URL": "https://fixture.example/root/",
|
||||||
|
"VPN_PUBLIC_GATEWAY_HOST": "entry.fixture.example",
|
||||||
|
"VPN_PUBLIC_GATEWAY_IPV4": "198.51.100.25",
|
||||||
|
}
|
||||||
|
with patch.dict(os.environ, environment, clear=True):
|
||||||
|
settings = runpy.run_path(str(settings_path))
|
||||||
|
self.assertEqual(settings["ALLOWED_HOSTS"], ["fixture.example", "localhost"])
|
||||||
|
self.assertEqual(settings["CSRF_TRUSTED_ORIGINS"], ["https://fixture.example"])
|
||||||
|
self.assertEqual(settings["PUBLIC_BASE_URL"], "https://fixture.example/root")
|
||||||
|
self.assertEqual(settings["VPN_PUBLIC_GATEWAY_HOST"], "entry.fixture.example")
|
||||||
|
self.assertEqual(settings["VPN_PUBLIC_GATEWAY_IPV4"], "198.51.100.25")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# 纵横家 0.3.20 前后台升级实施计划
|
||||||
|
|
||||||
|
> **实施方式:** 在唯一干净的 `windows-v0.3.19` 源码谱系上按 TDD 实施;每项先制造可重复失败,再做最小修复。生产后台在运行态清单、备份与回滚条件未核验前不得覆盖。
|
||||||
|
|
||||||
|
**目标:** 修复已连接节点业务持续失败却不切换、连接等待过长、过期 DERP 旁路和无限日志增长;同步纠正后台正式源码的旧域名默认契约,形成可构建、可回滚、可发布的 0.3.20。
|
||||||
|
|
||||||
|
**基线:** `54a3433b81ec0917610a7045ce31f0a25f9439cf` (`windows-v0.3.19`),工作树在实施前为干净状态。
|
||||||
|
|
||||||
|
**技术栈:** .NET 8 WinForms、Xray、Tailscale、Django、PostgreSQL、Docker Compose、NSIS、Gitea。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 任务 1:业务级失败触发自动节点冷却与回退
|
||||||
|
|
||||||
|
**文件:**
|
||||||
|
- 修改:`windows/ConnectionHealthPolicy.cs`
|
||||||
|
- 修改:`windows/MainForm.cs`
|
||||||
|
- 修改:`windows/ConnectionHealthSelfTest.cs`
|
||||||
|
- 可能新增:`windows/BusinessFailurePolicy.cs`
|
||||||
|
- 可能新增:`windows/BusinessFailurePolicySelfTest.cs`
|
||||||
|
|
||||||
|
1. 先增加失败测试:自动调度时,普通路径与强制代理均连续确认 Codex 业务失败达到阈值后,当前节点进入冷却并触发一次 `Switch`;中间一次成功必须清零;手动指定节点仍只告警、不改节点。
|
||||||
|
2. 运行目标自测,确认新断言在 0.3.19 上失败。
|
||||||
|
3. 用独立、单调时钟驱动的连续失败策略实现最小修复;不得把单个站点的一次超时或直接路径异常当作节点故障。
|
||||||
|
4. 把策略接入现有健康循环和自动调度路径,保留现有网络恢复、会话授权与同节点公网回退约束。
|
||||||
|
5. 重跑目标自测和完整 Windows 自测集。
|
||||||
|
|
||||||
|
## 任务 2:动态读取当前 DERP Map,删除编译期退役 IP
|
||||||
|
|
||||||
|
**文件:**
|
||||||
|
- 修改:`windows/TunRouting.cs`
|
||||||
|
- 修改:`windows/RouteLeaseSelfTest.cs`
|
||||||
|
- 新增:`windows/DerpMapRoutes.cs`
|
||||||
|
- 新增:`windows/DerpMapRoutesSelfTest.cs`
|
||||||
|
|
||||||
|
1. 先增加失败测试:仅 902、902+905、903/904 已退役、畸形 JSON、超量节点和非公网地址。
|
||||||
|
2. 运行目标自测,确认当前写死列表不能满足测试。
|
||||||
|
3. 以受限超时调用本机 `tailscale debug derp-map`,只接受有界数量的合法公网 IPv4;失败时至少保留青岛管理入口旁路,不制造未知路由。
|
||||||
|
4. `TunRouting.CreateOwnedRoutes` 只使用当次已验证 DERP 地址,不再写死 VPN002/003/004 公网 IP。
|
||||||
|
5. 验证既有路由不会被删除,连接停止后只清理本次拥有的路由。
|
||||||
|
|
||||||
|
## 任务 3:有界日志、脱敏与常数级尾部读取
|
||||||
|
|
||||||
|
**文件:**
|
||||||
|
- 修改:`windows/AppPaths.cs`
|
||||||
|
- 修改:`windows/XrayManager.cs`
|
||||||
|
- 修改:`windows/ProxyProbe.cs`
|
||||||
|
- 新增:`windows/BoundedLog.cs`
|
||||||
|
- 新增:`windows/BoundedLogSelfTest.cs`
|
||||||
|
|
||||||
|
1. 先增加失败测试:超过上限时轮转、NUL/损坏尾部可恢复、只读取末尾记录、探测目标不进入持久日志。
|
||||||
|
2. 运行目标自测,确认 0.3.19 无限追加和全文件扫描行为失败。
|
||||||
|
3. 实现固定上限与单份备份轮转;错误路径从文件尾部有界读取,禁止持久化真实浏览目标。
|
||||||
|
4. 重跑自测,并确认现有日志不会在构建或升级时被主动删除。
|
||||||
|
|
||||||
|
## 任务 4:缩短连接等待但不降低出口证明
|
||||||
|
|
||||||
|
**文件:**
|
||||||
|
- 修改:`windows/NodeTransportConnector.cs`
|
||||||
|
- 修改:`windows/XrayManager.cs`
|
||||||
|
- 修改:`windows/TailnetTransportSelfTest.cs`
|
||||||
|
- 可能新增:`windows/ConnectionTimingSelfTest.cs`
|
||||||
|
|
||||||
|
1. 用假时钟/受控探针固定当前 5 秒 TCP 预检、45 秒整体验证和公网回退顺序,新增测试证明可并行的只读准备工作不会重复串行等待。
|
||||||
|
2. 在不移除 Reality/代理 HTTPS 出口验证的前提下,合并重复探测并让快速成功路径提前完成。
|
||||||
|
3. 确保 Tailscale 失败仍只回退同一授权节点的青岛入口,且手动取消立即恢复网络。
|
||||||
|
4. 重跑连接、切网、TUN、升级恢复相关自测。
|
||||||
|
|
||||||
|
## 任务 5:后台正式源码纠正生产域名默认契约
|
||||||
|
|
||||||
|
**文件:**
|
||||||
|
- 修改:`backend/toplc_vpn/settings.py`
|
||||||
|
- 修改:`backend/control/tests/test_dispatch.py`
|
||||||
|
- 修改:`backend/README.md`
|
||||||
|
|
||||||
|
1. 先增加/调整测试,要求无环境覆盖时公开域名为 `vpn.ucvl.cn`、固定入口为 `47.104.134.190`,并确认显式环境变量仍优先。
|
||||||
|
2. 运行测试,确认旧默认 `vpn.toplc.cn` 使测试失败。
|
||||||
|
3. 只改默认值和文档,不改模型、迁移、节点授权、DERP 或限速策略。
|
||||||
|
4. 运行后台完整可用测试集和 Django `check --deploy` 的离线安全检查。
|
||||||
|
|
||||||
|
## 任务 6:版本、构建、验收与发布
|
||||||
|
|
||||||
|
**文件:**
|
||||||
|
- 修改:`windows/VPNPlus.csproj`
|
||||||
|
- 修改:`windows/README.md`
|
||||||
|
- 新增:`windows/release/RELEASE-NOTES-0.3.20.md`
|
||||||
|
- 生成:构建清单、安装包、SHA256、验收报告
|
||||||
|
|
||||||
|
1. 版本提升到 0.3.20,构建自包含 Windows x64 与 NSIS 安装包。
|
||||||
|
2. 执行所有离线自测、隔离安装/升级/回退、源文件与产物哈希绑定。
|
||||||
|
3. 在不接管现用网络的条件下做 API、Tailscale 端点、青岛回退和业务出口只读验收;任何失败均不得发布。
|
||||||
|
4. 提交源码、签出 `windows-v0.3.20` 标签,推送公司代码库,上传安装包和校验文件,核对自动升级清单。
|
||||||
|
|
||||||
|
## 任务 7:生产后台门禁与全员通知
|
||||||
|
|
||||||
|
1. 仅在取得 VPN004 严格主机密钥校验的有效管理会话后,生成脱敏运行态清单:Compose 叠加顺序、镜像摘要、挂载、迁移头、数据库备份和自动回滚。
|
||||||
|
2. 在克隆环境重建当前生产组合并通过回归;再部署仅域名默认契约候选。无法满足门禁时保留现网,不假称已升级。
|
||||||
|
3. 前后台正式发布并复验后,更新内部资源库和下载链接。
|
||||||
|
4. 发布公司动态配图新闻。
|
||||||
|
5. 通过企业微信“尚书台”发送全员通知;不使用小小优,不重复发送。
|
||||||
+2
-1
@@ -43,7 +43,8 @@ internal static class AppPaths
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
EnsureDirectory();
|
EnsureDirectory();
|
||||||
File.AppendAllText(LogFile, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}", Encoding.UTF8);
|
BoundedLog.Append(LogFile, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}",
|
||||||
|
BoundedLog.ApplicationMaxBytes);
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace UCVL.VPNPlus;
|
||||||
|
|
||||||
|
internal readonly record struct TailReadResult(string Text, int BytesRead);
|
||||||
|
|
||||||
|
internal static class BoundedLog
|
||||||
|
{
|
||||||
|
internal const long ApplicationMaxBytes = 4L * 1024 * 1024;
|
||||||
|
internal const long XrayMaxBytes = 4L * 1024 * 1024;
|
||||||
|
internal const int ErrorTailMaxBytes = 64 * 1024;
|
||||||
|
|
||||||
|
private static readonly UTF8Encoding Utf8 = new(false, false);
|
||||||
|
private static readonly ConcurrentDictionary<string, object> Gates = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
internal static void Append(string path, string value, long maxBytes)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||||
|
ArgumentNullException.ThrowIfNull(value);
|
||||||
|
if (maxBytes < 1 || maxBytes > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(maxBytes));
|
||||||
|
|
||||||
|
var content = FitToLimit(value, (int)maxBytes);
|
||||||
|
path = Path.GetFullPath(path);
|
||||||
|
var gate = Gates.GetOrAdd(path, static _ => new object());
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
var directory = Path.GetDirectoryName(path);
|
||||||
|
if (!string.IsNullOrWhiteSpace(directory)) Directory.CreateDirectory(directory);
|
||||||
|
var existingLength = File.Exists(path) ? new FileInfo(path).Length : 0;
|
||||||
|
if (existingLength > 0 && existingLength + content.Length > maxBytes)
|
||||||
|
Rotate(path, maxBytes);
|
||||||
|
using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read | FileShare.Delete);
|
||||||
|
stream.Write(content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static TailReadResult ReadTail(string path, int maxLines, int maxBytes)
|
||||||
|
{
|
||||||
|
if (maxLines < 1) throw new ArgumentOutOfRangeException(nameof(maxLines));
|
||||||
|
if (maxBytes < 1) throw new ArgumentOutOfRangeException(nameof(maxBytes));
|
||||||
|
if (!File.Exists(path)) return new("", 0);
|
||||||
|
|
||||||
|
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||||
|
FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, FileOptions.RandomAccess);
|
||||||
|
var bytesToRead = (int)Math.Min(stream.Length, maxBytes);
|
||||||
|
if (bytesToRead == 0) return new("", 0);
|
||||||
|
var startedMidFile = stream.Length > bytesToRead;
|
||||||
|
stream.Seek(-bytesToRead, SeekOrigin.End);
|
||||||
|
var buffer = new byte[bytesToRead];
|
||||||
|
var total = 0;
|
||||||
|
while (total < buffer.Length)
|
||||||
|
{
|
||||||
|
var read = stream.Read(buffer, total, buffer.Length - total);
|
||||||
|
if (read == 0) break;
|
||||||
|
total += read;
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = Utf8.GetString(buffer, 0, total).Replace("\0", "", StringComparison.Ordinal)
|
||||||
|
.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n');
|
||||||
|
var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries).AsEnumerable();
|
||||||
|
if (startedMidFile) lines = lines.Skip(1);
|
||||||
|
return new(string.Join(Environment.NewLine, lines.TakeLast(maxLines)), total);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] FitToLimit(string value, int maxBytes)
|
||||||
|
{
|
||||||
|
var content = Utf8.GetBytes(value);
|
||||||
|
if (content.Length <= maxBytes) return content;
|
||||||
|
|
||||||
|
var start = content.Length - maxBytes;
|
||||||
|
while (start < content.Length && (content[start] & 0xc0) == 0x80) start++;
|
||||||
|
return content[start..];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Rotate(string path, long maxBytes)
|
||||||
|
{
|
||||||
|
var backup = path + ".1";
|
||||||
|
var length = new FileInfo(path).Length;
|
||||||
|
if (length <= maxBytes)
|
||||||
|
{
|
||||||
|
File.Move(path, backup, overwrite: true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A pre-upgrade unbounded log is trimmed only when the next append
|
||||||
|
// naturally triggers rotation; loading, building and upgrading do not touch it.
|
||||||
|
using (var source = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
|
||||||
|
using (var destination = new FileStream(backup, FileMode.Create, FileAccess.Write, FileShare.Read))
|
||||||
|
{
|
||||||
|
source.Seek(-maxBytes, SeekOrigin.End);
|
||||||
|
source.CopyTo(destination);
|
||||||
|
}
|
||||||
|
File.Delete(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace UCVL.VPNPlus;
|
||||||
|
|
||||||
|
internal static class BoundedLogSelfTest
|
||||||
|
{
|
||||||
|
internal static bool Run()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "ucvl-bounded-log-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
const long limit = 192;
|
||||||
|
var logPath = Path.Combine(directory, "rotation.log");
|
||||||
|
var original = new string('a', 180) + "\n";
|
||||||
|
File.WriteAllText(logPath, original, new UTF8Encoding(false));
|
||||||
|
var originalLength = new FileInfo(logPath).Length;
|
||||||
|
|
||||||
|
// Reading and loading the helper must not delete or truncate an existing log.
|
||||||
|
_ = BoundedLog.ReadTail(logPath, 1, 64);
|
||||||
|
if (!File.Exists(logPath) || new FileInfo(logPath).Length != originalLength
|
||||||
|
|| File.Exists(logPath + ".1")) return false;
|
||||||
|
|
||||||
|
BoundedLog.Append(logPath, "rotation-entry\n", limit);
|
||||||
|
var backupPath = logPath + ".1";
|
||||||
|
if (!File.Exists(backupPath)
|
||||||
|
|| File.ReadAllText(backupPath, Encoding.UTF8) != original
|
||||||
|
|| new FileInfo(logPath).Length > limit) return false;
|
||||||
|
|
||||||
|
for (var i = 0; i < 40; i++)
|
||||||
|
BoundedLog.Append(logPath, $"line-{i:D2}-xxxxxxxx\n", limit);
|
||||||
|
if (new FileInfo(logPath).Length > limit
|
||||||
|
|| !File.Exists(backupPath)
|
||||||
|
|| new FileInfo(backupPath).Length > limit
|
||||||
|
|| File.Exists(logPath + ".2")) return false;
|
||||||
|
|
||||||
|
var legacyPath = Path.Combine(directory, "legacy-unbounded.log");
|
||||||
|
File.WriteAllText(legacyPath, new string('l', 2048), new UTF8Encoding(false));
|
||||||
|
if (new FileInfo(legacyPath).Length != 2048 || File.Exists(legacyPath + ".1")) return false;
|
||||||
|
BoundedLog.Append(legacyPath, "new\n", limit);
|
||||||
|
if (new FileInfo(legacyPath).Length > limit
|
||||||
|
|| new FileInfo(legacyPath + ".1").Length > limit) return false;
|
||||||
|
|
||||||
|
var tailPath = Path.Combine(directory, "damaged-tail.log");
|
||||||
|
var prefix = Encoding.UTF8.GetBytes("PREFIX-MUST-NOT-BE-READ\n" + new string('p', 4096) + "\n");
|
||||||
|
var damagedTail = new List<byte>(prefix);
|
||||||
|
damagedTail.AddRange([0x00, 0xC3, 0x28, (byte)'\n']);
|
||||||
|
damagedTail.AddRange(Encoding.UTF8.GetBytes("tail-one\ntail-two\ntail-three\n"));
|
||||||
|
File.WriteAllBytes(tailPath, damagedTail.ToArray());
|
||||||
|
|
||||||
|
var result = BoundedLog.ReadTail(tailPath, 3, 128);
|
||||||
|
if (result.BytesRead > 128
|
||||||
|
|| result.Text.Contains("PREFIX-MUST-NOT-BE-READ", StringComparison.Ordinal)
|
||||||
|
|| result.Text.Contains('\0')
|
||||||
|
|| !result.Text.Contains("tail-one", StringComparison.Ordinal)
|
||||||
|
|| !result.Text.Contains("tail-two", StringComparison.Ordinal)
|
||||||
|
|| !result.Text.Contains("tail-three", StringComparison.Ordinal)) return false;
|
||||||
|
|
||||||
|
var message = ProxyProbe.BuildFailureLog(new IOException("secret-target.example:443"));
|
||||||
|
return message.Contains(nameof(IOException), StringComparison.Ordinal)
|
||||||
|
&& !message.Contains("secret-target", StringComparison.OrdinalIgnoreCase)
|
||||||
|
&& !message.Contains(":443", StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
try { Directory.Delete(directory, recursive: true); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.ComponentModel;
|
using System.ComponentModel;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
using System.Security;
|
using System.Security;
|
||||||
|
|
||||||
namespace UCVL.VPNPlus;
|
namespace UCVL.VPNPlus;
|
||||||
@@ -35,6 +36,14 @@ internal sealed class ClientRuntimeException(string componentPath, ClientRuntime
|
|||||||
|
|
||||||
internal static class ClientRuntime
|
internal static class ClientRuntime
|
||||||
{
|
{
|
||||||
|
private const uint SemFailCriticalErrors = 0x0001;
|
||||||
|
private const uint SemNoGpFaultErrorBox = 0x0002;
|
||||||
|
private const uint SemNoOpenFileErrorBox = 0x8000;
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool SetThreadErrorMode(uint newMode, out uint oldMode);
|
||||||
|
|
||||||
internal static readonly string[] Components = ["xray.exe", "geoip.dat", "geosite.dat", "wintun.dll"];
|
internal static readonly string[] Components = ["xray.exe", "geoip.dat", "geosite.dat", "wintun.dll"];
|
||||||
|
|
||||||
internal static void Validate(string installationDirectory)
|
internal static void Validate(string installationDirectory)
|
||||||
@@ -62,6 +71,8 @@ internal static class ClientRuntime
|
|||||||
|
|
||||||
internal static bool Start(Process process)
|
internal static bool Start(Process process)
|
||||||
{
|
{
|
||||||
|
var changedErrorMode = SetThreadErrorMode(
|
||||||
|
SemFailCriticalErrors | SemNoGpFaultErrorBox | SemNoOpenFileErrorBox, out var previousErrorMode);
|
||||||
try { return process.Start(); }
|
try { return process.Start(); }
|
||||||
// The executable can disappear or become blocked after preflight.
|
// The executable can disappear or become blocked after preflight.
|
||||||
// Classify only known local CreateProcess failures, not socket errors,
|
// Classify only known local CreateProcess failures, not socket errors,
|
||||||
@@ -72,5 +83,9 @@ internal static class ClientRuntime
|
|||||||
: error.NativeErrorCode is 5 or 32 or 33 ? ClientRuntimeFault.Unreadable : ClientRuntimeFault.CannotStart;
|
: error.NativeErrorCode is 5 or 32 or 33 ? ClientRuntimeFault.Unreadable : ClientRuntimeFault.CannotStart;
|
||||||
throw new ClientRuntimeException(process.StartInfo.FileName, fault, error);
|
throw new ClientRuntimeException(process.StartInfo.FileName, fault, error);
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (changedErrorMode) SetThreadErrorMode(previousErrorMode, out _);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ internal sealed class ConnectionHealthPolicy
|
|||||||
internal bool IsDue(long now, bool running) => !running || now >= _nextProbe;
|
internal bool IsDue(long now, bool running) => !running || now >= _nextProbe;
|
||||||
internal Decision Observe(long revision, int? testedCore, int? currentCore,
|
internal Decision Observe(long revision, int? testedCore, int? currentCore,
|
||||||
bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false,
|
bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false,
|
||||||
bool activeTailnet = false, bool businessUnavailable = false)
|
bool activeTailnet = false, bool businessUnavailable = false, bool automaticSelection = false)
|
||||||
{
|
{
|
||||||
if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting)
|
if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting)
|
||||||
return Decision.Ignore;
|
return Decision.Ignore;
|
||||||
@@ -34,10 +34,18 @@ internal sealed class ConnectionHealthPolicy
|
|||||||
return Decision.Keep;
|
return Decision.Keep;
|
||||||
}
|
}
|
||||||
if (currentCore is not null && businessUnavailable && proxyHealthy) {
|
if (currentCore is not null && businessUnavailable && proxyHealthy) {
|
||||||
Failures = 0; _nextProbe = now + 20_000;
|
_nextProbe = now + 20_000;
|
||||||
const Decision advisory = Decision.WebsiteUnavailable;
|
const Decision advisory = Decision.WebsiteUnavailable;
|
||||||
var confirmed = _advisoryCandidate == advisory;
|
var confirmed = _advisoryCandidate == advisory;
|
||||||
_advisoryCandidate = advisory;
|
_advisoryCandidate = advisory;
|
||||||
|
if (automaticSelection) {
|
||||||
|
// Both the ordinary route and the forced proxy business probe
|
||||||
|
// failed. An automatically selected node gets two advisory
|
||||||
|
// rounds, then must yield instead of remaining degraded forever.
|
||||||
|
Failures = confirmed ? Failures + 1 : 1;
|
||||||
|
if (Failures >= 3) return Decision.Switch;
|
||||||
|
}
|
||||||
|
else Failures = 0;
|
||||||
return confirmed ? advisory : Decision.PendingAdvisory;
|
return confirmed ? advisory : Decision.PendingAdvisory;
|
||||||
}
|
}
|
||||||
_advisoryCandidate = null;
|
_advisoryCandidate = null;
|
||||||
|
|||||||
@@ -54,6 +54,9 @@ internal static class ConnectionHealthSelfTest
|
|||||||
== ConnectionHealthPolicy.Decision.Ignore;
|
== ConnectionHealthPolicy.Decision.Ignore;
|
||||||
ConnectionHealthPolicy.Decision Website(long now) => policy.Observe(policy.Revision, 10, 10,
|
ConnectionHealthPolicy.Decision Website(long now) => policy.Observe(policy.Revision, 10, 10,
|
||||||
true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true);
|
true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true);
|
||||||
|
ConnectionHealthPolicy.Decision AutomaticWebsite(long now) => policy.Observe(policy.Revision, 10, 10,
|
||||||
|
true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true,
|
||||||
|
automaticSelection: true);
|
||||||
ConnectionHealthPolicy.Decision TailnetEgress(long now) => policy.Observe(policy.Revision, 10, 10,
|
ConnectionHealthPolicy.Decision TailnetEgress(long now) => policy.Observe(policy.Revision, 10, 10,
|
||||||
true, false, false, false, false, now, activeTailnet: true);
|
true, false, false, false, false, now, activeTailnet: true);
|
||||||
|
|
||||||
@@ -79,6 +82,21 @@ internal static class ConnectionHealthSelfTest
|
|||||||
checks["new_core_starts_advisory_confirmation_over"] = TailnetEgress(1_085_000) == ConnectionHealthPolicy.Decision.PendingAdvisory;
|
checks["new_core_starts_advisory_confirmation_over"] = TailnetEgress(1_085_000) == ConnectionHealthPolicy.Decision.PendingAdvisory;
|
||||||
checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null,
|
checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null,
|
||||||
true, false, false, false, false, 1_105_000, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch;
|
true, false, false, false, false, 1_105_000, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch;
|
||||||
|
policy.BeginCore(1_120_000);
|
||||||
|
checks["automatic_business_failure_is_bounded"] =
|
||||||
|
AutomaticWebsite(1_125_000) == ConnectionHealthPolicy.Decision.PendingAdvisory
|
||||||
|
&& AutomaticWebsite(1_145_000) == ConnectionHealthPolicy.Decision.WebsiteUnavailable
|
||||||
|
&& AutomaticWebsite(1_165_000) == ConnectionHealthPolicy.Decision.Switch;
|
||||||
|
checks["business_success_clears_automatic_failure_streak"] =
|
||||||
|
Observe(true, 1_185_000) == ConnectionHealthPolicy.Decision.Keep
|
||||||
|
&& AutomaticWebsite(1_205_000) == ConnectionHealthPolicy.Decision.PendingAdvisory
|
||||||
|
&& policy.Failures == 1;
|
||||||
|
policy.BeginCore(1_220_000);
|
||||||
|
checks["manual_business_failure_warns_without_switching"] =
|
||||||
|
Website(1_225_000) == ConnectionHealthPolicy.Decision.PendingAdvisory
|
||||||
|
&& Enumerable.Range(1, 5).All(index =>
|
||||||
|
Website(1_225_000 + index * 20_000) == ConnectionHealthPolicy.Decision.WebsiteUnavailable)
|
||||||
|
&& policy.Failures == 0;
|
||||||
revision = policy.Revision;
|
revision = policy.Revision;
|
||||||
policy.Invalidate();
|
policy.Invalidate();
|
||||||
checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10,
|
checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10,
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace UCVL.VPNPlus;
|
||||||
|
|
||||||
|
// DERP relays change independently of the client release. Read only the
|
||||||
|
// already-installed Tailscale client's current map; never manufacture or cache
|
||||||
|
// relay addresses in the application.
|
||||||
|
internal static class DerpRouteDiscovery
|
||||||
|
{
|
||||||
|
private const int MaxMapCharacters = 256 * 1024;
|
||||||
|
private const int MaxRelayAddresses = 64;
|
||||||
|
|
||||||
|
internal static IReadOnlyList<IPAddress> ParsePublicIpv4Addresses(string json)
|
||||||
|
{
|
||||||
|
if (json.Length > MaxMapCharacters) throw new InvalidDataException("DERP Map 超过安全大小限制。");
|
||||||
|
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 24 });
|
||||||
|
if (!document.RootElement.TryGetProperty("Regions", out var regions)
|
||||||
|
|| regions.ValueKind != JsonValueKind.Object)
|
||||||
|
throw new InvalidDataException("DERP Map 缺少 Regions。");
|
||||||
|
|
||||||
|
var result = new HashSet<IPAddress>();
|
||||||
|
foreach (var region in regions.EnumerateObject())
|
||||||
|
{
|
||||||
|
if (!region.Value.TryGetProperty("Nodes", out var nodes) || nodes.ValueKind != JsonValueKind.Array)
|
||||||
|
continue;
|
||||||
|
foreach (var node in nodes.EnumerateArray())
|
||||||
|
{
|
||||||
|
if (!node.TryGetProperty("IPv4", out var value) || value.ValueKind != JsonValueKind.String)
|
||||||
|
continue;
|
||||||
|
var text = value.GetString()?.Trim();
|
||||||
|
if (!IPAddress.TryParse(text, out var address)
|
||||||
|
|| address.AddressFamily != AddressFamily.InterNetwork
|
||||||
|
|| !IsPublicIpv4(address))
|
||||||
|
continue;
|
||||||
|
result.Add(address);
|
||||||
|
if (result.Count > MaxRelayAddresses)
|
||||||
|
throw new InvalidDataException("DERP Map 节点数量超过安全限制。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result.OrderBy(address => address.ToString(), StringComparer.Ordinal).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static async Task<IReadOnlyList<IPAddress>> DiscoverAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var executable = InstalledExecutable();
|
||||||
|
if (executable is null) return [];
|
||||||
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||||
|
deadline.CancelAfter(TimeSpan.FromSeconds(2));
|
||||||
|
Process? process = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
process = new Process
|
||||||
|
{
|
||||||
|
StartInfo = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = executable,
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
StandardOutputEncoding = Encoding.UTF8,
|
||||||
|
StandardErrorEncoding = Encoding.UTF8,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
process.StartInfo.ArgumentList.Add("debug");
|
||||||
|
process.StartInfo.ArgumentList.Add("derp-map");
|
||||||
|
if (!process.Start()) return [];
|
||||||
|
var stdout = ReadBoundedAsync(process.StandardOutput, deadline.Token);
|
||||||
|
var stderr = ReadBoundedAsync(process.StandardError, deadline.Token);
|
||||||
|
await process.WaitForExitAsync(deadline.Token).ConfigureAwait(false);
|
||||||
|
var map = await stdout.ConfigureAwait(false);
|
||||||
|
_ = await stderr.ConfigureAwait(false);
|
||||||
|
return process.ExitCode == 0 ? ParsePublicIpv4Addresses(map) : [];
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception error) when (error is OperationCanceledException or IOException
|
||||||
|
or InvalidDataException or JsonException
|
||||||
|
or System.ComponentModel.Win32Exception)
|
||||||
|
{
|
||||||
|
AppPaths.WriteLog($"DERP Map 未能读取,本次不添加未知中继旁路:{error.GetType().Name}");
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (process is not null)
|
||||||
|
{
|
||||||
|
try { if (!process.HasExited) process.Kill(true); } catch { }
|
||||||
|
process.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? InstalledExecutable()
|
||||||
|
{
|
||||||
|
var roots = new[]
|
||||||
|
{
|
||||||
|
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
|
||||||
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||||
|
};
|
||||||
|
foreach (var root in roots.Where(root => !string.IsNullOrWhiteSpace(root)))
|
||||||
|
{
|
||||||
|
var candidate = Path.Combine(root, "Tailscale", "tailscale.exe");
|
||||||
|
if (File.Exists(candidate)) return candidate;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> ReadBoundedAsync(StreamReader reader, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var buffer = new char[4096];
|
||||||
|
var value = new StringBuilder();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (count == 0) return value.ToString();
|
||||||
|
if (value.Length + count > MaxMapCharacters)
|
||||||
|
throw new InvalidDataException("DERP Map 输出超过安全大小限制。");
|
||||||
|
value.Append(buffer, 0, count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsPublicIpv4(IPAddress address)
|
||||||
|
{
|
||||||
|
var bytes = address.GetAddressBytes();
|
||||||
|
if (bytes[0] is 0 or 10 or 127 || bytes[0] >= 224) return false;
|
||||||
|
if (bytes[0] == 100 && bytes[1] is >= 64 and <= 127) return false;
|
||||||
|
if (bytes[0] == 169 && bytes[1] == 254) return false;
|
||||||
|
if (bytes[0] == 172 && bytes[1] is >= 16 and <= 31) return false;
|
||||||
|
if (bytes[0] == 192 && bytes[1] == 168) return false;
|
||||||
|
if (bytes[0] == 198 && bytes[1] is 18 or 19) return false;
|
||||||
|
if (bytes[0] == 192 && bytes[1] == 0 && bytes[2] is 0 or 2) return false;
|
||||||
|
if (bytes[0] == 198 && bytes[1] == 51 && bytes[2] == 100) return false;
|
||||||
|
if (bytes[0] == 203 && bytes[1] == 0 && bytes[2] == 113) return false;
|
||||||
|
return !address.Equals(IPAddress.Broadcast);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -857,7 +857,7 @@ internal sealed partial class MainForm : Form
|
|||||||
var healthy = health.Healthy;
|
var healthy = health.Healthy;
|
||||||
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
|
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
|
||||||
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
|
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
|
||||||
_xray.UsesTailnet, health.BusinessUnavailable);
|
_xray.UsesTailnet, health.BusinessUnavailable, automaticSelection: !ManualSelection);
|
||||||
if (decision is ConnectionHealthPolicy.Decision.Ignore or ConnectionHealthPolicy.Decision.PendingAdvisory) return;
|
if (decision is ConnectionHealthPolicy.Decision.Ignore or ConnectionHealthPolicy.Decision.PendingAdvisory) return;
|
||||||
if (healthy && _xray.IsRunning) {
|
if (healthy && _xray.IsRunning) {
|
||||||
if (_displayedHealthWarning is not null) {
|
if (_displayedHealthWarning is not null) {
|
||||||
|
|||||||
@@ -130,6 +130,7 @@ internal static class NodeTransportConnector
|
|||||||
// Plain TCP/ping, or a successful DIRECT smart request, is not proof.
|
// Plain TCP/ping, or a successful DIRECT smart request, is not proof.
|
||||||
if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。");
|
if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。");
|
||||||
deadline.Token.ThrowIfCancellationRequested();
|
deadline.Token.ThrowIfCancellationRequested();
|
||||||
|
Report("connection_phase", "proxy_verified_tailnet");
|
||||||
Report("selected", "tailnet_verified");
|
Report("selected", "tailnet_verified");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -161,6 +162,7 @@ internal static class NodeTransportConnector
|
|||||||
}
|
}
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
if (verifyPublicEgress) preference.CommitDomainFallback();
|
if (verifyPublicEgress) preference.CommitDomainFallback();
|
||||||
|
if (verifyPublicEgress) Report("connection_phase", "proxy_verified_public");
|
||||||
Report("selected", "public_ingress");
|
Report("selected", "public_ingress");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,11 +130,14 @@ internal static class ProxyProbe
|
|||||||
}
|
}
|
||||||
catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ArgumentException)
|
catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ArgumentException)
|
||||||
{
|
{
|
||||||
AppPaths.WriteLog($"vpn-ai 代理复测失败:{observation.Target}:{observation.Port} {exception.GetBaseException().Message}");
|
AppPaths.WriteLog(BuildFailureLog(exception));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static string BuildFailureLog(Exception exception) =>
|
||||||
|
$"vpn-ai 代理复测失败;error={exception.GetBaseException().GetType().Name}";
|
||||||
|
|
||||||
internal static bool SelfTest()
|
internal static bool SelfTest()
|
||||||
{
|
{
|
||||||
var domain = BuildConnectRequest("domain", "example.com", 443);
|
var domain = BuildConnectRequest("domain", "example.com", 443);
|
||||||
@@ -144,7 +147,8 @@ internal static class ProxyProbe
|
|||||||
&& domain[4] == "example.com".Length
|
&& domain[4] == "example.com".Length
|
||||||
&& domain[^2] == 0x01 && domain[^1] == 0xbb
|
&& domain[^2] == 0x01 && domain[^1] == 0xbb
|
||||||
&& ipv4[3] == 0x01 && ipv4.Length == 10
|
&& ipv4[3] == 0x01 && ipv4.Length == 10
|
||||||
&& ipv6[3] == 0x04 && ipv6.Length == 22;
|
&& ipv6[3] == 0x04 && ipv6.Length == 22
|
||||||
|
&& BoundedLogSelfTest.Run();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] BuildConnectRequest(string targetType, string target, int port)
|
private static byte[] BuildConnectRequest(string targetType, string target, int port)
|
||||||
|
|||||||
@@ -1,5 +1,21 @@
|
|||||||
# 优创⁺纵横家 Windows 客户端
|
# 优创⁺纵横家 Windows 客户端
|
||||||
|
|
||||||
|
## Windows 0.3.20
|
||||||
|
|
||||||
|
连接准备完成后立即验证真实代理出口,后台学习不再阻塞首次连接。自动调度线路连续出现业务级不可用时,会先从同节点 Tailscale 入口回退到青岛公网入口;同节点仍不可用时再冷却并选择其他可用节点。手动选定节点不会被自动切换。
|
||||||
|
|
||||||
|
Tailscale 中继旁路不再写死已退役的东京、硅谷和纽约公网地址,而是从本机 Tailscale 的当前 DERP Map 限时读取、校验并按当前物理网卡建立临时路由。日志改为有界轮换,错误尾部读取限制为 64 KiB,避免长期运行后日志无限增长拖慢启动和故障诊断。
|
||||||
|
|
||||||
|
损坏或不可执行的本地 `xray.exe` 现在会作为本机组件故障返回,不再触发 Windows 系统级错误对话框而卡住升级或关机。后台源码的默认公开域名、CSRF 来源和青岛入口统一为 `vpn.ucvl.cn` 与 `47.104.134.190`,环境变量覆盖仍保留。
|
||||||
|
|
||||||
|
## Windows 0.3.19
|
||||||
|
|
||||||
|
修复公司路由已经提供内网路径时,客户端仍跳过已授权代理入口的问题。客户端验证当前网卡能否访问节点代理端口,并将代理绑定到验证通过的网卡。持续检查使用当前连接的实际网卡。
|
||||||
|
|
||||||
|
内网入口或代理出网验证失败时,通过青岛转发连接同一台海外节点。公网回退通过 HTTPS 出网验证后显示连接成功,正常的公网会话继续使用当前入口。
|
||||||
|
|
||||||
|
2026 年 11 月 24 日从实际账号取得配置,分别测试 VPN002、VPN003、VPN004 的域名入口和青岛固定 IP。具体测试范围、安装包摘要和源码随版本验收记录提供。
|
||||||
|
|
||||||
## Windows 0.3.18
|
## Windows 0.3.18
|
||||||
|
|
||||||
宽屏和紧凑窗口采用同一阅读顺序。左侧设置调度与代理模式,右侧显示生效的节点和模式。本机上传与下载趋势默认同屏,下方显示有权限查看的服务器走势。累计用量使用一条数字栏。登录后的窗口按钮收起到系统托盘,托盘图标提供恢复和退出。
|
宽屏和紧凑窗口采用同一阅读顺序。左侧设置调度与代理模式,右侧显示生效的节点和模式。本机上传与下载趋势默认同屏,下方显示有权限查看的服务器走势。累计用量使用一条数字栏。登录后的窗口按钮收起到系统托盘,托盘图标提供恢复和退出。
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using System.Security.AccessControl;
|
using System.Security.AccessControl;
|
||||||
|
using System.Security.Principal;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace UCVL.VPNPlus;
|
namespace UCVL.VPNPlus;
|
||||||
@@ -10,6 +11,36 @@ internal static class ReplacementContinuitySelfTest
|
|||||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||||
private static extern uint GetFileAttributesW(string path);
|
private static extern uint GetFileAttributesW(string path);
|
||||||
|
|
||||||
|
private sealed record SecuritySnapshot(string Owner, string Group, bool Protected, string[] Rules);
|
||||||
|
|
||||||
|
private static SecuritySnapshot Snapshot(string path)
|
||||||
|
{
|
||||||
|
var security = new FileInfo(path).GetAccessControl(
|
||||||
|
AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
|
||||||
|
var rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier))
|
||||||
|
.OfType<FileSystemAccessRule>()
|
||||||
|
.Select(rule => string.Join('|',
|
||||||
|
rule.IdentityReference.Value,
|
||||||
|
(int)rule.AccessControlType,
|
||||||
|
(int)rule.FileSystemRights,
|
||||||
|
(int)rule.InheritanceFlags,
|
||||||
|
(int)rule.PropagationFlags,
|
||||||
|
rule.IsInherited))
|
||||||
|
.OrderBy(value => value, StringComparer.Ordinal)
|
||||||
|
.ToArray();
|
||||||
|
return new(
|
||||||
|
security.GetOwner(typeof(SecurityIdentifier))!.Value,
|
||||||
|
security.GetGroup(typeof(SecurityIdentifier))!.Value,
|
||||||
|
security.AreAccessRulesProtected,
|
||||||
|
rules);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool SameSecurity(SecuritySnapshot expected, SecuritySnapshot actual) =>
|
||||||
|
expected.Owner == actual.Owner
|
||||||
|
&& expected.Group == actual.Group
|
||||||
|
&& expected.Protected == actual.Protected
|
||||||
|
&& expected.Rules.SequenceEqual(actual.Rules, StringComparer.Ordinal);
|
||||||
|
|
||||||
internal static void Run(string root, Dictionary<string, bool> checks)
|
internal static void Run(string root, Dictionary<string, bool> checks)
|
||||||
{
|
{
|
||||||
var dir = Path.Combine(root, "concurrent-replacement");
|
var dir = Path.Combine(root, "concurrent-replacement");
|
||||||
@@ -23,8 +54,7 @@ internal static class ReplacementContinuitySelfTest
|
|||||||
var acl = new FileInfo(target).GetAccessControl();
|
var acl = new FileInfo(target).GetAccessControl();
|
||||||
acl.SetAccessRuleProtection(true, true);
|
acl.SetAccessRuleProtection(true, true);
|
||||||
new FileInfo(target).SetAccessControl(acl);
|
new FileInfo(target).SetAccessControl(acl);
|
||||||
const AccessControlSections sections = AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group;
|
var oldSecurity = Snapshot(target);
|
||||||
var oldSecurity = new FileInfo(target).GetAccessControl(sections).GetSecurityDescriptorSddlForm(sections);
|
|
||||||
var errors = new Dictionary<string, int>();
|
var errors = new Dictionary<string, int>();
|
||||||
var observations = 0L;
|
var observations = 0L;
|
||||||
var completed = 0;
|
var completed = 0;
|
||||||
@@ -62,8 +92,7 @@ internal static class ReplacementContinuitySelfTest
|
|||||||
}
|
}
|
||||||
void Check(string key, bool ok) { checks[key] = ok; if (!ok) throw new IOException(key); }
|
void Check(string key, bool ok) { checks[key] = ok; if (!ok) throw new IOException(key); }
|
||||||
Check("concurrent_500_replacements_keep_public_path", completed == 500 && observations > 0 && errors.Count == 0);
|
Check("concurrent_500_replacements_keep_public_path", completed == 500 && observations > 0 && errors.Count == 0);
|
||||||
Check("replacement_keeps_owner_group_and_protected_dacl", new FileInfo(target).GetAccessControl(sections)
|
Check("replacement_keeps_owner_group_and_protected_dacl", SameSecurity(oldSecurity, Snapshot(target)));
|
||||||
.GetSecurityDescriptorSddlForm(sections) == oldSecurity);
|
|
||||||
var before = InstallationTransaction.Digest(target);
|
var before = InstallationTransaction.Digest(target);
|
||||||
var refused = false;
|
var refused = false;
|
||||||
using (var held = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
|
using (var held = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||||
|
|||||||
@@ -44,9 +44,23 @@ internal static class RouteLeaseSelfTest
|
|||||||
24, gateway, [gateway]);
|
24, gateway, [gateway]);
|
||||||
var management = new Ipv4Route("47.104.134.190", "255.255.255.255", "192.168.1.1", 10);
|
var management = new Ipv4Route("47.104.134.190", "255.255.255.255", "192.168.1.1", 10);
|
||||||
var tailnet = new Ipv4Route("100.99.142.38", "255.255.255.255", "0.0.0.0", 30);
|
var tailnet = new Ipv4Route("100.99.142.38", "255.255.255.255", "0.0.0.0", 30);
|
||||||
string[] derpAddresses = ["8.216.53.107", "47.254.94.29", "192.236.188.22"];
|
const string currentAndFutureDerpMap = """
|
||||||
var derpRoutes = derpAddresses.Select(address => new Ipv4Route(address, "255.255.255.255", "192.168.1.1", 10)).ToArray();
|
{"Regions":{"902":{"RegionID":902,"RegionCode":"qingdao","Nodes":[
|
||||||
var protectedRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(tailnet.Destination)], 20, preserveProxyRoute: true);
|
{"Name":"qingdao-1","RegionID":902,"HostName":"ucvl.cn","IPv4":"47.104.134.190"},
|
||||||
|
{"Name":"future-relay","RegionID":902,"HostName":"relay.example","IPv4":"1.1.1.1"}
|
||||||
|
]}}}
|
||||||
|
""";
|
||||||
|
var discoveredDerpAddresses = DerpRouteDiscovery.ParsePublicIpv4Addresses(currentAndFutureDerpMap);
|
||||||
|
var unsafeDerpAddresses = DerpRouteDiscovery.ParsePublicIpv4Addresses("""
|
||||||
|
{"Regions":{"1":{"Nodes":[
|
||||||
|
{"IPv4":"100.67.30.7"},{"IPv4":"192.168.8.1"},{"IPv4":"127.0.0.1"},
|
||||||
|
{"IPv4":"203.0.113.10"},{"IPv4":"47.104.134.190"}
|
||||||
|
]}}}
|
||||||
|
""");
|
||||||
|
string[] retiredDerpAddresses = ["8.216.53.107", "47.254.94.29", "192.236.188.22"];
|
||||||
|
var retiredDerpRoutes = retiredDerpAddresses.Select(address => new Ipv4Route(address, "255.255.255.255", "192.168.1.1", 10)).ToArray();
|
||||||
|
var protectedRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(tailnet.Destination)], 20,
|
||||||
|
preserveProxyRoute: true, discoveredDerpAddresses);
|
||||||
var publicRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(management.Destination)], 20, preserveProxyRoute: false);
|
var publicRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(management.Destination)], 20, preserveProxyRoute: false);
|
||||||
var privateRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse("172.16.0.111")], 20, preserveProxyRoute: true);
|
var privateRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse("172.16.0.111")], 20, preserveProxyRoute: true);
|
||||||
report["management_ipv4_bypasses_tun_in_all_modes"] =
|
report["management_ipv4_bypasses_tun_in_all_modes"] =
|
||||||
@@ -56,26 +70,31 @@ internal static class RouteLeaseSelfTest
|
|||||||
report["tailscale_and_private_proxy_routes_are_not_replaced"] =
|
report["tailscale_and_private_proxy_routes_are_not_replaced"] =
|
||||||
protectedRoutes.All(r => r.Destination != tailnet.Destination)
|
protectedRoutes.All(r => r.Destination != tailnet.Destination)
|
||||||
&& privateRoutes.All(r => r.Destination != "172.16.0.111");
|
&& privateRoutes.All(r => r.Destination != "172.16.0.111");
|
||||||
report["tailscale_derp_uses_physical_host_routes_before_tun_defaults"] =
|
report["tailscale_derp_uses_current_map_before_tun_defaults"] =
|
||||||
derpRoutes.All(derp => protectedRoutes.SkipLast(2).Count(derp.SamePath) == 1)
|
discoveredDerpAddresses.All(address => protectedRoutes.SkipLast(2).Any(route => route.Destination == address.ToString()))
|
||||||
&& protectedRoutes.TakeLast(2).SequenceEqual(split);
|
&& protectedRoutes.TakeLast(2).SequenceEqual(split);
|
||||||
|
report["retired_derp_routes_are_never_reintroduced"] =
|
||||||
|
retiredDerpRoutes.All(derp => !protectedRoutes.Any(derp.SamePath));
|
||||||
|
report["derp_map_accepts_only_public_non_test_ipv4"] =
|
||||||
|
unsafeDerpAddresses.Select(address => address.ToString()).SequenceEqual(["47.104.134.190"]);
|
||||||
report["derp_routes_are_added_only_for_tailscale"] =
|
report["derp_routes_are_added_only_for_tailscale"] =
|
||||||
derpRoutes.All(derp => !privateRoutes.Any(derp.SamePath) && !publicRoutes.Any(derp.SamePath));
|
discoveredDerpAddresses.All(address => !privateRoutes.Any(route => route.Destination == address.ToString()
|
||||||
var preexisting = new[] { tailnet, management, derpRoutes[0] };
|
&& route.Destination != management.Destination));
|
||||||
|
var preexisting = new[] { tailnet, management };
|
||||||
table.Routes.AddRange(preexisting);
|
table.Routes.AddRange(preexisting);
|
||||||
await lease.ApplyAsync(protectedRoutes, CancellationToken.None);
|
await lease.ApplyAsync(protectedRoutes, CancellationToken.None);
|
||||||
report["existing_derp_route_is_reused"] = table.Routes.Count(derpRoutes[0].SamePath) == 1;
|
report["existing_management_derp_route_is_reused"] = table.Routes.Count(management.SamePath) == 1;
|
||||||
await lease.RestoreAsync(CancellationToken.None);
|
await lease.RestoreAsync(CancellationToken.None);
|
||||||
report["existing_management_tailnet_and_derp_paths_survive_cleanup"] =
|
report["existing_management_tailnet_and_derp_paths_survive_cleanup"] =
|
||||||
table.Routes.SequenceEqual(preexisting) && !File.Exists(path);
|
table.Routes.SequenceEqual(preexisting) && !File.Exists(path);
|
||||||
table.Routes.Remove(derpRoutes[0]);
|
|
||||||
var wifi = new TunRouting.PhysicalNetwork("Fixture Wi-Fi", 11, IPAddress.Parse("172.20.1.30"),
|
var wifi = new TunRouting.PhysicalNetwork("Fixture Wi-Fi", 11, IPAddress.Parse("172.20.1.30"),
|
||||||
24, IPAddress.Parse("172.20.1.1"), [IPAddress.Parse("172.20.1.1")]);
|
24, IPAddress.Parse("172.20.1.1"), [IPAddress.Parse("172.20.1.1")]);
|
||||||
var rebound = TunRouting.CreateOwnedRoutes(wifi, [IPAddress.Parse(tailnet.Destination)], 21, preserveProxyRoute: true);
|
var rebound = TunRouting.CreateOwnedRoutes(wifi, [IPAddress.Parse(tailnet.Destination)], 21,
|
||||||
|
preserveProxyRoute: true, discoveredDerpAddresses);
|
||||||
await lease.ApplyAsync(rebound, CancellationToken.None);
|
await lease.ApplyAsync(rebound, CancellationToken.None);
|
||||||
report["tailscale_derp_routes_rebind_to_new_physical_uplink"] =
|
report["tailscale_derp_routes_rebind_to_new_physical_uplink"] =
|
||||||
derpRoutes.All(old => !table.Routes.Any(old.SamePath)
|
discoveredDerpAddresses.All(address => table.Routes.Any(route => route.Destination == address.ToString()
|
||||||
&& table.Routes.Any((old with { InterfaceIndex = 11, NextHop = "172.20.1.1" }).SamePath));
|
&& route.InterfaceIndex == 11 && route.NextHop == "172.20.1.1"));
|
||||||
await lease.RestoreAsync(CancellationToken.None);
|
await lease.RestoreAsync(CancellationToken.None);
|
||||||
report["derp_rebind_cleanup_preserves_original_routes"] = table.Routes.SequenceEqual([tailnet, management]) && !File.Exists(path);
|
report["derp_rebind_cleanup_preserves_original_routes"] = table.Routes.SequenceEqual([tailnet, management]) && !File.Exists(path);
|
||||||
table.Routes.Clear();
|
table.Routes.Clear();
|
||||||
|
|||||||
@@ -2,14 +2,16 @@ namespace UCVL.VPNPlus;
|
|||||||
|
|
||||||
internal static class StartupLearningWarmup
|
internal static class StartupLearningWarmup
|
||||||
{
|
{
|
||||||
// The readiness callback starts only transport proof. The setup owner keeps
|
// The readiness callback starts only transport learning. The setup owner
|
||||||
// its lifecycle lock until DNS/network setup succeeds; rule commits wait on
|
// keeps its lifecycle lock until DNS/network setup succeeds; rule commits
|
||||||
// that existing lock. Setup time never spends the post-setup learning budget.
|
// wait on that existing lock. Once setup is ready, learning continues in a
|
||||||
|
// bounded observed task and no longer delays the mandatory proxy proof.
|
||||||
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
|
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
|
||||||
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null)
|
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null,
|
||||||
|
Action<Exception?>? onBackgroundCompleted = null)
|
||||||
{
|
{
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
using var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
|
var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
|
||||||
CancellationTokenSource? learning = null;
|
CancellationTokenSource? learning = null;
|
||||||
Task? work = null;
|
Task? work = null;
|
||||||
try
|
try
|
||||||
@@ -18,21 +20,48 @@ internal static class StartupLearningWarmup
|
|||||||
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
|
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
|
||||||
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
|
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
|
||||||
learning.Token.ThrowIfCancellationRequested();
|
learning.Token.ThrowIfCancellationRequested();
|
||||||
work = learn(learning.Token);
|
work = learn(learning.Token)
|
||||||
|
?? throw new InvalidOperationException("Startup learning did not return a task.");
|
||||||
});
|
});
|
||||||
token.ThrowIfCancellationRequested();
|
token.ThrowIfCancellationRequested();
|
||||||
if (work is null) return;
|
if (work is null)
|
||||||
budget.CancelAfter(TimeSpan.FromSeconds(15));
|
{
|
||||||
await work;
|
learning?.Dispose();
|
||||||
token.ThrowIfCancellationRequested();
|
budget.Dispose();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
finally
|
learning!.Token.ThrowIfCancellationRequested();
|
||||||
|
budget.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
|
_ = ObserveBackgroundAsync(work, learning, budget, onBackgroundCompleted);
|
||||||
|
}
|
||||||
|
catch
|
||||||
{
|
{
|
||||||
// A failed setup must leave no outstanding proof/commit task. Drain
|
// A failed setup must leave no outstanding proof/commit task. Drain
|
||||||
// cancellation without replacing the original setup/learning error.
|
// cancellation without replacing the original setup/learning error.
|
||||||
learning?.Cancel();
|
learning?.Cancel();
|
||||||
if (work is not null) try { await work; } catch { }
|
if (work is not null) try { await work; } catch { }
|
||||||
learning?.Dispose();
|
learning?.Dispose();
|
||||||
|
budget.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task ObserveBackgroundAsync(Task work, CancellationTokenSource learning,
|
||||||
|
CancellationTokenSource budget, Action<Exception?>? onCompleted)
|
||||||
|
{
|
||||||
|
Exception? failure = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await work.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (learning.IsCancellationRequested) { }
|
||||||
|
catch (Exception error) { failure = error; }
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
try { learning.Cancel(); } catch { }
|
||||||
|
learning.Dispose();
|
||||||
|
budget.Dispose();
|
||||||
|
try { onCompleted?.Invoke(failure); } catch { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,9 +13,6 @@ internal static class TunRouting
|
|||||||
{
|
{
|
||||||
internal const string AdapterName = "UCVL VPNPlus";
|
internal const string AdapterName = "UCVL VPNPlus";
|
||||||
private static readonly string OwnedAdapterInstanceId = BuildOwnedAdapterInstanceId();
|
private static readonly string OwnedAdapterInstanceId = BuildOwnedAdapterInstanceId();
|
||||||
private static readonly IPAddress[] CompanyDerpAddresses =
|
|
||||||
[IPAddress.Parse("8.216.53.107"), IPAddress.Parse("47.254.94.29"), IPAddress.Parse("192.236.188.22")];
|
|
||||||
|
|
||||||
internal sealed record PhysicalNetwork(
|
internal sealed record PhysicalNetwork(
|
||||||
string InterfaceName,
|
string InterfaceName,
|
||||||
int InterfaceIndex,
|
int InterfaceIndex,
|
||||||
@@ -156,8 +153,11 @@ internal static class TunRouting
|
|||||||
if (preserveTailnetAddress is not null)
|
if (preserveTailnetAddress is not null)
|
||||||
TailnetTransport.RequireCurrentBinding(preserveTailnetAddress, tailnetBinding, physicalNetwork);
|
TailnetTransport.RequireCurrentBinding(preserveTailnetAddress, tailnetBinding, physicalNetwork);
|
||||||
}
|
}
|
||||||
|
var derpAddresses = preserveTailnetAddress is null
|
||||||
|
? Array.Empty<IPAddress>()
|
||||||
|
: await DerpRouteDiscovery.DiscoverAsync(cancellationToken).ConfigureAwait(false);
|
||||||
var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index,
|
var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index,
|
||||||
preservePrivateNodeRoute || preserveTailnetAddress is not null);
|
preservePrivateNodeRoute || preserveTailnetAddress is not null, derpAddresses);
|
||||||
// The journal records additions before applying them and skips exact
|
// The journal records additions before applying them and skips exact
|
||||||
// pre-existing routes. The user's LAN and Tailnet routes stay in place.
|
// pre-existing routes. The user's LAN and Tailnet routes stay in place.
|
||||||
await new NetworkRouteLease(AppPaths.TunStateFile, new WindowsRouteTable()).ApplyAsync(routes, cancellationToken);
|
await new NetworkRouteLease(AppPaths.TunStateFile, new WindowsRouteTable()).ApplyAsync(routes, cancellationToken);
|
||||||
@@ -167,14 +167,15 @@ internal static class TunRouting
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal static IReadOnlyList<Ipv4Route> CreateOwnedRoutes(PhysicalNetwork physicalNetwork,
|
internal static IReadOnlyList<Ipv4Route> CreateOwnedRoutes(PhysicalNetwork physicalNetwork,
|
||||||
IReadOnlyCollection<IPAddress> proxyIpv4Addresses, int tunIndex, bool preserveProxyRoute)
|
IReadOnlyCollection<IPAddress> proxyIpv4Addresses, int tunIndex, bool preserveProxyRoute,
|
||||||
|
IReadOnlyCollection<IPAddress>? derpAddresses = null)
|
||||||
{
|
{
|
||||||
var bypassAddresses = physicalNetwork.Ipv4DnsServers.Append(PlatformBootstrapTransport.ManagementAddress);
|
var bypassAddresses = physicalNetwork.Ipv4DnsServers.Append(PlatformBootstrapTransport.ManagementAddress);
|
||||||
if (!preserveProxyRoute) bypassAddresses = proxyIpv4Addresses.Concat(bypassAddresses);
|
if (!preserveProxyRoute) bypassAddresses = proxyIpv4Addresses.Concat(bypassAddresses);
|
||||||
// Keep the overlay target on Tailscale and its relay traffic on the physical uplink.
|
// Keep the overlay target on Tailscale and its relay traffic on the physical uplink.
|
||||||
// A TUN default route could otherwise send the relay through the proxy that depends on it.
|
// A TUN default route could otherwise send the relay through the proxy that depends on it.
|
||||||
if (preserveProxyRoute && proxyIpv4Addresses.Any(address => TailnetTransport.IsTailnetAddress(address.ToString())))
|
if (preserveProxyRoute && proxyIpv4Addresses.Any(address => TailnetTransport.IsTailnetAddress(address.ToString())))
|
||||||
bypassAddresses = bypassAddresses.Concat(CompanyDerpAddresses);
|
bypassAddresses = bypassAddresses.Concat(derpAddresses ?? []);
|
||||||
var routes = bypassAddresses.Distinct().Select(address =>
|
var routes = bypassAddresses.Distinct().Select(address =>
|
||||||
{
|
{
|
||||||
var nextHop = IsOnLink(address, physicalNetwork.Ipv4Address, physicalNetwork.Ipv4PrefixLength)
|
var nextHop = IsOnLink(address, physicalNetwork.Ipv4Address, physicalNetwork.Ipv4PrefixLength)
|
||||||
|
|||||||
@@ -10,10 +10,10 @@
|
|||||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||||
<Version>0.3.18</Version>
|
<Version>0.3.20</Version>
|
||||||
<AssemblyVersion>0.3.18.0</AssemblyVersion>
|
<AssemblyVersion>0.3.20.0</AssemblyVersion>
|
||||||
<FileVersion>0.3.18.0</FileVersion>
|
<FileVersion>0.3.20.0</FileVersion>
|
||||||
<InformationalVersion>0.3.18</InformationalVersion>
|
<InformationalVersion>0.3.20</InformationalVersion>
|
||||||
<Product>纵横家</Product>
|
<Product>纵横家</Product>
|
||||||
<Company>优创未来(UCVL)</Company>
|
<Company>优创未来(UCVL)</Company>
|
||||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||||
|
|||||||
+11
-5
@@ -273,7 +273,11 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
|||||||
Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
|
Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
|
||||||
ScheduleLearningAsync(new LearningObservation { Target=target, Port=443, AccessKind="http",
|
ScheduleLearningAsync(new LearningObservation { Target=target, Port=443, AccessKind="http",
|
||||||
Node=_nodeSlug, Scope=PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public" }, warmupToken))),
|
Node=_nodeSlug, Scope=PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public" }, warmupToken))),
|
||||||
cancellationToken);
|
cancellationToken,
|
||||||
|
onBackgroundCompleted: error => AppPaths.WriteLog(new TransportDiagnostic(
|
||||||
|
"connection_phase", error is null ? "learning_finished_or_cancelled" : "learning_failed_observed",
|
||||||
|
_nodeSlug).SafeMessage));
|
||||||
|
AppPaths.WriteLog(new TransportDiagnostic("connection_phase", "runtime_ready", _nodeSlug).SafeMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal async Task StopAsync()
|
internal async Task StopAsync()
|
||||||
@@ -642,7 +646,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
|||||||
&& !value.Contains("Failed to start", StringComparison.OrdinalIgnoreCase)) return;
|
&& !value.Contains("Failed to start", StringComparison.OrdinalIgnoreCase)) return;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
File.AppendAllText(AppPaths.XrayLogFile, $"{DateTimeOffset.Now:O} {value}{Environment.NewLine}");
|
BoundedLog.Append(AppPaths.XrayLogFile, $"{DateTimeOffset.Now:O} {value}{Environment.NewLine}",
|
||||||
|
BoundedLog.XrayMaxBytes);
|
||||||
}
|
}
|
||||||
catch { }
|
catch { }
|
||||||
}
|
}
|
||||||
@@ -704,9 +709,10 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (!File.Exists(AppPaths.XrayLogFile)) return "";
|
var tail = BoundedLog.ReadTail(AppPaths.XrayLogFile, 3, BoundedLog.ErrorTailMaxBytes);
|
||||||
var lines = File.ReadLines(AppPaths.XrayLogFile).TakeLast(3);
|
return string.IsNullOrWhiteSpace(tail.Text)
|
||||||
return $" {string.Join(" ", lines)}";
|
? ""
|
||||||
|
: $" {tail.Text.Replace(Environment.NewLine, " ", StringComparison.Ordinal)}";
|
||||||
}
|
}
|
||||||
catch { return ""; }
|
catch { return ""; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ using (var epoch = new CancellationTokenSource())
|
|||||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||||
{
|
{
|
||||||
var tunReady = Signal(); var nrptStarted = Signal(); var finishNrpt = Signal();
|
var tunReady = Signal(); var nrptStarted = Signal(); var finishNrpt = Signal();
|
||||||
|
var allowCommit = Signal(); var learningFinished = Signal();
|
||||||
var proofFinished = false; var committed = false; var setupFinished = false;
|
var proofFinished = false; var committed = false; var setupFinished = false;
|
||||||
var clock = new ManualClock();
|
var clock = new ManualClock();
|
||||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||||
@@ -25,38 +26,56 @@ using (var lifecycle = new SemaphoreSlim(1, 1))
|
|||||||
finally { lifecycle.Release(); }
|
finally { lifecycle.Release(); }
|
||||||
}, async token => {
|
}, async token => {
|
||||||
proofFinished = true;
|
proofFinished = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
await lifecycle.WaitAsync(token);
|
await lifecycle.WaitAsync(token);
|
||||||
try { token.ThrowIfCancellationRequested(); committed = setupFinished; }
|
try
|
||||||
|
{
|
||||||
|
token.ThrowIfCancellationRequested();
|
||||||
|
await allowCommit.Task.WaitAsync(token);
|
||||||
|
committed = setupFinished;
|
||||||
|
}
|
||||||
finally { lifecycle.Release(); }
|
finally { lifecycle.Release(); }
|
||||||
|
}
|
||||||
|
finally { learningFinished.TrySetResult(); }
|
||||||
}, CancellationToken.None, clock);
|
}, CancellationToken.None, clock);
|
||||||
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
|
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
|
||||||
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
|
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
|
||||||
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
|
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
|
||||||
finishNrpt.SetResult(); await run.WaitAsync(TimeSpan.FromSeconds(3));
|
finishNrpt.SetResult();
|
||||||
checks["completed_proof_commits_after_setup"] = committed;
|
var readyBeforeLearning = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||||
|
checks["connection_readiness_does_not_wait_for_learning_commit"] = readyBeforeLearning && !committed;
|
||||||
|
allowCommit.SetResult();
|
||||||
|
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
checks["background_proof_commits_after_setup"] = committed;
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
var clock = new ManualClock(); var setupEntered = Signal(); var finishSetup = Signal();
|
var clock = new ManualClock(); var setupEntered = Signal(); var finishSetup = Signal();
|
||||||
var learningStarted = Signal(); var cancelled = false;
|
var learningStarted = Signal(); var learningFinished = Signal(); var cancelled = false;
|
||||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||||
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
|
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
|
||||||
}, async token => {
|
}, async token => {
|
||||||
learningStarted.SetResult();
|
learningStarted.SetResult();
|
||||||
try { await Task.Delay(Timeout.Infinite, token); }
|
try { await Task.Delay(Timeout.Infinite, token); }
|
||||||
catch (OperationCanceledException) { cancelled = true; }
|
catch (OperationCanceledException) { cancelled = true; }
|
||||||
|
finally { learningFinished.TrySetResult(); }
|
||||||
}, CancellationToken.None, clock);
|
}, CancellationToken.None, clock);
|
||||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
clock.Advance(TimeSpan.FromMinutes(1));
|
clock.Advance(TimeSpan.FromMinutes(1));
|
||||||
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
|
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
|
||||||
finishSetup.SetResult(); await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
finishSetup.SetResult(); await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
await learningStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
await learningStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
var readyBeforeBudget = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||||
|
checks["connection_readiness_returns_while_learning_is_background"] = readyBeforeBudget && !cancelled;
|
||||||
clock.Advance(TimeSpan.FromMilliseconds(14_999));
|
clock.Advance(TimeSpan.FromMilliseconds(14_999));
|
||||||
checks["learning_retains_fifteen_seconds_after_setup"] = !cancelled && !run.IsCompleted;
|
checks["background_learning_retains_fifteen_second_budget"] = !cancelled;
|
||||||
clock.Advance(TimeSpan.FromMilliseconds(1));
|
clock.Advance(TimeSpan.FromMilliseconds(1));
|
||||||
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
checks["learning_stops_at_post_setup_budget"] = cancelled;
|
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
checks["background_learning_stops_at_post_setup_budget"] = cancelled;
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -69,7 +88,8 @@ using (var lifecycle = new SemaphoreSlim(1, 1))
|
|||||||
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
|
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
|
||||||
{
|
{
|
||||||
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
|
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
|
||||||
var setupEntered = Signal(); var finishSetup = Signal(); var stopped = false; var active = false;
|
var setupEntered = Signal(); var finishSetup = Signal(); var learningFinished = Signal();
|
||||||
|
var stopped = false; var active = false;
|
||||||
var failure = new IOException("synthetic setup failure"); Exception? observed = null;
|
var failure = new IOException("synthetic setup failure"); Exception? observed = null;
|
||||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||||
begin(epoch.Token); setupEntered.SetResult();
|
begin(epoch.Token); setupEntered.SetResult();
|
||||||
@@ -78,13 +98,14 @@ foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel"
|
|||||||
}, async token => {
|
}, async token => {
|
||||||
active = true;
|
active = true;
|
||||||
try { await Task.Delay(Timeout.Infinite, token); }
|
try { await Task.Delay(Timeout.Infinite, token); }
|
||||||
finally { active = false; stopped = true; }
|
finally { active = false; stopped = true; learningFinished.TrySetResult(); }
|
||||||
}, caller.Token, new ManualClock());
|
}, caller.Token, new ManualClock());
|
||||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
if (reason == "caller_cancel") caller.Cancel();
|
if (reason == "caller_cancel") caller.Cancel();
|
||||||
if (reason == "epoch_cancel") epoch.Cancel();
|
if (reason == "epoch_cancel") epoch.Cancel();
|
||||||
finishSetup.TrySetResult();
|
finishSetup.TrySetResult();
|
||||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (Exception error) { observed = error; }
|
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (Exception error) { observed = error; }
|
||||||
|
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
checks[reason + "_drains_learning_without_late_work"] = stopped && !active;
|
checks[reason + "_drains_learning_without_late_work"] = stopped && !active;
|
||||||
checks[reason + "_preserves_original_failure"] = reason == "setup_failure"
|
checks[reason + "_preserves_original_failure"] = reason == "setup_failure"
|
||||||
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
|
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
|
||||||
@@ -151,21 +172,47 @@ using (var lifecycle = new SemaphoreSlim(1, 1))
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Production learning handlers absorb cancellation after cleaning up their own
|
// Production learning handlers absorb cancellation after cleaning up their own
|
||||||
// probes. The startup owner must still propagate the user's cancelled connect.
|
// probes. Once readiness has returned, later cancellation belongs only to the
|
||||||
|
// bounded background learning run and cannot retroactively fail the connection.
|
||||||
{
|
{
|
||||||
using var caller = new CancellationTokenSource();
|
using var caller = new CancellationTokenSource();
|
||||||
var clock = new ManualClock(); var learnerFinishedNormally = false;
|
var clock = new ManualClock(); var learningFinished = Signal(); var learnerFinishedNormally = false;
|
||||||
var run = StartupLearningWarmup.RunAsync(begin => {
|
var run = StartupLearningWarmup.RunAsync(begin => {
|
||||||
begin(CancellationToken.None); return Task.CompletedTask;
|
begin(CancellationToken.None); return Task.CompletedTask;
|
||||||
}, async token => {
|
}, async token => {
|
||||||
try { await Task.Delay(Timeout.Infinite, token); }
|
try { await Task.Delay(Timeout.Infinite, token); }
|
||||||
catch (OperationCanceledException) { learnerFinishedNormally = true; }
|
catch (OperationCanceledException) { learnerFinishedNormally = true; }
|
||||||
|
finally { learningFinished.TrySetResult(); }
|
||||||
}, caller.Token, clock);
|
}, caller.Token, clock);
|
||||||
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
var readyBeforeCancel = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||||
caller.Cancel();
|
caller.Cancel();
|
||||||
var cancelled = false;
|
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch { }
|
||||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
|
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
checks["caller_cancellation_propagates_when_learning_swallows_it"] = cancelled && learnerFinishedNormally;
|
checks["post_readiness_cancellation_only_stops_background_learning"] =
|
||||||
|
readyBeforeCancel && run.IsCompletedSuccessfully && learnerFinishedNormally;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A background learning fault must be observed and reported without changing a
|
||||||
|
// readiness result that already completed successfully.
|
||||||
|
{
|
||||||
|
var releaseLearning = Signal(); var completionReported = Signal();
|
||||||
|
var failure = new IOException("synthetic background learning failure"); Exception? observed = null;
|
||||||
|
var run = StartupLearningWarmup.RunAsync(begin => {
|
||||||
|
begin(CancellationToken.None); return Task.CompletedTask;
|
||||||
|
}, async _ => {
|
||||||
|
await releaseLearning.Task;
|
||||||
|
throw failure;
|
||||||
|
}, CancellationToken.None, new ManualClock(), onBackgroundCompleted: error => {
|
||||||
|
observed = error;
|
||||||
|
completionReported.TrySetResult();
|
||||||
|
});
|
||||||
|
var readyBeforeFault = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||||
|
releaseLearning.SetResult();
|
||||||
|
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
await completionReported.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||||
|
checks["background_fault_is_observed_without_reversing_readiness"] =
|
||||||
|
readyBeforeFault && run.IsCompletedSuccessfully && ReferenceEquals(observed, failure);
|
||||||
}
|
}
|
||||||
|
|
||||||
var report = new { passed = checks.Values.All(v => v), checks, production_coordinator = true,
|
var report = new { passed = checks.Values.All(v => v), checks, production_coordinator = true,
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# 纵横家 Windows 0.3.20
|
||||||
|
|
||||||
|
发布日期:2026-11-28
|
||||||
|
|
||||||
|
## 连接与故障切换
|
||||||
|
|
||||||
|
- 将首次连接中的规则学习移到受控后台任务;TUN、DNS 和 NRPT 就绪后立即进行代理 HTTPS 出口验证,不再为学习任务额外等待最多 15 秒。
|
||||||
|
- 自动调度下,普通业务路径和强制代理业务探测连续三轮均不可用时执行故障切换。Tailscale 入口先回退到同一节点的青岛公网入口;公网入口仍不可用时才冷却该节点并选择其他可用节点。
|
||||||
|
- 手动指定节点保持用户选择,只显示业务不可用提示,不擅自切换到另一节点。
|
||||||
|
- Tailscale DERP 旁路地址改为从已安装的官方 Tailscale 客户端当前 DERP Map 动态读取。读取限时 2 秒、输出上限 256 KiB、最多 64 个经过公共 IPv4 校验的地址;失败时不制造未知旁路。
|
||||||
|
|
||||||
|
## 稳定性与诊断
|
||||||
|
|
||||||
|
- `vpnplus.log` 和 `xray.log` 各限制为 4 MiB 活动文件加一个轮换备份;旧版超大日志只在下一次自然写入时处理,安装和读取不会主动改写。
|
||||||
|
- Xray 错误摘要最多读取末尾 64 KiB 和三行,并清理无效 NUL 字节;代理复测日志不再记录目标地址、端口或底层异常正文。
|
||||||
|
- 启动不可执行或损坏的 `xray.exe` 时临时禁止 Windows 系统错误对话框,转为纵横家本机组件故障,保证自动升级、退出和关机流程不会被隐藏窗口阻塞。
|
||||||
|
|
||||||
|
## 后台源码
|
||||||
|
|
||||||
|
- 默认管理域名、允许主机、CSRF 来源和公开入口统一为 `vpn.ucvl.cn`。
|
||||||
|
- 默认青岛公网入口为 `47.104.134.190`;部署环境仍可通过环境变量覆盖所有公开地址。
|
||||||
|
- 新增生产默认值与环境覆盖测试,完整 Django 测试集保持通过。
|
||||||
|
|
||||||
|
## 验收边界
|
||||||
|
|
||||||
|
- Windows 自检均在隔离临时目录执行,不修改已安装客户端或现有网络。
|
||||||
|
- 后台生产容器只有在取得 VPN004 Tailscale 管理入口的有效 SSH 授权、完成运行态备份和回滚核验后才能升级;源码发布不等于生产后台已经部署。
|
||||||
|
- 安装包尚未包含公司 Authenticode 签名,Windows 仍可能显示未知发布者提示。
|
||||||
Reference in New Issue
Block a user