Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 308d71021e | |||
| 54a3433b81 | |||
| 16ac8227ea |
@@ -1,18 +1,18 @@
|
||||
# 纵横家开源源码
|
||||
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.7、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
|
||||
| 目录 | 内容与状态 |
|
||||
| --- | --- |
|
||||
| windows/ | Windows Forms / .NET 8 源码;公开导出删除许可来源不明的可选登录插图,保留原创山水 fallback |
|
||||
| backend/ | Django 后台源码与迁移;不含生产数据库、运行配置或凭据 |
|
||||
| ios/ | iPhone/iPad Swift / Packet Tunnel 源码;未提供 IPA,未声称 Xcode/签名/实机验收通过 |
|
||||
| android/ | 原 GPL-3.0 公开源码及固定候选提交链接 |
|
||||
|
||||
这是源码开源,不是全平台正式软件发布或自动升级验收。没有修改生产部署、现用客户端、公司账号授权或稳定升级源。源码中的公司公开 API/下载域名保留兼容用途,但不会授予公司服务权限。
|
||||
|
||||
真实内部节点地址已在公开导出中一致替换为 CGNAT/RFC1918/RFC5737 示例及 example.invalid 域名;它们不是可连接的生产配置。自行部署必须配置自己的后台域名、节点、证书、数据库、密钥及访问策略,不应直接使用示例端点。
|
||||
|
||||
Windows 构建说明见 windows/README.md,后台说明见 backend/README.md,Apple 源码限制及资源恢复见 ios/README.md。依赖、许可例外见 THIRD_PARTY_NOTICES.md;漏洞报告与凭据处理见 SECURITY.md。SOURCE-PROVENANCE.json 记录来源与导出变更,PUBLICATION-AUDIT.json 仅记录脱敏路径与计数。
|
||||
|
||||
macOS 已交接由独立维护者负责,不包含在此次导出,也未在此重新开发、测试或发布。
|
||||
# 纵横家开源源码
|
||||
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.20、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
|
||||
| 目录 | 内容与状态 |
|
||||
| --- | --- |
|
||||
| windows/ | Windows Forms / .NET 8 源码;0.3.20 加入动态 DERP 旁路、业务故障切换、后台学习和有界日志修复 |
|
||||
| backend/ | Django 后台源码与迁移;公开入口默认值已迁移到 `vpn.ucvl.cn`,不含生产数据库、运行配置或凭据 |
|
||||
| ios/ | iPhone/iPad Swift / Packet Tunnel 源码;未提供 IPA,未声称 Xcode/签名/实机验收通过 |
|
||||
| android/ | 原 GPL-3.0 公开源码及固定候选提交链接 |
|
||||
|
||||
这是源码开源,不是全平台正式软件发布或自动升级验收。没有修改生产部署、现用客户端、公司账号授权或稳定升级源。源码中的公司公开 API/下载域名保留兼容用途,但不会授予公司服务权限。
|
||||
|
||||
真实内部节点地址已在公开导出中一致替换为 CGNAT/RFC1918/RFC5737 示例及 example.invalid 域名;它们不是可连接的生产配置。自行部署必须配置自己的后台域名、节点、证书、数据库、密钥及访问策略,不应直接使用示例端点。
|
||||
|
||||
Windows 构建说明见 windows/README.md,后台说明见 backend/README.md,Apple 源码限制及资源恢复见 ios/README.md。依赖、许可例外见 THIRD_PARTY_NOTICES.md;漏洞报告与凭据处理见 SECURITY.md。SOURCE-PROVENANCE.json 记录来源与导出变更,PUBLICATION-AUDIT.json 仅记录脱敏路径与计数。
|
||||
|
||||
macOS 已交接由独立维护者负责,不包含在此次导出,也未在此重新开发、测试或发布。
|
||||
|
||||
+13
-7
@@ -1,7 +1,13 @@
|
||||
# 纵横家 Django 后台开源源码
|
||||
|
||||
来源为固定的 phone-20261010 源码 freeze(含 0001–0015 迁移),不是生产部署或正式迁移验收。公司自有代码按 MIT 开源,依赖保持原许可证;不含数据库、用户信息、环境变量、SSH/代理/企业微信/支付凭据、生产镜像或私有 Git 历史。
|
||||
|
||||
使用隔离的 Python 虚拟环境和 requirements.txt 安装依赖,按 toplc_vpn/settings.py 的环境变量入口提供自己的 Django secret、数据库、主机与代理配置。先审查配置与迁移,在自己的非生产数据库测试后再部署。不要直接接入现有生产数据或使用示例节点值。本仓库未提供一键安全生产部署承诺。
|
||||
|
||||
内部节点地址已一致替换为示例;公司公开 API/下载域名只为兼容保留。生产环境应自行配置账户审批、套餐、节点、策略、审计与服务访问控制。公开源码不授予公司服务器访问权限。
|
||||
# 纵横家 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 历史。
|
||||
|
||||
使用隔离的 Python 虚拟环境和 requirements.txt 安装依赖,按 toplc_vpn/settings.py 的环境变量入口提供自己的 Django secret、数据库、主机与代理配置。先审查配置与迁移,在自己的非生产数据库测试后再部署。不要直接接入现有生产数据或使用示例节点值。本仓库未提供一键安全生产部署承诺。
|
||||
|
||||
内部节点地址已一致替换为示例;公司公开 API/下载域名只为兼容保留。生产环境应自行配置账户审批、套餐、节点、策略、审计与服务访问控制。公开源码不授予公司服务器访问权限。
|
||||
|
||||
@@ -1,118 +1,118 @@
|
||||
from datetime import timedelta
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from control.dispatch import choose_node, build_dispatch_snapshot
|
||||
from control.models import ClientSession, Device, Node, NodeTrafficSample, Plan, Subscription, UsageRecord
|
||||
|
||||
|
||||
@override_settings(SECURE_SSL_REDIRECT=False)
|
||||
class DispatchTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username="dispatch-test", account_status="active")
|
||||
self.plan = Plan.objects.create(name="测试", slug="dispatch-test")
|
||||
self.sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", provisioning_state="active")
|
||||
self.nodes = []
|
||||
for index, rate in enumerate([1000000, 1000, 0]):
|
||||
node = Node.objects.create(name=f"VPN00{index+1}", slug=f"n{index}", region="测试", server=f"00{index}.vpn.toplc.cn",
|
||||
port=11080+index, protocol="vless_reality", status="online", active=True, subscription_enabled=True,
|
||||
last_seen_at=timezone.now(), fallback_only=index == 2, sni="example.com", reality_public_key="test", reality_short_id="1234")
|
||||
NodeTrafficSample.objects.create(node=node, download_bytes_per_second=rate)
|
||||
self.nodes.append(node)
|
||||
self.session, self.token = self.new_session("one")
|
||||
|
||||
def new_session(self, device):
|
||||
return ClientSession.issue(self.sub, Device.objects.create(subscription=self.sub, device_id=device))
|
||||
|
||||
def test_chooses_lower_load_not_unused_reserve(self):
|
||||
node, decision = choose_node(self.session)
|
||||
self.assertEqual(node, self.nodes[1])
|
||||
self.assertEqual(decision["rate_bps"], 1000)
|
||||
|
||||
def test_healthy_session_stays_even_when_load_changes(self):
|
||||
node, _ = choose_node(self.session)
|
||||
NodeTrafficSample.objects.filter(node=node).update(download_bytes_per_second=99000000)
|
||||
selected, decision = choose_node(self.session)
|
||||
self.assertEqual(selected, node)
|
||||
self.assertTrue(decision["sticky"])
|
||||
|
||||
def test_exclusions_are_per_request_and_configured_reserve_is_last(self):
|
||||
first, _ = choose_node(self.session)
|
||||
second, _ = choose_node(self.session, [first.slug])
|
||||
self.assertEqual(second, self.nodes[0])
|
||||
last, _ = choose_node(self.session, [n.slug for n in self.nodes[:2]])
|
||||
self.assertEqual(last, self.nodes[2])
|
||||
self.assertEqual(Node.objects.filter(status="online").count(), 3)
|
||||
|
||||
def test_new_us_003_can_participate_as_a_primary(self):
|
||||
node = self.nodes[2]
|
||||
node.name, node.region, node.fallback_only = "VPN003", "美国", False
|
||||
node.save(update_fields=["name", "region", "fallback_only"])
|
||||
self.assertEqual(choose_node(self.session)[0], node)
|
||||
self.assertEqual(build_dispatch_snapshot()["health_scope"], "agent_heartbeat_not_end_to_end")
|
||||
|
||||
def test_retired_000_is_never_selected_even_with_lowest_load(self):
|
||||
retired = Node.objects.create(name="VPN000", slug="retired-000", region="美国",
|
||||
server="000.vpn.toplc.cn", port=11080, protocol="vless_reality", status="online",
|
||||
active=False, subscription_enabled=False, last_seen_at=timezone.now(),
|
||||
fallback_only=False, sni="example.com", reality_public_key="test", reality_short_id="1234")
|
||||
NodeTrafficSample.objects.create(node=retired, download_bytes_per_second=0)
|
||||
self.assertNotEqual(choose_node(self.session)[0], retired)
|
||||
self.assertNotIn(retired.pk, [item["id"] for item in build_dispatch_snapshot()["nodes"]])
|
||||
|
||||
def test_new_connection_can_rebalance_without_moving_old_connection(self):
|
||||
node, _ = choose_node(self.session)
|
||||
NodeTrafficSample.objects.filter(node=node).update(download_bytes_per_second=99000000)
|
||||
self.assertEqual(choose_node(self.session)[0], node)
|
||||
self.assertEqual(choose_node(self.session, new_connection=True)[0], self.nodes[0])
|
||||
|
||||
def test_stale_heartbeat_is_not_healthy(self):
|
||||
Node.objects.filter(pk__in=[n.pk for n in self.nodes[:2]]).update(last_seen_at=timezone.now()-timedelta(minutes=4))
|
||||
self.assertEqual(choose_node(self.session)[0], self.nodes[2])
|
||||
Node.objects.update(status="offline")
|
||||
self.assertIsNone(choose_node(self.session)[0])
|
||||
|
||||
def test_reservations_spread_equal_load_arrivals(self):
|
||||
NodeTrafficSample.objects.all().update(download_bytes_per_second=0)
|
||||
first, _ = choose_node(self.session)
|
||||
second, _ = choose_node(self.new_session("two")[0])
|
||||
self.assertNotEqual(first, second)
|
||||
self.assertFalse(second.fallback_only)
|
||||
|
||||
def test_dedicated_subscription_never_escapes_allowed_nodes(self):
|
||||
self.sub.route_mode = Subscription.RouteMode.DEDICATED
|
||||
self.sub.save()
|
||||
self.sub.allowed_nodes.set([self.nodes[0]])
|
||||
self.assertEqual(choose_node(self.session)[0], self.nodes[0])
|
||||
self.assertIsNone(choose_node(self.session, [self.nodes[0].slug])[0])
|
||||
|
||||
def test_unknown_load_is_not_zero(self):
|
||||
NodeTrafficSample.objects.filter(node=self.nodes[1]).delete()
|
||||
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"])
|
||||
|
||||
@override_settings(VPN_PUBLIC_GATEWAY_HOST="vpn.toplc.cn", VPN_PUBLIC_GATEWAY_IPV4="192.0.2.1")
|
||||
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}")
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
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()["node"]["slug"], self.nodes[1].slug)
|
||||
self.assertEqual(response.json()["config"]["outbounds"][0]["settings"]["vnext"][0]["address"], self.nodes[1].server)
|
||||
|
||||
@override_settings(VPN_PUBLIC_GATEWAY_HOST="vpn.toplc.cn", VPN_PUBLIC_GATEWAY_IPV4="100.73.44.33")
|
||||
def test_config_never_publishes_overlay_gateway_address(self):
|
||||
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.json()["gateway"], {"host": "vpn.toplc.cn", "ipv4": None})
|
||||
|
||||
def test_history_aggregates_nodes_only_for_own_subscription(self):
|
||||
from control.views import _client_profile_payload
|
||||
for node in self.nodes:
|
||||
UsageRecord.objects.create(subscription=self.sub, node=node, day=timezone.localdate(), upload_bytes=10, download_bytes=20)
|
||||
history = _client_profile_payload(self.sub)["usage_history"]
|
||||
self.assertEqual(len(history), 7)
|
||||
self.assertEqual(history[-1]["upload_bytes"], 30)
|
||||
self.assertEqual(history[-1]["download_bytes"], 60)
|
||||
self.assertEqual(history[0]["upload_bytes"], 0)
|
||||
from datetime import timedelta
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from control.dispatch import choose_node, build_dispatch_snapshot
|
||||
from control.models import ClientSession, Device, Node, NodeTrafficSample, Plan, Subscription, UsageRecord
|
||||
|
||||
|
||||
@override_settings(SECURE_SSL_REDIRECT=False)
|
||||
class DispatchTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username="dispatch-test", account_status="active")
|
||||
self.plan = Plan.objects.create(name="测试", slug="dispatch-test")
|
||||
self.sub = Subscription.objects.create(user=self.user, plan=self.plan, status="active", provisioning_state="active")
|
||||
self.nodes = []
|
||||
for index, rate in enumerate([1000000, 1000, 0]):
|
||||
node = Node.objects.create(name=f"VPN00{index+1}", slug=f"n{index}", region="测试", server=f"00{index}.vpn.toplc.cn",
|
||||
port=11080+index, protocol="vless_reality", status="online", active=True, subscription_enabled=True,
|
||||
last_seen_at=timezone.now(), fallback_only=index == 2, sni="example.com", reality_public_key="test", reality_short_id="1234")
|
||||
NodeTrafficSample.objects.create(node=node, download_bytes_per_second=rate)
|
||||
self.nodes.append(node)
|
||||
self.session, self.token = self.new_session("one")
|
||||
|
||||
def new_session(self, device):
|
||||
return ClientSession.issue(self.sub, Device.objects.create(subscription=self.sub, device_id=device))
|
||||
|
||||
def test_chooses_lower_load_not_unused_reserve(self):
|
||||
node, decision = choose_node(self.session)
|
||||
self.assertEqual(node, self.nodes[1])
|
||||
self.assertEqual(decision["rate_bps"], 1000)
|
||||
|
||||
def test_healthy_session_stays_even_when_load_changes(self):
|
||||
node, _ = choose_node(self.session)
|
||||
NodeTrafficSample.objects.filter(node=node).update(download_bytes_per_second=99000000)
|
||||
selected, decision = choose_node(self.session)
|
||||
self.assertEqual(selected, node)
|
||||
self.assertTrue(decision["sticky"])
|
||||
|
||||
def test_exclusions_are_per_request_and_configured_reserve_is_last(self):
|
||||
first, _ = choose_node(self.session)
|
||||
second, _ = choose_node(self.session, [first.slug])
|
||||
self.assertEqual(second, self.nodes[0])
|
||||
last, _ = choose_node(self.session, [n.slug for n in self.nodes[:2]])
|
||||
self.assertEqual(last, self.nodes[2])
|
||||
self.assertEqual(Node.objects.filter(status="online").count(), 3)
|
||||
|
||||
def test_new_us_003_can_participate_as_a_primary(self):
|
||||
node = self.nodes[2]
|
||||
node.name, node.region, node.fallback_only = "VPN003", "美国", False
|
||||
node.save(update_fields=["name", "region", "fallback_only"])
|
||||
self.assertEqual(choose_node(self.session)[0], node)
|
||||
self.assertEqual(build_dispatch_snapshot()["health_scope"], "agent_heartbeat_not_end_to_end")
|
||||
|
||||
def test_retired_000_is_never_selected_even_with_lowest_load(self):
|
||||
retired = Node.objects.create(name="VPN000", slug="retired-000", region="美国",
|
||||
server="000.vpn.toplc.cn", port=11080, protocol="vless_reality", status="online",
|
||||
active=False, subscription_enabled=False, last_seen_at=timezone.now(),
|
||||
fallback_only=False, sni="example.com", reality_public_key="test", reality_short_id="1234")
|
||||
NodeTrafficSample.objects.create(node=retired, download_bytes_per_second=0)
|
||||
self.assertNotEqual(choose_node(self.session)[0], retired)
|
||||
self.assertNotIn(retired.pk, [item["id"] for item in build_dispatch_snapshot()["nodes"]])
|
||||
|
||||
def test_new_connection_can_rebalance_without_moving_old_connection(self):
|
||||
node, _ = choose_node(self.session)
|
||||
NodeTrafficSample.objects.filter(node=node).update(download_bytes_per_second=99000000)
|
||||
self.assertEqual(choose_node(self.session)[0], node)
|
||||
self.assertEqual(choose_node(self.session, new_connection=True)[0], self.nodes[0])
|
||||
|
||||
def test_stale_heartbeat_is_not_healthy(self):
|
||||
Node.objects.filter(pk__in=[n.pk for n in self.nodes[:2]]).update(last_seen_at=timezone.now()-timedelta(minutes=4))
|
||||
self.assertEqual(choose_node(self.session)[0], self.nodes[2])
|
||||
Node.objects.update(status="offline")
|
||||
self.assertIsNone(choose_node(self.session)[0])
|
||||
|
||||
def test_reservations_spread_equal_load_arrivals(self):
|
||||
NodeTrafficSample.objects.all().update(download_bytes_per_second=0)
|
||||
first, _ = choose_node(self.session)
|
||||
second, _ = choose_node(self.new_session("two")[0])
|
||||
self.assertNotEqual(first, second)
|
||||
self.assertFalse(second.fallback_only)
|
||||
|
||||
def test_dedicated_subscription_never_escapes_allowed_nodes(self):
|
||||
self.sub.route_mode = Subscription.RouteMode.DEDICATED
|
||||
self.sub.save()
|
||||
self.sub.allowed_nodes.set([self.nodes[0]])
|
||||
self.assertEqual(choose_node(self.session)[0], self.nodes[0])
|
||||
self.assertIsNone(choose_node(self.session, [self.nodes[0].slug])[0])
|
||||
|
||||
def test_unknown_load_is_not_zero(self):
|
||||
NodeTrafficSample.objects.filter(node=self.nodes[1]).delete()
|
||||
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"])
|
||||
|
||||
@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):
|
||||
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.json()["config_contract"], 2)
|
||||
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()["config"]["outbounds"][0]["settings"]["vnext"][0]["address"], self.nodes[1].server)
|
||||
|
||||
@override_settings(VPN_PUBLIC_GATEWAY_HOST="vpn.toplc.cn", VPN_PUBLIC_GATEWAY_IPV4="100.73.44.33")
|
||||
def test_config_never_publishes_overlay_gateway_address(self):
|
||||
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.json()["gateway"], {"host": "vpn.toplc.cn", "ipv4": None})
|
||||
|
||||
def test_history_aggregates_nodes_only_for_own_subscription(self):
|
||||
from control.views import _client_profile_payload
|
||||
for node in self.nodes:
|
||||
UsageRecord.objects.create(subscription=self.sub, node=node, day=timezone.localdate(), upload_bytes=10, download_bytes=20)
|
||||
history = _client_profile_payload(self.sub)["usage_history"]
|
||||
self.assertEqual(len(history), 7)
|
||||
self.assertEqual(history[-1]["upload_bytes"], 30)
|
||||
self.assertEqual(history[-1]["download_bytes"], 60)
|
||||
self.assertEqual(history[0]["upload_bytes"], 0)
|
||||
|
||||
@@ -347,7 +347,7 @@ def client_profile(request):
|
||||
|
||||
def _client_gateway_payload():
|
||||
"""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()
|
||||
public_ipv4 = None
|
||||
if configured_ipv4:
|
||||
|
||||
+156
-156
@@ -1,156 +1,156 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def env_bool(name, default=False):
|
||||
return os.getenv(name, str(default)).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def env_list(name, default=""):
|
||||
return [item.strip() for item in os.getenv(name, default).split(",") if item.strip()]
|
||||
|
||||
|
||||
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "")
|
||||
DEBUG = env_bool("DJANGO_DEBUG", False)
|
||||
if not SECRET_KEY:
|
||||
if DEBUG:
|
||||
SECRET_KEY = "development-only-insecure-secret-key"
|
||||
else:
|
||||
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")
|
||||
CSRF_TRUSTED_ORIGINS = env_list("DJANGO_CSRF_TRUSTED_ORIGINS", "https://vpn.toplc.cn")
|
||||
|
||||
INSTALLED_APPS = [
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
"accounts.apps.AccountsConfig",
|
||||
"control.apps.ControlConfig",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"accounts.middleware.LoginRateLimitMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = "toplc_vpn.urls"
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [BASE_DIR / "templates"],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
"control.context_processors.platform_settings",
|
||||
],
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = "toplc_vpn.wsgi.application"
|
||||
ASGI_APPLICATION = "toplc_vpn.asgi.application"
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"NAME": os.getenv("POSTGRES_DB", "toplc_vpn"),
|
||||
"USER": os.getenv("POSTGRES_USER", "toplc_vpn"),
|
||||
"PASSWORD": os.getenv("POSTGRES_PASSWORD", ""),
|
||||
"HOST": os.getenv("POSTGRES_HOST", "db"),
|
||||
"PORT": os.getenv("POSTGRES_PORT", "5432"),
|
||||
"CONN_MAX_AGE": 60,
|
||||
"CONN_HEALTH_CHECKS": True,
|
||||
}
|
||||
}
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 10}},
|
||||
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
|
||||
]
|
||||
PASSWORD_HASHERS = [
|
||||
"django.contrib.auth.hashers.Argon2PasswordHasher",
|
||||
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
|
||||
]
|
||||
|
||||
AUTH_USER_MODEL = "accounts.User"
|
||||
LOGIN_URL = "login"
|
||||
LOGIN_REDIRECT_URL = "portal-dashboard"
|
||||
LOGOUT_REDIRECT_URL = "login"
|
||||
|
||||
LANGUAGE_CODE = "zh-hans"
|
||||
TIME_ZONE = "Asia/Shanghai"
|
||||
USE_I18N = True
|
||||
USE_TZ = True
|
||||
|
||||
STATIC_URL = "/static/"
|
||||
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||
STATICFILES_DIRS = [BASE_DIR / "static"]
|
||||
STORAGES = {
|
||||
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
|
||||
"staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
|
||||
}
|
||||
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
PUBLIC_BASE_URL = os.getenv("VPN_PUBLIC_BASE_URL", "https://vpn.toplc.cn").rstrip("/")
|
||||
# Credentials are injected server-side; no admin form or browser receives the secret.
|
||||
WECOM_ENABLED = env_bool("WECOM_ENABLED", False)
|
||||
WECOM_CORP_ID = os.getenv("WECOM_CORP_ID", "").strip()
|
||||
WECOM_AGENT_ID = os.getenv("WECOM_AGENT_ID", "").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_IPV4 = os.getenv("VPN_PUBLIC_GATEWAY_IPV4", "").strip()
|
||||
# Optional employee-only same-node transport hint. Enabling also requires the
|
||||
# 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_ENDPOINTS_JSON = os.getenv("VPN_TAILSCALE_ENDPOINTS_JSON", "")
|
||||
# Private auxiliary is NOT a public/core node. Keep disabled until board-side
|
||||
# per-device authorization/renewal/revocation and reboot acceptance are complete.
|
||||
VPN_PRIVATE_AUXILIARY_ENABLED = env_bool("VPN_PRIVATE_AUXILIARY_ENABLED", False)
|
||||
VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID = int(os.getenv("VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID", "0"))
|
||||
VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256 = os.getenv("VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256", "").strip()
|
||||
VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256 = os.getenv("VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256", "").strip()
|
||||
VPN_PRIVATE_AUXILIARY_ADDRESS = os.getenv("VPN_PRIVATE_AUXILIARY_ADDRESS", "192.168.50.111").strip()
|
||||
VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS = os.getenv("VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS", "").strip()
|
||||
|
||||
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
||||
USE_X_FORWARDED_HOST = True
|
||||
SECURE_SSL_REDIRECT = env_bool("DJANGO_SECURE_SSL_REDIRECT", True)
|
||||
SECURE_HSTS_SECONDS = int(os.getenv("DJANGO_HSTS_SECONDS", "31536000"))
|
||||
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
|
||||
SECURE_HSTS_PRELOAD = False
|
||||
SESSION_COOKIE_SECURE = not DEBUG
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = "Lax"
|
||||
CSRF_COOKIE_SECURE = not DEBUG
|
||||
CSRF_COOKIE_SAMESITE = "Lax"
|
||||
X_FRAME_OPTIONS = "DENY"
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
SECURE_REFERRER_POLICY = "same-origin"
|
||||
|
||||
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {"console": {"class": "logging.StreamHandler"}},
|
||||
"root": {"handlers": ["console"], "level": "INFO"},
|
||||
}
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def env_bool(name, default=False):
|
||||
return os.getenv(name, str(default)).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def env_list(name, default=""):
|
||||
return [item.strip() for item in os.getenv(name, default).split(",") if item.strip()]
|
||||
|
||||
|
||||
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "")
|
||||
DEBUG = env_bool("DJANGO_DEBUG", False)
|
||||
if not SECRET_KEY:
|
||||
if DEBUG:
|
||||
SECRET_KEY = "development-only-insecure-secret-key"
|
||||
else:
|
||||
raise RuntimeError("DJANGO_SECRET_KEY is required when DJANGO_DEBUG is false")
|
||||
|
||||
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.ucvl.cn")
|
||||
|
||||
INSTALLED_APPS = [
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
"accounts.apps.AccountsConfig",
|
||||
"control.apps.ControlConfig",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"accounts.middleware.LoginRateLimitMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = "toplc_vpn.urls"
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [BASE_DIR / "templates"],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
"control.context_processors.platform_settings",
|
||||
],
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = "toplc_vpn.wsgi.application"
|
||||
ASGI_APPLICATION = "toplc_vpn.asgi.application"
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"NAME": os.getenv("POSTGRES_DB", "toplc_vpn"),
|
||||
"USER": os.getenv("POSTGRES_USER", "toplc_vpn"),
|
||||
"PASSWORD": os.getenv("POSTGRES_PASSWORD", ""),
|
||||
"HOST": os.getenv("POSTGRES_HOST", "db"),
|
||||
"PORT": os.getenv("POSTGRES_PORT", "5432"),
|
||||
"CONN_MAX_AGE": 60,
|
||||
"CONN_HEALTH_CHECKS": True,
|
||||
}
|
||||
}
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 10}},
|
||||
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
|
||||
]
|
||||
PASSWORD_HASHERS = [
|
||||
"django.contrib.auth.hashers.Argon2PasswordHasher",
|
||||
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
|
||||
]
|
||||
|
||||
AUTH_USER_MODEL = "accounts.User"
|
||||
LOGIN_URL = "login"
|
||||
LOGIN_REDIRECT_URL = "portal-dashboard"
|
||||
LOGOUT_REDIRECT_URL = "login"
|
||||
|
||||
LANGUAGE_CODE = "zh-hans"
|
||||
TIME_ZONE = "Asia/Shanghai"
|
||||
USE_I18N = True
|
||||
USE_TZ = True
|
||||
|
||||
STATIC_URL = "/static/"
|
||||
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||
STATICFILES_DIRS = [BASE_DIR / "static"]
|
||||
STORAGES = {
|
||||
"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
|
||||
"staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"},
|
||||
}
|
||||
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
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.
|
||||
WECOM_ENABLED = env_bool("WECOM_ENABLED", False)
|
||||
WECOM_CORP_ID = os.getenv("WECOM_CORP_ID", "").strip()
|
||||
WECOM_AGENT_ID = os.getenv("WECOM_AGENT_ID", "").strip()
|
||||
WECOM_SECRET = os.getenv("WECOM_SECRET", "").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", "47.104.134.190").strip()
|
||||
# Optional employee-only same-node transport hint. Enabling also requires the
|
||||
# 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_ENDPOINTS_JSON = os.getenv("VPN_TAILSCALE_ENDPOINTS_JSON", "")
|
||||
# Private auxiliary is NOT a public/core node. Keep disabled until board-side
|
||||
# per-device authorization/renewal/revocation and reboot acceptance are complete.
|
||||
VPN_PRIVATE_AUXILIARY_ENABLED = env_bool("VPN_PRIVATE_AUXILIARY_ENABLED", False)
|
||||
VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID = int(os.getenv("VPN_PRIVATE_AUXILIARY_VALIDATION_DEVICE_ID", "0"))
|
||||
VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256 = os.getenv("VPN_PRIVATE_AUXILIARY_TLS_LEAF_SHA256", "").strip()
|
||||
VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256 = os.getenv("VPN_PRIVATE_AUXILIARY_AGENT_TOKEN_SHA256", "").strip()
|
||||
VPN_PRIVATE_AUXILIARY_ADDRESS = os.getenv("VPN_PRIVATE_AUXILIARY_ADDRESS", "192.168.50.111").strip()
|
||||
VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS = os.getenv("VPN_PRIVATE_AUXILIARY_CONNECT_ADDRESS", "").strip()
|
||||
|
||||
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
||||
USE_X_FORWARDED_HOST = True
|
||||
SECURE_SSL_REDIRECT = env_bool("DJANGO_SECURE_SSL_REDIRECT", True)
|
||||
SECURE_HSTS_SECONDS = int(os.getenv("DJANGO_HSTS_SECONDS", "31536000"))
|
||||
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
|
||||
SECURE_HSTS_PRELOAD = False
|
||||
SESSION_COOKIE_SECURE = not DEBUG
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = "Lax"
|
||||
CSRF_COOKIE_SECURE = not DEBUG
|
||||
CSRF_COOKIE_SAMESITE = "Lax"
|
||||
X_FRAME_OPTIONS = "DENY"
|
||||
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||
SECURE_REFERRER_POLICY = "same-origin"
|
||||
|
||||
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {"console": {"class": "logging.StreamHandler"}},
|
||||
"root": {"handlers": ["console"], "level": "INFO"},
|
||||
}
|
||||
|
||||
@@ -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. 通过企业微信“尚书台”发送全员通知;不使用小小优,不重复发送。
|
||||
+56
-55
@@ -1,55 +1,56 @@
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class AppPaths
|
||||
{
|
||||
internal static readonly string DataDirectory = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"UCVL",
|
||||
"VPNPlus");
|
||||
|
||||
internal static string DeviceIdFile => Path.Combine(DataDirectory, "device-id.txt");
|
||||
internal static string TokenFile => Path.Combine(DataDirectory, "session.bin");
|
||||
internal static string ProxyStateFile => Path.Combine(DataDirectory, "proxy-state.json");
|
||||
internal static string TunStateFile => Path.Combine(DataDirectory, "tun-state.json");
|
||||
internal static string LearnedRoutesFile => Path.Combine(DataDirectory, "learned-routes.json");
|
||||
internal static string ConfigFile => Path.Combine(DataDirectory, "xray-config.json");
|
||||
internal static string PidFile => Path.Combine(DataDirectory, "xray.pid");
|
||||
internal static string LogFile => Path.Combine(DataDirectory, "vpnplus.log");
|
||||
internal static string XrayLogFile => Path.Combine(DataDirectory, "xray.log");
|
||||
internal static string ConnectionSelfTestFile => Path.Combine(DataDirectory, "connection-self-test.json");
|
||||
|
||||
internal static void EnsureDirectory() => Directory.CreateDirectory(DataDirectory);
|
||||
|
||||
internal static string GetOrCreateDeviceId()
|
||||
{
|
||||
EnsureDirectory();
|
||||
if (File.Exists(DeviceIdFile))
|
||||
{
|
||||
var existing = File.ReadAllText(DeviceIdFile, Encoding.UTF8).Trim();
|
||||
if (Guid.TryParse(existing, out _))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
var deviceId = Guid.NewGuid().ToString("D");
|
||||
File.WriteAllText(DeviceIdFile, deviceId, new UTF8Encoding(false));
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
internal static void WriteLog(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
EnsureDirectory();
|
||||
File.AppendAllText(LogFile, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}", Encoding.UTF8);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Logging must never prevent connecting or restoring the system proxy.
|
||||
}
|
||||
}
|
||||
|
||||
internal static void WriteError(Exception exception) => WriteLog($"ERROR {exception}");
|
||||
}
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class AppPaths
|
||||
{
|
||||
internal static readonly string DataDirectory = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"UCVL",
|
||||
"VPNPlus");
|
||||
|
||||
internal static string DeviceIdFile => Path.Combine(DataDirectory, "device-id.txt");
|
||||
internal static string TokenFile => Path.Combine(DataDirectory, "session.bin");
|
||||
internal static string ProxyStateFile => Path.Combine(DataDirectory, "proxy-state.json");
|
||||
internal static string TunStateFile => Path.Combine(DataDirectory, "tun-state.json");
|
||||
internal static string LearnedRoutesFile => Path.Combine(DataDirectory, "learned-routes.json");
|
||||
internal static string ConfigFile => Path.Combine(DataDirectory, "xray-config.json");
|
||||
internal static string PidFile => Path.Combine(DataDirectory, "xray.pid");
|
||||
internal static string LogFile => Path.Combine(DataDirectory, "vpnplus.log");
|
||||
internal static string XrayLogFile => Path.Combine(DataDirectory, "xray.log");
|
||||
internal static string ConnectionSelfTestFile => Path.Combine(DataDirectory, "connection-self-test.json");
|
||||
|
||||
internal static void EnsureDirectory() => Directory.CreateDirectory(DataDirectory);
|
||||
|
||||
internal static string GetOrCreateDeviceId()
|
||||
{
|
||||
EnsureDirectory();
|
||||
if (File.Exists(DeviceIdFile))
|
||||
{
|
||||
var existing = File.ReadAllText(DeviceIdFile, Encoding.UTF8).Trim();
|
||||
if (Guid.TryParse(existing, out _))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
var deviceId = Guid.NewGuid().ToString("D");
|
||||
File.WriteAllText(DeviceIdFile, deviceId, new UTF8Encoding(false));
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
internal static void WriteLog(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
EnsureDirectory();
|
||||
BoundedLog.Append(LogFile, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}",
|
||||
BoundedLog.ApplicationMaxBytes);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Logging must never prevent connecting or restoring the system proxy.
|
||||
}
|
||||
}
|
||||
|
||||
internal static void WriteError(Exception exception) => WriteLog($"ERROR {exception}");
|
||||
}
|
||||
|
||||
@@ -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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
-76
@@ -1,76 +1,91 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Security;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal enum ClientRuntimeFault { Missing, Unreadable, Empty, CannotStart }
|
||||
|
||||
// An installation failure is local to every node. Never feed it into node or
|
||||
// transport health/cooldown, or retry it by changing the user's network route.
|
||||
internal sealed class ClientRuntimeException(string componentPath, ClientRuntimeFault fault, Exception? inner = null)
|
||||
: IOException(MessageFor(componentPath, fault), inner)
|
||||
{
|
||||
internal string ComponentPath { get; } = Path.GetFullPath(componentPath);
|
||||
internal ClientRuntimeFault Fault { get; } = fault;
|
||||
|
||||
private static string MessageFor(string path, ClientRuntimeFault fault)
|
||||
{
|
||||
var issue = fault switch
|
||||
{
|
||||
ClientRuntimeFault.Missing => "缺失",
|
||||
ClientRuntimeFault.Empty => "为空或已损坏",
|
||||
ClientRuntimeFault.CannotStart => "无法启动(程序文件或依赖异常)",
|
||||
_ => "无法读取(权限或文件占用)",
|
||||
};
|
||||
return $"本机客户端组件{issue}:{Path.GetFileName(path)}\n位置:{Path.GetFullPath(path)}\n\n"
|
||||
+ "请重新运行纵横家最新完整安装包,在原安装目录修复。账号和配置会保留。";
|
||||
}
|
||||
|
||||
// Only local installation identity. No token, node config or credentials.
|
||||
internal string Diagnostic => $"client_runtime fault={Fault} component={Clean(ComponentPath)}"
|
||||
+ $" process={Clean(Environment.ProcessPath ?? "unknown")} version={Clean(Application.ProductVersion)}";
|
||||
private static string Clean(string value) => value.Replace('\r', ' ').Replace('\n', ' ');
|
||||
}
|
||||
|
||||
internal static class ClientRuntime
|
||||
{
|
||||
internal static readonly string[] Components = ["xray.exe", "geoip.dat", "geosite.dat", "wintun.dll"];
|
||||
|
||||
internal static void Validate(string installationDirectory)
|
||||
{
|
||||
// Resolve exclusively beside this application, never the current
|
||||
// working directory, PATH, or an unrelated installed Xray binary.
|
||||
var directory = Path.Combine(Path.GetFullPath(installationDirectory), "xray");
|
||||
foreach (var name in Components)
|
||||
{
|
||||
var path = Path.Combine(directory, name);
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete);
|
||||
if (stream.Length == 0 || stream.ReadByte() < 0)
|
||||
throw new ClientRuntimeException(path, ClientRuntimeFault.Empty);
|
||||
}
|
||||
catch (ClientRuntimeException) { throw; }
|
||||
catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException)
|
||||
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Missing, error); }
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException or SecurityException)
|
||||
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Unreadable, error); }
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool Start(Process process)
|
||||
{
|
||||
try { return process.Start(); }
|
||||
// The executable can disappear or become blocked after preflight.
|
||||
// Classify only known local CreateProcess failures, not socket errors,
|
||||
// arbitrary IO, or remote Reality/TLS/configuration failures.
|
||||
catch (Win32Exception error) when (error.NativeErrorCode is 2 or 3 or 5 or 32 or 33 or 126 or 193 or 216 or 225 or 740)
|
||||
{
|
||||
var fault = error.NativeErrorCode is 2 or 3 ? ClientRuntimeFault.Missing
|
||||
: error.NativeErrorCode is 5 or 32 or 33 ? ClientRuntimeFault.Unreadable : ClientRuntimeFault.CannotStart;
|
||||
throw new ClientRuntimeException(process.StartInfo.FileName, fault, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal enum ClientRuntimeFault { Missing, Unreadable, Empty, CannotStart }
|
||||
|
||||
// An installation failure is local to every node. Never feed it into node or
|
||||
// transport health/cooldown, or retry it by changing the user's network route.
|
||||
internal sealed class ClientRuntimeException(string componentPath, ClientRuntimeFault fault, Exception? inner = null)
|
||||
: IOException(MessageFor(componentPath, fault), inner)
|
||||
{
|
||||
internal string ComponentPath { get; } = Path.GetFullPath(componentPath);
|
||||
internal ClientRuntimeFault Fault { get; } = fault;
|
||||
|
||||
private static string MessageFor(string path, ClientRuntimeFault fault)
|
||||
{
|
||||
var issue = fault switch
|
||||
{
|
||||
ClientRuntimeFault.Missing => "缺失",
|
||||
ClientRuntimeFault.Empty => "为空或已损坏",
|
||||
ClientRuntimeFault.CannotStart => "无法启动(程序文件或依赖异常)",
|
||||
_ => "无法读取(权限或文件占用)",
|
||||
};
|
||||
return $"本机客户端组件{issue}:{Path.GetFileName(path)}\n位置:{Path.GetFullPath(path)}\n\n"
|
||||
+ "请重新运行纵横家最新完整安装包,在原安装目录修复。账号和配置会保留。";
|
||||
}
|
||||
|
||||
// Only local installation identity. No token, node config or credentials.
|
||||
internal string Diagnostic => $"client_runtime fault={Fault} component={Clean(ComponentPath)}"
|
||||
+ $" process={Clean(Environment.ProcessPath ?? "unknown")} version={Clean(Application.ProductVersion)}";
|
||||
private static string Clean(string value) => value.Replace('\r', ' ').Replace('\n', ' ');
|
||||
}
|
||||
|
||||
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 void Validate(string installationDirectory)
|
||||
{
|
||||
// Resolve exclusively beside this application, never the current
|
||||
// working directory, PATH, or an unrelated installed Xray binary.
|
||||
var directory = Path.Combine(Path.GetFullPath(installationDirectory), "xray");
|
||||
foreach (var name in Components)
|
||||
{
|
||||
var path = Path.Combine(directory, name);
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete);
|
||||
if (stream.Length == 0 || stream.ReadByte() < 0)
|
||||
throw new ClientRuntimeException(path, ClientRuntimeFault.Empty);
|
||||
}
|
||||
catch (ClientRuntimeException) { throw; }
|
||||
catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException)
|
||||
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Missing, error); }
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException or SecurityException)
|
||||
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Unreadable, error); }
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool Start(Process process)
|
||||
{
|
||||
var changedErrorMode = SetThreadErrorMode(
|
||||
SemFailCriticalErrors | SemNoGpFaultErrorBox | SemNoOpenFileErrorBox, out var previousErrorMode);
|
||||
try { return process.Start(); }
|
||||
// The executable can disappear or become blocked after preflight.
|
||||
// Classify only known local CreateProcess failures, not socket errors,
|
||||
// arbitrary IO, or remote Reality/TLS/configuration failures.
|
||||
catch (Win32Exception error) when (error.NativeErrorCode is 2 or 3 or 5 or 32 or 33 or 126 or 193 or 216 or 225 or 740)
|
||||
{
|
||||
var fault = error.NativeErrorCode is 2 or 3 ? ClientRuntimeFault.Missing
|
||||
: error.NativeErrorCode is 5 or 32 or 33 ? ClientRuntimeFault.Unreadable : ClientRuntimeFault.CannotStart;
|
||||
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 Decision Observe(long revision, int? testedCore, int? currentCore,
|
||||
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)
|
||||
return Decision.Ignore;
|
||||
@@ -34,10 +34,18 @@ internal sealed class ConnectionHealthPolicy
|
||||
return Decision.Keep;
|
||||
}
|
||||
if (currentCore is not null && businessUnavailable && proxyHealthy) {
|
||||
Failures = 0; _nextProbe = now + 20_000;
|
||||
_nextProbe = now + 20_000;
|
||||
const Decision advisory = Decision.WebsiteUnavailable;
|
||||
var confirmed = _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;
|
||||
}
|
||||
_advisoryCandidate = null;
|
||||
|
||||
@@ -54,6 +54,9 @@ internal static class ConnectionHealthSelfTest
|
||||
== ConnectionHealthPolicy.Decision.Ignore;
|
||||
ConnectionHealthPolicy.Decision Website(long now) => policy.Observe(policy.Revision, 10, 10,
|
||||
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,
|
||||
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["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;
|
||||
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;
|
||||
policy.Invalidate();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -63,9 +63,8 @@ internal sealed partial class MainForm
|
||||
_checkingTailnetReadiness = true;
|
||||
try
|
||||
{
|
||||
if (_xray.TailnetProbeEndpoint is { } endpoint)
|
||||
reachable = await TailnetEndpointConfirmation.ProbeAsync(
|
||||
probeToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, probeToken), _lifetime.Token);
|
||||
reachable = await TailnetEndpointConfirmation.ProbeAsync(
|
||||
_xray.ProbeCurrentOrPreferredTailnetAsync, _lifetime.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; }
|
||||
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
|
||||
|
||||
+10
-4
@@ -564,19 +564,25 @@ internal sealed partial class MainForm : Form
|
||||
var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate);
|
||||
_currentNodeLabel.Text = $"{candidateName} · 正在连接";
|
||||
SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}");
|
||||
TailnetTransport.RouteBinding? tailnetBinding = null;
|
||||
connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference,
|
||||
async (config, connectionToken) => {
|
||||
candidateStarted = true;
|
||||
replacementStarted = true;
|
||||
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
|
||||
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
|
||||
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate));
|
||||
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate),
|
||||
tailnetBinding: TailnetTransport.Address(config) is null ? null : tailnetBinding);
|
||||
}, _xray.StopAsync, _xray.CheckProxyHealthAsync,
|
||||
TailnetTransport.RequireProbeRoute,
|
||||
null,
|
||||
message => { _statusDetail.Text = $"{candidateName} · {message}"; },
|
||||
() => Environment.TickCount64, connectionToken,
|
||||
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
||||
endpointProbe: async (address, port, probeToken) =>
|
||||
{
|
||||
tailnetBinding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
|
||||
return tailnetBinding is not null;
|
||||
},
|
||||
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
|
||||
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
|
||||
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
|
||||
@@ -851,7 +857,7 @@ internal sealed partial class MainForm : Form
|
||||
var healthy = health.Healthy;
|
||||
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
|
||||
_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 (healthy && _xray.IsRunning) {
|
||||
if (_displayedHealthWarning is not null) {
|
||||
|
||||
@@ -71,7 +71,7 @@ internal static class NodeTransportConnector
|
||||
// No background race or periodic optimization may replace a healthy session.
|
||||
internal static async Task<bool> ConnectAsync(ConfigResponse response, TailnetPreference preference,
|
||||
Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
|
||||
Action<string> requireRoute, Action<string> status, Func<long> ticks,
|
||||
Action<string>? requireRoute, Action<string> status, Func<long> ticks,
|
||||
CancellationToken token, bool allowKnownEndpoints = false,
|
||||
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
|
||||
Action<TransportDiagnostic>? diagnostic = null)
|
||||
@@ -83,7 +83,7 @@ internal static class NodeTransportConnector
|
||||
void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug));
|
||||
if (tailnet is null) Report("tailnet_skipped", reason);
|
||||
else Report("tailnet_candidate", reason);
|
||||
if (tailnet is not null)
|
||||
if (tailnet is not null && requireRoute is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -130,6 +130,7 @@ internal static class NodeTransportConnector
|
||||
// Plain TCP/ping, or a successful DIRECT smart request, is not proof.
|
||||
if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。");
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
Report("connection_phase", "proxy_verified_tailnet");
|
||||
Report("selected", "tailnet_verified");
|
||||
return true;
|
||||
}
|
||||
@@ -161,6 +162,7 @@ internal static class NodeTransportConnector
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (verifyPublicEgress) preference.CommitDomainFallback();
|
||||
if (verifyPublicEgress) Report("connection_phase", "proxy_verified_public");
|
||||
Report("selected", "public_ingress");
|
||||
return false;
|
||||
}
|
||||
|
||||
+184
-180
@@ -1,180 +1,184 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Net.Security;
|
||||
using System.Security.Authentication;
|
||||
using System.Text.Json;
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ProxyProbe
|
||||
{
|
||||
private const int SocksPort = 10808;
|
||||
|
||||
internal sealed record PathComparison(bool? DirectTls, bool? ProxyTls)
|
||||
{
|
||||
internal bool ShouldProxy => DirectTls == false && ProxyTls == true;
|
||||
}
|
||||
|
||||
internal static async Task<PathComparison> CompareTlsAsync(LearningObservation observation,
|
||||
int directPort, int proxyPort, CancellationToken token)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return new(null, null);
|
||||
var destination = await ResolvePublicAsync(observation, proxyPort, token);
|
||||
if (destination is null) return new(null, null); // Resolver/node failure is not direct-path failure.
|
||||
var direct = await TlsAtAsync(observation.Target, destination, directPort, 4, token);
|
||||
if (direct) return new(true, null); // Do not send business TLS over the proxy when direct works.
|
||||
var proxy = await TlsAtAsync(observation.Target, destination, proxyPort, 6, token);
|
||||
return new(false, proxy);
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeTlsAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token, int resolverProxyPort = 0)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return null;
|
||||
var destination = await ResolvePublicAsync(observation, resolverProxyPort > 0 ? resolverProxyPort : forcedProxyPort, token);
|
||||
return destination is not null && await TlsAtAsync(observation.Target, destination, forcedProxyPort, 6, token);
|
||||
}
|
||||
|
||||
private static async Task<IPAddress?> ResolvePublicAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
IPAddress? destination;
|
||||
if (observation.TargetType == "ip") destination = IPAddress.Parse(observation.Target);
|
||||
else
|
||||
{
|
||||
// Resolve through the already authorized node, not local poisoned DNS.
|
||||
// Pin the returned public IP into SOCKS CONNECT; TLS still verifies the
|
||||
// original hostname. No arbitrary HTTP URL, redirect or request replay.
|
||||
using var http = new HttpClient(new SocketsHttpHandler { UseProxy = true,
|
||||
Proxy = new WebProxy($"socks5://127.0.0.1:{forcedProxyPort}"), AllowAutoRedirect = false,
|
||||
ConnectTimeout = TimeSpan.FromSeconds(4) }) { MaxResponseContentBufferSize = 32768 };
|
||||
var body = await http.GetStringAsync("https://8.8.8.8/resolve?type=A&name=" + Uri.EscapeDataString(observation.Target), timeout.Token);
|
||||
using var dns = JsonDocument.Parse(body);
|
||||
if (!dns.RootElement.TryGetProperty("Answer", out var answers)) return null;
|
||||
var ips = answers.EnumerateArray().Where(a => a.TryGetProperty("type", out var type) && type.GetInt32() == 1)
|
||||
.Select(a => IPAddress.TryParse(a.GetProperty("data").GetString(), out var ip) ? ip : null).ToArray();
|
||||
if (ips.Length == 0 || ips.Any(ip => ip is null || !LearningPolicy.PublicIp(ip))) return null;
|
||||
destination = ips[0];
|
||||
}
|
||||
return destination is not null && LearningPolicy.PublicIp(destination) ? destination : null;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return null; }
|
||||
}
|
||||
|
||||
internal static async Task<bool> TlsAtAsync(string target, IPAddress destination, int socksPort, int seconds, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(seconds));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, socksPort, timeout.Token);
|
||||
var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 5, 1, 0 }, timeout.Token);
|
||||
var greeting = new byte[2]; await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 5 || greeting[1] != 0) return false;
|
||||
await stream.WriteAsync(BuildConnectRequest("ip", destination.ToString(), 443), timeout.Token);
|
||||
var header = new byte[4]; await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 5 || header[1] != 0) return false;
|
||||
var length = header[3] switch { 1 => 4, 4 => 16, 3 => await ReadDomainLengthAsync(stream, timeout.Token), _ => 0 };
|
||||
if (length < 1) return false;
|
||||
await stream.ReadExactlyAsync(new byte[length + 2], timeout.Token);
|
||||
using var tls = new SslStream(stream, false); // Default platform certificate validation, no bypass.
|
||||
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = target }, timeout.Token);
|
||||
return tls.IsAuthenticated && tls.IsEncrypted;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return false; }
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeAsync(
|
||||
LearningObservation observation,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.Equals(observation.Network, "tcp", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, SocksPort, timeout.Token);
|
||||
await using var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 0x05, 0x01, 0x00 }, timeout.Token);
|
||||
var greeting = new byte[2];
|
||||
await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 0x05 || greeting[1] != 0x00) return false;
|
||||
|
||||
var request = BuildConnectRequest(observation.TargetType, observation.Target, observation.Port);
|
||||
await stream.WriteAsync(request, timeout.Token);
|
||||
var header = new byte[4];
|
||||
await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 0x05 || header[1] != 0x00) return false;
|
||||
var addressLength = header[3] switch
|
||||
{
|
||||
0x01 => 4,
|
||||
0x04 => 16,
|
||||
0x03 => await ReadDomainLengthAsync(stream, timeout.Token),
|
||||
_ => 0,
|
||||
};
|
||||
if (addressLength <= 0) return false;
|
||||
var remainder = new byte[addressLength + 2];
|
||||
await stream.ReadExactlyAsync(remainder, timeout.Token);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ArgumentException)
|
||||
{
|
||||
AppPaths.WriteLog($"vpn-ai 代理复测失败:{observation.Target}:{observation.Port} {exception.GetBaseException().Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
var domain = BuildConnectRequest("domain", "example.com", 443);
|
||||
var ipv4 = BuildConnectRequest("ip", "203.0.113.10", 8443);
|
||||
var ipv6 = BuildConnectRequest("ip", "2001:db8::10", 443);
|
||||
return domain[3] == 0x03
|
||||
&& domain[4] == "example.com".Length
|
||||
&& domain[^2] == 0x01 && domain[^1] == 0xbb
|
||||
&& ipv4[3] == 0x01 && ipv4.Length == 10
|
||||
&& ipv6[3] == 0x04 && ipv6.Length == 22;
|
||||
}
|
||||
|
||||
private static byte[] BuildConnectRequest(string targetType, string target, int port)
|
||||
{
|
||||
if (port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(port));
|
||||
var request = new List<byte> { 0x05, 0x01, 0x00 };
|
||||
if (string.Equals(targetType, "ip", StringComparison.OrdinalIgnoreCase)
|
||||
&& IPAddress.TryParse(target.Trim('[', ']'), out var address))
|
||||
{
|
||||
request.Add(address.AddressFamily == AddressFamily.InterNetwork ? (byte)0x01 : (byte)0x04);
|
||||
request.AddRange(address.GetAddressBytes());
|
||||
}
|
||||
else
|
||||
{
|
||||
var ascii = new IdnMapping().GetAscii(target.Trim().TrimEnd('.'));
|
||||
var bytes = Encoding.ASCII.GetBytes(ascii);
|
||||
if (bytes.Length is < 1 or > 255) throw new ArgumentException("域名长度无效", nameof(target));
|
||||
request.Add(0x03);
|
||||
request.Add((byte)bytes.Length);
|
||||
request.AddRange(bytes);
|
||||
}
|
||||
request.Add((byte)(port >> 8));
|
||||
request.Add((byte)(port & 0xff));
|
||||
return request.ToArray();
|
||||
}
|
||||
|
||||
private static async Task<int> ReadDomainLengthAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var length = new byte[1];
|
||||
await stream.ReadExactlyAsync(length, cancellationToken);
|
||||
return length[0];
|
||||
}
|
||||
}
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Net.Security;
|
||||
using System.Security.Authentication;
|
||||
using System.Text.Json;
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ProxyProbe
|
||||
{
|
||||
private const int SocksPort = 10808;
|
||||
|
||||
internal sealed record PathComparison(bool? DirectTls, bool? ProxyTls)
|
||||
{
|
||||
internal bool ShouldProxy => DirectTls == false && ProxyTls == true;
|
||||
}
|
||||
|
||||
internal static async Task<PathComparison> CompareTlsAsync(LearningObservation observation,
|
||||
int directPort, int proxyPort, CancellationToken token)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return new(null, null);
|
||||
var destination = await ResolvePublicAsync(observation, proxyPort, token);
|
||||
if (destination is null) return new(null, null); // Resolver/node failure is not direct-path failure.
|
||||
var direct = await TlsAtAsync(observation.Target, destination, directPort, 4, token);
|
||||
if (direct) return new(true, null); // Do not send business TLS over the proxy when direct works.
|
||||
var proxy = await TlsAtAsync(observation.Target, destination, proxyPort, 6, token);
|
||||
return new(false, proxy);
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeTlsAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token, int resolverProxyPort = 0)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return null;
|
||||
var destination = await ResolvePublicAsync(observation, resolverProxyPort > 0 ? resolverProxyPort : forcedProxyPort, token);
|
||||
return destination is not null && await TlsAtAsync(observation.Target, destination, forcedProxyPort, 6, token);
|
||||
}
|
||||
|
||||
private static async Task<IPAddress?> ResolvePublicAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
IPAddress? destination;
|
||||
if (observation.TargetType == "ip") destination = IPAddress.Parse(observation.Target);
|
||||
else
|
||||
{
|
||||
// Resolve through the already authorized node, not local poisoned DNS.
|
||||
// Pin the returned public IP into SOCKS CONNECT; TLS still verifies the
|
||||
// original hostname. No arbitrary HTTP URL, redirect or request replay.
|
||||
using var http = new HttpClient(new SocketsHttpHandler { UseProxy = true,
|
||||
Proxy = new WebProxy($"socks5://127.0.0.1:{forcedProxyPort}"), AllowAutoRedirect = false,
|
||||
ConnectTimeout = TimeSpan.FromSeconds(4) }) { MaxResponseContentBufferSize = 32768 };
|
||||
var body = await http.GetStringAsync("https://8.8.8.8/resolve?type=A&name=" + Uri.EscapeDataString(observation.Target), timeout.Token);
|
||||
using var dns = JsonDocument.Parse(body);
|
||||
if (!dns.RootElement.TryGetProperty("Answer", out var answers)) return null;
|
||||
var ips = answers.EnumerateArray().Where(a => a.TryGetProperty("type", out var type) && type.GetInt32() == 1)
|
||||
.Select(a => IPAddress.TryParse(a.GetProperty("data").GetString(), out var ip) ? ip : null).ToArray();
|
||||
if (ips.Length == 0 || ips.Any(ip => ip is null || !LearningPolicy.PublicIp(ip))) return null;
|
||||
destination = ips[0];
|
||||
}
|
||||
return destination is not null && LearningPolicy.PublicIp(destination) ? destination : null;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return null; }
|
||||
}
|
||||
|
||||
internal static async Task<bool> TlsAtAsync(string target, IPAddress destination, int socksPort, int seconds, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(seconds));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, socksPort, timeout.Token);
|
||||
var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 5, 1, 0 }, timeout.Token);
|
||||
var greeting = new byte[2]; await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 5 || greeting[1] != 0) return false;
|
||||
await stream.WriteAsync(BuildConnectRequest("ip", destination.ToString(), 443), timeout.Token);
|
||||
var header = new byte[4]; await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 5 || header[1] != 0) return false;
|
||||
var length = header[3] switch { 1 => 4, 4 => 16, 3 => await ReadDomainLengthAsync(stream, timeout.Token), _ => 0 };
|
||||
if (length < 1) return false;
|
||||
await stream.ReadExactlyAsync(new byte[length + 2], timeout.Token);
|
||||
using var tls = new SslStream(stream, false); // Default platform certificate validation, no bypass.
|
||||
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = target }, timeout.Token);
|
||||
return tls.IsAuthenticated && tls.IsEncrypted;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return false; }
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeAsync(
|
||||
LearningObservation observation,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.Equals(observation.Network, "tcp", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, SocksPort, timeout.Token);
|
||||
await using var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 0x05, 0x01, 0x00 }, timeout.Token);
|
||||
var greeting = new byte[2];
|
||||
await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 0x05 || greeting[1] != 0x00) return false;
|
||||
|
||||
var request = BuildConnectRequest(observation.TargetType, observation.Target, observation.Port);
|
||||
await stream.WriteAsync(request, timeout.Token);
|
||||
var header = new byte[4];
|
||||
await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 0x05 || header[1] != 0x00) return false;
|
||||
var addressLength = header[3] switch
|
||||
{
|
||||
0x01 => 4,
|
||||
0x04 => 16,
|
||||
0x03 => await ReadDomainLengthAsync(stream, timeout.Token),
|
||||
_ => 0,
|
||||
};
|
||||
if (addressLength <= 0) return false;
|
||||
var remainder = new byte[addressLength + 2];
|
||||
await stream.ReadExactlyAsync(remainder, timeout.Token);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ArgumentException)
|
||||
{
|
||||
AppPaths.WriteLog(BuildFailureLog(exception));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal static string BuildFailureLog(Exception exception) =>
|
||||
$"vpn-ai 代理复测失败;error={exception.GetBaseException().GetType().Name}";
|
||||
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
var domain = BuildConnectRequest("domain", "example.com", 443);
|
||||
var ipv4 = BuildConnectRequest("ip", "203.0.113.10", 8443);
|
||||
var ipv6 = BuildConnectRequest("ip", "2001:db8::10", 443);
|
||||
return domain[3] == 0x03
|
||||
&& domain[4] == "example.com".Length
|
||||
&& domain[^2] == 0x01 && domain[^1] == 0xbb
|
||||
&& ipv4[3] == 0x01 && ipv4.Length == 10
|
||||
&& ipv6[3] == 0x04 && ipv6.Length == 22
|
||||
&& BoundedLogSelfTest.Run();
|
||||
}
|
||||
|
||||
private static byte[] BuildConnectRequest(string targetType, string target, int port)
|
||||
{
|
||||
if (port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(port));
|
||||
var request = new List<byte> { 0x05, 0x01, 0x00 };
|
||||
if (string.Equals(targetType, "ip", StringComparison.OrdinalIgnoreCase)
|
||||
&& IPAddress.TryParse(target.Trim('[', ']'), out var address))
|
||||
{
|
||||
request.Add(address.AddressFamily == AddressFamily.InterNetwork ? (byte)0x01 : (byte)0x04);
|
||||
request.AddRange(address.GetAddressBytes());
|
||||
}
|
||||
else
|
||||
{
|
||||
var ascii = new IdnMapping().GetAscii(target.Trim().TrimEnd('.'));
|
||||
var bytes = Encoding.ASCII.GetBytes(ascii);
|
||||
if (bytes.Length is < 1 or > 255) throw new ArgumentException("域名长度无效", nameof(target));
|
||||
request.Add(0x03);
|
||||
request.Add((byte)bytes.Length);
|
||||
request.AddRange(bytes);
|
||||
}
|
||||
request.Add((byte)(port >> 8));
|
||||
request.Add((byte)(port & 0xff));
|
||||
return request.ToArray();
|
||||
}
|
||||
|
||||
private static async Task<int> ReadDomainLengthAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var length = new byte[1];
|
||||
await stream.ReadExactlyAsync(length, cancellationToken);
|
||||
return length[0];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,21 @@
|
||||
# 优创⁺纵横家 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
|
||||
|
||||
宽屏和紧凑窗口采用同一阅读顺序。左侧设置调度与代理模式,右侧显示生效的节点和模式。本机上传与下载趋势默认同屏,下方显示有权限查看的服务器走势。累计用量使用一条数字栏。登录后的窗口按钮收起到系统托盘,托盘图标提供恢复和退出。
|
||||
|
||||
@@ -1,80 +1,109 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.AccessControl;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Only synthetic TEMP data; calls the actual production replacement method.
|
||||
internal static class ReplacementContinuitySelfTest
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern uint GetFileAttributesW(string path);
|
||||
|
||||
internal static void Run(string root, Dictionary<string, bool> checks)
|
||||
{
|
||||
var dir = Path.Combine(root, "concurrent-replacement");
|
||||
Directory.CreateDirectory(dir);
|
||||
var first = Path.Combine(dir, "first.bin");
|
||||
var second = Path.Combine(dir, "second.bin");
|
||||
var target = Path.Combine(dir, "main.bin");
|
||||
File.WriteAllBytes(first, Enumerable.Repeat((byte)0x35, 4096).ToArray());
|
||||
File.WriteAllBytes(second, Enumerable.Repeat((byte)0x71, 4096).ToArray());
|
||||
File.Copy(first, target);
|
||||
var acl = new FileInfo(target).GetAccessControl();
|
||||
acl.SetAccessRuleProtection(true, true);
|
||||
new FileInfo(target).SetAccessControl(acl);
|
||||
const AccessControlSections sections = AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group;
|
||||
var oldSecurity = new FileInfo(target).GetAccessControl(sections).GetSecurityDescriptorSddlForm(sections);
|
||||
var errors = new Dictionary<string, int>();
|
||||
var observations = 0L;
|
||||
var completed = 0;
|
||||
var stop = 0;
|
||||
using var ready = new ManualResetEventSlim();
|
||||
var observer = new Thread(() => {
|
||||
ready.Set();
|
||||
while (Volatile.Read(ref stop) == 0)
|
||||
{
|
||||
if (GetFileAttributesW(target) == uint.MaxValue)
|
||||
{
|
||||
var error = Marshal.GetLastWin32Error().ToString();
|
||||
errors[error] = errors.GetValueOrDefault(error) + 1;
|
||||
}
|
||||
observations++;
|
||||
}
|
||||
});
|
||||
observer.Start(); ready.Wait();
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
var source = (i % 2 == 0) ? second : first;
|
||||
InstallationTransaction.Replace(source, target);
|
||||
if (!File.ReadAllBytes(source).SequenceEqual(File.ReadAllBytes(target)))
|
||||
throw new IOException("Replacement bytes do not match");
|
||||
completed++;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref stop, 1); observer.Join();
|
||||
File.WriteAllText(Path.Combine(root, "replacement-observations.json"), JsonSerializer.Serialize(
|
||||
new { Completed = completed, Observations = observations, Win32Errors = errors }));
|
||||
}
|
||||
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("replacement_keeps_owner_group_and_protected_dacl", new FileInfo(target).GetAccessControl(sections)
|
||||
.GetSecurityDescriptorSddlForm(sections) == oldSecurity);
|
||||
var before = InstallationTransaction.Digest(target);
|
||||
var refused = false;
|
||||
using (var held = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
try { InstallationTransaction.Replace(second, target); }
|
||||
catch (IOException) { refused = true; }
|
||||
}
|
||||
Check("locked_replacement_preserves_exact_original", refused && InstallationTransaction.Digest(target) == before);
|
||||
Check("replacement_removes_only_own_staging_files", Directory.GetFiles(dir, "*.update-*.tmp").Length == 0);
|
||||
var fresh = Path.Combine(dir, "new.bin");
|
||||
InstallationTransaction.Replace(second, fresh);
|
||||
Check("replacement_new_file_matches_source", InstallationTransaction.Digest(second) == InstallationTransaction.Digest(fresh));
|
||||
}
|
||||
}
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Only synthetic TEMP data; calls the actual production replacement method.
|
||||
internal static class ReplacementContinuitySelfTest
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
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)
|
||||
{
|
||||
var dir = Path.Combine(root, "concurrent-replacement");
|
||||
Directory.CreateDirectory(dir);
|
||||
var first = Path.Combine(dir, "first.bin");
|
||||
var second = Path.Combine(dir, "second.bin");
|
||||
var target = Path.Combine(dir, "main.bin");
|
||||
File.WriteAllBytes(first, Enumerable.Repeat((byte)0x35, 4096).ToArray());
|
||||
File.WriteAllBytes(second, Enumerable.Repeat((byte)0x71, 4096).ToArray());
|
||||
File.Copy(first, target);
|
||||
var acl = new FileInfo(target).GetAccessControl();
|
||||
acl.SetAccessRuleProtection(true, true);
|
||||
new FileInfo(target).SetAccessControl(acl);
|
||||
var oldSecurity = Snapshot(target);
|
||||
var errors = new Dictionary<string, int>();
|
||||
var observations = 0L;
|
||||
var completed = 0;
|
||||
var stop = 0;
|
||||
using var ready = new ManualResetEventSlim();
|
||||
var observer = new Thread(() => {
|
||||
ready.Set();
|
||||
while (Volatile.Read(ref stop) == 0)
|
||||
{
|
||||
if (GetFileAttributesW(target) == uint.MaxValue)
|
||||
{
|
||||
var error = Marshal.GetLastWin32Error().ToString();
|
||||
errors[error] = errors.GetValueOrDefault(error) + 1;
|
||||
}
|
||||
observations++;
|
||||
}
|
||||
});
|
||||
observer.Start(); ready.Wait();
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
var source = (i % 2 == 0) ? second : first;
|
||||
InstallationTransaction.Replace(source, target);
|
||||
if (!File.ReadAllBytes(source).SequenceEqual(File.ReadAllBytes(target)))
|
||||
throw new IOException("Replacement bytes do not match");
|
||||
completed++;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref stop, 1); observer.Join();
|
||||
File.WriteAllText(Path.Combine(root, "replacement-observations.json"), JsonSerializer.Serialize(
|
||||
new { Completed = completed, Observations = observations, Win32Errors = errors }));
|
||||
}
|
||||
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("replacement_keeps_owner_group_and_protected_dacl", SameSecurity(oldSecurity, Snapshot(target)));
|
||||
var before = InstallationTransaction.Digest(target);
|
||||
var refused = false;
|
||||
using (var held = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
try { InstallationTransaction.Replace(second, target); }
|
||||
catch (IOException) { refused = true; }
|
||||
}
|
||||
Check("locked_replacement_preserves_exact_original", refused && InstallationTransaction.Digest(target) == before);
|
||||
Check("replacement_removes_only_own_staging_files", Directory.GetFiles(dir, "*.update-*.tmp").Length == 0);
|
||||
var fresh = Path.Combine(dir, "new.bin");
|
||||
InstallationTransaction.Replace(second, fresh);
|
||||
Check("replacement_new_file_matches_source", InstallationTransaction.Digest(second) == InstallationTransaction.Digest(fresh));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,9 +44,23 @@ internal static class RouteLeaseSelfTest
|
||||
24, gateway, [gateway]);
|
||||
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);
|
||||
string[] derpAddresses = ["8.216.53.107", "47.254.94.29", "192.236.188.22"];
|
||||
var derpRoutes = derpAddresses.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);
|
||||
const string currentAndFutureDerpMap = """
|
||||
{"Regions":{"902":{"RegionID":902,"RegionCode":"qingdao","Nodes":[
|
||||
{"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 privateRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse("172.16.0.111")], 20, preserveProxyRoute: true);
|
||||
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"] =
|
||||
protectedRoutes.All(r => r.Destination != tailnet.Destination)
|
||||
&& privateRoutes.All(r => r.Destination != "172.16.0.111");
|
||||
report["tailscale_derp_uses_physical_host_routes_before_tun_defaults"] =
|
||||
derpRoutes.All(derp => protectedRoutes.SkipLast(2).Count(derp.SamePath) == 1)
|
||||
report["tailscale_derp_uses_current_map_before_tun_defaults"] =
|
||||
discoveredDerpAddresses.All(address => protectedRoutes.SkipLast(2).Any(route => route.Destination == address.ToString()))
|
||||
&& 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"] =
|
||||
derpRoutes.All(derp => !privateRoutes.Any(derp.SamePath) && !publicRoutes.Any(derp.SamePath));
|
||||
var preexisting = new[] { tailnet, management, derpRoutes[0] };
|
||||
discoveredDerpAddresses.All(address => !privateRoutes.Any(route => route.Destination == address.ToString()
|
||||
&& route.Destination != management.Destination));
|
||||
var preexisting = new[] { tailnet, management };
|
||||
table.Routes.AddRange(preexisting);
|
||||
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);
|
||||
report["existing_management_tailnet_and_derp_paths_survive_cleanup"] =
|
||||
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"),
|
||||
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);
|
||||
report["tailscale_derp_routes_rebind_to_new_physical_uplink"] =
|
||||
derpRoutes.All(old => !table.Routes.Any(old.SamePath)
|
||||
&& table.Routes.Any((old with { InterfaceIndex = 11, NextHop = "172.20.1.1" }).SamePath));
|
||||
discoveredDerpAddresses.All(address => table.Routes.Any(route => route.Destination == address.ToString()
|
||||
&& route.InterfaceIndex == 11 && route.NextHop == "172.20.1.1"));
|
||||
await lease.RestoreAsync(CancellationToken.None);
|
||||
report["derp_rebind_cleanup_preserves_original_routes"] = table.Routes.SequenceEqual([tailnet, management]) && !File.Exists(path);
|
||||
table.Routes.Clear();
|
||||
|
||||
@@ -1,38 +1,67 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class StartupLearningWarmup
|
||||
{
|
||||
// The readiness callback starts only transport proof. The setup owner keeps
|
||||
// its lifecycle lock until DNS/network setup succeeds; rule commits wait on
|
||||
// that existing lock. Setup time never spends the post-setup learning budget.
|
||||
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
|
||||
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
using var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
|
||||
CancellationTokenSource? learning = null;
|
||||
Task? work = null;
|
||||
try
|
||||
{
|
||||
await setup(epoch => {
|
||||
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
|
||||
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
|
||||
learning.Token.ThrowIfCancellationRequested();
|
||||
work = learn(learning.Token);
|
||||
});
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (work is null) return;
|
||||
budget.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
await work;
|
||||
token.ThrowIfCancellationRequested();
|
||||
}
|
||||
finally
|
||||
{
|
||||
// A failed setup must leave no outstanding proof/commit task. Drain
|
||||
// cancellation without replacing the original setup/learning error.
|
||||
learning?.Cancel();
|
||||
if (work is not null) try { await work; } catch { }
|
||||
learning?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class StartupLearningWarmup
|
||||
{
|
||||
// The readiness callback starts only transport learning. The setup owner
|
||||
// keeps its lifecycle lock until DNS/network setup succeeds; rule commits
|
||||
// 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,
|
||||
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null,
|
||||
Action<Exception?>? onBackgroundCompleted = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
|
||||
CancellationTokenSource? learning = null;
|
||||
Task? work = null;
|
||||
try
|
||||
{
|
||||
await setup(epoch => {
|
||||
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
|
||||
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
|
||||
learning.Token.ThrowIfCancellationRequested();
|
||||
work = learn(learning.Token)
|
||||
?? throw new InvalidOperationException("Startup learning did not return a task.");
|
||||
});
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (work is null)
|
||||
{
|
||||
learning?.Dispose();
|
||||
budget.Dispose();
|
||||
return;
|
||||
}
|
||||
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
|
||||
// cancellation without replacing the original setup/learning error.
|
||||
learning?.Cancel();
|
||||
if (work is not null) try { await work; } catch { }
|
||||
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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+76
-15
@@ -100,9 +100,40 @@ internal static class TailnetTransport
|
||||
|
||||
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
|
||||
|
||||
// Check the authorized proxy port through the existing OS route. Proxy
|
||||
// authentication and egress are verified separately after startup.
|
||||
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
|
||||
internal sealed record RouteBinding(string InterfaceName, int InterfaceIndex, IPAddress LocalAddress, IPAddress? Gateway = null);
|
||||
|
||||
// A company router can forward the authorized address over its Tailscale even
|
||||
// when Windows has only a default route. Bind the probe to the chosen interface.
|
||||
// A TCP response only permits trying the node; the normal proxy proof still runs.
|
||||
internal static async Task<RouteBinding?> ProbeAuthorizedRouteAsync(string address, int port, CancellationToken token,
|
||||
Func<string, RouteBinding>? readSpecificRoute = null,
|
||||
Func<PhysicalUplink.Reading>? readUplink = null,
|
||||
Func<string, int, RouteBinding, CancellationToken, Task<bool>>? probe = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return null;
|
||||
RouteBinding? binding;
|
||||
try { binding = readSpecificRoute is null ? ResolveRoute(address, true) : readSpecificRoute(address); }
|
||||
catch (Exception error) when (IsRouteUnavailable(error))
|
||||
{
|
||||
var uplink = readUplink is null ? PhysicalUplink.Read() : readUplink();
|
||||
binding = uplink.Success ? GatewayBinding(uplink.Network) : null;
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (binding is null) return null;
|
||||
var reachable = await (probe ?? ProbeBoundEndpointAsync)(address, port, binding, token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
return reachable ? binding : null;
|
||||
}
|
||||
|
||||
private static RouteBinding? GatewayBinding(TunRouting.PhysicalNetwork? network)
|
||||
{
|
||||
if (network is null || network.InterfaceIndex <= 0 || network.Ipv4Gateway.Equals(IPAddress.Any)
|
||||
|| IsTailnetAddress(network.Ipv4Address.ToString())) return null;
|
||||
return new(network.InterfaceName, network.InterfaceIndex, network.Ipv4Address, network.Ipv4Gateway);
|
||||
}
|
||||
|
||||
internal static async Task<bool> ProbeBoundEndpointAsync(string address, int port, RouteBinding binding, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
|
||||
@@ -110,16 +141,47 @@ internal static class TailnetTransport
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds));
|
||||
try
|
||||
{
|
||||
RequireProbeRoute(address);
|
||||
// The first connection may need to establish a Tailscale path.
|
||||
// Test the actual proxy listener instead of gating on ICMP.
|
||||
using var socket = new TcpClient(AddressFamily.InterNetwork);
|
||||
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
// Winsock IP_UNICAST_IF expects the IPv4 interface index in network byte order.
|
||||
const SocketOptionName ipUnicastInterface = (SocketOptionName)31;
|
||||
socket.SetSocketOption(SocketOptionLevel.IP, ipUnicastInterface, IPAddress.HostToNetworkOrder(binding.InterfaceIndex));
|
||||
socket.Bind(new IPEndPoint(binding.LocalAddress, 0));
|
||||
await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
|
||||
catch (Exception e) when (e is SocketException or NetworkInformationException
|
||||
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception) { return false; }
|
||||
catch (Exception error) when (IsRouteUnavailable(error)) { return false; }
|
||||
}
|
||||
|
||||
private static bool IsRouteUnavailable(Exception error) => error is SocketException or NetworkInformationException
|
||||
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception;
|
||||
|
||||
internal static RouteBinding RequireCurrentBinding(string address, RouteBinding? binding, TunRouting.PhysicalNetwork physicalNetwork)
|
||||
{
|
||||
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
|
||||
if (binding?.Gateway is not null)
|
||||
{
|
||||
var uplink = PhysicalUplink.Read(binding.InterfaceIndex);
|
||||
if (!uplink.Success || GatewayBinding(uplink.Network) != binding || GatewayBinding(physicalNetwork) != binding)
|
||||
throw new InvalidOperationException("公司网关路径已变化,请重新检测内网入口。");
|
||||
return binding;
|
||||
}
|
||||
var current = ResolveRoute(address, true);
|
||||
if (binding is not null && current != binding)
|
||||
throw new InvalidOperationException("Tailscale 路由已变化,请重新检测内网入口。");
|
||||
return current;
|
||||
}
|
||||
|
||||
// Strict native-route detection for private-node policy and the standalone probe.
|
||||
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
|
||||
try
|
||||
{
|
||||
return await ProbeBoundEndpointAsync(address, port, ResolveRoute(address, true), token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception error) when (IsRouteUnavailable(error)) { return false; }
|
||||
}
|
||||
|
||||
internal static bool SameAuthorizedFallback(string current, string? fallback)
|
||||
@@ -144,13 +206,13 @@ internal static class TailnetTransport
|
||||
// default route. No adapter-name, service or route-prefix prerequisite.
|
||||
// This UDP Connect sends no payload. Refuse our own TUN to avoid recursion;
|
||||
// no /32 or user route is manufactured or removed.
|
||||
internal static string RequireExistingRoute(string address) => ResolveRoute(address, false);
|
||||
internal static string RequireExistingRoute(string address) => ResolveRoute(address, false).InterfaceName;
|
||||
|
||||
// Candidate discovery requires a specific existing route to the authorized
|
||||
// Tailnet address. A generic internet default must not carry probe packets.
|
||||
internal static void RequireProbeRoute(string address) => ResolveRoute(address, true);
|
||||
|
||||
private static string ResolveRoute(string address, bool requireSpecificRoute)
|
||||
private static RouteBinding ResolveRoute(string address, bool requireSpecificRoute)
|
||||
{
|
||||
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
|
||||
using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
@@ -160,12 +222,11 @@ internal static class TailnetTransport
|
||||
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback
|
||||
&& !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
|
||||
.FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local)));
|
||||
if (owner is null)
|
||||
if (local is null || owner?.GetIPProperties().GetIPv4Properties()?.Index is not { } index)
|
||||
throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。");
|
||||
if (requireSpecificRoute && (owner.GetIPProperties().GetIPv4Properties()?.Index is not { } index
|
||||
|| SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index))
|
||||
if (requireSpecificRoute && SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index)
|
||||
throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。");
|
||||
return owner.Name;
|
||||
return new(owner.Name, index, local);
|
||||
}
|
||||
|
||||
internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
@@ -74,6 +75,42 @@ internal static class TailnetTransportSelfTest
|
||||
checks["ambiguous_interface_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,route with {InterfaceIndex=9}],usable) is null;
|
||||
checks["noncontiguous_mask_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Mask="255.0.255.0"}],usable) is null;
|
||||
checks["unrelated_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Destination="172.16.0.0",Mask="255.255.0.0"}],usable) is null;
|
||||
const string target = "100.99.142.38";
|
||||
const int targetPort = 10803;
|
||||
var native = new TailnetTransport.RouteBinding("Tailscale", 34, IPAddress.Parse("100.65.4.8"));
|
||||
var office = new TunRouting.PhysicalNetwork("Ethernet", 9, IPAddress.Parse("172.16.1.154"),
|
||||
24, IPAddress.Parse("172.16.1.1"), [IPAddress.Parse("172.16.1.1")]);
|
||||
var gateway = new TailnetTransport.RouteBinding(office.InterfaceName, office.InterfaceIndex,
|
||||
office.Ipv4Address, office.Ipv4Gateway);
|
||||
TailnetTransport.RouteBinding NoSpecificRoute(string _) => throw new InvalidOperationException();
|
||||
PhysicalUplink.Reading OfficeUplink() => new(true, office);
|
||||
var testedBindings = new List<TailnetTransport.RouteBinding>();
|
||||
Task<bool> Reachable(string address, int port, TailnetTransport.RouteBinding binding, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
testedBindings.Add(binding);
|
||||
return Task.FromResult(address == target && port == targetPort);
|
||||
}
|
||||
checks["native_route_precedes_gateway"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
|
||||
CancellationToken.None, _ => native, () => throw new InvalidOperationException("Unused uplink"), Reachable) == native
|
||||
&& testedBindings.SequenceEqual([native]);
|
||||
testedBindings.Clear();
|
||||
checks["company_gateway_requires_authorized_port_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
|
||||
CancellationToken.None, NoSpecificRoute, OfficeUplink, Reachable) == gateway
|
||||
&& testedBindings.SequenceEqual([gateway]);
|
||||
checks["unreachable_company_gateway_falls_back"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
|
||||
CancellationToken.None, NoSpecificRoute, OfficeUplink, (_, _, _, _) => Task.FromResult(false)) is null;
|
||||
checks["no_gateway_no_unbound_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
|
||||
CancellationToken.None, NoSpecificRoute, () => new(true, office with { Ipv4Gateway = IPAddress.Any }),
|
||||
(_, _, _, _) => throw new InvalidOperationException("Unbound probe")) is null;
|
||||
checks["non_tailnet_address_never_probed"] = await TailnetTransport.ProbeAuthorizedRouteAsync("198.51.100.20", targetPort,
|
||||
CancellationToken.None, _ => throw new InvalidOperationException("Unexpected route lookup"), OfficeUplink, Reachable) is null;
|
||||
|
||||
var routerRuntime = JsonNode.Parse(TunConfigBuilder.Build(prepared, office.InterfaceName, false, includeTun: false,
|
||||
tailnetInterfaceName: gateway.InterfaceName))!.AsObject();
|
||||
checks["router_runtime_binds_only_chosen_physical_interface"] =
|
||||
routerRuntime["outbounds"]![0]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue<string>() == office.InterfaceName
|
||||
&& Host(prepared) == target;
|
||||
|
||||
var preference = new TailnetPreference();
|
||||
long tick = 100;
|
||||
|
||||
+11
-9
@@ -13,9 +13,6 @@ internal static class TunRouting
|
||||
{
|
||||
internal const string AdapterName = "UCVL VPNPlus";
|
||||
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(
|
||||
string InterfaceName,
|
||||
int InterfaceIndex,
|
||||
@@ -112,7 +109,8 @@ internal static class TunRouting
|
||||
IReadOnlyCollection<IPAddress> proxyServerAddresses,
|
||||
CancellationToken cancellationToken,
|
||||
bool preservePrivateNodeRoute = false,
|
||||
string? preserveTailnetAddress = null)
|
||||
string? preserveTailnetAddress = null,
|
||||
TailnetTransport.RouteBinding? tailnetBinding = null)
|
||||
{
|
||||
if (!IsElevated()) throw new InvalidOperationException("TUN 全电脑代理需要管理员权限,请以管理员身份重新启动优创⁺纵横家。");
|
||||
var proxyIpv4Addresses = proxyServerAddresses
|
||||
@@ -134,7 +132,6 @@ internal static class TunRouting
|
||||
if (preservePrivateNodeRoute || proxyIpv4Addresses.Count != 1
|
||||
|| proxyIpv4Addresses[0].ToString() != preserveTailnetAddress)
|
||||
throw new InvalidOperationException("Tailscale 节点旁路目标不匹配。");
|
||||
TailnetTransport.RequireExistingRoute(preserveTailnetAddress);
|
||||
}
|
||||
var tunDnsServer = physicalNetwork.Ipv4DnsServers.FirstOrDefault();
|
||||
if (tunDnsServer is null)
|
||||
@@ -153,10 +150,14 @@ internal static class TunRouting
|
||||
if (preservePrivateNodeRoute || preserveTailnetAddress is not null)
|
||||
{
|
||||
if (preservePrivateNodeRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString());
|
||||
if (preserveTailnetAddress is not null) TailnetTransport.RequireExistingRoute(preserveTailnetAddress);
|
||||
if (preserveTailnetAddress is not null)
|
||||
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,
|
||||
preservePrivateNodeRoute || preserveTailnetAddress is not null);
|
||||
preservePrivateNodeRoute || preserveTailnetAddress is not null, derpAddresses);
|
||||
// The journal records additions before applying them and skips exact
|
||||
// pre-existing routes. The user's LAN and Tailnet routes stay in place.
|
||||
await new NetworkRouteLease(AppPaths.TunStateFile, new WindowsRouteTable()).ApplyAsync(routes, cancellationToken);
|
||||
@@ -166,14 +167,15 @@ internal static class TunRouting
|
||||
}
|
||||
|
||||
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);
|
||||
if (!preserveProxyRoute) bypassAddresses = proxyIpv4Addresses.Concat(bypassAddresses);
|
||||
// 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.
|
||||
if (preserveProxyRoute && proxyIpv4Addresses.Any(address => TailnetTransport.IsTailnetAddress(address.ToString())))
|
||||
bypassAddresses = bypassAddresses.Concat(CompanyDerpAddresses);
|
||||
bypassAddresses = bypassAddresses.Concat(derpAddresses ?? []);
|
||||
var routes = bypassAddresses.Distinct().Select(address =>
|
||||
{
|
||||
var nextHop = IsOnLink(address, physicalNetwork.Ipv4Address, physicalNetwork.Ipv4PrefixLength)
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.3.18</Version>
|
||||
<AssemblyVersion>0.3.18.0</AssemblyVersion>
|
||||
<FileVersion>0.3.18.0</FileVersion>
|
||||
<InformationalVersion>0.3.18</InformationalVersion>
|
||||
<Version>0.3.20</Version>
|
||||
<AssemblyVersion>0.3.20.0</AssemblyVersion>
|
||||
<FileVersion>0.3.20.0</FileVersion>
|
||||
<InformationalVersion>0.3.20</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
|
||||
+47
-17
@@ -32,7 +32,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
// A public fallback is sticky: automatic physical-network recovery must
|
||||
// never promote it to this cached internal alternative.
|
||||
private string? _preferredTailnetConfigJson;
|
||||
private string? _tailnetInterfaceName;
|
||||
private TailnetTransport.RouteBinding? _tailnetBinding;
|
||||
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
|
||||
internal (string Address, int Port)? TailnetProbeEndpoint
|
||||
{
|
||||
@@ -56,6 +56,18 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred));
|
||||
}
|
||||
}
|
||||
internal async Task<bool> ProbeCurrentOrPreferredTailnetAsync(CancellationToken token)
|
||||
{
|
||||
if (TailnetProbeEndpoint is not { } endpoint) return false;
|
||||
if (!UsesTailnet)
|
||||
return await TailnetTransport.ProbeAuthorizedRouteAsync(endpoint.Address, endpoint.Port, token) is not null;
|
||||
|
||||
var binding = _tailnetBinding;
|
||||
// For an active session, verify the path used by Xray. A healthy
|
||||
// alternate interface must not conceal failure of the current one.
|
||||
return binding is not null
|
||||
&& await TailnetTransport.ProbeBoundEndpointAsync(endpoint.Address, endpoint.Port, binding, token);
|
||||
}
|
||||
private string _routeMode = "smart";
|
||||
private string _nodeSlug = "";
|
||||
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
|
||||
@@ -89,12 +101,20 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
replacementStarted = true;
|
||||
await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests.
|
||||
token.ThrowIfCancellationRequested();
|
||||
TailnetTransport.RouteBinding? binding = null;
|
||||
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
|
||||
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); },
|
||||
async (config, rebindToken) =>
|
||||
{
|
||||
_baseConfigJson = config;
|
||||
await StartCoreAsync(rebindToken, tailnetBinding: TailnetTransport.Address(config) is null ? null : binding);
|
||||
},
|
||||
StopCoreAsync, CheckProxyHealthAsync, token,
|
||||
preferredTailnetConfig: _preferredTailnetConfigJson,
|
||||
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); },
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
||||
endpointProbe: async (address, port, probeToken) =>
|
||||
{
|
||||
binding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
|
||||
return binding is not null;
|
||||
},
|
||||
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage),
|
||||
verifyPublicEgress: _routeMode is "smart" or "global" && !PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson!));
|
||||
}
|
||||
@@ -209,7 +229,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
}
|
||||
|
||||
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
|
||||
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null)
|
||||
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null,
|
||||
TailnetTransport.RouteBinding? tailnetBinding = null)
|
||||
{
|
||||
// Fail locally before ownership/recovery or stopping a healthy core.
|
||||
ValidateRuntime();
|
||||
@@ -237,7 +258,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
_preferredTailnetConfigJson = preferred;
|
||||
_routeMode = routeMode;
|
||||
_nodeSlug = nodeSlug;
|
||||
await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null);
|
||||
await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null, tailnetBinding);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -252,7 +273,11 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
|
||||
ScheduleLearningAsync(new LearningObservation { Target=target, Port=443, AccessKind="http",
|
||||
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()
|
||||
@@ -264,7 +289,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
_baseConfigJson = null;
|
||||
_tailnetFallbackConfigJson = null;
|
||||
_preferredTailnetConfigJson = null;
|
||||
_tailnetInterfaceName = null;
|
||||
_tailnetBinding = null;
|
||||
_nodeSlug = "";
|
||||
_boundNetwork = null;
|
||||
}
|
||||
@@ -289,7 +314,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
}
|
||||
|
||||
private async Task StartCoreAsync(CancellationToken cancellationToken,
|
||||
Action<CancellationToken>? beginStartupLearning = null)
|
||||
Action<CancellationToken>? beginStartupLearning = null, TailnetTransport.RouteBinding? tailnetBinding = null)
|
||||
{
|
||||
ValidateRuntime();
|
||||
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
|
||||
@@ -299,10 +324,12 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost;
|
||||
if (preservePrivateRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(PrivateAuxiliaryRuntime.Address(_baseConfigJson));
|
||||
var tailnetAddress = TailnetTransport.Address(_baseConfigJson);
|
||||
var tailnetInterface = tailnetAddress is null ? null : TailnetTransport.RequireExistingRoute(tailnetAddress);
|
||||
_tailnetInterfaceName = tailnetInterface;
|
||||
var proxyServerAddresses = await ResolveProxyServerAddressesAsync(_baseConfigJson, cancellationToken);
|
||||
var physicalNetwork = TunRouting.GetPhysicalNetwork(proxyServerAddresses);
|
||||
_tailnetBinding = tailnetAddress is null ? null : TailnetTransport.RequireCurrentBinding(tailnetAddress, tailnetBinding, physicalNetwork);
|
||||
var tailnetInterface = _tailnetBinding?.InterfaceName;
|
||||
if (_tailnetBinding?.Gateway is not null)
|
||||
AppPaths.WriteLog(new TransportDiagnostic("tailnet_route", "authorized_port_reached_via_gateway", _nodeSlug).SafeMessage);
|
||||
_learningEpoch = new CancellationTokenSource();
|
||||
_learningBudget = new LearningProbeBudget();
|
||||
_networkLearned.Clear();
|
||||
@@ -389,7 +416,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
|
||||
try
|
||||
{
|
||||
await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken, preservePrivateRoute, tailnetAddress);
|
||||
await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken,
|
||||
preservePrivateRoute, tailnetAddress, _tailnetBinding);
|
||||
// Apply 0.2.5 routing first, then wait until Windows has completed
|
||||
// DAD before applications can use the tunnel's DNS/IPv4 path.
|
||||
await TunRouting.WaitForAdapterAsync(cancellationToken, requireIpv4Ready: true);
|
||||
@@ -534,7 +562,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
var config = LearningPolicy.Merge(_directFirstConfig, new RoutingManifest { Contract = 1,
|
||||
Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() });
|
||||
var routing = TunConfigBuilder.BuildLearningRouting(config, _boundNetwork.InterfaceName,
|
||||
_learningProbePort, _directProbePort, _tailnetInterfaceName);
|
||||
_learningProbePort, _directProbePort, _tailnetBinding?.InterfaceName);
|
||||
await XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, token);
|
||||
_networkLearned.Applied();
|
||||
}
|
||||
@@ -618,7 +646,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
&& !value.Contains("Failed to start", StringComparison.OrdinalIgnoreCase)) return;
|
||||
try
|
||||
{
|
||||
File.AppendAllText(AppPaths.XrayLogFile, $"{DateTimeOffset.Now:O} {value}{Environment.NewLine}");
|
||||
BoundedLog.Append(AppPaths.XrayLogFile, $"{DateTimeOffset.Now:O} {value}{Environment.NewLine}",
|
||||
BoundedLog.XrayMaxBytes);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
@@ -680,9 +709,10 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(AppPaths.XrayLogFile)) return "";
|
||||
var lines = File.ReadLines(AppPaths.XrayLogFile).TakeLast(3);
|
||||
return $" {string.Join(" ", lines)}";
|
||||
var tail = BoundedLog.ReadTail(AppPaths.XrayLogFile, 3, BoundedLog.ErrorTailMaxBytes);
|
||||
return string.IsNullOrWhiteSpace(tail.Text)
|
||||
? ""
|
||||
: $" {tail.Text.Replace(Environment.NewLine, " ", StringComparison.Ordinal)}";
|
||||
}
|
||||
catch { return ""; }
|
||||
}
|
||||
|
||||
@@ -1,209 +1,256 @@
|
||||
using System.Text.Json;
|
||||
using UCVL.VPNPlus;
|
||||
|
||||
var checks = new Dictionary<string, bool>();
|
||||
TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
// The real coordinator receives controlled external setup/probe phases. The
|
||||
// semaphore is the same boundary used by XrayManager to defer rule commits.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
var tunReady = Signal(); var nrptStarted = Signal(); var finishNrpt = Signal();
|
||||
var proofFinished = false; var committed = false; var setupFinished = false;
|
||||
var clock = new ManualClock();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
await tunReady.Task;
|
||||
begin(epoch.Token);
|
||||
nrptStarted.SetResult();
|
||||
await finishNrpt.Task;
|
||||
setupFinished = true;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
await lifecycle.WaitAsync(token);
|
||||
try { token.ThrowIfCancellationRequested(); committed = setupFinished; }
|
||||
finally { lifecycle.Release(); }
|
||||
}, CancellationToken.None, clock);
|
||||
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
|
||||
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
|
||||
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
|
||||
finishNrpt.SetResult(); await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["completed_proof_commits_after_setup"] = committed;
|
||||
}
|
||||
|
||||
{
|
||||
var clock = new ManualClock(); var setupEntered = Signal(); var finishSetup = Signal();
|
||||
var learningStarted = Signal(); var cancelled = false;
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
|
||||
}, async token => {
|
||||
learningStarted.SetResult();
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { cancelled = true; }
|
||||
}, CancellationToken.None, clock);
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
|
||||
finishSetup.SetResult(); await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
await learningStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromMilliseconds(14_999));
|
||||
checks["learning_retains_fifteen_seconds_after_setup"] = !cancelled && !run.IsCompleted;
|
||||
clock.Advance(TimeSpan.FromMilliseconds(1));
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["learning_stops_at_post_setup_budget"] = cancelled;
|
||||
}
|
||||
|
||||
{
|
||||
var learningCalls = 0;
|
||||
await StartupLearningWarmup.RunAsync(_ => Task.CompletedTask,
|
||||
_ => { learningCalls++; return Task.CompletedTask; }, CancellationToken.None, new ManualClock());
|
||||
checks["setup_without_smart_readiness_never_starts_learning"] = learningCalls == 0;
|
||||
}
|
||||
|
||||
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
|
||||
var setupEntered = Signal(); var finishSetup = Signal(); var stopped = false; var active = false;
|
||||
var failure = new IOException("synthetic setup failure"); Exception? observed = null;
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(epoch.Token); setupEntered.SetResult();
|
||||
await finishSetup.Task.WaitAsync(caller.Token);
|
||||
if (reason == "setup_failure") throw failure;
|
||||
}, async token => {
|
||||
active = true;
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { active = false; stopped = true; }
|
||||
}, caller.Token, new ManualClock());
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
if (reason == "caller_cancel") caller.Cancel();
|
||||
if (reason == "epoch_cancel") epoch.Cancel();
|
||||
finishSetup.TrySetResult();
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (Exception error) { observed = error; }
|
||||
checks[reason + "_drains_learning_without_late_work"] = stopped && !active;
|
||||
checks[reason + "_preserves_original_failure"] = reason == "setup_failure"
|
||||
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
|
||||
}
|
||||
|
||||
// Failed NRPT setup cancels the same epoch while still holding the lifecycle
|
||||
// lock. A proof already waiting to commit must not escape cleanup or apply late.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
var proofFinished = false; var committed = false; var drained = false;
|
||||
var failure = new IOException("synthetic NRPT failure"); Exception? observed = null;
|
||||
try
|
||||
{
|
||||
await StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
begin(epoch.Token);
|
||||
epoch.Cancel();
|
||||
throw failure;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
try
|
||||
{
|
||||
await lifecycle.WaitAsync(token);
|
||||
try { token.ThrowIfCancellationRequested(); committed = true; }
|
||||
finally { lifecycle.Release(); }
|
||||
}
|
||||
finally { drained = true; }
|
||||
}, CancellationToken.None, new ManualClock());
|
||||
}
|
||||
catch (Exception error) { observed = error; }
|
||||
checks["failed_nrpt_cancels_pending_rule_commit"] = proofFinished && drained && !committed;
|
||||
checks["pending_commit_cancellation_preserves_setup_error"] = ReferenceEquals(observed, failure);
|
||||
}
|
||||
|
||||
{
|
||||
var clock = new ManualClock();
|
||||
using var caller = new CancellationTokenSource(TimeSpan.FromSeconds(45), clock);
|
||||
var learningStopped = false; var setupStarted = Signal();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupStarted.SetResult();
|
||||
await Task.Delay(Timeout.Infinite, caller.Token);
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { learningStopped = true; }
|
||||
}, caller.Token, clock);
|
||||
await setupStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromSeconds(45));
|
||||
var cancelled = false;
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
|
||||
checks["caller_forty_five_second_bound_remains_active_during_setup"] = cancelled && learningStopped;
|
||||
}
|
||||
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); caller.Cancel(); var setupCalled = false;
|
||||
try { await StartupLearningWarmup.RunAsync(_ => { setupCalled = true; return Task.CompletedTask; },
|
||||
_ => Task.CompletedTask, caller.Token, new ManualClock()); }
|
||||
catch (OperationCanceledException) { }
|
||||
checks["cancelled_caller_does_not_start_setup"] = !setupCalled;
|
||||
}
|
||||
|
||||
// Production learning handlers absorb cancellation after cleaning up their own
|
||||
// probes. The startup owner must still propagate the user's cancelled connect.
|
||||
{
|
||||
using var caller = new CancellationTokenSource();
|
||||
var clock = new ManualClock(); var learnerFinishedNormally = false;
|
||||
var run = StartupLearningWarmup.RunAsync(begin => {
|
||||
begin(CancellationToken.None); return Task.CompletedTask;
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { learnerFinishedNormally = true; }
|
||||
}, caller.Token, clock);
|
||||
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
caller.Cancel();
|
||||
var cancelled = false;
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
|
||||
checks["caller_cancellation_propagates_when_learning_swallows_it"] = cancelled && learnerFinishedNormally;
|
||||
}
|
||||
|
||||
var report = new { passed = checks.Values.All(v => v), checks, production_coordinator = true,
|
||||
simulated_external_phases = true, network_modified = false, production_client_started = false };
|
||||
Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return report.passed ? 0 : 91;
|
||||
|
||||
sealed class ManualClock : TimeProvider
|
||||
{
|
||||
private readonly List<ManualTimer> timers = [];
|
||||
internal long ElapsedTicks { get; private set; }
|
||||
internal TaskCompletionSource Armed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
var timer = new ManualTimer(this, callback, state); lock (timers) timers.Add(timer);
|
||||
timer.Change(dueTime, period); return timer;
|
||||
}
|
||||
internal void Advance(TimeSpan elapsed)
|
||||
{
|
||||
ManualTimer[] snapshot; lock (timers) { ElapsedTicks += elapsed.Ticks; snapshot = timers.ToArray(); }
|
||||
foreach (var timer in snapshot) timer.FireIfDue();
|
||||
}
|
||||
private sealed class ManualTimer(ManualClock clock, TimerCallback callback, object? state) : ITimer
|
||||
{
|
||||
private long? due; private bool disposed;
|
||||
public bool Change(TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
if (disposed) return false;
|
||||
due = dueTime == Timeout.InfiniteTimeSpan ? null : clock.ElapsedTicks + dueTime.Ticks;
|
||||
if (dueTime == TimeSpan.FromSeconds(15)) clock.Armed.TrySetResult();
|
||||
return true;
|
||||
}
|
||||
internal void FireIfDue()
|
||||
{
|
||||
if (!disposed && due is { } value && value <= clock.ElapsedTicks)
|
||||
{ due = null; callback(state); }
|
||||
}
|
||||
public void Dispose() { disposed = true; due = null; }
|
||||
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
}
|
||||
using System.Text.Json;
|
||||
using UCVL.VPNPlus;
|
||||
|
||||
var checks = new Dictionary<string, bool>();
|
||||
TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
// The real coordinator receives controlled external setup/probe phases. The
|
||||
// semaphore is the same boundary used by XrayManager to defer rule commits.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
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 clock = new ManualClock();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
await tunReady.Task;
|
||||
begin(epoch.Token);
|
||||
nrptStarted.SetResult();
|
||||
await finishNrpt.Task;
|
||||
setupFinished = true;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
try
|
||||
{
|
||||
await lifecycle.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
await allowCommit.Task.WaitAsync(token);
|
||||
committed = setupFinished;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}
|
||||
finally { learningFinished.TrySetResult(); }
|
||||
}, CancellationToken.None, clock);
|
||||
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
|
||||
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
|
||||
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
|
||||
finishNrpt.SetResult();
|
||||
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 learningStarted = Signal(); var learningFinished = Signal(); var cancelled = false;
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
|
||||
}, async token => {
|
||||
learningStarted.SetResult();
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { cancelled = true; }
|
||||
finally { learningFinished.TrySetResult(); }
|
||||
}, CancellationToken.None, clock);
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
|
||||
finishSetup.SetResult(); await clock.Armed.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));
|
||||
checks["background_learning_retains_fifteen_second_budget"] = !cancelled;
|
||||
clock.Advance(TimeSpan.FromMilliseconds(1));
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["background_learning_stops_at_post_setup_budget"] = cancelled;
|
||||
}
|
||||
|
||||
{
|
||||
var learningCalls = 0;
|
||||
await StartupLearningWarmup.RunAsync(_ => Task.CompletedTask,
|
||||
_ => { learningCalls++; return Task.CompletedTask; }, CancellationToken.None, new ManualClock());
|
||||
checks["setup_without_smart_readiness_never_starts_learning"] = learningCalls == 0;
|
||||
}
|
||||
|
||||
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
|
||||
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 run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(epoch.Token); setupEntered.SetResult();
|
||||
await finishSetup.Task.WaitAsync(caller.Token);
|
||||
if (reason == "setup_failure") throw failure;
|
||||
}, async token => {
|
||||
active = true;
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { active = false; stopped = true; learningFinished.TrySetResult(); }
|
||||
}, caller.Token, new ManualClock());
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
if (reason == "caller_cancel") caller.Cancel();
|
||||
if (reason == "epoch_cancel") epoch.Cancel();
|
||||
finishSetup.TrySetResult();
|
||||
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 + "_preserves_original_failure"] = reason == "setup_failure"
|
||||
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
|
||||
}
|
||||
|
||||
// Failed NRPT setup cancels the same epoch while still holding the lifecycle
|
||||
// lock. A proof already waiting to commit must not escape cleanup or apply late.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
var proofFinished = false; var committed = false; var drained = false;
|
||||
var failure = new IOException("synthetic NRPT failure"); Exception? observed = null;
|
||||
try
|
||||
{
|
||||
await StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
begin(epoch.Token);
|
||||
epoch.Cancel();
|
||||
throw failure;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
try
|
||||
{
|
||||
await lifecycle.WaitAsync(token);
|
||||
try { token.ThrowIfCancellationRequested(); committed = true; }
|
||||
finally { lifecycle.Release(); }
|
||||
}
|
||||
finally { drained = true; }
|
||||
}, CancellationToken.None, new ManualClock());
|
||||
}
|
||||
catch (Exception error) { observed = error; }
|
||||
checks["failed_nrpt_cancels_pending_rule_commit"] = proofFinished && drained && !committed;
|
||||
checks["pending_commit_cancellation_preserves_setup_error"] = ReferenceEquals(observed, failure);
|
||||
}
|
||||
|
||||
{
|
||||
var clock = new ManualClock();
|
||||
using var caller = new CancellationTokenSource(TimeSpan.FromSeconds(45), clock);
|
||||
var learningStopped = false; var setupStarted = Signal();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupStarted.SetResult();
|
||||
await Task.Delay(Timeout.Infinite, caller.Token);
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { learningStopped = true; }
|
||||
}, caller.Token, clock);
|
||||
await setupStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromSeconds(45));
|
||||
var cancelled = false;
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
|
||||
checks["caller_forty_five_second_bound_remains_active_during_setup"] = cancelled && learningStopped;
|
||||
}
|
||||
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); caller.Cancel(); var setupCalled = false;
|
||||
try { await StartupLearningWarmup.RunAsync(_ => { setupCalled = true; return Task.CompletedTask; },
|
||||
_ => Task.CompletedTask, caller.Token, new ManualClock()); }
|
||||
catch (OperationCanceledException) { }
|
||||
checks["cancelled_caller_does_not_start_setup"] = !setupCalled;
|
||||
}
|
||||
|
||||
// Production learning handlers absorb cancellation after cleaning up their own
|
||||
// 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();
|
||||
var clock = new ManualClock(); var learningFinished = Signal(); var learnerFinishedNormally = false;
|
||||
var run = StartupLearningWarmup.RunAsync(begin => {
|
||||
begin(CancellationToken.None); return Task.CompletedTask;
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { learnerFinishedNormally = true; }
|
||||
finally { learningFinished.TrySetResult(); }
|
||||
}, caller.Token, clock);
|
||||
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
var readyBeforeCancel = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||
caller.Cancel();
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch { }
|
||||
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
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,
|
||||
simulated_external_phases = true, network_modified = false, production_client_started = false };
|
||||
Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return report.passed ? 0 : 91;
|
||||
|
||||
sealed class ManualClock : TimeProvider
|
||||
{
|
||||
private readonly List<ManualTimer> timers = [];
|
||||
internal long ElapsedTicks { get; private set; }
|
||||
internal TaskCompletionSource Armed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
var timer = new ManualTimer(this, callback, state); lock (timers) timers.Add(timer);
|
||||
timer.Change(dueTime, period); return timer;
|
||||
}
|
||||
internal void Advance(TimeSpan elapsed)
|
||||
{
|
||||
ManualTimer[] snapshot; lock (timers) { ElapsedTicks += elapsed.Ticks; snapshot = timers.ToArray(); }
|
||||
foreach (var timer in snapshot) timer.FireIfDue();
|
||||
}
|
||||
private sealed class ManualTimer(ManualClock clock, TimerCallback callback, object? state) : ITimer
|
||||
{
|
||||
private long? due; private bool disposed;
|
||||
public bool Change(TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
if (disposed) return false;
|
||||
due = dueTime == Timeout.InfiniteTimeSpan ? null : clock.ElapsedTicks + dueTime.Ticks;
|
||||
if (dueTime == TimeSpan.FromSeconds(15)) clock.Armed.TrySetResult();
|
||||
return true;
|
||||
}
|
||||
internal void FireIfDue()
|
||||
{
|
||||
if (!disposed && due is { } value && value <= clock.ElapsedTicks)
|
||||
{ due = null; callback(state); }
|
||||
}
|
||||
public void Dispose() { disposed = true; due = null; }
|
||||
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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