Compare commits

..
12 Commits
Author SHA1 Message Date
shenandshen 9e05f1ad93 test: add automated regression and mesh proxy coexistence suites 2026-11-03 20:50:02 -08:00
shenandshen b656c1896a fix: improve SDK UDP throughput and transport selection
Yield during UDP receive bursts to let session consumers drain bounded queues. Prioritize measured RTT over protocol preference and enlarge user-space subnet TCP buffers with validated limits.

Add packet-level throughput diagnostics, transport selection coverage, and investigation records. SDK regression suite: 21 tests passed; local delay and throughput experiments documented.
2026-10-15 23:53:10 -07:00
shenandshen c1d0739b95 feat: support custom bypass rules and mesh routing policies 2026-10-15 07:06:34 -07:00
shenleiandClaude Opus 5.5 dc1bfc99d2 Move mesh networking logic into the SDK and fix lifecycle bugs
SDK:
- Add build_config/migrate_config, mesh_cidrs, route_generation, health
  and start_bridged; expose abi_info (capability revision 2).
- Add wait_routes long-poll; stop wakes waiters, and context_free now
  stops the network immediately instead of waiting for waiters to time out.

Hosts:
- Dart: waitRoutes(), MeshProxySession route watcher, ABI capability check.
- Android: fix a deadlock where every VPN request waited on its own
  single-thread worker; requests are now async, status is served from a
  snapshot, and combined mode reports Partial when the mesh stops.
- macOS helper: mesh-only unified mode stops when the mesh is lost;
  installed_subnet_routes excludes the overlay.
- Lab: restore Partial sessions, write migrated profiles back, remove the
  unreachable TOML import dialog; native test now connects via the form.

Docs updated accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:17:42 +09:00
shenleiandClaude Code 29d236f3fe Add copy-all-logs buttons and log status refresh failures
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-15 13:47:56 +09:00
shenleiandClaude Code 5b7523fc4f Fix desktop TUN address leak that broke VPN rebuilds
sing-tun creates its utun control socket without SOCK_CLOEXEC
(tun_darwin.go), so any child the unified helper spawns while the
engine runs - the DnsGuard scutil process, route commands - inherits
that socket and pins the utun interface past engine stop. The
announcement-driven rebuild then fails with "desktop TUN address
already in use" and tears down the whole VPN session.

Mark every utun socket in the process close-on-exec as soon as the
engine starts. Stop now only warns when Darwin still holds the
retiring address (classified via cleanupFailure), and Start waits
bounded for an address this engine itself retained while failing fast
on any other owner.

Adds a root-only drain diagnostic with a real-profile pass, a
child-guard regression test that reproduced the production failure
before the fix, and a --self-test-unified-rebuild helper self-test
that forces stop/start cycles in combined mode end to end.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-15 13:47:52 +09:00
shenleiandClaude Haiku 5.5 50cfbb6867 Raise data-plane TCP buffers to lift single-stream throughput
Single TCP streams through the SDK data plane were capped at about
window / RTT with a 128 KiB window. Raise the per-socket TCP receive
buffer to 1 MiB and transmit buffer to 512 KiB. smoltcp negotiates
window scaling from the buffer size, so no wire-format change is needed.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-15 10:30:43 +09:00
shenandshen 72566b9a8a Add proxy speed measurement, connection logs and standalone Android packaging 2026-10-13 23:08:57 -07:00
shenandshen f94dab0555 Improve VPN video routing, profile storage and authorization reuse 2026-10-13 00:34:16 -07:00
shenandshen c94143dfae Keep macOS client running in the menu bar when its window closes
Retain the main Flutter window, add reopen and explicit quit actions, and preserve its controller while hidden. Fix native test host paths and cover the window and menu lifecycle with XCTest.
2026-10-12 18:46:53 -07:00
shenandshen c7cc2aa865 Fix VPN internet connectivity and simplify client setup
Initialize Android physical interfaces and preserve macOS scoped routes. Add redacted diagnostics, default DNS, ordered auto-save, simplified controls, scanner rotation settings, and native regression coverage. Restore vendored build sources and document validation and stability checks.
2026-10-12 06:51:25 -07:00
shenleiandClaude Haiku 5.5 2f185f914d Snapshot uncommitted work: proxy UI, sing-box integration, socks bridge
- Lab app: proxy panel, node editor, configuration and detail pages,
  responsive layout, and related tests
- Add meshport-socks crate and sing-box bridge scripts/docs
- Add singbox_flutter binding and meshport_client_core package
- FFI, VPN helper (unified mac path), and Android/macOS runner updates
- Docs for architecture, client runtime, UI design, and validation
- UI design output artifacts under outputs/ui

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-12 10:06:15 +09:00
225 changed files with 23181 additions and 881 deletions
+10
View File
@@ -1,8 +1,18 @@
/target/
/work/
/build/
/outputs/android/
/outputs/macos/
# Runtime captures remain local; commit the validation summaries instead.
/outputs/validation/*.log
/outputs/validation/automated-tests/
__pycache__/
**/.dart_tool/
**/build/
!vendor/easytier/easytier/build/
!vendor/easytier/easytier/build/**
!vendor/easytier/easytier-proto/build/
!vendor/easytier/easytier-proto/build/**
**/.flutter-plugins-dependencies
**/Flutter/ephemeral/
.DS_Store
Generated
+24
View File
@@ -2398,8 +2398,11 @@ name = "meshport-ffi"
version = "0.1.0"
dependencies = [
"anyhow",
"easytier",
"easytier-core",
"meshport",
"meshport-easytier",
"meshport-socks",
"serde_json",
"tokio",
"tracing",
@@ -2415,6 +2418,27 @@ dependencies = [
"tokio",
]
[[package]]
name = "meshport-socks"
version = "0.1.0"
dependencies = [
"aes-gcm",
"anyhow",
"bytes",
"easytier",
"easytier-core",
"futures",
"libloading",
"meshport",
"meshport-easytier",
"parking_lot",
"serde_json",
"smoltcp",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "meshport-test-server"
version = "0.1.0"
+1
View File
@@ -19,3 +19,4 @@ easytier-core = { path = "vendor/easytier/easytier-core", default-features = fal
meshport = { path = "crates/meshport" }
meshport-easytier = { path = "crates/meshport-easytier" }
meshport-netstack = { path = "crates/meshport-netstack" }
meshport-socks = { path = "crates/meshport-socks" }
+25 -2
View File
@@ -36,10 +36,16 @@ cargo run -p meshport-test-server -- 10.77.0.2:7007
## 目录
下一阶段的设计文档:[移动端 UI V4(24 页与公共状态)](docs/ui-design.md)、[组网与代理组合架构](docs/next-stage-architecture.md)。这些是拟实施方案,当前实现范围仍以下文为准。
已完成的下一阶段基础能力:[SOCKS 桥接](docs/socks-bridge.md)、[sing-box 引擎封装与本机 TCP/UDP 联调](docs/singbox-integration.md)。新增 [客户端原生绑定、代理配置与联合运行](docs/client-runtime.md),支持节点/订阅导入、规则/全局/直连和基础 DNS;[高级客户端功能](docs/advanced-client-features.md)已接入自动订阅更新、规则集、DoH/DoT、原生文件和二维码导入、登录启动与自动连接。出口仍手动选择。Android 单一 VPN 原型待真机验证,macOS 统一 TUN/helper、FakeIP 和 24 页主要界面已接入;具体测试范围及禁用功能见 [验证记录](docs/development-validation.md)。
- `crates/meshport`:Rust 公共 API。
- `crates/meshport-easytier`:固定上游快照、配置约束、实例与状态适配。
- `crates/meshport-netstack`:复用 EasyTier 已有 smoltcp 数据面,提供通信类型和回显验证。
- `crates/meshport-ffi`:C ABI、实例/连接句柄、JSON 控制接口。
- `crates/meshport-socks`:可选的本机 SOCKS5 IPv4 TCP/UDP 组网桥接,原生任务并发转发;[接入说明](docs/socks-bridge.md)。
- `engines/singbox`:固定版本 Go 引擎封装,受管理的本机组网分流与跨语言验证。
- `bindings/flutter/meshport_flutter`:Dart FFI SDK,原生调用放在后台 isolate。
- `apps/meshport_lab`:响应式 Flutter 验证工具。
- `tools/meshport-vpn-helper`:macOS 开发版特权 TUN 控制与自检。
@@ -50,12 +56,12 @@ cargo run -p meshport-test-server -- 10.77.0.2:7007
## 使用边界
- 默认应用内模式不创建 TUN/TAP,只影响 SDK 连接;macOS 开发版可切换系统组网模式,创建 utun 并安装虚拟网段路由。详见 [系统组网](docs/system-vpn.md)。
- SDK 默认应用内模式不创建 TUN/TAP,只影响 SDK 连接;Lab 客户端默认统一 VPN,使用 TUN 接入代理,也可选择仅组网模式。详见 [系统组网](docs/system-vpn.md)。
- IPv4 数据面;底层 TCP/UDP 传输。其他协议、安全模式和完整 EasyTier 配置未全部开放。
- UDP 接收当前按已经主动发送过的远端会话匹配;不支持陌生远端首包的通用 UDP 服务端监听。
- Rust API 为 async;ABI v1 是同步、每 context 串行的开发接口。Dart 放到后台 isolate 避免阻塞 UI,但尚不适合高并发/低开销的最终游戏数据面。
- 超时写入可能已经发送部分 TCP 数据,不能盲目重发。
- macOS 设置页可独立保存配置到 Keychain,启动自动回填,手动连接;扫码、文件导入、完整候选路径优化、长期压测和移动端后台运行尚未完成。
- macOS 和 Android 配置保存到用户私有目录,启动自动回填,自动连接可独立设置;旧配置支持迁移。支持扫码和文件导入,长期压测和移动端后台稳定性仍需验证。
- 稳定性页面目前执行真实的重复连接/回显探测;不表示所有设计稿中的测试模式均已实现。
线路策略和实测工具见 [跨国线路优化](docs/optimization.md)。
@@ -65,3 +71,20 @@ cargo run -p meshport-test-server -- 10.77.0.2:7007
详见 [架构](docs/architecture.md)、[配置](docs/configuration.md)、[ABI](docs/ffi-contract.md)、[验证记录](docs/testing.md)和[兼容范围](docs/compatibility.md)。
两种模式均自动学习符合规则的节点公告子网,无需填写远端 CIDR。应用内模式仅供 SDK TCP/UDP 访问;系统模式自动同步 OS 路由。规则及 macOS 启动方式见 [系统组网](docs/system-vpn.md)。
## 自动化测试
```sh
python3 scripts/test.py # Rust、Go、Flutter 和 macOS 配置存储回归
python3 scripts/test.py sdk engine # 只测 SDK 与引擎联调
python3 scripts/test.py client --native # macOS:重新构建原生库后跑 Flutter 原生测试
python3 scripts/test.py throughput # 可选:本机模拟延迟与吞吐诊断
python3 scripts/test.py speed --min-mbps 10 # 重复测速矩阵、丢包检查及速度门槛
python3 scripts/test.py combined # sing-box + SDK 同进程双路负载、UDP 和故障隔离
```
脚本逐项保存日志,输出 JSON 与 JUnit 报告,任一步失败时返回非零状态;默认不运行吞吐诊断或系统 VPN/真机测试。参数、依赖和 CI 使用方式见 [自动化测试](docs/automated-testing.md)。
## 清理构建缓存
运行 `python3 scripts/clean-build-artifacts.py` 预览,增加 `--delete` 删除可重新生成的构建缓存和临时测试产物。脚本保留工具链、用户配置、Git 历史和 `outputs/android`、`outputs/macos` 安装包;下次构建需要重新生成缓存。
+31 -2
View File
@@ -1,3 +1,5 @@
import java.util.Properties
plugins {
id("com.android.application")
id("kotlin-android")
@@ -5,6 +7,16 @@ plugins {
id("dev.flutter.flutter-gradle-plugin")
}
val standalone = System.getenv("MESHPORT_ANDROID_STANDALONE") == "1"
val standaloneSigning = Properties().apply {
if (standalone) {
val path = requireNotNull(System.getenv("MESHPORT_ANDROID_SIGNING_PROPERTIES")) {
"Use scripts/package-lab-android.sh --standalone to prepare signing"
}
file(path).inputStream().use { load(it) }
}
}
android {
buildFeatures { buildConfig = true }
namespace = "com.example.meshport_lab"
@@ -22,7 +34,8 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "com.example.meshport_lab"
applicationId = if (standalone) "com.meshport.client.standalone" else "com.example.meshport_lab"
manifestPlaceholders["meshportAppLabel"] = if (standalone) "MeshPort 独立版" else "MeshPort"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 26
@@ -36,13 +49,23 @@ android {
versionName = flutter.versionName
}
signingConfigs {
if (standalone) {
create("standalone") {
storeFile = file(standaloneSigning.getProperty("storeFile"))
storePassword = standaloneSigning.getProperty("storePassword")
keyAlias = standaloneSigning.getProperty("keyAlias")
keyPassword = standaloneSigning.getProperty("keyPassword")
}
}
}
buildTypes {
debug { ndk { abiFilters.clear(); abiFilters += "arm64-v8a" } }
release {
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
signingConfig = signingConfigs.getByName(if (standalone) "standalone" else "debug")
}
}
externalNativeBuild { cmake { path = file("src/main/cpp/CMakeLists.txt"); version = "3.22.1" } }
@@ -51,3 +74,9 @@ android {
flutter {
source = "../.."
}
// Offline QR decoding and an in-app camera capture Activity.
dependencies {
implementation("com.journeyapps:zxing-android-embedded:4.3.0")
testImplementation("junit:junit:4.13.2")
}
@@ -1,20 +1,25 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<application
android:allowBackup="false"
android:label="MeshPort"
android:label="${meshportAppLabel}"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<service android:name=".MeshVpnService" android:exported="false"
<!-- Override ZXing's sensorLandscape default and respect user rotation. -->
<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="fullUser"
tools:replace="android:screenOrientation" />
<service android:name="com.example.meshport_lab.MeshVpnService" android:exported="false"
android:permission="android.permission.BIND_VPN_SERVICE" android:foregroundServiceType="specialUse">
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="User initiated mesh networking VPN" />
</service>
<activity
android:name=".MainActivity"
android:name="com.example.meshport_lab.MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
@@ -4,6 +4,8 @@ add_library(meshport_ffi SHARED IMPORTED)
set_target_properties(meshport_ffi PROPERTIES
IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmeshport_ffi.so"
IMPORTED_NO_SONAME TRUE)
add_library(meshport_proxy SHARED IMPORTED)
set_target_properties(meshport_proxy PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmeshport_proxy.so" IMPORTED_NO_SONAME TRUE)
add_library(meshport_android SHARED bridge.cpp)
target_link_libraries(meshport_android meshport_ffi)
target_link_libraries(meshport_android meshport_ffi meshport_proxy)
target_link_options(meshport_android PRIVATE "-Wl,-z,max-page-size=16384")
@@ -2,7 +2,15 @@
#include <cstdint>
#include <cstring>
#include <string>
#include <sys/ioctl.h>
#include <linux/if_tun.h>
#include <net/if.h>
extern "C" {
uint64_t meshport_proxy_context_new();
void meshport_proxy_context_free(uint64_t);
char* meshport_proxy_call(uint64_t, const char*);
void meshport_proxy_string_free(char*);
void meshport_proxy_set_socket_protector(uintptr_t);
uint64_t meshport_context_new();
void meshport_context_free(uint64_t);
char* meshport_call(uint64_t, const char*);
@@ -21,6 +29,7 @@ static bool protectSocket(int fd) {
if (attached) vm->DetachCurrentThread();
return ok;
}
static int proxyProtectSocket(int fd) { return protectSocket(fd) ? 1 : 0; }
extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* value, void*) {
vm = value;
JNIEnv* env = nullptr;
@@ -31,6 +40,7 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* value, void*) {
protectMethod = env->GetStaticMethodID(bridge, "protectFd", "(I)Z");
if (!protectMethod) return JNI_ERR;
meshport_set_android_socket_protector(protectSocket);
meshport_proxy_set_socket_protector(reinterpret_cast<uintptr_t>(proxyProtectSocket));
return JNI_VERSION_1_6;
}
extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_newContext(JNIEnv*, jobject) {
@@ -39,7 +49,7 @@ extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_n
extern "C" JNIEXPORT void JNICALL Java_com_example_meshport_1lab_NativeBridge_freeContext(JNIEnv*, jobject, jlong handle) {
meshport_context_free(static_cast<uint64_t>(handle));
}
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_call(JNIEnv* env, jobject, jlong handle, jstring text) {
static jstring controlCall(JNIEnv* env, jlong handle, jstring text, bool proxy) {
auto stringClass = env->FindClass("java/lang/String");
auto charset = env->NewStringUTF("UTF-8");
auto getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
@@ -49,11 +59,25 @@ extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge
if (size > 131072) return env->NewStringUTF("{\"ok\":false,\"error\":\"Request too large\"}");
std::string input(size, '\0');
env->GetByteArrayRegion(bytes, 0, size, reinterpret_cast<jbyte*>(input.data()));
char* response = meshport_call(static_cast<uint64_t>(handle), input.c_str());
char* response = (proxy ? meshport_proxy_call : meshport_call)(static_cast<uint64_t>(handle), input.c_str());
if (!response) return nullptr;
auto output = env->NewByteArray(static_cast<jsize>(strlen(response)));
env->SetByteArrayRegion(output, 0, env->GetArrayLength(output), reinterpret_cast<jbyte*>(response));
meshport_string_free(response);
(proxy ? meshport_proxy_string_free : meshport_string_free)(response);
auto constructor = env->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V");
return static_cast<jstring>(env->NewObject(stringClass, constructor, output, charset));
}
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_call(JNIEnv* env, jobject, jlong handle, jstring text) { return controlCall(env,handle,text,false); }
extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_newProxyContext(JNIEnv*, jobject) {
return static_cast<jlong>(meshport_proxy_context_new());
}
extern "C" JNIEXPORT void JNICALL Java_com_example_meshport_1lab_NativeBridge_freeProxyContext(JNIEnv*, jobject, jlong handle) {
meshport_proxy_context_free(static_cast<uint64_t>(handle));
}
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_proxyCall(JNIEnv* env, jobject, jlong handle, jstring text) { return controlCall(env,handle,text,true); }
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_tunName(JNIEnv* env, jobject, jint fd) {
struct ifreq request{};
if (ioctl(fd,TUNGETIFF,&request)<0) return nullptr;
return env->NewStringUTF(request.ifr_name);
}
@@ -0,0 +1,83 @@
package com.example.meshport_lab
import java.io.File
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardCopyOption
import java.nio.file.StandardOpenOption
import java.nio.file.attribute.PosixFilePermissions
/** App-private local profiles. Legacy access is used once and never on save. */
class LocalProfileFiles(val root: File, private val namespace: String, private val legacyRead: () -> String?) {
init { require(namespace == "proxy" || namespace == "profile") }
private val name = if (namespace == "proxy") "proxy-profile.json" else "network-profile.toml"
private val file get() = File(root, name).toPath()
private val done get() = File(root, ".$name.migrated").toPath()
private val pending get() = File(root, ".$name.migration-pending").toPath()
private fun exists(path: java.nio.file.Path) = Files.exists(path, NOFOLLOW_LINKS)
private fun prepare() {
val path = root.toPath()
if (!exists(path)) Files.createDirectories(path, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")))
check(Files.isDirectory(path, NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) { "Invalid configuration directory" }
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwx------"))
}
private fun verify(path: java.nio.file.Path) {
check(Files.isRegularFile(path, NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) { "Invalid configuration file" }
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-------"))
}
private fun write(data: ByteArray, target: java.nio.file.Path) {
prepare()
if (exists(target)) verify(target)
val temp = Files.createTempFile(root.toPath(), ".profile-", ".tmp",
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")))
try {
FileChannel.open(temp, StandardOpenOption.WRITE).use { channel ->
val buffer = ByteBuffer.wrap(data)
while (buffer.hasRemaining()) channel.write(buffer)
channel.force(true)
}
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} finally { Files.deleteIfExists(temp) }
}
private fun finish() {
write(byteArrayOf(), done)
if (exists(pending)) { verify(pending); Files.delete(pending) }
}
fun save(text: String) {
val data = text.toByteArray(Charsets.UTF_8)
require(data.size <= 65536) { "Configuration exceeds storage limit" }
write(data, file)
finish()
}
fun load(): String? {
prepare()
if (exists(file)) {
verify(file)
check(Files.size(file) <= 65536) { "Configuration exceeds storage limit" }
return Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(Files.readAllBytes(file))).toString()
}
if (exists(done) || exists(pending)) return null
return try {
val text = legacyRead()
if (text == null) finish() else save(text)
text
} catch (_: Exception) { write(byteArrayOf(), pending); null }
}
fun migrationPending(): Boolean { prepare(); return exists(pending) }
fun migratePending() {
prepare()
if (!exists(pending)) return
if (exists(file)) { verify(file); finish(); return }
val text = legacyRead()
if (text == null) finish() else save(text)
}
fun delete() {
prepare()
if (exists(file)) { verify(file); Files.delete(file) }
finish() // Do not resurrect a deleted local profile from legacy storage.
}
}
@@ -4,6 +4,19 @@ import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.app.Activity
import android.graphics.BitmapFactory
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.multi.GenericMultipleBarcodeReader
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction
import android.content.Intent
import android.net.VpnService
import android.os.Handler
@@ -16,9 +29,41 @@ class MainActivity : FlutterActivity() {
private val background = Executors.newSingleThreadExecutor()
private val main = Handler(Looper.getMainLooper())
private var permissionResult: MethodChannel.Result? = null
private var importResult: MethodChannel.Result? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "meshport/system_vpn").setMethodCallHandler { call, result ->
if (call.method == "runtime_log") {
// Flutter redacts credentials before sending these bounded events.
val text = call.arguments as? String ?: ""
Log.i("MeshPortRuntime", text.take(4096))
result.success(null)
return@setMethodCallHandler
}
if (call.method in listOf("import_file", "import_qr_image", "scan_qr")) {
if (importResult != null) { result.error("IMPORT_BUSY", "Import already open", null); return@setMethodCallHandler }
importResult = result
try {
if (call.method == "scan_qr") {
val options = ScanOptions().setDesiredBarcodeFormats(ScanOptions.QR_CODE).setBeepEnabled(false).setPrompt("扫描配置二维码").setOrientationLocked(false)
startActivityForResult(ScanContract().createIntent(this, options), 2003)
} else {
val image = call.method == "import_qr_image"
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType(if (image) "image/*" else "*/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivityForResult(intent, if (image) 2002 else 2001)
}
} catch (_: Exception) { importResult=null;result.error("IMPORT_UNAVAILABLE", "No file picker or camera available", null) }
return@setMethodCallHandler
}
if (call.method == "startup_status" || call.method == "set_startup") {
val prefs = getSharedPreferences("startup",MODE_PRIVATE)
if (call.method == "set_startup") {
val args = call.arguments as? Map<*, *>
if (args?.containsKey("login") == true) {result.error("UNSUPPORTED", "Android does not use macOS login items", null); return@setMethodCallHandler}
(args?.get("auto_connect") as? Boolean)?.let { prefs.edit().putBoolean("auto_connect",it).apply() }
}
result.success(mapOf("auto_connect" to prefs.getBoolean("auto_connect",false),"login_status" to "unsupported"));return@setMethodCallHandler
}
if (call.method == "prepare_android_vpn") {
if (permissionResult != null) { result.error("VPN_BUSY", "VPN authorization pending", null); return@setMethodCallHandler }
val intent = VpnService.prepare(this)
@@ -31,6 +76,15 @@ class MainActivity : FlutterActivity() {
try {
val profiles = ProfileStore(this)
when (call.method) {
"profile_storage_status" -> {
val pending = profiles.migrationPending() || ProfileStore(this,"proxy").migrationPending()
main.post { result.success(mapOf("path" to profiles.directory, "migration_pending" to pending)) }
}
"migrate_profiles" -> {
ProfileStore(this,"proxy").migratePending()
profiles.migratePending()
main.post { result.success(null) }
}
"debug_os_echo" -> {
check(BuildConfig.DEBUG)
val host = "10.253.79.1"
@@ -52,6 +106,9 @@ class MainActivity : FlutterActivity() {
}
main.post { result.success(true) }
}
"load_proxy_profile" -> { val value = ProfileStore(this,"proxy").load(); main.post { result.success(value) } }
"save_proxy_profile" -> { ProfileStore(this,"proxy").save(call.arguments as String); main.post { result.success(null) } }
"delete_proxy_profile" -> { ProfileStore(this,"proxy").delete(); main.post { result.success(null) } }
"load_profile" -> { val value = profiles.load(); main.post { result.success(value) } }
"save_profile" -> { profiles.save(call.arguments as String); main.post { result.success(null) } }
"delete_profile" -> { profiles.delete(); main.post { result.success(null) } }
@@ -84,11 +141,10 @@ class MainActivity : FlutterActivity() {
val reply = JSONObject().put("ok", true).put("data", data).toString()
main.post { result.success(reply) }
} else {
service.worker.execute {
try {
val reply = service.request(request).toString()
main.post { result.success(reply) }
} catch (error: Throwable) { main.post { result.error("VPN_REQUEST", error.message, null) } }
service.request(request) { reply ->
reply.fold(
{ main.post { result.success(it.toString()) } },
{ error -> main.post { result.error("VPN_REQUEST", error.message, null) } })
}
}
}
@@ -101,6 +157,46 @@ class MainActivity : FlutterActivity() {
@Deprecated("Legacy VPN permission result")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode in 2001..2003) {
val pending = importResult; importResult=null
if (pending == null) return
if (resultCode != Activity.RESULT_OK) { pending.success(null);return }
if (requestCode == 2003) {
val contents = ScanContract().parseResult(resultCode,data).contents
if (contents != null && contents.toByteArray(Charsets.UTF_8).size > 1024*1024) pending.error("IMPORT_LIMIT","QR payload too large",null) else pending.success(contents)
return
}
val uri=data?.data
if(uri==null) {pending.error("IMPORT_FAILED","No file selected",null);return}
background.execute {
try {
val max = if(requestCode==2002) 20*1024*1024 else 1024*1024
val bytes = contentResolver.openInputStream(uri)?.use { input ->
val output=ByteArrayOutputStream();val buffer=ByteArray(8192)
while(true) {val n=input.read(buffer);if(n<0) break;require(output.size()+n <= max);output.write(buffer,0,n)}
output.toByteArray()
} ?: error("Unreadable file")
val text = if(requestCode==2001) {
Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString()
} else {
val bounds=BitmapFactory.Options().apply {inJustDecodeBounds=true}
BitmapFactory.decodeByteArray(bytes,0,bytes.size,bounds)
require(bounds.outWidth>0 && bounds.outHeight>0 && bounds.outWidth.toLong()*bounds.outHeight<=20000000)
val bitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.size) ?: error("Invalid image")
try {
val pixels=IntArray(bitmap.width*bitmap.height);bitmap.getPixels(pixels,0,bitmap.width,0,0,bitmap.width,bitmap.height)
val binary=BinaryBitmap(HybridBinarizer(RGBLuminanceSource(bitmap.width,bitmap.height,pixels)))
val hints=mapOf(DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE))
val codes=GenericMultipleBarcodeReader(MultiFormatReader()).decodeMultiple(binary,hints).map {it.text}.toSet()
require(codes.size==1);codes.single()
} finally {bitmap.recycle()}
}
require(text.toByteArray(Charsets.UTF_8).size<=1024*1024)
main.post {pending.success(text)}
} catch (_:Exception) {main.post {pending.error("IMPORT_FAILED","Invalid, oversized file or no unique QR code",null)}}
}
return
}
if (requestCode == 1001) {
Log.i("MeshPortVPN", "VPN permission result: $resultCode")
val pending = permissionResult; permissionResult = null
@@ -111,6 +207,7 @@ class MainActivity : FlutterActivity() {
override fun onDestroy() {
permissionResult?.error("VPN_CANCELLED", "Activity closed during VPN authorization", null)
permissionResult = null
importResult?.error("IMPORT_CANCELLED", "Activity closed", null); importResult=null
background.shutdown()
super.onDestroy()
}
@@ -17,13 +17,32 @@ import java.net.InetAddress
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
// All service state is confined to `worker`: requests from the activity, the
// health tick, network callbacks and route updates run there one at a time.
// Status reads a snapshot refreshed after every worker task, so a slow TUN
// rebuild never stalls the UI poll.
class MeshVpnService : VpnService() {
companion object { @Volatile var current: MeshVpnService? = null; private set }
val worker = ScheduledThreadPoolExecutor(1)
private val worker = ScheduledThreadPoolExecutor(1)
@Volatile private var statusSnapshot: String? = null
// Invalidates the route watcher thread of a previous session.
@Volatile private var watchSession = 0
private var handle = 0L
private var tun: ParcelFileDescriptor? = null
private var ipv4 = ""
private var installed = emptyList<String>()
private var proxyHandle = 0L
private var unified = false
private var meshEnabled = true
private var proxyProfile = JSONObject()
private val protected = sortedSetOf<String>()
private var physical: android.net.Network? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
// Overlay and routed destinations come from the SDK projection; the
// service only installs them and never derives prefixes itself.
private var overlayAddress = ""
private var overlayPrefix = 0
private var overlayNetwork = ""
private var meshCidrs = emptyList<String>()
private var routeGeneration = -1L
private var running = false
private var failure: String? = null
override fun onCreate() {
@@ -33,24 +52,111 @@ class MeshVpnService : VpnService() {
manager.createNotificationChannel(NotificationChannel("meshport_vpn", "MeshPort 组网", NotificationManager.IMPORTANCE_LOW))
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
startForeground(77, Notification.Builder(this, "meshport_vpn")
.setContentTitle("MeshPort").setContentText("虚拟组网服务正在运行")
.setContentTitle("MeshPort").setContentText("VPN 服务正在运行")
.setSmallIcon(R.drawable.ic_stat_meshport).setContentIntent(open).setOngoing(true).build())
// Health tick. Route changes normally arrive from the watcher thread;
// the generation check here only covers a watcher that has exited.
worker.scheduleWithFixedDelay({
if (running) try {
val snapshot = native(JSONObject().put("op", "status")).getJSONObject("data")
val routes = snapshot.getJSONObject("platform_network").getJSONArray("subnet_routes")
val next = (0 until routes.length()).map { routes.getString(it) }.sorted()
if (next != installed) rebuild(next)
} catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
try { tick() } finally { refreshStatus() }
}, 2, 2, TimeUnit.SECONDS)
}
private fun tick() {
if (running) try {
if (unified) {
check(proxyCall(JSONObject().put("op","status")).getJSONObject("data").getString("state") == "Running")
if (!meshEnabled) return
}
val data = native(JSONObject().put("op", "status")).getJSONObject("data")
val health = data.optJSONObject("health") ?: JSONObject()
val routable = health.optBoolean(if (unified) "mesh_routable" else "engine_running")
if (!routable) {
// Combined mode keeps the proxy and drops mesh routes;
// mesh-only unified and system VPN have nothing left to serve.
check(unified && proxyProfile.optString("feature", "combined") == "combined") { "Mesh network stopped" }
if (meshCidrs.isNotEmpty()) {
Log.w("MeshPortVPN", "Mesh unavailable; proxy continues without mesh routes")
restartProxy(emptyList())
}
return
}
val platform = data.getJSONObject("platform_network")
applyRoutes(handle, platform.getLong("route_generation"), strings(platform.getJSONArray("mesh_cidrs")))
} catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
}
/** Runs [block] on `worker`, then republishes the status snapshot. */
private fun onWorker(block: () -> Unit) = worker.execute { try { block() } finally { refreshStatus() } }
private fun refreshStatus() {
statusSnapshot = try { dispatch(JSONObject().put("op", "status")).toString() } catch (_: Exception) { null }
}
/** Runs on `worker`. Ignores stale updates from a previous context. */
private fun applyRoutes(context: Long, generation: Long, cidrs: List<String>) {
if (!running || context != handle || generation == routeGeneration) return
if (cidrs != meshCidrs) { if (unified) restartProxy(cidrs) else rebuild(cidrs) }
routeGeneration = generation
}
/** Long-polls the SDK route watch off `worker` so a slow wait never delays requests. */
private fun watchRoutes(context: Long, from: Long) {
val session = ++watchSession
Thread({
var generation = from
while (session == watchSession) {
val reply = try {
JSONObject(NativeBridge.call(context, JSONObject().put("op", "wait_routes")
.put("after_generation", generation).put("timeout_ms", 10000).toString()))
} catch (_: Exception) { return@Thread }
// An error means the context is gone; a stopped network is
// left to the health tick, which knows the session's mode.
if (!reply.optBoolean("ok")) return@Thread
val data = reply.getJSONObject("data")
if (!data.optBoolean("running")) return@Thread
if (!data.optBoolean("changed")) continue
generation = data.getLong("route_generation")
val cidrs = strings(data.getJSONArray("mesh_cidrs"))
val next = generation
try {
onWorker {
if (session == watchSession) try { applyRoutes(context, next, cidrs) }
catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
}
} catch (_: java.util.concurrent.RejectedExecutionException) { return@Thread }
}
}, "meshport-route-watch").apply { isDaemon = true }.start()
}
private fun strings(list: org.json.JSONArray) = (0 until list.length()).map { list.getString(it) }
private fun useOverlay(overlay: JSONObject?, mode: String) {
checkNotNull(overlay) { "Static mesh address required for $mode" }
overlayAddress = overlay.getString("address")
overlayPrefix = overlay.getInt("prefix")
overlayNetwork = overlay.getString("network")
}
private fun native(request: JSONObject): JSONObject {
check(handle != 0L) { "VPN context not started" }
val response = JSONObject(NativeBridge.call(handle, request.toString()))
check(response.optBoolean("ok")) { response.optString("error", "Native request failed") }
return response
}
fun request(request: JSONObject): JSONObject {
/**
* Callable from any thread; [reply] runs on `worker`, or immediately for a
* status answered from the snapshot. Never blocks the caller.
*/
fun request(request: JSONObject, reply: (Result<JSONObject>) -> Unit) {
val snapshot = statusSnapshot
if (request.optString("op") == "status" && snapshot != null) {
reply(Result.success(JSONObject(snapshot))); return
}
try {
// Republish the snapshot before replying, so the caller's next
// status already reflects this operation.
worker.execute {
val result = runCatching { dispatch(request) }
refreshStatus()
reply(result)
}
} catch (error: java.util.concurrent.RejectedExecutionException) {
reply(Result.failure(IllegalStateException("VPN service is stopping")))
}
}
private fun dispatch(request: JSONObject): JSONObject {
return when (request.getString("op")) {
"start" -> {
check(!running) { "VPN already started" }
@@ -59,23 +165,35 @@ class MeshVpnService : VpnService() {
try {
handle = NativeBridge.newContext()
val config = request.getString("toml")
val validation = native(JSONObject().put("op", "validate").put("toml", config).put("include_profile", true)).getJSONObject("data")
unified = request.has("unified_profile")
if (unified) {
proxyProfile = JSONObject(request.getJSONObject("unified_profile").toString())
meshEnabled = proxyProfile.optString("feature", "combined") != "proxy"
startUnified(config)
return JSONObject().put("ok",true).put("data", JSONObject().put("started",true))
}
val validation = native(JSONObject().put("op", "validate").put("toml", config)).getJSONObject("data")
check(validation.getString("runtime_mode") == "system_vpn")
ipv4 = validation.getJSONObject("profile").getString("ipv4")
useOverlay(validation.optJSONObject("overlay"), "system VPN")
Log.i("MeshPortVPN", "Starting native engine")
// The SDK rejects an overlay that overlaps an existing interface.
val result = native(request)
Log.i("MeshPortVPN", "Native engine started")
running = true
rebuild(emptyList())
val platform = native(JSONObject().put("op", "status")).getJSONObject("data").getJSONObject("platform_network")
rebuild(strings(platform.getJSONArray("mesh_cidrs")))
routeGeneration = platform.getLong("route_generation")
watchRoutes(handle, routeGeneration)
result
} catch (error: Throwable) { shutdown(); stopSelf(); throw error }
}
"stop" -> { shutdown(); stopSelf(); JSONObject().put("ok", true).put("data", JSONObject()) }
"status" -> {
if (!running) JSONObject().put("ok", true).put("data", JSONObject().put("state", if (failure == null) "Stopped" else "Failed").put("peer_count", 0))
else native(request).also { reply ->
reply.getJSONObject("data").getJSONObject("platform_network")
.put("installed_subnet_routes", org.json.JSONArray(installed)).put("route_installation", "android_vpn")
else (if (unified) unifiedStatus() else native(request)).also { reply ->
// A stopped mesh reports no platform_network.
reply.getJSONObject("data").optJSONObject("platform_network")
?.put("installed_subnet_routes", org.json.JSONArray(meshCidrs - overlayNetwork))?.put("route_installation", "android_vpn")
}
}
"diagnostics_enable" -> {
@@ -84,22 +202,17 @@ class MeshVpnService : VpnService() {
else -> native(request)
}
}
private fun rebuild(routes: List<String>) {
val parts = ipv4.split('/')
val address = parts[0]
val prefix = if (parts.size == 2) parts[1].toInt() else 24
val raw = InetAddress.getByName(address).address
val network = raw.mapIndexed { index, byte ->
val bits = (prefix - index * 8).coerceIn(0, 8)
(byte.toInt() and (0xff shl (8 - bits))).and(0xff)
}.joinToString(".")
private fun rebuild(cidrs: List<String>) {
// The overlay network is always on the TUN, even when the SDK does not
// project it as routable for bridged hosts.
val routes = (cidrs + overlayNetwork).toSortedSet()
val builder = Builder().setSession("MeshPort").setMtu(1280)
.addAddress(address, prefix).addRoute(network, prefix).allowFamily(OsConstants.AF_INET6)
.addAddress(overlayAddress, overlayPrefix).allowFamily(OsConstants.AF_INET6)
for (route in routes) {
val cidr = route.split('/')
builder.addRoute(cidr[0], cidr[1].toInt())
}
Log.i("MeshPortVPN", "Establishing TUN with ${routes.size} learned routes")
Log.i("MeshPortVPN", "Establishing TUN with ${routes.size} mesh routes")
val next = builder.establish() ?: error("Android VPN authorization revoked")
val previous = tun
try {
@@ -116,7 +229,7 @@ class MeshVpnService : VpnService() {
// network. Wait for the exact address and route set on this TUN,
// including removals, before exposing it as usable to callers.
val connectivity = getSystemService(ConnectivityManager::class.java)
val expected = (routes + "$network/$prefix").map {
val expected = routes.map {
val cidr = it.split('/')
IpPrefix(InetAddress.getByName(cidr[0]), cidr[1].toInt())
}.toSet()
@@ -126,7 +239,7 @@ class MeshVpnService : VpnService() {
val capabilities = connectivity.getNetworkCapabilities(candidate)
val properties = connectivity.getLinkProperties(candidate)
capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true &&
properties?.linkAddresses?.any { it.address.hostAddress == address } == true &&
properties?.linkAddresses?.any { it.address.hostAddress == overlayAddress } == true &&
properties.routes.filter { it.destination.address is java.net.Inet4Address && it.type == android.net.RouteInfo.RTN_UNICAST }
.map { it.destination }.toSet() == expected
}
@@ -138,17 +251,128 @@ class MeshVpnService : VpnService() {
Thread.sleep(300)
Log.i("MeshPortVPN", "TUN ready")
tun = next
installed = routes
meshCidrs = cidrs
previous?.close()
} catch (error: Exception) { next.close(); throw error }
}
private fun proxyCall(value: JSONObject): JSONObject {
val result = JSONObject(NativeBridge.proxyCall(proxyHandle, value.toString()))
check(result.optBoolean("ok")) { result.optString("error", "Proxy engine failed") }
return result
}
private fun physicalNetwork(): android.net.Network {
val manager = getSystemService(ConnectivityManager::class.java)
return manager.allNetworks.firstOrNull {
val caps = manager.getNetworkCapabilities(it)
caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
} ?: error("No physical network available")
}
private fun startUnified(config: String) {
val manager = getSystemService(ConnectivityManager::class.java)
physical = physicalNetwork(); setUnderlyingNetworks(arrayOf(physical!!))
Log.i("MeshPortVPN", "Unified VPN: physical network selected; mesh enabled=$meshEnabled")
var routes = emptyList<String>()
if (meshEnabled) {
// One SDK step: application mode, static routable overlay, no local
// overlap, then network + bridge, rolled back together on failure.
val started = native(JSONObject().put("op","start_bridged").put("toml",config)
.put("check_local_overlap",true).put("require_static_overlay",true)).getJSONObject("data")
useOverlay(started.optJSONObject("overlay"), "unified VPN")
proxyProfile.put("mesh_socks", started.getString("listen"))
routes = strings(started.getJSONArray("mesh_cidrs"))
routeGeneration = started.getLong("route_generation")
protected.add(overlayNetwork)
}
val builder = Builder().setSession("MeshPort · 代理与组网").setMtu(1280)
.addAddress("172.19.0.1",30).addAddress("fdfe:dcba:9876::1",126)
val internet = proxyProfile.optString("feature","combined") != "mesh"
if (internet) {
builder.addRoute("0.0.0.0",0).addRoute("::",0).addDnsServer("172.19.0.2")
} else {
for (route in (protected + routes).toSortedSet()) { val cidr=route.split('/');builder.addRoute(cidr[0],cidr[1].toInt()) }
builder.allowFamily(OsConstants.AF_INET6)
}
tun = builder.establish() ?: error("VPN authorization revoked")
Log.i("MeshPortVPN", "Unified VPN: TUN established; internet routes=$internet")
proxyHandle = NativeBridge.newProxyContext()
check(proxyHandle != 0L)
proxyCall(JSONObject().put("op","configure_cache").put("directory",cacheDir.absolutePath))
// The TUN above already carries these routes; no re-establish needed.
meshCidrs = routes
restartProxy(routes)
running = true
if (meshEnabled) watchRoutes(handle, routeGeneration)
Log.i("MeshPortVPN", "Unified VPN: proxy engine ready")
networkCallback = object: ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: android.net.Network) { onWorker { updatePhysical() } }
override fun onLost(network: android.net.Network) { onWorker { updatePhysical() } }
}
manager.registerNetworkCallback(android.net.NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(),networkCallback!!)
}
private fun updatePhysical() {
if (!running || !unified) return
try {
val next = physicalNetwork()
if (next != physical) { physical=next;setUnderlyingNetworks(arrayOf(next));restartProxy(meshCidrs) }
} catch (_: Exception) { failure="物理网络已断开,请重新连接";shutdown();stopSelf() }
}
private fun restartProxy(routes: List<String>) {
proxyCall(JSONObject().put("op","stop"))
val config = JSONObject(proxyProfile.toString())
if (meshEnabled) protected.addAll(routes)
val manager = getSystemService(ConnectivityManager::class.java)
val iface = manager.getLinkProperties(physical!!)?.interfaceName ?: error("Physical interface unavailable")
val index = java.net.NetworkInterface.getByName(iface)?.index ?: error("Physical index unavailable")
if (proxyProfile.optString("feature") == "mesh" && routes != meshCidrs) {
val builder = Builder().setSession("MeshPort · 组网").setMtu(1280)
.addAddress("172.19.0.1",30).addAddress("fdfe:dcba:9876::1",126).allowFamily(OsConstants.AF_INET6)
for (route in protected) { val cidr=route.split('/');builder.addRoute(cidr[0],cidr[1].toInt()) }
val previous=tun
try { tun=builder.establish() ?: error("VPN authorization revoked") } finally { previous?.close() }
}
config.put("listen_port",10818).put("mesh_cidrs",org.json.JSONArray(routes))
.put("protected_cidrs",org.json.JSONArray(protected))
.put("tun",JSONObject().put("fd",tun!!.fd).put("name",NativeBridge.tunName(tun!!.fd) ?: error("TUN name unavailable"))
.put("physical_interface",iface).put("physical_index",index))
proxyCall(JSONObject().put("op","start").put("config",config))
Log.i("MeshPortVPN", "Unified VPN: protected physical sockets; mesh routes=${routes.size}")
meshCidrs = routes
}
private fun unifiedStatus(): JSONObject {
val data = if (meshEnabled) native(JSONObject().put("op","status")).getJSONObject("data")
else JSONObject().put("state","Running").put("peer_count",0)
// The VPN and proxy are up even when the mesh is not: report Partial
// (as the macOS helper does) so hosts still treat it as connected.
if (meshEnabled && data.optJSONObject("health")?.optBoolean("mesh_routable") != true) data.put("state","Partial")
data.put("runtime_mode","unified_vpn").put("proxy",proxyCall(JSONObject().put("op","status")).getJSONObject("data"))
val platform = data.optJSONObject("platform_network") ?: JSONObject()
platform.put("ready",tun!=null).put("route_installation","singbox_tun").put("protected_subnets",org.json.JSONArray(protected))
data.put("platform_network",platform)
return JSONObject().put("ok",true).put("data",data)
}
private fun shutdown() {
if (running || handle != 0L || proxyHandle != 0L || tun != null) Log.i("MeshPortVPN", "Stopping VPN and releasing TUN")
running = false
if (handle != 0L) { NativeBridge.freeContext(handle); handle = 0L }
tun?.close(); tun = null; installed = emptyList()
watchSession++
if (proxyHandle != 0L) { NativeBridge.freeProxyContext(proxyHandle); proxyHandle = 0L }
val connectivity = getSystemService(ConnectivityManager::class.java)
networkCallback?.let { try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {} }
networkCallback = null; physical = null; protected.clear(); unified = false
if (handle != 0L) {
// Stop first: it wakes an in-flight wait_routes, which otherwise
// keeps the network alive until its timeout after the free.
try { native(JSONObject().put("op", "stop")) } catch (_: Exception) {}
NativeBridge.freeContext(handle); handle = 0L
}
tun?.close(); tun = null; meshCidrs = emptyList(); routeGeneration = -1L
overlayAddress = ""; overlayPrefix = 0; overlayNetwork = ""
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int = START_NOT_STICKY
override fun onRevoke() { worker.execute { shutdown(); stopSelf() } }
override fun onRevoke() { onWorker { shutdown(); stopSelf() } }
override fun onDestroy() {
worker.execute { shutdown(); if (current === this) current = null; worker.shutdown() }
super.onDestroy()
@@ -2,6 +2,10 @@ package com.example.meshport_lab
object NativeBridge {
init { System.loadLibrary("meshport_android") }
external fun tunName(fd: Int): String?
external fun newProxyContext(): Long
external fun freeProxyContext(handle: Long)
external fun proxyCall(handle: Long, request: String): String
external fun newContext(): Long
external fun freeContext(handle: Long)
external fun call(handle: Long, request: String): String
@@ -1,40 +1,30 @@
package com.example.meshport_lab
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.io.File
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class ProfileStore(context: Context, namespace: String = "profile") {
private val prefs = context.getSharedPreferences("meshport_$namespace", Context.MODE_PRIVATE)
private val alias = "MeshPort.Network.$namespace"
private fun key(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getKey(alias, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
}.generateKey()
}
fun save(config: String) {
require(config.toByteArray(Charsets.UTF_8).size <= 65536)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key())
val data = cipher.doFinal(config.toByteArray(Charsets.UTF_8))
check(prefs.edit().putString("data", Base64.encodeToString(data, Base64.NO_WRAP))
.putString("iv", Base64.encodeToString(cipher.iv, Base64.NO_WRAP)).commit())
}
fun load(): String? {
private val local = LocalProfileFiles(File(context.filesDir, "MeshPort"), namespace, ::loadLegacy)
val directory: String get() = local.root.absolutePath
private fun loadLegacy(): String? {
val data = prefs.getString("data", null) ?: return null
val iv = prefs.getString("iv", null) ?: error("Missing profile IV")
val iv = prefs.getString("iv", null) ?: error("Missing legacy profile IV")
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val key = store.getKey(alias, null) as? SecretKey ?: error("Legacy profile key unavailable")
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)))
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)))
return cipher.doFinal(Base64.decode(data, Base64.NO_WRAP)).toString(Charsets.UTF_8)
}
fun delete() { check(prefs.edit().clear().commit()) }
fun save(config: String) = local.save(config)
fun load(): String? = local.load()
fun delete() = local.delete()
fun migrationPending(): Boolean = local.migrationPending()
fun migratePending() = local.migratePending()
}
@@ -0,0 +1,68 @@
package com.example.meshport_lab
import org.junit.Test
import org.junit.After
import org.junit.Assert.*
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermissions
class LocalProfileFilesTest {
private val root = Files.createTempDirectory("meshport-profile-tests").toFile()
@After fun cleanup() { Files.walk(root.toPath()).use { it.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists) } }
@Test fun migrationAndReadsUseLocalFilesWithPrivatePermissions() {
var legacyReads = 0
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { legacyReads++; "{\"nodes\":[]}" }
assertEquals("{\"nodes\":[]}", store.load())
store.save("{\"nodes\":[\"fixture\"]}")
assertEquals("{\"nodes\":[\"fixture\"]}", store.load())
assertEquals(1, legacyReads)
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(dir.toPath()))
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(dir.resolve("proxy-profile.json").toPath()))
val reopened = LocalProfileFiles(dir, "proxy") { error("Unexpected legacy access") }
assertEquals(store.load(), reopened.load())
store.delete()
assertNull(store.load())
assertEquals(1, legacyReads)
}
@Test fun failedMigrationIsNotRepeatedAndCanBeRetriedExplicitly() {
var reads = 0
var available = false
val store = LocalProfileFiles(root.resolve("MeshPort"), "profile") {
reads++; check(available); "network_name = \"fixture\""
}
assertNull(store.load())
assertNull(store.load())
assertEquals(1, reads)
assertTrue(store.migrationPending())
available = true
store.migratePending()
assertEquals("network_name = \"fixture\"", store.load())
assertFalse(store.migrationPending())
assertEquals(2, reads)
}
@Test fun rejectedWriteAndCorruptFileDoNotOverwriteValidOrLegacyData() {
var reads = 0
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { reads++; null }
store.save("valid")
assertThrows(IllegalArgumentException::class.java) { store.save("x".repeat(65537)) }
assertEquals("valid", store.load())
Files.write(dir.resolve("proxy-profile.json").toPath(), byteArrayOf(-1))
assertThrows(java.nio.charset.CharacterCodingException::class.java) { store.load() }
assertEquals(0, reads)
}
@Test fun symlinksCannotReadOrOverwriteOutsideFiles() {
val dir = root.resolve("MeshPort")
val store = LocalProfileFiles(dir, "proxy") { null }
store.save("initial")
val outside = root.resolve("outside").apply { writeText("unchanged") }
val profile = dir.resolve("proxy-profile.json").toPath()
Files.delete(profile)
Files.createSymbolicLink(profile, outside.toPath())
assertThrows(IllegalStateException::class.java) { store.load() }
assertThrows(IllegalStateException::class.java) { store.save("replacement") }
assertEquals("unchanged", outside.readText())
}
}
@@ -36,11 +36,12 @@ Future<void> waitForRoutes(
final state = await client.status();
lastState = state;
final platform = state['platform_network'] as Map? ?? {};
// mesh_cidrs is the SDK's routable set (overlay + accepted subnets).
final routes =
platform[installed ? 'installed_subnet_routes' : 'subnet_routes']
platform[installed ? 'installed_subnet_routes' : 'mesh_cidrs']
as List? ??
[];
if (withdrawn ? routes.isEmpty : routes.contains('10.253.79.0/24')) return;
if (routes.contains('10.253.79.0/24') != withdrawn) return;
await Future<void>.delayed(const Duration(milliseconds: 200));
}
debugPrint('ANDROID_ROUTE_TIMEOUT_STATE ${jsonEncode(lastState)}');
@@ -0,0 +1,168 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
const channel = MethodChannel('meshport/system_vpn');
const fixtureHost = String.fromEnvironment('ANDROID_PROXY_FIXTURE');
Future<void> httpsCheck() async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 20);
try {
final request = await client.getUrl(
Uri.parse('https://www.gstatic.com/generate_204'),
);
final reply = await request.close().timeout(const Duration(seconds: 30));
expect(reply.statusCode, 204);
await reply.drain<void>();
} finally {
client.close(force: true);
}
}
Future<void> proxyTcpCheck() async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 10);
try {
final request = await client.getUrl(
Uri.parse('http://198.51.100.45:18082/meshport-device-test'),
);
final reply = await request.close().timeout(const Duration(seconds: 15));
expect(reply.statusCode, 200);
expect(await utf8.decoder.bind(reply).join(), 'MeshPort proxy fixture');
} finally {
client.close(force: true);
}
}
Future<void> udpCheck() async {
final socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
final reply = Completer<Datagram>();
final subscription = socket.listen((event) {
if (event == RawSocketEvent.read) {
final packet = socket.receive();
if (packet != null && !reply.isCompleted) reply.complete(packet);
}
}, onError: reply.completeError);
final payload = utf8.encode('MeshPort Android UDP');
try {
socket.send(payload, InternetAddress('198.51.100.45'), 18083);
expect(
(await reply.future.timeout(const Duration(seconds: 15))).data,
orderedEquals(payload),
);
} finally {
await subscription.cancel();
socket.close();
}
}
Future<void> tunDnsCheck() async {
final socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
final reply = Completer<Datagram>();
final subscription = socket.listen((event) {
if (event == RawSocketEvent.read) {
final packet = socket.receive();
if (packet != null && !reply.isCompleted) reply.complete(packet);
}
}, onError: reply.completeError);
// An uncached name asks the VPN DNS server to use the default encrypted DNS.
final packet = BytesBuilder()
..add([0x4d, 0x50, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0]);
for (final label in 'example.com'.split('.')) {
packet.addByte(label.length);
packet.add(ascii.encode(label));
}
packet.add([0, 0, 1, 0, 1]);
try {
socket.send(packet.toBytes(), InternetAddress('172.19.0.2'), 53);
final data = (await reply.future.timeout(const Duration(seconds: 30))).data;
expect(data.length, greaterThan(12));
expect(data.take(2), [0x4d, 0x50]);
expect(data[3] & 15, 0, reason: 'DNS response must succeed');
expect((data[6] << 8) | data[7], greaterThan(0));
} finally {
await subscription.cancel();
socket.close();
}
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets(
'Android unified VPN default DNS and proxy data plane',
(tester) async {
expect(fixtureHost, isNotEmpty);
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: Center(child: Text('MeshPort Android 代理验证中'))),
),
);
expect(await channel.invokeMethod<bool>('debug_storage_self_test'), true);
await httpsCheck();
debugPrint('ANDROID_BASELINE_HTTPS_PASS');
final profile = ProxyProfile()
..feature = 'proxy'
..mode = 'global'
..entry = 'unified_vpn';
profile.addNodes(
importProxyNodes('socks5://$fixtureHost:18084#Device-test').nodes,
);
profile.validateConnection();
expect(profile.selectedId, profile.nodes.single.id);
expect(profile.effectiveProxyDns, ProxyProfile.defaultProxyDns);
debugPrint('WAITING_FOR_ANDROID_VPN_PERMISSION');
final vpn = await openAndroidSystemVpn(
prepare: () => channel.invokeMethod<void>('prepare_android_vpn'),
request: (request) async =>
jsonDecode(
(await channel.invokeMethod<String>(
'android_vpn_request',
jsonEncode(request),
))!,
)
as Map<String, dynamic>,
);
try {
for (var attempt = 0; attempt < 2; attempt++) {
await vpn.request({
'op': 'start',
'toml': '', // Proxy-only must not require a mesh configuration.
'unified_profile': profile.runtime(),
});
// Wait for system clients to observe the newly established VPN.
await Future<void>.delayed(const Duration(seconds: 2));
final state = await vpn.status();
expect(state['state'], 'Running');
expect(state['platform_network']['ready'], true);
await proxyTcpCheck();
debugPrint('ANDROID_UNIFIED_OS_TCP_PASS_$attempt');
await udpCheck();
debugPrint('ANDROID_UNIFIED_OS_UDP_PASS_$attempt');
await tunDnsCheck();
debugPrint('ANDROID_DEFAULT_DOH_PASS_$attempt');
await httpsCheck();
debugPrint('ANDROID_UNIFIED_HTTPS_PASS_$attempt');
await vpn.stop();
await Future<void>.delayed(const Duration(seconds: 2));
expect((await vpn.status())['state'], 'Stopped');
await httpsCheck();
debugPrint('ANDROID_NETWORK_RESTORED_PASS_$attempt');
}
} catch (_) {
debugPrint(
'ANDROID_UNIFIED_FAILURE_STATE ${jsonEncode(await vpn.status())}',
);
rethrow;
} finally {
await vpn.close();
}
},
timeout: const Timeout(Duration(minutes: 8)),
);
}
+27 -20
View File
@@ -7,26 +7,33 @@ class MeshPortApp extends StatelessWidget {
Widget build(BuildContext context) => MaterialApp(
title: 'MeshPort',
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xff087d8e),
surface: const Color(0xfffaf8f4),
),
scaffoldBackgroundColor: const Color(0xfffaf8f4),
inputDecorationTheme: const InputDecorationTheme(
border: OutlineInputBorder(),
isDense: true,
),
cardTheme: CardThemeData(
elevation: 0,
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: const BorderSide(color: Color(0xffe4e0d9)),
),
),
theme: meshPortTheme(),
home: const LabScreen(
initializeNative: !bool.fromEnvironment('MESHPORT_UI_PREVIEW'),
),
home: const LabScreen(),
);
}
ThemeData meshPortTheme() => ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xff087d8e),
surface: const Color(0xfffaf8f4),
),
scaffoldBackgroundColor: const Color(0xfffaf8f4),
inputDecorationTheme: const InputDecorationTheme(
border: OutlineInputBorder(),
isDense: false,
contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 18),
helperMaxLines: 3,
errorMaxLines: 3,
),
cardTheme: CardThemeData(
elevation: 0,
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: const BorderSide(color: Color(0xffe4e0d9)),
),
),
);
@@ -1,41 +0,0 @@
import 'package:flutter/material.dart';
/// The dialog owns its controller until the route has actually been removed.
class ConfigImportDialog extends StatefulWidget {
const ConfigImportDialog({super.key});
@override
State<ConfigImportDialog> createState() => _ConfigImportDialogState();
}
class _ConfigImportDialogState extends State<ConfigImportDialog> {
final editor = TextEditingController();
@override
void dispose() {
editor.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AlertDialog(
title: const Text('导入 TOML'),
content: SizedBox(
width: 560,
child: TextField(
controller: editor,
maxLines: 12,
autofocus: true,
decoration: const InputDecoration(hintText: '粘贴完整配置。不支持的配置将拒绝导入。'),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(context, editor.text),
child: const Text('校验并连接'),
),
],
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,460 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'network_telemetry.dart';
class LiveDetailPage extends StatefulWidget {
final String title;
final Widget Function() builder;
const LiveDetailPage({super.key, required this.title, required this.builder});
@override
State<LiveDetailPage> createState() => _LiveDetailPageState();
}
class _LiveDetailPageState extends State<LiveDetailPage> {
Timer? timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 820),
child: widget.builder(),
),
),
),
);
}
class NodeDetailBody extends StatelessWidget {
final Map<String, dynamic> node, status;
final Map<String, dynamic>? peer;
const NodeDetailBody({
super.key,
required this.node,
required this.peer,
required this.status,
});
@override
Widget build(BuildContext context) {
// Path and latency source come classified from the SDK `nodes` projection.
final direct = node['path'] == 'direct';
final latency = node['latency_ms'];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'${node['hostname'] ?? node['peer_id']}',
style: Theme.of(context).textTheme.headlineSmall,
),
ListTile(
title: const Text('当前路径'),
subtitle: Text(
'${direct ? '直连' : '中继'} · 下一跳 ${node['next_hop_peer_id'] ?? node['peer_id']}',
),
),
ListTile(
title: const Text('直连能力'),
subtitle: Text(
'${node['direct_available'] == true ? '有直连可用' : '未发现直连'} · ${peer?['hole_punched'] == true ? '打洞建立' : '未确认打洞'}',
),
),
ListTile(
title: Text(node['latency_source'] == 'link_rtt' ? '链路 RTT' : '路由估算'),
subtitle: Text(latency == null ? '未测得' : '$latency ms'),
),
ListTile(
title: const Text('虚拟地址 / NAT'),
subtitle: Text(
'${node['ipv4'] ?? '—'} · ${node['udp_nat_type'] ?? '未知'}',
),
),
ListTile(
title: const Text('当前链路上传 / 下载'),
subtitle: Text(
peer == null
? '通过下一跳,未单独计量'
: '↑ ${formatBytes(peer?['tx_bytes_per_second'], rate: true)} · ↓ ${formatBytes(peer?['rx_bytes_per_second'], rate: true)}',
),
),
ListTile(
title: const Text('链路累计'),
subtitle: Text(
'↑ ${formatBytes(peer?['tx_bytes'])} · ↓ ${formatBytes(peer?['rx_bytes'])}',
),
),
const Text('隧道统计包含控制流量。页面显示最近 SDK 采样;没有采样时间的值不保证是即时测量。'),
const Divider(),
const Text('发布子网'),
for (final subnet in node['advertised_subnets'] as List? ?? [])
ListTile(title: Text('$subnet')),
const Divider(),
Text('核心 ${node['version'] ?? '未知'} · 节点 ID ${node['peer_id']}'),
],
);
}
}
class SubnetListPageBody extends StatelessWidget {
final Map<String, dynamic> status;
final Map<String, dynamic> Function()? statusProvider;
const SubnetListPageBody({
super.key,
required this.status,
this.statusProvider,
});
@override
Widget build(BuildContext context) {
final platform = status['platform_network'] as Map? ?? {};
final accepted = (platform['subnet_routes'] as List? ?? [])
.cast<String>()
.toSet();
final installed = (platform['installed_subnet_routes'] as List? ?? [])
.cast<String>()
.toSet();
final protected = (platform['protected_subnets'] as List? ?? [])
.cast<String>()
.toSet();
final sources = <String, List<Map<String, dynamic>>>{};
for (final row in status['routes'] as List? ?? []) {
for (final subnet in row['advertised_subnets'] as List? ?? []) {
sources
.putIfAbsent('$subnet', () => [])
.add(Map<String, dynamic>.from(row));
}
}
final all = {...sources.keys, ...accepted, ...protected};
final system =
status['runtime_mode'] == 'system_vpn' ||
status['runtime_mode'] == 'unified_vpn';
String label(String subnet) {
if (accepted.contains(subnet)) {
return system
? (platform['ready'] == true &&
(installed.contains(subnet) ||
platform['route_installation'] == 'macos_unified_tun')
? '已生效 · 系统接入'
: '接入中 / 待确认')
: '已生效 · 应用内可用';
}
if (protected.contains(subnet)) return '已失效 · 保护中';
return '已学习 · 未接入(查看详情)';
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'已学习 ${sources.length} · 当前接受 ${accepted.length} · 保护 ${protected.length}',
),
const Text('自动学习合规公告,无远端手动列表。合规判定由 SDK 执行;不接管所有私网。'),
if (all.isEmpty)
const Padding(padding: EdgeInsets.all(24), child: Text('暂无子网公告')),
for (final subnet in all)
Card(
child: ListTile(
title: Text(subnet),
subtitle: Text(label(subnet)),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => LiveDetailPage(
title: '子网详情',
builder: () => SubnetDetailBody(
subnet: subnet,
status: statusProvider?.call() ?? status,
),
),
),
),
),
),
],
);
}
}
class LogsPageBody extends StatefulWidget {
final List<String> logs;
final VoidCallback onClear;
const LogsPageBody({super.key, required this.logs, required this.onClear});
@override
State<LogsPageBody> createState() => _LogsPageBodyState();
}
class _LogsPageBodyState extends State<LogsPageBody> {
bool proxyOnly = false;
List<String> get visibleLogs => proxyOnly
? widget.logs
.where((line) => line.contains('代理') || line.contains('sing-box'))
.toList()
: widget.logs;
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text('显示本次会话最近 300 条事件。代理日志包含连接、目标地址、分流出口及引擎错误。复制保留目标地址,隐藏认证信息。'),
const SizedBox(height: 12),
SegmentedButton<bool>(
segments: const [
ButtonSegment(value: false, label: Text('全部日志')),
ButtonSegment(value: true, label: Text('代理日志')),
],
selected: {proxyOnly},
onSelectionChanged: (selection) =>
setState(() => proxyOnly = selection.single),
),
if (visibleLogs.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Text('暂无日志'),
),
Wrap(
spacing: 12,
children: [
OutlinedButton(
onPressed: () async {
await Clipboard.setData(
ClipboardData(text: widget.logs.join('\n')),
);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('已复制全部 ${widget.logs.length} 条日志')),
);
}
},
child: const Text('复制全部日志'),
),
OutlinedButton(
onPressed: () async {
await Clipboard.setData(
ClipboardData(text: visibleLogs.join('\n')),
);
if (context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('已复制当前日志')));
}
},
child: const Text('复制当前范围'),
),
TextButton(onPressed: widget.onClear, child: const Text('清空显示')),
],
),
for (final line in visibleLogs)
Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: SelectableText(
line,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
),
),
],
);
}
class OnboardingBody extends StatelessWidget {
const OnboardingBody({super.key});
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('欢迎使用 MeshPort', style: Theme.of(context).textTheme.headlineMedium),
const ListTile(
leading: Icon(Icons.hub_outlined),
title: Text('仅组网'),
subtitle: Text('填写网络名称、密钥、虚拟 IP 和引导节点,访问游戏服务器及节点公告子网。'),
),
const ListTile(
leading: Icon(Icons.language),
title: Text('仅代理'),
subtitle: Text('导入或添加代理节点,选择规则 / 全局 / 直连。无需组网凭据。'),
),
const ListTile(
leading: Icon(Icons.route),
title: Text('代理+组网'),
subtitle: Text('两侧配置齐全后连接,组网目标优先。统一 VPN 由一个 TUN 分流。'),
),
const Text(
'应用内入口仅供 SOCKS/SDK 接入,统一 VPN 才接管系统应用。管理员或系统 VPN 授权在连接时请求;默认手动连接,可在启动与后台设置中开启自动连接。',
),
],
);
}
class StartupPageBody extends StatefulWidget {
final MethodChannel channel;
const StartupPageBody({super.key, required this.channel});
@override
State<StartupPageBody> createState() => _StartupPageBodyState();
}
class _StartupPageBodyState extends State<StartupPageBody> {
Map<String, dynamic> preferences = {};
bool loading = true;
String error = '';
@override
void initState() {
super.initState();
unawaited(load());
}
Future<void> load() async {
try {
final status = await widget.channel.invokeMapMethod<String, dynamic>(
'startup_status',
);
if (mounted) setState(() => preferences = status ?? {});
} catch (_) {
if (mounted) setState(() => error = '此平台尚未接入启动管理');
} finally {
if (mounted) setState(() => loading = false);
}
}
Future<void> update(Map<String, dynamic> changes) async {
setState(() {
loading = true;
error = '';
});
try {
final status = await widget.channel.invokeMapMethod<String, dynamic>(
'set_startup',
changes,
);
if (mounted) setState(() => preferences = status ?? {});
} catch (_) {
if (mounted) {
setState(() => error = '设置失败。请将 APP 安装到 Applications,并检查系统登录项权限。');
}
} finally {
if (mounted) setState(() => loading = false);
}
}
@override
Widget build(BuildContext context) => Column(
children: [
if (error.isNotEmpty) Text(error),
const ListTile(
title: Text('启动回填已保存配置'),
subtitle: Text('网络及代理配置从安全存储读取。'),
),
SwitchListTile(
value: preferences['auto_connect'] == true,
onChanged: loading || !(Platform.isMacOS || Platform.isAndroid)
? null
: (v) => update({'auto_connect': v}),
title: const Text('自动连接'),
subtitle: const Text('下次启动按已保存入口与代理开关连接;需要时请求管理员授权。启动失败不反复重试。'),
),
SwitchListTile(
value: [
'enabled',
'requires_approval',
].contains(preferences['login_status']),
onChanged:
loading ||
!Platform.isMacOS ||
preferences['login_status'] == 'unsupported'
? null
: (v) => update({'login': v}),
title: const Text('登录时启动'),
subtitle: Text(
'macOS 13+ · 当前状态:${preferences['login_status'] ?? '读取中'}',
),
),
if (preferences['login_status'] == 'requires_approval')
TextButton(
onPressed: () =>
widget.channel.invokeMethod<void>('open_login_settings'),
child: const Text('打开系统登录项,允许 MeshPort'),
),
TextButton(onPressed: loading ? null : load, child: const Text('刷新系统状态')),
const Text('登录启动与自动连接可分别开启。默认关闭;退出后不会自动重新抢占 VPN。'),
ListTile(
title: const Text('后台运行'),
subtitle: Text(
Platform.isAndroid
? 'VPN 使用前台服务。被其他 VPN 替换时停止。'
: '退出应用会停止网络;订阅定时更新仅在应用运行期间执行。',
),
),
],
);
}
class SubnetDetailBody extends StatelessWidget {
final String subnet;
final Map<String, dynamic> status;
const SubnetDetailBody({
super.key,
required this.subnet,
required this.status,
});
@override
Widget build(BuildContext context) {
final platform = status['platform_network'] as Map? ?? {};
final accepted = (platform['subnet_routes'] as List? ?? []).contains(
subnet,
);
final protected = (platform['protected_subnets'] as List? ?? []).contains(
subnet,
);
final installed = (platform['installed_subnet_routes'] as List? ?? [])
.contains(subnet);
final system = [
'system_vpn',
'unified_vpn',
].contains(status['runtime_mode']);
final ready = platform['ready'] == true;
final sources = (status['routes'] as List? ?? []).where(
(r) => (r['advertised_subnets'] as List? ?? []).contains(subnet),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(subnet, style: Theme.of(context).textTheme.headlineSmall),
Text(
accepted
? (system
? (ready && installed ? '已生效 · 系统接入' : '接入中 / 待确认')
: '已生效 · 应用内可用')
: protected
? '已失效 · 保护中'
: '未接入',
),
for (final source in sources)
ListTile(
title: Text('发布者 ${source['hostname'] ?? source['peer_id']}'),
subtitle: Text(
'节点 ${source['peer_id']} · 下一跳 ${source['next_hop_peer_id'] ?? '未确定'}',
),
),
if (!accepted && !protected)
const Text('SDK 未接受或等待接入;可能为默认路由、公网、过宽子网、本地冲突或不可达。接口暂未提供具体拒绝原因。'),
if (!accepted && protected)
const Text('路径撤销后拒绝转发,不能回退互联网代理。显式停止会话解除保护,可能中断连接。'),
const Text('同 CIDR 发布者合并;实际下一跳由 SDK 选路。状态每 2 秒刷新。'),
],
);
}
}
File diff suppressed because it is too large Load Diff
@@ -13,8 +13,9 @@ String formatBytes(num? value, {bool rate = false}) {
}
class NodeTelemetry extends StatelessWidget {
const NodeTelemetry({super.key, required this.status});
const NodeTelemetry({super.key, required this.status, this.onNode});
final Map<String, dynamic> status;
final void Function(Map<String, dynamic>, Map<String, dynamic>?)? onNode;
@override
Widget build(BuildContext context) {
@@ -22,15 +23,12 @@ class NodeTelemetry extends StatelessWidget {
for (final peer in status['peers'] as List? ?? [])
peer['peer_id']: Map<String, dynamic>.from(peer),
};
final nodes = <dynamic, Map<String, dynamic>>{
for (final route in status['routes'] as List? ?? [])
route['peer_id']: Map<String, dynamic>.from(route),
};
for (final id in peers.keys) {
nodes.putIfAbsent(id, () => {'peer_id': id});
}
// The SDK merges routes and links and classifies path and latency source.
final nodes = [
for (final node in status['nodes'] as List? ?? [])
Map<String, dynamic>.from(node as Map),
];
final local = status['local_peer'] as Map?;
if (local != null) nodes.remove(local['peer_id']);
if (nodes.isEmpty && local == null) {
return const Text('尚未发现节点,连接后显示链路延迟与流量。');
}
@@ -76,71 +74,72 @@ class NodeTelemetry extends StatelessWidget {
),
if (local != null && nodes.isNotEmpty) const Divider(),
if (local != null && nodes.isEmpty) const Text('尚未发现其他节点。'),
...nodes.values.map((node) {
...nodes.map((node) {
final peer = peers[node['peer_id']];
final directAvailable = peer?['direct'] == true;
final direct =
directAvailable &&
(node['next_hop_peer_id'] == null ||
node['next_hop_peer_id'] == node['peer_id']);
final measured = direct ? (peer?['latency_ms'] as num?) : null;
final estimated = node['estimated_latency_ms'] as num?;
final latency = measured ?? estimated;
final latencyLabel = measured != null ? '链路 RTT' : '路由估算';
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
direct ? Icons.link : Icons.alt_route,
size: 20,
color: const Color(0xff087d8e),
),
const SizedBox(width: 10),
Expanded(
child: Text(
'${node['hostname'] ?? '节点 ${node['peer_id']}'}',
style: const TextStyle(fontWeight: FontWeight.w600),
final directAvailable = node['direct_available'] == true;
final direct = node['path'] == 'direct';
final metered = node['metered'] == true;
final latency = node['latency_ms'] as num?;
final latencyLabel = node['latency_source'] == 'link_rtt'
? '链路 RTT'
: '路由估算';
return InkWell(
onTap: onNode == null ? null : () => onNode!(node, peer),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
direct ? Icons.link : Icons.alt_route,
size: 20,
color: const Color(0xff087d8e),
),
),
const SizedBox(width: 10),
Expanded(
child: Text(
'${node['hostname'] ?? '节点 ${node['peer_id']}'}',
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
Text(
latency == null
? '等待测量'
: '${latency.toStringAsFixed(1)} ms',
style: const TextStyle(
color: Color(0xff8a611c),
fontWeight: FontWeight.w600,
),
),
],
),
const SizedBox(height: 6),
Text(
'${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${node['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}',
),
if (node['udp_nat_type'] != null)
Text(
latency == null
? '等待测量'
: '${latency.toStringAsFixed(1)} ms',
style: const TextStyle(
color: Color(0xff8a611c),
fontWeight: FontWeight.w600,
),
'UDP NAT:${node['udp_nat_type']} · 核心 ${node['version'] ?? '未知'}',
),
],
),
const SizedBox(height: 6),
Text(
'${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${direct && peer?['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}',
),
if (node['udp_nat_type'] != null)
if ((node['advertised_subnets'] as List? ?? []).isNotEmpty)
Text(
'发布子网:${(node['advertised_subnets'] as List).join(', ')}',
),
const SizedBox(height: 6),
Text(
'UDP NAT:${node['udp_nat_type']} · 核心 ${node['version'] ?? '未知'}',
!metered
? '流量经下一跳 ${node['next_hop_peer_id'] ?? '—'},未单独计量'
: '↓ ${formatBytes(node['rx_bytes_per_second'] as num?, rate: true)} ↑ ${formatBytes(node['tx_bytes_per_second'] as num?, rate: true)}',
),
if ((node['advertised_subnets'] as List? ?? []).isNotEmpty)
Text(
'发布子网:${(node['advertised_subnets'] as List).join(', ')}',
),
const SizedBox(height: 6),
Text(
peer == null
? '流量经下一跳 ${node['next_hop_peer_id'] ?? '—'},未单独计量'
: '↓ ${formatBytes(peer['rx_bytes_per_second'] as num?, rate: true)} ↑ ${formatBytes(peer['tx_bytes_per_second'] as num?, rate: true)}',
),
if (peer != null)
Text(
'当前链路累计 ↓ ${formatBytes(peer['rx_bytes'] as num?)} ↑ ${formatBytes(peer['tx_bytes'] as num?)}',
style: Theme.of(context).textTheme.bodySmall,
),
],
if (metered)
Text(
'当前链路累计 ↓ ${formatBytes(node['rx_bytes'] as num?)} ↑ ${formatBytes(node['tx_bytes'] as num?)}',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
);
}),
@@ -0,0 +1,381 @@
import 'package:flutter/material.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'configuration_pages.dart';
import 'package:singbox_flutter/singbox_flutter.dart';
class ProxyNodeEditor extends StatefulWidget {
final ProxyNode? node;
const ProxyNodeEditor({super.key, this.node});
@override
State<ProxyNodeEditor> createState() => _ProxyNodeEditorState();
}
String headerText(dynamic value) =>
value is List ? value.map((v) => '$v').join(', ') : value?.toString() ?? '';
class _ProxyNodeEditorState extends State<ProxyNodeEditor> {
late final original = widget.node?.options ?? <String, dynamic>{};
late String protocol = original['type'] as String? ?? 'socks';
late String security = original['tls']?['reality']?['enabled'] == true
? 'reality'
: original['tls']?['enabled'] == true
? 'tls'
: 'none';
late String transport = original['transport']?['type'] as String? ?? 'tcp';
late String cipher = original['method'] as String? ?? 'aes-128-gcm';
late final label = TextEditingController(text: widget.node?.name ?? '我的节点');
late final host = TextEditingController(
text: original['server'] as String? ?? '',
);
late final port = TextEditingController(
text: '${original['server_port'] ?? 1080}',
);
late final username = TextEditingController(
text: original['username'] as String? ?? '',
);
late final password = TextEditingController(
text: original['password'] as String? ?? '',
);
late final uuid = TextEditingController(
text: original['uuid'] as String? ?? '',
);
late final sni = TextEditingController(
text: original['tls']?['server_name'] as String? ?? '',
);
late final publicKey = TextEditingController(
text: original['tls']?['reality']?['public_key'] as String? ?? '',
);
late final shortId = TextEditingController(
text: original['tls']?['reality']?['short_id'] as String? ?? '',
);
late final path = TextEditingController(
text: original['transport']?['path'] as String? ?? '/',
);
late final wsHost = TextEditingController(
text: headerText(original['transport']?['headers']?['Host']),
);
late final service = TextEditingController(
text: original['transport']?['service_name'] as String? ?? '',
);
late final flow = TextEditingController(
text: original['flow'] as String? ?? '',
);
String error = '';
bool dirty = false, testing = false;
String testResult = '';
bool reveal = false;
bool get tlsSupported =>
{'http', 'vmess', 'vless', 'trojan'}.contains(protocol);
bool get transportSupported =>
{'vmess', 'vless', 'trojan'}.contains(protocol);
@override
void dispose() {
for (final c in [
label,
host,
port,
username,
password,
uuid,
sni,
publicKey,
shortId,
path,
wsHost,
service,
flow,
]) {
c.dispose();
}
super.dispose();
}
Widget field(
String title,
TextEditingController controller, {
bool secret = false,
}) => Padding(
padding: const EdgeInsets.only(bottom: 12),
child: TextField(
controller: controller,
onChanged: (_) => setState(() => dirty = true),
obscureText: secret && !reveal,
decoration: InputDecoration(labelText: title),
),
);
Widget choose(
String title,
String value,
List<String> values,
void Function(String) changed,
) => Padding(
padding: const EdgeInsets.only(bottom: 12),
child: DropdownButtonFormField<String>(
isExpanded: true,
key: ValueKey('$title-$value'),
initialValue: value,
decoration: InputDecoration(labelText: title),
items: values
.map((v) => DropdownMenuItem(value: v, child: Text(v)))
.toList(),
onChanged: (v) => setState(() {
changed(v!);
dirty = true;
}),
),
);
ProxyNode draftNode() {
// Preserve supported advanced values on edits, but changing protocol resets
// its options. Imported transports that this form cannot edit use JSON.
final options = <String, dynamic>{
if (original['type'] == protocol) ...original,
'type': protocol,
'server': host.text.trim(),
'server_port': int.tryParse(port.text) ?? 0,
};
if ({'socks', 'http'}.contains(protocol)) {
options['username'] = username.text;
options['password'] = password.text;
if (protocol == 'socks') options['version'] = '5';
}
if ({'trojan', 'shadowsocks'}.contains(protocol)) {
options['password'] = password.text;
}
if ({'vmess', 'vless'}.contains(protocol)) {
options['uuid'] = uuid.text.trim();
}
if (protocol == 'shadowsocks') options['method'] = cipher;
if (protocol == 'vmess') {
options['security'] = original['security'] ?? 'auto';
}
if (protocol == 'vless') {
if (flow.text.trim().isNotEmpty) {
options['flow'] = flow.text.trim();
} else {
options.remove('flow');
}
}
if (tlsSupported && security != 'none') {
final tls = <String, dynamic>{
if (original['type'] == protocol && original['tls'] is Map)
...Map<String, dynamic>.from(original['tls']),
'enabled': true,
'server_name': sni.text.trim().isEmpty
? host.text.trim()
: sni.text.trim(),
};
tls.remove('reality');
if (security == 'reality') {
if (publicKey.text.trim().isEmpty ||
!RegExp(r'^[0-9a-fA-F]{0,16}$').hasMatch(shortId.text) ||
shortId.text.length.isOdd) {
throw const FormatException('Reality 公钥或 Short ID 无效');
}
tls['reality'] = {
'enabled': true,
'public_key': publicKey.text.trim(),
'short_id': shortId.text,
};
tls['utls'] = {
'enabled': true,
'fingerprint': original['tls']?['utls']?['fingerprint'] ?? 'chrome',
};
}
options['tls'] = tls;
} else {
options.remove('tls');
}
options.remove('transport');
if (transportSupported && transport == 'ws') {
options['transport'] = {
if (original['type'] == protocol &&
original['transport']?['type'] == 'ws')
...Map<String, dynamic>.from(original['transport']),
'type': 'ws',
'path': path.text,
'headers': {
if (original['type'] == protocol &&
original['transport']?['headers'] is Map)
...Map<String, dynamic>.from(original['transport']['headers'])
..remove('Host'),
if (wsHost.text.trim().isNotEmpty) 'Host': wsHost.text.trim(),
},
};
}
if (transportSupported && transport == 'grpc') {
options['transport'] = {
if (original['type'] == protocol &&
original['transport']?['type'] == 'grpc')
...Map<String, dynamic>.from(original['transport']),
'type': 'grpc',
'service_name': service.text.trim(),
};
}
final node = ProxyNode(
id: widget.node?.source == 'manual'
? widget.node!.id
: '${DateTime.now().microsecondsSinceEpoch}',
name: label.text.trim().isEmpty ? '我的节点' : label.text.trim(),
options: options,
);
return node;
}
void save() {
try {
final node = draftNode();
setState(() => dirty = false);
Navigator.pop(context, node);
} on FormatException catch (e) {
setState(() => error = e.message);
} catch (_) {
setState(() => error = '节点字段无效');
}
}
Future<void> testDraft() async {
if (testing) return;
setState(() => testing = true);
NativeProxyEngine? engine;
try {
final node = draftNode();
engine = await NativeProxyEngine.open();
final result = await engine.probeNode(node.options);
if (mounted) {
setState(
() => testResult =
'HTTP 检测耗时:${(result['elapsed_ms'] as num).toStringAsFixed(1)} ms · HTTP ${result['status_code']}',
);
}
} catch (_) {
if (mounted) setState(() => testResult = '草稿检测失败,请检查节点配置或网络;没有保存或切换出口。');
} finally {
try {
await engine?.close();
} finally {
if (mounted) setState(() => testing = false);
}
}
}
@override
Widget build(BuildContext context) => PopScope(
canPop: !dirty,
onPopInvokedWithResult: (didPop, result) async {
if (!didPop && await confirmDiscard(context) && context.mounted) {
Navigator.pop(context);
}
},
child: Scaffold(
appBar: AppBar(
title: Text(widget.node?.source == 'manual' ? '编辑节点' : '添加手动节点'),
actions: [
TextButton(
onPressed: testing ? null : save,
child: const Text('保存节点'),
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 16,
children: [
if (error.isNotEmpty)
Text(
error,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
),
if (widget.node != null && widget.node!.source != 'manual')
const Text('订阅节点保持只读,这里保存的是手动副本。'),
field('名称', label),
choose('协议', protocol, supportedProxyTypes.toList(), (v) {
protocol = v;
security = v == 'trojan' ? 'tls' : 'none';
transport = 'tcp';
}),
field('服务器', host),
field('端口', port),
if ({'socks', 'http'}.contains(protocol))
field('用户名(可选)', username),
if ({
'socks',
'http',
'trojan',
'shadowsocks',
}.contains(protocol))
field('密码', password, secret: true),
if ({'vmess', 'vless'}.contains(protocol))
field('UUID', uuid, secret: true),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('显示认证字段'),
value: reveal,
onChanged: (v) => setState(() => reveal = v),
),
if (protocol == 'shadowsocks')
choose(
'加密方法',
cipher,
{
cipher,
'aes-128-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305',
'2022-blake3-aes-128-gcm',
'2022-blake3-aes-256-gcm',
'2022-blake3-chacha20-poly1305',
}.toList(),
(v) => cipher = v,
),
if (protocol == 'vless') field('Flow(可选)', flow),
if (tlsSupported) ...[
choose(
'安全方式',
security,
protocol == 'vless' || security == 'reality'
? ['none', 'tls', 'reality']
: ['none', 'tls'],
(v) => security = v,
),
if (security != 'none') field('TLS Server Name', sni),
if (security == 'reality') ...[
field('Reality 公钥', publicKey),
field('Short ID', shortId),
],
],
if (transportSupported) ...[
choose('传输方式', transport, [
'tcp',
'ws',
'grpc',
], (v) => transport = v),
if (transport == 'ws') ...[
field('WebSocket 路径', path),
field('WebSocket Host(可选)', wsHost),
],
if (transport == 'grpc') field('gRPC Service Name', service),
],
OutlinedButton(
onPressed: testing ? null : testDraft,
child: Text(testing ? '检测中…' : '检测草稿连通性'),
),
if (testResult.isNotEmpty) Text(testResult),
const Text(
'检测使用独立本机引擎访问 HTTPS 测试目标,不保存、不安装路由、不切换运行出口。耗时不等于组网 RTT。',
),
const Text('保存为草稿,不启动正式代理,也不改变正在运行的出口。'),
],
),
),
),
),
),
);
}
@@ -0,0 +1,663 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'proxy_node_editor.dart';
import 'configuration_pages.dart';
import 'proxy_source_pages.dart';
import 'detail_pages.dart';
class ProxyPanel extends StatefulWidget {
final ProxyProfile profile;
final String entry;
final void Function(String) entryChanged;
final bool busy, running;
final bool draftChanged, saving, saveFailed;
final Future<void> Function() save, connect;
final VoidCallback changed;
final VoidCallback? showLogs;
const ProxyPanel({
super.key,
required this.profile,
required this.entry,
required this.entryChanged,
required this.busy,
required this.running,
required this.save,
required this.connect,
required this.changed,
this.showLogs,
this.draftChanged = false,
this.saving = false,
this.saveFailed = false,
});
@override
State<ProxyPanel> createState() => _ProxyPanelState();
}
class _ProxyPanelState extends State<ProxyPanel> {
ProxyProfile get p => widget.profile;
bool working = false;
String error = '';
void change(VoidCallback work) {
setState(() {
work();
error = '';
});
widget.changed();
}
Future<void> act(Future<void> Function() work) async {
if (working || widget.busy) return;
setState(() {
working = true;
error = '';
});
try {
await work();
} catch (e) {
if (mounted) {
setState(
() => error = e is FormatException
? e.message
: '操作失败,请检查配置、网络及概览中的实际运行状态。',
);
}
} finally {
if (mounted) setState(() => working = false);
}
}
Future<bool> confirm(String title, String text) async =>
await showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: Text(title),
content: Text(text),
actions: [
TextButton(
onPressed: () => Navigator.pop(c, false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(c, true),
child: const Text('确认'),
),
],
),
) ??
false;
Future<String?> input(
String title, {
String initial = '',
String hint = '',
bool secret = false,
}) => showDialog<String>(
context: context,
builder: (_) => _TextEditorDialog(
title: title,
initial: initial,
hint: hint,
secret: secret,
),
);
Future<void> importNodes() async {
final preview = await Navigator.push<Object>(
context,
MaterialPageRoute(builder: (_) => const ProxyImportPage()),
);
if (preview == null || !mounted) return;
if (preview is ImportPreview) {
change(() => p.addNodes(preview.nodes));
}
if (preview is Map<String, dynamic>) {
final sub = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => SubscriptionEditor(subscription: preview),
),
);
if (sub != null && mounted) {
final next = Map<String, dynamic>.from(sub)..remove('update');
change(() => p.subscriptions.add(next));
if (sub['update'] == true) await updateSubscription(next);
}
}
}
Future<void> editNode([ProxyNode? existing]) async {
final transport = existing?.options['transport']?['type'];
if (transport != null && !{'ws', 'grpc'}.contains(transport)) {
final value = await input(
'高级节点 JSON',
initial: const JsonEncoder.withIndent(
' ',
).convert({...existing!.options, 'tag': existing.name}),
);
if (value == null) return;
final preview = importProxyNodes(value);
if (preview.nodes.length != 1) throw const FormatException('只接受一个节点');
final node = preview.nodes.single;
change(() {
if (existing.source == 'manual') {
p.nodes[p.nodes.indexWhere((n) => n.id == existing.id)] = ProxyNode(
id: existing.id,
name: node.name,
options: node.options,
);
} else {
p.addNodes([node]);
}
});
return;
}
final node = await Navigator.push<ProxyNode>(
context,
MaterialPageRoute(builder: (_) => ProxyNodeEditor(node: existing)),
);
if (node == null || !mounted) return;
change(
() => existing == null || existing.source != 'manual'
? p.addNodes([node])
: p.nodes[p.nodes.indexWhere((n) => n.id == existing.id)] = node,
);
}
Future<void> editSubscription([Map<String, dynamic>? existing]) async {
final result = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => SubscriptionEditor(subscription: existing),
),
);
if (result == null || !mounted) return;
final next = Map<String, dynamic>.from(result)..remove('update');
change(
() => existing == null
? p.subscriptions.add(next)
: p.subscriptions[p.subscriptions.indexOf(existing)] = next,
);
if (result['update'] == true) await updateSubscription(next);
}
Future<void> updateSubscription(Map<String, dynamic> sub) async {
final source = sub['id'] as String;
final preview = await fetchSubscription(
sub['url'] as String,
source: source,
);
if (preview.nodes.isEmpty) throw const FormatException('订阅没有可用节点,保留原配置');
final old = p.nodes.where((n) => n.source == source).toList();
final replacement = preview.nodes.map((n) {
final retained = old
.where((o) => jsonEncode(o.options) == jsonEncode(n.options))
.firstOrNull;
return ProxyNode(
id: retained?.id ?? n.id,
name: n.name,
source: source,
options: n.options,
);
}).toList();
final removed =
p.selectedId != null &&
old.any((n) => n.id == p.selectedId) &&
!replacement.any((n) => n.id == p.selectedId);
if (!mounted ||
!await confirm(
'订阅更新预览',
'${replacement.length} 个支持节点,忽略 ${preview.unsupported} 个项目。${removed ? '当前选中节点将被删除,需重新选择;正在运行的出口保持到显式重连。' : '相同节点保留选择。'}',
)) {
return;
}
change(() {
replaceSubscription(p, source, preview, DateTime.now());
});
}
Widget subscriptionsBody() {
final disabled = working || widget.busy;
return section('订阅', [
OutlinedButton(
onPressed: disabled ? null : () => act(() => editSubscription()),
child: const Text('添加订阅'),
),
for (final sub in p.subscriptions)
ListTile(
title: Text(sub['name'] as String),
subtitle: Text(
'${sub['updated'] == null ? '尚未更新' : '更新于 ${sub['updated']}'} · ${sub['auto_update'] == true ? '自动更新 ${sub['interval_minutes'] ?? 360} 分钟' : '手动更新'}',
),
trailing: Wrap(
children: [
IconButton(
tooltip: '编辑',
onPressed: disabled
? null
: () => act(() => editSubscription(sub)),
icon: const Icon(Icons.edit_outlined),
),
IconButton(
tooltip: '更新并预览',
onPressed: disabled
? null
: () => act(() => updateSubscription(sub)),
icon: const Icon(Icons.sync),
),
IconButton(
tooltip: '删除订阅及所属节点',
onPressed: disabled
? null
: () => act(() async {
if (await confirm(
'删除订阅',
'删除该来源的节点,手动节点保留;正在运行的出口保持到重连。',
)) {
change(() {
p.nodes.removeWhere((n) => n.source == sub['id']);
p.subscriptions.remove(sub);
if (!p.nodes.any((n) => n.id == p.selectedId)) {
p.selectedId = null;
}
});
}
}),
icon: const Icon(Icons.delete_outline),
),
],
),
),
]);
}
Widget section(String title, List<Widget> children) => Card(
child: Padding(
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(title, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 20),
for (final child in children) ...[child, const SizedBox(height: 18)],
],
),
),
);
@override
Widget build(BuildContext context) {
final disabled = widget.busy || working;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (error.isNotEmpty)
Text(
error,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
section('连接', [
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: p.feature,
decoration: const InputDecoration(labelText: '连接方式'),
items: const [
DropdownMenuItem(value: 'mesh', child: Text('仅组网')),
DropdownMenuItem(value: 'proxy', child: Text('仅代理')),
DropdownMenuItem(value: 'combined', child: Text('代理 + 组网')),
],
onChanged: disabled
? null
: (v) => change(() {
p.feature = v!;
if (widget.entry == 'system_vpn' && v != 'mesh') {
widget.entryChanged('unified_vpn');
}
}),
),
Text(
p.feature == 'mesh'
? '填写组网配置后连接。'
: p.mode == 'direct'
? '直连模式无需代理节点。'
: '导入节点后连接即可,已提供默认加密 DNS。',
),
if (p.feature != 'mesh')
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: p.mode,
decoration: const InputDecoration(labelText: '上网模式'),
items: const [
DropdownMenuItem(value: 'bypass_cn', child: Text('绕过中国大陆')),
DropdownMenuItem(value: 'rule', child: Text('自定义规则')),
DropdownMenuItem(value: 'global', child: Text('全局代理')),
DropdownMenuItem(value: 'direct', child: Text('直连')),
],
onChanged: disabled || p.feature == 'mesh'
? null
: (v) => change(() => p.mode = v!),
),
if (p.mode == 'bypass_cn' && p.feature != 'mesh')
const Text('优先执行自定义分流规则,其余中国大陆 IP 和普通私网直连,其他流量通过代理。首次使用会下载分流规则。'),
Text(
widget.entry == 'application'
? '应用内代理:需要在使用它的软件中设置 SOCKS5 127.0.0.1:10818。'
: widget.entry == 'system_vpn'
? '连接后接入组网地址。'
: '连接后设备流量自动接入。',
),
Wrap(
spacing: 8,
runSpacing: 12,
children: [
FilledButton.icon(
onPressed: disabled ? null : () => act(widget.connect),
icon: Icon(
widget.running && !widget.draftChanged
? Icons.stop
: Icons.power_settings_new,
),
label: Text(
widget.running
? (widget.draftChanged ? '重连应用修改' : '断开连接')
: '连接',
),
),
if (widget.showLogs != null)
OutlinedButton.icon(
onPressed: widget.showLogs,
icon: const Icon(Icons.monitor_heart_outlined),
label: const Text('诊断与日志'),
),
if (widget.saveFailed)
OutlinedButton(
onPressed: disabled ? null : () => act(widget.save),
child: const Text('重试保存'),
),
],
),
Text(
widget.saveFailed
? '配置未保存,请重试。'
: widget.saving
? '正在自动保存…'
: widget.running && widget.draftChanged
? '修改已保存,重连后生效。'
: '配置修改后自动保存。',
),
]),
section('代理节点', [
Wrap(
spacing: 8,
runSpacing: 12,
children: [
OutlinedButton(
onPressed: disabled ? null : () => act(importNodes),
child: const Text('导入与预览'),
),
OutlinedButton(
onPressed: disabled ? null : () => act(() => editNode()),
child: const Text('添加节点'),
),
],
),
if (p.nodes.isEmpty) const Text('导入第一个节点即可开始;多个节点时请选择一个出口。'),
for (final node in p.nodes)
ListTile(
leading: IconButton(
tooltip: '选择出口',
icon: Icon(
p.selectedId == node.id
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
onPressed: disabled
? null
: () => change(() => p.selectedId = node.id),
),
title: Text(
node.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => ProxyNodeDetails(
node: node,
selected: node.id == p.selectedId,
select: () => change(() => p.selectedId = node.id),
edit: () => act(() => editNode(node)),
),
),
),
subtitle: Text(
'${node.options['type']} · ${node.options['server']}:${node.options['server_port']} · ${node.source == 'manual' ? '手动' : '订阅'}',
),
trailing: PopupMenuButton<String>(
enabled: !disabled,
onSelected: (v) => act(() async {
if (v == 'edit') {
await editNode(node);
} else if (await confirm('删除节点', '删除草稿中的节点,不会立即改变正在运行的出口。')) {
change(() {
p.nodes.remove(node);
if (p.selectedId == node.id) p.selectedId = null;
});
}
}),
itemBuilder: (_) => [
PopupMenuItem(
value: 'edit',
child: Text(node.source == 'manual' ? '编辑' : '复制为手动节点'),
),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
),
]),
section('订阅', [
ListTile(
title: const Text('订阅管理'),
subtitle: Text('${p.subscriptions.length} 个来源'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) =>
LiveDetailPage(title: '订阅管理', builder: subscriptionsBody),
),
),
),
]),
Card(
child: ExpansionTile(
key: const PageStorageKey('proxy-advanced'),
title: const Text('高级设置'),
subtitle: const Text('网络入口、DNS 与分流规则'),
children: [
Padding(
padding: const EdgeInsets.fromLTRB(18, 20, 18, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DropdownButtonFormField<String>(
key: ValueKey('entry-${widget.entry}'),
isExpanded: true,
initialValue: widget.entry,
decoration: const InputDecoration(labelText: '网络入口'),
items: const [
DropdownMenuItem(
value: 'application',
child: Text('应用内 SOCKS5'),
),
DropdownMenuItem(
value: 'system_vpn',
child: Text('独立系统组网'),
),
DropdownMenuItem(
value: 'unified_vpn',
child: Text('统一 VPN · 单一 TUN'),
),
],
onChanged: disabled
? null
: (v) => widget.entryChanged(v!),
),
const SizedBox(height: 16),
const Text('修改连接设置后,重连使其生效。'),
const Divider(height: 48),
Text('分流规则', style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 12),
const Text(
'组网地址优先走组网;已失效的已知组网地址拒绝访问。',
style: TextStyle(height: 1.5),
),
const SizedBox(height: 16),
if (p.mode == 'rule' && p.feature != 'mesh') ...[
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: p.defaultAction,
decoration: const InputDecoration(
labelText: '规则模式默认出口',
),
items: const [
DropdownMenuItem(value: 'proxy', child: Text('代理')),
DropdownMenuItem(value: 'direct', child: Text('直连')),
DropdownMenuItem(value: 'mesh', child: Text('组网')),
DropdownMenuItem(value: 'reject', child: Text('拒绝')),
],
onChanged: disabled
? null
: (v) => change(() => p.defaultAction = v!),
),
const SizedBox(height: 16),
],
if (p.mode == 'bypass_cn' && p.feature != 'mesh') ...[
const Text(
'自定义规则优先,其余私网及中国大陆 IP 直连,其他流量走代理。',
style: TextStyle(height: 1.5),
),
const SizedBox(height: 12),
],
Text(
'${p.rules.length} 条普通规则 · '
'${p.ruleSets.where((set) => set['enabled'] == true).length} 个启用规则集 · '
'${{'rule', 'bypass_cn'}.contains(p.mode) && p.feature != 'mesh' ? '按顺序执行' : '已暂停'}',
),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerLeft,
child: OutlinedButton(
onPressed: disabled
? null
: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => RulesPage(
profile: p,
changed: widget.changed,
),
),
),
child: const Text('编辑普通规则'),
),
),
const Divider(height: 48),
Text(
'DNS 设置',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 12),
Text(
'启动 DNS:${p.dnsServer}',
style: const TextStyle(height: 1.5),
),
const SizedBox(height: 8),
Text(
'直连 DNS:${p.directDnsServer.isEmpty ? '启动 DNS' : p.directDnsServer}',
style: const TextStyle(height: 1.5),
),
const SizedBox(height: 8),
Text(
'代理 DNS:${p.effectiveProxyDns}',
style: const TextStyle(height: 1.5),
),
const SizedBox(height: 16),
Align(
alignment: Alignment.centerLeft,
child: OutlinedButton(
onPressed: disabled
? null
: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => DnsPage(
profile: p,
changed: widget.changed,
),
),
),
child: const Text('编辑 DNS'),
),
),
const SizedBox(height: 16),
Text(
'FakeIP:${p.fakeIP ? '开启' : '关闭'} · 组网域名自动排除,解析失败无公共 DNS 回退。',
style: const TextStyle(height: 1.5),
),
],
),
),
],
),
),
],
);
}
}
class _TextEditorDialog extends StatefulWidget {
final String title, initial, hint;
final bool secret;
const _TextEditorDialog({
required this.title,
required this.initial,
required this.hint,
required this.secret,
});
@override
State<_TextEditorDialog> createState() => _TextEditorDialogState();
}
class _TextEditorDialogState extends State<_TextEditorDialog> {
late final controller = TextEditingController(text: widget.initial);
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AlertDialog(
title: Text(widget.title),
content: SizedBox(
width: 520,
child: TextField(
controller: controller,
autofocus: true,
maxLines: widget.secret ? 1 : 8,
obscureText: widget.secret,
decoration: InputDecoration(hintText: widget.hint),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(context, controller.text),
child: const Text('确定'),
),
],
);
}
@@ -0,0 +1,295 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'configuration_pages.dart';
class ProxyImportPage extends StatefulWidget {
const ProxyImportPage({super.key});
@override
State<ProxyImportPage> createState() => _ProxyImportPageState();
}
class _ProxyImportPageState extends State<ProxyImportPage> {
final input = TextEditingController();
ImportPreview? preview;
String error = '';
Future<void> importNative(String method) async {
try {
final text = await const MethodChannel(
'meshport/system_vpn',
).invokeMethod<String>(method);
if (text != null && mounted) {
setState(() {
input.text = text;
preview = null;
error = '';
});
}
} catch (_) {
if (mounted) setState(() => error = '导入失败,请检查文件格式或相机权限;此入口需要平台支持。');
}
}
@override
void dispose() {
input.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('导入代理配置')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'支持分享链接、Base64 和 sing-box JSON;只提取节点,不覆盖 TUN、DNS 或路由。文件和二维码内容先填入编辑框,预览确认后才导入。',
),
Wrap(
spacing: 8,
children: [
OutlinedButton(
onPressed: () => importNative('import_file'),
child: const Text('文件导入'),
),
OutlinedButton(
onPressed: () => importNative('scan_qr'),
child: const Text('相机扫码'),
),
OutlinedButton(
onPressed: () => importNative('import_qr_image'),
child: const Text('二维码图片'),
),
],
),
TextField(
controller: input,
maxLines: 8,
onChanged: (_) => setState(() => preview = null),
decoration: const InputDecoration(labelText: '粘贴配置内容'),
),
if (error.isNotEmpty)
Text(
error,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
OutlinedButton(
onPressed: () {
try {
final p = importProxyNodes(input.text);
setState(() {
preview = p;
error = '';
});
} catch (_) {
setState(() => error = '解析失败:请检查格式、字段和支持协议;输入已保留。');
}
},
child: const Text('解析并预览'),
),
if (input.text.trim().startsWith('https://') &&
!input.text.trim().contains('\n'))
TextButton(
onPressed: () => Navigator.pop(context, <String, dynamic>{
'id': 'subscription-${DateTime.now().microsecondsSinceEpoch}',
'name': '导入的订阅',
'url': input.text.trim(),
}),
child: const Text('作为订阅地址添加'),
),
if (preview != null) ...[
const Text('导入预览'),
Text(
'${preview!.nodes.length} 个支持节点,忽略 ${preview!.unsupported} 个不支持项目',
),
for (final node in preview!.nodes)
ListTile(
title: Text(node.name),
subtitle: Text(
'${node.options['type']} · ${node.options['server']}:${node.options['server_port']}',
),
),
FilledButton(
onPressed: () => Navigator.pop(context, preview),
child: const Text('确认导入'),
),
],
],
),
),
);
}
class SubscriptionEditor extends StatefulWidget {
final Map<String, dynamic>? subscription;
const SubscriptionEditor({super.key, this.subscription});
@override
State<SubscriptionEditor> createState() => _SubscriptionEditorState();
}
class _SubscriptionEditorState extends State<SubscriptionEditor> {
late final name = TextEditingController(
text: widget.subscription?['name'] ?? '',
),
url = TextEditingController(text: widget.subscription?['url'] ?? '');
late bool autoUpdate = widget.subscription?['auto_update'] == true;
late int interval = widget.subscription?['interval_minutes'] ?? 360;
bool reveal = false, dirty = false;
String error = '';
@override
void dispose() {
name.dispose();
url.dispose();
super.dispose();
}
void save(bool update) {
final uri = Uri.tryParse(url.text.trim());
if (uri == null ||
uri.scheme != 'https' ||
uri.host.isEmpty ||
uri.userInfo.isNotEmpty ||
uri.fragment.isNotEmpty ||
name.text.trim().isEmpty) {
setState(() => error = '需要订阅名称和有效 HTTPS 地址,不接受 URL 认证或片段');
return;
}
setState(() => dirty = false);
Navigator.pop(context, {
...?(widget.subscription),
'auto_update': autoUpdate,
'interval_minutes': interval,
'id':
widget.subscription?['id'] ??
'subscription-${DateTime.now().microsecondsSinceEpoch}',
'name': name.text.trim(),
'url': url.text.trim(),
'update': update,
});
}
@override
Widget build(BuildContext context) => DraftScaffold(
title: '编辑订阅',
dirty: dirty,
busy: false,
save: () => save(false),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (error.isNotEmpty) Text(error),
TextField(
controller: name,
onChanged: (_) => setState(() => dirty = true),
decoration: const InputDecoration(labelText: '名称'),
),
TextField(
controller: url,
obscureText: !reveal,
onChanged: (_) => setState(() => dirty = true),
decoration: const InputDecoration(labelText: 'HTTPS 订阅地址'),
),
SwitchListTile(
value: reveal,
onChanged: (v) => setState(() => reveal = v),
title: const Text('显示订阅地址'),
),
SwitchListTile(
title: const Text('自动更新订阅'),
subtitle: const Text('应用运行期间更新;失败保留旧节点,正在运行的会话需重连才能使用新节点。'),
value: autoUpdate,
onChanged: (v) => setState(() {
autoUpdate = v;
dirty = true;
}),
),
if (autoUpdate)
DropdownButtonFormField<int>(
initialValue: interval,
items: [15, 60, 360, 720, 1440, 10080]
.map((v) => DropdownMenuItem(value: v, child: Text('$v 分钟')))
.toList(),
onChanged: (v) => setState(() {
interval = v!;
dirty = true;
}),
),
const Text('保存只修改来源地址;保存并更新会下载到暂存结果,预览确认后才替换该来源节点。手动节点保留。'),
FilledButton(onPressed: () => save(true), child: const Text('保存并更新')),
const SwitchListTile(
value: false,
onChanged: null,
title: Text('自动更新 · 暂未开放'),
),
const Text('下载限制:15 秒超时、1 MiB、禁止 HTTP 跳转。'),
],
),
);
}
class ProxyNodeDetails extends StatelessWidget {
final ProxyNode node;
final bool selected;
final VoidCallback select, edit;
const ProxyNodeDetails({
super.key,
required this.node,
required this.selected,
required this.select,
required this.edit,
});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('代理节点详情')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(node.name, style: Theme.of(context).textTheme.headlineSmall),
ListTile(
title: const Text('来源'),
subtitle: Text(node.source == 'manual' ? '手动节点' : '订阅节点 · 只读'),
),
ListTile(
title: const Text('协议 / 服务器'),
subtitle: Text(
'${node.options['type']} · ${node.options['server']}:${node.options['server_port']}',
),
),
const ListTile(
title: Text('认证字段'),
subtitle: Text('默认隐藏;编辑手动节点或副本时显式查看。'),
),
ListTile(
title: const Text('安全 / 传输'),
subtitle: Text(
'${node.options['tls']?['reality']?['enabled'] == true
? 'Reality'
: node.options['tls']?['enabled'] == true
? 'TLS'
: '无 TLS'} · ${node.options['transport']?['type'] ?? 'tcp'}',
),
),
Text(selected ? '当前草稿选中出口' : '尚未选中;选择不等于启动'),
FilledButton(
onPressed: () {
select();
Navigator.pop(context);
},
child: const Text('选为草稿出口'),
),
OutlinedButton(
onPressed: edit,
child: Text(node.source == 'manual' ? '编辑节点' : '复制为手动节点'),
),
const Text(
'运行出口保持到显式重连;手动节点编辑页支持草稿 HTTP 检测。出口由用户手动选择,HTTP 检测耗时不等于 RTT。',
),
],
),
),
);
}
@@ -0,0 +1,74 @@
import 'dart:async';
import 'dart:io';
class ProxySpeedResult {
final int bytes;
final Duration elapsed;
final Duration firstByte;
const ProxySpeedResult(this.bytes, this.elapsed, this.firstByte);
double get mbps => bytes * 8 / elapsed.inMicroseconds.clamp(1, 1 << 62);
}
/// Explicit loopback HTTP proxy only: never fall back to a physical connection.
class ProxySpeedTest {
HttpClient? _client;
bool _cancelled = false;
static const maxBytes = 32 * 1024 * 1024;
void cancel() {
_cancelled = true;
_client?.close(force: true);
}
Future<ProxySpeedResult> run({
required int port,
Uri? resource,
Duration limit = const Duration(seconds: 15),
void Function(int bytes, Duration elapsed)? onProgress,
}) async {
if (_client != null) throw StateError('测速正在进行');
if (port < 1 || port > 65535) throw ArgumentError('无效代理端口');
_cancelled = false;
final client = HttpClient()..connectionTimeout = const Duration(seconds: 8);
_client = client;
client.findProxy = (_) => 'PROXY 127.0.0.1:$port';
final clock = Stopwatch()..start();
var bytes = 0;
Duration? firstByte;
var timedOut = false;
final timeout = Timer(limit, () {
timedOut = true;
client.close(force: true);
});
try {
final request = await client.getUrl(
resource ??
Uri.parse('https://speed.cloudflare.com/__down?bytes=$maxBytes'),
);
request.followRedirects = false;
request.headers.set(HttpHeaders.acceptEncodingHeader, 'identity');
final response = await request.close();
if (response.statusCode != HttpStatus.ok) {
throw HttpException('测速资源返回 HTTP ${response.statusCode}');
}
await for (final chunk in response) {
if (_cancelled) throw StateError('测速已取消');
firstByte ??= clock.elapsed;
bytes += chunk.length;
onProgress?.call(bytes, clock.elapsed);
if (bytes >= maxBytes) break;
}
} catch (_) {
if (_cancelled) throw StateError('测速已取消');
if (!timedOut || bytes == 0) rethrow;
} finally {
timeout.cancel();
clock.stop();
client.close(force: true);
_client = null;
}
if (_cancelled) throw StateError('测速已取消');
if (bytes == 0) throw StateError('测速未收到数据');
return ProxySpeedResult(bytes, clock.elapsed, firstByte ?? clock.elapsed);
}
}
@@ -0,0 +1,44 @@
/// Keeps known credentials for the whole session, including replaced drafts.
class DiagnosticRedactor {
final _secrets = <String>{};
void remember(Object? value, {String? key}) {
if (value is Map) {
for (final entry in value.entries) {
remember(entry.value, key: '${entry.key}');
}
} else if (value is Iterable) {
for (final item in value) {
remember(item, key: key);
}
} else if (value is String &&
value.isNotEmpty &&
{
'password',
'username',
'uuid',
'network_secret',
'token',
'private_key',
}.contains(key)) {
_secrets.add(value);
}
}
String sanitize(String text) {
final secrets = _secrets.toList()
..sort((a, b) => b.length.compareTo(a.length));
for (final value in secrets) {
text = text.replaceAll(value, '[已隐藏]');
}
text = text.replaceAllMapped(
RegExp(r'([a-zA-Z][a-zA-Z0-9+.-]*://)[^\s/]+@'),
(m) => '${m[1]}[已隐藏]@',
);
text = text.replaceAllMapped(
RegExp(r'([a-zA-Z][a-zA-Z0-9+.-]*://[^\s?]+)\?[^\s]+'),
(m) => '${m[1]}?[已隐藏]',
);
return text;
}
}
+4 -1
View File
@@ -1,4 +1,4 @@
platform :osx, '10.15'
platform :osx, '12.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
@@ -38,5 +38,8 @@ end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_macos_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '12.0'
end
end
end
+16
View File
@@ -0,0 +1,16 @@
PODS:
- FlutterMacOS (1.0.0)
DEPENDENCIES:
- FlutterMacOS (from `Flutter/ephemeral`)
EXTERNAL SOURCES:
FlutterMacOS:
:path: Flutter/ephemeral
SPEC CHECKSUMS:
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
PODFILE CHECKSUM: 13edfb9e70ac3646927b8e6c9a212ad1d0fa29b2
COCOAPODS: 1.16.2
@@ -21,12 +21,15 @@
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
A137C030AA00000000000001 /* LocalProfileStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A137C030AA00000000000002 /* LocalProfileStore.swift */; };
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
4AB602CD95E220C185C9978C /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BBFCA921103BE03628578208 /* Pods_RunnerTests.framework */; };
B0B2671181DD147C22F9DA95 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7A55BFDF956E46C7632C102B /* Pods_Runner.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -60,11 +63,14 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
A137C030AA00000000000002 /* LocalProfileStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalProfileStore.swift; sourceTree = "<group>"; };
092517D44FE622E53982B8F7 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
33CC10ED2044A3C60003C045 /* meshport_lab.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "meshport_lab.app"; sourceTree = BUILT_PRODUCTS_DIR; };
33CC10ED2044A3C60003C045 /* meshport_lab.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = meshport_lab.app; sourceTree = BUILT_PRODUCTS_DIR; };
33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
@@ -76,8 +82,14 @@
33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
393D3BD1764A737A49EE8A67 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = "<group>"; };
671D7CA622257FEE05245595 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = "<group>"; };
7A18F7D923A92E299909B27F /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
7A55BFDF956E46C7632C102B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
927C0C870CC973445A7543D6 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
BBFCA921103BE03628578208 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -85,6 +97,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
4AB602CD95E220C185C9978C /* Pods_RunnerTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -92,6 +105,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
B0B2671181DD147C22F9DA95 /* Pods_Runner.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -125,6 +139,7 @@
331C80D6294CF71000263BE5 /* RunnerTests */,
33CC10EE2044A3C60003C045 /* Products */,
D73912EC22F37F3D000D13A0 /* Frameworks */,
7A80F7A78DF7A6F1790E273C /* Pods */,
);
sourceTree = "<group>";
};
@@ -164,6 +179,7 @@
children = (
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
A137C030AA00000000000002 /* LocalProfileStore.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
@@ -172,9 +188,25 @@
path = Runner;
sourceTree = "<group>";
};
7A80F7A78DF7A6F1790E273C /* Pods */ = {
isa = PBXGroup;
children = (
092517D44FE622E53982B8F7 /* Pods-Runner.debug.xcconfig */,
927C0C870CC973445A7543D6 /* Pods-Runner.release.xcconfig */,
7A18F7D923A92E299909B27F /* Pods-Runner.profile.xcconfig */,
393D3BD1764A737A49EE8A67 /* Pods-RunnerTests.debug.xcconfig */,
0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */,
671D7CA622257FEE05245595 /* Pods-RunnerTests.profile.xcconfig */,
);
name = Pods;
path = Pods;
sourceTree = "<group>";
};
D73912EC22F37F3D000D13A0 /* Frameworks */ = {
isa = PBXGroup;
children = (
7A55BFDF956E46C7632C102B /* Pods_Runner.framework */,
BBFCA921103BE03628578208 /* Pods_RunnerTests.framework */,
);
name = Frameworks;
sourceTree = "<group>";
@@ -186,6 +218,7 @@
isa = PBXNativeTarget;
buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
buildPhases = (
29CF92A05BAD308ACBBCF0A7 /* [CP] Check Pods Manifest.lock */,
331C80D1294CF70F00263BE5 /* Sources */,
331C80D2294CF70F00263BE5 /* Frameworks */,
331C80D3294CF70F00263BE5 /* Resources */,
@@ -204,6 +237,7 @@
isa = PBXNativeTarget;
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
49184CD3D43FEC521263B28B /* [CP] Check Pods Manifest.lock */,
33CC10E92044A3C60003C045 /* Sources */,
33CC10EA2044A3C60003C045 /* Frameworks */,
33CC10EB2044A3C60003C045 /* Resources */,
@@ -291,6 +325,28 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
29CF92A05BAD308ACBBCF0A7 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
3399D490228B24CF009A79C7 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
@@ -329,6 +385,28 @@
shellPath = /bin/sh;
shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";
};
49184CD3D43FEC521263B28B /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -345,6 +423,7 @@
buildActionMask = 2147483647;
files = (
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
A137C030AA00000000000001 /* LocalProfileStore.swift in Sources */,
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
);
@@ -380,6 +459,7 @@
/* Begin XCBuildConfiguration section */
331C80DB294CF71000263BE5 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 393D3BD1764A737A49EE8A67 /* Pods-RunnerTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
@@ -388,12 +468,13 @@
PRODUCT_BUNDLE_IDENTIFIER = com.example.meshportLab.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshport_lab.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshport_lab";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MeshPort.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MeshPort";
};
name = Debug;
};
331C80DC294CF71000263BE5 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
@@ -402,12 +483,13 @@
PRODUCT_BUNDLE_IDENTIFIER = com.example.meshportLab.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshport_lab.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshport_lab";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MeshPort.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MeshPort";
};
name = Release;
};
331C80DD294CF71000263BE5 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 671D7CA622257FEE05245595 /* Pods-RunnerTests.profile.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
@@ -416,7 +498,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.example.meshportLab.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/meshport_lab.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/meshport_lab";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MeshPort.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MeshPort";
};
name = Profile;
};
@@ -461,7 +543,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.15;
MACOSX_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
@@ -543,7 +625,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.15;
MACOSX_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
@@ -593,7 +675,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.15;
MACOSX_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
@@ -15,7 +15,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -31,7 +31,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -66,7 +66,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -83,7 +83,7 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "meshport_lab.app"
BuildableName = "MeshPort.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
@@ -4,4 +4,7 @@
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
@@ -3,10 +3,54 @@ import FlutterMacOS
@main
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
private(set) var statusItem: NSStatusItem?
// Flutter's nib outlet is weak; retain the same window and engine while hidden.
private var retainedMainWindow: NSWindow?
override func applicationDidFinishLaunching(_ notification: Notification) {
// FlutterAppDelegate initializes its UI in applicationWillFinishLaunching;
// it has no applicationDidFinishLaunching implementation to call via super.
retainedMainWindow = mainFlutterWindow
mainFlutterWindow?.isReleasedWhenClosed = false
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
let image = NSImage(systemSymbolName: "network", accessibilityDescription: "MeshPort")
image?.isTemplate = true
item.button?.image = image
item.button?.toolTip = "MeshPort"
item.button?.setAccessibilityLabel("MeshPort")
let menu = NSMenu()
let open = NSMenuItem(title: "打开 MeshPort", action: #selector(showMainWindow), keyEquivalent: "")
open.target = self
menu.addItem(open)
menu.addItem(.separator())
let quit = NSMenuItem(title: "退出 MeshPort", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
quit.target = NSApp
menu.addItem(quit)
item.menu = menu
statusItem = item
}
@objc private func showMainWindow() {
guard let window = retainedMainWindow else { return }
NSApp.activate(ignoringOtherApps: true)
if window.isMiniaturized { window.deminiaturize(nil) }
window.makeKeyAndOrderFront(nil)
}
deinit {
if let item = statusItem { NSStatusBar.system.removeStatusItem(item) }
}
override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
showMainWindow()
return true
}
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return false
}
override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
@@ -10,5 +10,7 @@
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
</dict>
</plist>
@@ -24,6 +24,8 @@
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>$(PRODUCT_COPYRIGHT)</string>
<key>NSCameraUsageDescription</key>
<string>扫描二维码以导入代理或组网配置。</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
@@ -0,0 +1,141 @@
import Foundation
import Security
import Darwin
import LocalAuthentication
enum StoredProfile: CaseIterable {
case proxy, network
var fileName: String { self == .proxy ? "proxy-profile.json" : "network-profile.toml" }
var service: String { self == .proxy ? "MeshPort.Lab.ProxyProfile" : "MeshPort.Lab.NetworkProfile" }
var account: String { self == .proxy ? "last-proxy" : "last-network" }
}
final class LocalProfileStore {
typealias LegacyReader = (StoredProfile, Bool) throws -> Data?
let root: URL
private let legacyReader: LegacyReader
private let fm = FileManager.default
private let limit = 65536
init(root: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Application Support/MeshPort", isDirectory: true),
legacyReader: @escaping LegacyReader = LocalProfileStore.readKeychain) {
self.root = root
self.legacyReader = legacyReader
}
private func failure(_ message: String) -> NSError {
NSError(domain: "MeshPort.LocalProfile", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
}
private func verify(_ url: URL, directory: Bool = false) throws {
let attrs = try fm.attributesOfItem(atPath: url.path)
guard attrs[.type] as? FileAttributeType == (directory ? .typeDirectory : .typeRegular),
(attrs[.ownerAccountID] as? NSNumber)?.uint32Value == getuid() else {
throw failure("Configuration path must be owned by the current user and cannot be a symbolic link")
}
try fm.setAttributes([.posixPermissions: directory ? 0o700 : 0o600], ofItemAtPath: url.path)
}
private func prepare() throws {
if !fm.fileExists(atPath: root.path) {
try fm.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
}
try verify(root, directory: true)
}
private func marker(_ kind: StoredProfile, _ suffix: String) -> URL {
root.appendingPathComponent(".\(kind.fileName).\(suffix)")
}
private func exists(_ url: URL) -> Bool {
// Attributes also detect dangling symlinks, which fileExists follows.
(try? fm.attributesOfItem(atPath: url.path)) != nil
}
private func atomicWrite(_ data: Data, to target: URL) throws {
try prepare()
if exists(target) { try verify(target) }
var template = Array(root.appendingPathComponent(".profile-XXXXXX").path.utf8CString)
let fd = mkstemp(&template)
guard fd >= 0 else { throw failure("Cannot create private configuration file") }
let temporary = String(cString: template)
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
defer { try? handle.close(); unlink(temporary) }
guard fchmod(fd, 0o600) == 0 else { throw failure("Cannot protect configuration file") }
try handle.write(contentsOf: data)
try handle.synchronize()
guard rename(temporary, target.path) == 0 else { throw failure("Cannot replace configuration file") }
}
private func finishMigration(_ kind: StoredProfile) throws {
try atomicWrite(Data(), to: marker(kind, "migrated"))
let pending = marker(kind, "migration-pending")
if exists(pending) { try verify(pending); try fm.removeItem(at: pending) }
}
func save(_ text: String, kind: StoredProfile) throws {
guard let data = text.data(using: .utf8), data.count <= limit else {
throw failure("Configuration exceeds storage limit")
}
try atomicWrite(data, to: root.appendingPathComponent(kind.fileName))
try finishMigration(kind)
}
func load(_ kind: StoredProfile) throws -> String? {
try prepare()
let file = root.appendingPathComponent(kind.fileName)
if exists(file) {
try verify(file)
let size = (try fm.attributesOfItem(atPath: file.path)[.size] as? NSNumber)?.intValue ?? limit + 1
guard size <= limit, let text = String(data: try Data(contentsOf: file), encoding: .utf8) else {
throw failure("Invalid local configuration")
}
return text
}
if exists(marker(kind, "migrated")) || exists(marker(kind, "migration-pending")) { return nil }
// Never show a Keychain dialog during automatic startup migration.
do { return try migrate(kind, interactive: false) }
catch {
try atomicWrite(Data(), to: marker(kind, "migration-pending"))
return nil
}
}
private func migrate(_ kind: StoredProfile, interactive: Bool) throws -> String? {
guard let data = try legacyReader(kind, interactive) else {
try finishMigration(kind)
return nil
}
guard data.count <= limit, let text = String(data: data, encoding: .utf8) else {
throw failure("Invalid legacy configuration")
}
try save(text, kind: kind)
return text
}
func migratePending() throws {
try prepare()
for kind in StoredProfile.allCases where exists(marker(kind, "migration-pending")) {
// Never overwrite local edits with the legacy backup.
if exists(root.appendingPathComponent(kind.fileName)) { try finishMigration(kind) }
else { _ = try migrate(kind, interactive: true) }
}
}
func migrationPending() throws -> Bool {
try prepare()
return StoredProfile.allCases.contains { exists(marker($0, "migration-pending")) }
}
func delete(_ kind: StoredProfile) throws {
try prepare()
let file = root.appendingPathComponent(kind.fileName)
if exists(file) { try verify(file); try fm.removeItem(at: file) }
// A deleted profile must not reappear from the old Keychain backup.
try finishMigration(kind)
}
static func readKeychain(_ kind: StoredProfile, _ interactive: Bool) throws -> Data? {
var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: kind.service, kSecAttrAccount as String: kind.account,
kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]
let authentication = LAContext()
authentication.interactionNotAllowed = !interactive
query[kSecUseAuthenticationContext as String] = authentication
var value: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &value)
if status == errSecItemNotFound { return nil }
guard status == errSecSuccess, let data = value as? Data else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
}
return data
}
}
@@ -1,9 +1,27 @@
import Cocoa
import Security
import FlutterMacOS
import ServiceManagement
import UniformTypeIdentifiers
import AVFoundation
import Vision
import ImageIO
import OSLog
class MainFlutterWindow: NSWindow {
private let runtimeLogger = Logger(subsystem: "com.example.meshportLab", category: "Runtime")
private var vpnChannel: FlutterMethodChannel?
private var qrScanner: MeshQRScanner?
private var importing = false
private let profileStore = LocalProfileStore()
private let profileQueue = DispatchQueue(label: "com.meshport.local-profiles")
override func close() {
// Hiding keeps the Flutter engine, drafts and active network sessions alive.
// Only the explicit Quit action terminates the application.
qrScanner?.cancelScan()
orderOut(nil)
}
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
@@ -13,40 +31,36 @@ class MainFlutterWindow: NSWindow {
RegisterGeneratedPlugins(registry: flutterViewController)
vpnChannel = FlutterMethodChannel(name: "meshport/system_vpn", binaryMessenger: flutterViewController.engine.binaryMessenger)
vpnChannel?.setMethodCallHandler { call, result in
let profileQuery: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "MeshPort.Lab.NetworkProfile",
kSecAttrAccount as String: "last-network"
]
if call.method == "save_profile", let config = call.arguments as? String,
config.utf8.count <= 65536, let data = config.data(using: .utf8) {
let attributes = [kSecValueData as String: data]
var status = SecItemUpdate(profileQuery as CFDictionary, attributes as CFDictionary)
if status == errSecItemNotFound {
var item = profileQuery
item[kSecValueData as String] = data
status = SecItemAdd(item as CFDictionary, nil)
vpnChannel?.setMethodCallHandler { [weak self] call, result in
guard let self = self else { result(FlutterError(code:"WINDOW_CLOSED",message:"Window closed",details:nil)); return }
if self.handleCapabilities(call, result:result) { return }
let profileMethod = call.method.replacingOccurrences(of: "_proxy_profile", with: "_profile")
if ["save_profile", "load_profile", "delete_profile", "profile_storage_status", "migrate_profiles"].contains(profileMethod) {
let kind: StoredProfile = call.method.contains("_proxy_profile") ? .proxy : .network
self.profileQueue.async {
do {
let value: Any?
switch profileMethod {
case "save_profile":
guard let text = call.arguments as? String else {
throw NSError(domain: "MeshPort.LocalProfile", code: 1)
}
try self.profileStore.save(text, kind: kind)
value = nil
case "load_profile": value = try self.profileStore.load(kind)
case "delete_profile": try self.profileStore.delete(kind); value = nil
case "migrate_profiles": try self.profileStore.migratePending(); value = nil
default:
value = ["path": self.profileStore.root.path,
"migration_pending": try self.profileStore.migrationPending()]
}
DispatchQueue.main.async { result(value) }
} catch {
DispatchQueue.main.async {
result(FlutterError(code: "PROFILE_STORAGE", message: "Could not read, save or migrate local configuration", details: (error as NSError).code))
}
}
}
if status == errSecSuccess { result(nil) }
else { result(FlutterError(code: "KEYCHAIN_SAVE", message: "Could not save network profile to Keychain", details: status)) }
return
}
if call.method == "load_profile" {
var query = profileQuery
query[kSecReturnData as String] = true
query[kSecMatchLimit as String] = kSecMatchLimitOne
var value: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &value)
if status == errSecItemNotFound { result(nil) }
else if status == errSecSuccess, let data = value as? Data { result(String(data: data, encoding: .utf8)) }
else { result(FlutterError(code: "KEYCHAIN_LOAD", message: "Could not read network profile", details: status)) }
return
}
if call.method == "delete_profile" {
let status = SecItemDelete(profileQuery as CFDictionary)
if status == errSecSuccess || status == errSecItemNotFound { result(nil) }
else { result(FlutterError(code: "KEYCHAIN_DELETE", message: "Could not delete network profile", details: status)) }
return
}
guard call.method == "launch", let args = call.arguments as? [String: Any],
@@ -77,4 +91,167 @@ class MainFlutterWindow: NSWindow {
}
super.awakeFromNib()
}
private func startupStatus() -> [String: Any] {
var status = "unsupported"
if #available(macOS 13.0, *) {
switch SMAppService.mainApp.status {
case .enabled: status = "enabled"
case .requiresApproval: status = "requires_approval"
case .notRegistered: status = "disabled"
case .notFound: status = "not_found"
@unknown default: status = "unknown"
}
}
return ["login_status":status,"auto_connect":UserDefaults.standard.bool(forKey:"MeshPort.autoConnect")]
}
private func handleCapabilities(_ call: FlutterMethodCall, result: @escaping FlutterResult) -> Bool {
if call.method == "runtime_log" {
guard let message = call.arguments as? String, message.utf8.count <= 8192 else {
result(FlutterError(code: "BAD_LOG", message: "Invalid diagnostic event", details: nil)); return true
}
// Flutter sends only credential-redacted diagnostic events, never profiles.
runtimeLogger.notice("\(message, privacy: .public)")
result(nil); return true
}
if call.method == "startup_status" { result(startupStatus()); return true }
if call.method == "set_startup" {
guard let args = call.arguments as? [String:Any] else { result(FlutterError(code:"BAD_ARGUMENT",message:"Invalid preferences",details:nil));return true }
do {
if let login = args["login"] as? Bool {
if #available(macOS 13.0, *) {
if login { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }
} else { throw NSError(domain:"MeshPort",code:13) }
}
if let connect = args["auto_connect"] as? Bool { UserDefaults.standard.set(connect,forKey:"MeshPort.autoConnect") }
result(startupStatus())
} catch { result(FlutterError(code:"STARTUP_SETTINGS",message:"Unable to update login preferences; install the app in Applications and check System Settings",details:nil)) }
return true
}
if call.method == "open_login_settings" {
if #available(macOS 13.0, *) { SMAppService.openSystemSettingsLoginItems() }
result(nil); return true
}
if call.method == "import_file" || call.method == "import_qr_image" {
guard !importing && qrScanner == nil else { result(FlutterError(code:"IMPORT_BUSY",message:"Import already open",details:nil));return true }
importing = true
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false; panel.canChooseDirectories = false
if #available(macOS 11.0, *) {
panel.allowedContentTypes = call.method == "import_qr_image" ? [.image] : [.text,.json,.data]
}
panel.beginSheetModal(for:self) { [weak self] response in
self?.importing = false
guard response == .OK, let url = panel.url else { result(nil); return }
let access = url.startAccessingSecurityScopedResource()
defer { if access { url.stopAccessingSecurityScopedResource() } }
do {
let size = try url.resourceValues(forKeys:[.fileSizeKey]).fileSize ?? Int.max
let isImage = call.method == "import_qr_image"
guard size <= (isImage ? 20*1024*1024 : 1024*1024) else { throw NSError(domain:"MeshPort",code:1) }
if isImage {
guard let source = CGImageSourceCreateWithURL(url as CFURL,nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source,0,nil) as? [CFString:Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int,
width > 0 && height > 0 && width <= 20000000 / height else { throw NSError(domain:"MeshPort",code:2) }
let request = VNDetectBarcodesRequest(); request.symbologies = [.qr]
try VNImageRequestHandler(url:url,options:[:]).perform([request])
let codes = Set((request.results ?? []).compactMap { $0.payloadStringValue })
guard codes.count == 1, let code = codes.first, code.utf8.count <= 1024*1024 else { throw NSError(domain:"MeshPort",code:3) }
result(code)
} else {
let data = try Data(contentsOf:url)
guard data.count <= 1024*1024, let text = String(data:data,encoding:.utf8) else { throw NSError(domain:"MeshPort",code:4) }
result(text)
}
} catch { result(FlutterError(code:"IMPORT_FAILED",message:"Invalid, oversized file or no unique QR code",details:nil)) }
}
return true
}
if call.method == "scan_qr" {
guard !importing && qrScanner == nil else { result(FlutterError(code:"IMPORT_BUSY",message:"Import already open",details:nil));return true }
importing = true
AVCaptureDevice.requestAccess(for:.video) { [weak self] granted in
DispatchQueue.main.async {
guard let self = self else { result(nil);return }
self.importing = false
guard granted else { result(FlutterError(code:"CAMERA_PERMISSION",message:"Allow camera access in System Settings",details:nil));return }
let scanner = MeshQRScanner { [weak self] text, failed in
self?.qrScanner = nil
if failed { result(FlutterError(code:"CAMERA_FAILED",message:"Camera unavailable",details:nil)) } else { result(text) }
}
self.qrScanner = scanner
scanner.show(on:self)
}
}
return true
}
return false
}
}
// Only the native capture/panel lifetime lives here; Flutter owns imported drafts.
private final class MeshQRPreview: NSView {
let preview: AVCaptureVideoPreviewLayer
init(session:AVCaptureSession) {
preview = AVCaptureVideoPreviewLayer(session:session)
super.init(frame:NSRect(x:0,y:0,width:640,height:400))
wantsLayer = true; preview.videoGravity = .resizeAspectFill
layer?.addSublayer(preview)
}
required init?(coder:NSCoder) { fatalError("init(coder:) unsupported") }
override func layout() { super.layout(); preview.frame = bounds }
}
private final class MeshQRScanner: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, NSWindowDelegate {
let session = AVCaptureSession()
let queue = DispatchQueue(label:"MeshPort.qrCapture")
let completion: (String?,Bool) -> Void
var panel:NSPanel?
weak var parent:NSWindow?
var finished = false, lastFrame = Date.distantPast
init(completion:@escaping (String?,Bool) -> Void) { self.completion = completion }
func show(on window:NSWindow) {
parent = window
let panel = NSPanel(contentRect:NSRect(x:0,y:0,width:640,height:450),styleMask:[.titled,.closable],backing:.buffered,defer:false)
panel.title = "扫描配置二维码"; panel.delegate = self; self.panel = panel
let preview = MeshQRPreview(session:session)
let cancel = NSButton(title:"取消",target:self,action:#selector(cancelScan))
let stack = NSStackView(views:[preview,cancel]); stack.orientation = .vertical; stack.spacing = 8
panel.contentView = stack
preview.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([preview.widthAnchor.constraint(equalToConstant:640),preview.heightAnchor.constraint(equalToConstant:400)])
window.beginSheet(panel)
queue.async { [weak self] in
guard let self = self else { return }
do {
guard let device = AVCaptureDevice.default(for:.video) else { throw NSError(domain:"MeshPort",code:1) }
let input = try AVCaptureDeviceInput(device:device), output = AVCaptureVideoDataOutput()
output.alwaysDiscardsLateVideoFrames = true
output.setSampleBufferDelegate(self,queue:self.queue)
self.session.beginConfiguration()
guard self.session.canAddInput(input), self.session.canAddOutput(output) else { self.session.commitConfiguration(); throw NSError(domain:"MeshPort",code:2) }
self.session.addInput(input);self.session.addOutput(output);self.session.commitConfiguration()
self.session.startRunning()
} catch { DispatchQueue.main.async { self.finish(nil,failed:true) } }
}
}
@objc func cancelScan() { finish(nil,failed:false) }
func windowShouldClose(_ sender:NSWindow) -> Bool { cancelScan();return false }
func finish(_ text:String?,failed:Bool) {
guard !finished else { return }; finished = true
if let panel = panel { parent?.endSheet(panel);panel.orderOut(nil) }
queue.async { [self] in session.stopRunning() }
completion(text,failed)
}
func captureOutput(_ output:AVCaptureOutput,didOutput buffer:CMSampleBuffer,from connection:AVCaptureConnection) {
guard Date().timeIntervalSince(lastFrame) > 0.4 else { return };lastFrame=Date()
let request = VNDetectBarcodesRequest();request.symbologies=[.qr]
do {
guard let image = CMSampleBufferGetImageBuffer(buffer) else { return }
try VNImageRequestHandler(cvPixelBuffer:image,orientation:.up,options:[:]).perform([request])
let codes = Set((request.results ?? []).compactMap { $0.payloadStringValue })
if codes.count == 1, let text = codes.first, text.utf8.count <= 1024*1024 { DispatchQueue.main.async { [weak self] in self?.finish(text,failed:false) } }
} catch { /* A frame may be temporarily unreadable; the user can cancel. */ }
}
}
@@ -8,5 +8,7 @@
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.device.camera</key>
<true/>
</dict>
</plist>
@@ -1,12 +1,49 @@
import Cocoa
import FlutterMacOS
import XCTest
@testable import MeshPort
class RunnerTests: XCTestCase {
func testExample() {
// If you add code to the Runner application, consider adding tests here.
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
func testCloseRetainsControllerAndCanReopenSameWindow() {
let window = MainFlutterWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
styleMask: [.titled, .closable], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
let controller = NSViewController()
controller.view = NSView(frame: window.contentLayoutRect)
window.contentViewController = controller
window.makeKeyAndOrderFront(nil)
XCTAssertTrue(window.isVisible)
window.performClose(nil)
XCTAssertFalse(window.isVisible)
XCTAssertTrue(window.contentViewController === controller)
window.makeKeyAndOrderFront(nil)
XCTAssertTrue(window.isVisible)
XCTAssertTrue(window.contentViewController === controller)
window.orderOut(nil)
}
func testMenuReopensRetainedWindowAndQuitIsExplicit() {
let delegate = AppDelegate()
let window = MainFlutterWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
styleMask: [.titled, .closable], backing: .buffered, defer: false)
delegate.mainFlutterWindow = window
delegate.applicationDidFinishLaunching(Notification(name: NSApplication.didFinishLaunchingNotification))
XCTAssertFalse(delegate.applicationShouldTerminateAfterLastWindowClosed(NSApp))
guard let menu = delegate.statusItem?.menu, let open = menu.items.first,
let action = open.action, let quit = menu.items.last else {
return XCTFail("Menu bar actions missing")
}
XCTAssertEqual(open.title, "打开 MeshPort")
window.close()
XCTAssertFalse(window.isVisible)
XCTAssertTrue(NSApp.sendAction(action, to: open.target, from: open))
XCTAssertTrue(window.isVisible)
XCTAssertTrue(delegate.mainFlutterWindow === window)
XCTAssertEqual(quit.title, "退出 MeshPort")
XCTAssertTrue(quit.target === NSApp)
XCTAssertEqual(quit.action, #selector(NSApplication.terminate(_:)))
window.orderOut(nil)
}
}
+14
View File
@@ -154,6 +154,13 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.13.0"
meshport_client_core:
dependency: "direct main"
description:
path: "../../packages/meshport_client_core"
relative: true
source: path
version: "0.1.0"
meshport_flutter:
dependency: "direct main"
description:
@@ -193,6 +200,13 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.6"
singbox_flutter:
dependency: "direct main"
description:
path: "../../bindings/flutter/singbox_flutter"
relative: true
source: path
version: "0.1.0"
sky_engine:
dependency: transitive
description: flutter
+4
View File
@@ -28,6 +28,10 @@ environment:
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
meshport_client_core:
path: ../../packages/meshport_client_core
singbox_flutter:
path: ../../bindings/flutter/singbox_flutter
meshport_flutter:
path: ../../bindings/flutter/meshport_flutter
flutter:
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/proxy_source_pages.dart';
import 'package:meshport_lab/features/detail_pages.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
void main() {
const channel = MethodChannel('meshport/system_vpn');
tearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null),
);
testWidgets('file import fills draft and requires explicit node preview', (
tester,
) async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
channel,
(call) async =>
call.method == 'import_file' ? 'socks://127.0.0.1:1001' : null,
);
await tester.pumpWidget(const MaterialApp(home: ProxyImportPage()));
await tester.tap(find.text('文件导入'));
await tester.pumpAndSettle();
expect(find.text('确认导入'), findsNothing);
await tester.tap(find.text('解析并预览'));
await tester.pumpAndSettle();
expect(find.text('确认导入'), findsOneWidget);
});
testWidgets('subscription options and metadata survive save', (tester) async {
Map<String, dynamic>? result;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => TextButton(
onPressed: () async {
result = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => const SubscriptionEditor(
subscription: {
'id': 's',
'name': 'Test',
'url': 'https://example.test/sub',
'updated': '2026-10-10T00:00:00Z',
'auto_update': true,
'interval_minutes': 360,
},
),
),
);
},
child: const Text('open'),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
await tester.tap(find.text('自动更新订阅'));
await tester.tap(find.text('保存草稿'));
await tester.pumpAndSettle();
expect(result?['auto_update'], false);
expect(result?['updated'], '2026-10-10T00:00:00Z');
});
testWidgets(
'startup screen reads actual status without registering login item',
(tester) async {
final calls = <String>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
calls.add(call.method);
return {'login_status': 'requires_approval', 'auto_connect': false};
});
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: StartupPageBody(channel: channel)),
),
);
await tester.pumpAndSettle();
expect(find.text('打开系统登录项,允许 MeshPort'), findsOneWidget);
expect(calls, ['startup_status']);
},
);
testWidgets('DoT default port is accepted and saved', (tester) async {
final p = ProxyProfile();
await tester.pumpWidget(
MaterialApp(
home: DnsPage(profile: p, changed: () {}),
),
);
await tester.enterText(find.byType(TextField).at(1), 'tls://dns.example');
await tester.tap(find.text('保存草稿'));
await tester.pumpAndSettle();
expect(p.directDnsServer, 'tls://dns.example');
});
}
@@ -0,0 +1,151 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
void main() {
test('client supplies encrypted default DNS and protects proxy queries', () {
final p = ProxyProfile();
expect(p.runtime()['dns_protection'], true);
expect(p.validateConnection, throwsFormatException);
p.nodes = importProxyNodes('socks://127.0.0.1:1080').nodes;
p.selectedId = p.nodes.single.id;
p.proxyDnsServer = 'tls://resolver.example';
expect(p.validateConnection, returnsNormally);
p.proxyDnsServer = '';
expect(p.runtime()['proxy_dns_server'], ProxyProfile.defaultProxyDns);
expect(p.validateConnection, returnsNormally);
p.mode = 'direct';
expect(p.validateConnection, returnsNormally);
p.mode = 'global';
p.feature = 'mesh';
expect(p.validateConnection, returnsNormally);
});
test('proxy requires a selected node, while direct and mesh do not', () {
final p = ProxyProfile()..proxyDnsServer = 'tls://resolver.example';
for (final mode in ['rule', 'global', 'bypass_cn']) {
p.mode = mode;
expect(p.validateConnection, throwsFormatException);
}
p.nodes = importProxyNodes('socks://127.0.0.1:1080').nodes;
p.selectedId = 'deleted-node';
expect(p.validateConnection, throwsFormatException);
p.selectedId = p.nodes.single.id;
expect(p.validateConnection, returnsNormally);
p.nodes.clear();
p.mode = 'direct';
expect(p.validateConnection, returnsNormally);
p.mode = 'global';
p.feature = 'mesh';
expect(p.validateConnection, returnsNormally);
});
test('China bypass mode persists without rewriting custom rules', () {
final p = ProxyProfile()
..mode = 'bypass_cn'
..defaultAction = 'reject';
p.rules = [
{'type': 'ip_cidr', 'value': '0.0.0.0/0', 'action': 'reject'},
];
final restored = ProxyProfile.fromJson(jsonDecode(jsonEncode(p.toJson())));
expect(restored.mode, 'bypass_cn');
expect(restored.modeLabel, '绕过中国大陆');
expect(restored.rules, p.rules);
restored.mode = 'global';
expect(restored.runtime()['mode'], 'global');
expect(restored.rules, p.rules);
});
test('subscription merge preserves manual node and stable selection', () {
final p = ProxyProfile();
p.nodes = importProxyNodes(
'socks://127.0.0.1:1001\nsocks://127.0.0.1:1002',
source: 's',
).nodes;
final stable = p.nodes.first.id;
p.selectedId = stable;
final manual = importProxyNodes('socks://127.0.0.1:1003').nodes.single;
p.nodes.add(manual);
p.subscriptions = [
{'id': 's', 'auto_update': true, 'interval_minutes': 60},
];
final now = DateTime.utc(2026, 10, 11);
replaceSubscription(
p,
's',
importProxyNodes(
'socks://127.0.0.1:1001\nsocks://127.0.0.1:1004',
source: 's',
),
now,
);
expect(p.nodes.any((n) => identical(n, manual)), true);
expect(p.selectedId, stable);
expect(
subscriptionDue(
p.subscriptions.single,
now.add(const Duration(minutes: 59)),
),
false,
);
expect(
subscriptionDue(
p.subscriptions.single,
now.add(const Duration(hours: 1)),
),
true,
);
replaceSubscription(
p,
's',
importProxyNodes('socks://127.0.0.1:1005', source: 's'),
now,
);
expect(p.selectedId, isNull);
});
test(
'encrypted DNS and rulesets persist without leaking selected node into runtime storage',
() {
final p = ProxyProfile()
..directDnsServer = 'https://dns.example/dns-query'
..proxyDnsServer = 'tls://dns.example'
..proxyEnabled = true;
p.ruleSets = [
{
'tag': 'sites',
'enabled': true,
'rules': [
{
'domain_suffix': ['example.test'],
},
],
'action': 'direct',
},
];
final restored = ProxyProfile.fromJson(
jsonDecode(jsonEncode(p.toJson())),
);
expect(restored.runtime()['direct_dns_server'], p.directDnsServer);
expect(restored.ruleSets, p.ruleSets);
expect(restored.proxyEnabled, true);
for (final value in [
'https://dns.example/dns-query',
'tls://dns.example:853',
'tls://dns.example',
'1.1.1.1',
]) {
expect(validResolver(value), true);
}
for (final value in [
'http://dns.example',
'tls://dns.example/path',
'https://u:p@dns.example',
'https://dns.example:0',
'https://dns.example?x=1',
]) {
expect(validResolver(value), false);
}
},
);
}
@@ -0,0 +1,56 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
void main() {
testWidgets('bypass mode edits custom rules and retains preset fallback', (
tester,
) async {
final profile = ProxyProfile()
..feature = 'proxy'
..mode = 'bypass_cn'
..defaultAction = 'reject';
var saved = false;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) {
return TextButton(
onPressed: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) =>
RulesPage(profile: profile, changed: () => saved = true),
),
),
child: const Text('open'),
);
},
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
expect(find.textContaining('自定义规则和规则集优先'), findsOneWidget);
expect(find.text('当前模式暂停普通规则'), findsNothing);
expect(find.text('固定默认出口'), findsNothing);
expect(find.textContaining('预设默认出口:所选代理'), findsOneWidget);
await tester.tap(find.text('添加规则'));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'example.com');
await tester.tap(find.text('保存规则'));
await tester.pumpAndSettle();
await tester.tap(find.text('保存草稿'));
await tester.pumpAndSettle();
expect(saved, true);
expect(profile.rules.single, {
'type': 'domain_suffix',
'value': 'example.com',
'action': 'proxy',
});
// Keep the custom-mode fallback draft; the engine owns bypass mode's proxy fallback.
expect(profile.defaultAction, 'reject');
expect(profile.mode, 'bypass_cn');
});
}
@@ -0,0 +1,94 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
void main() {
testWidgets('DNS saves FakeIP draft and keeps mesh exclusions', (
tester,
) async {
final p = ProxyProfile()
..meshDns = [
{'suffix': 'mesh.test', 'server': '10.77.0.2'},
];
bool changed = false;
await tester.pumpWidget(
MaterialApp(
home: DnsPage(profile: p, changed: () => changed = true),
),
);
await tester.tap(find.text('FakeIP'));
await tester.pumpAndSettle();
expect(p.fakeIP, isFalse);
await tester.tap(find.text('保存草稿'));
await tester.pumpAndSettle();
expect(p.fakeIP, isTrue);
expect(changed, isTrue);
expect(p.runtime()['mesh_dns'], isNotEmpty);
p.feature = 'proxy';
expect(p.runtime()['mesh_dns'], isEmpty);
});
testWidgets('P2P disable pauses punching without losing values', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: NetworkConfigPage(
section: '连接与打洞',
initial: {
'flags': {'disable_p2p': true, 'disable_udp_hole_punching': true},
},
save: (_) async {},
),
),
);
final switches = tester
.widgetList<SwitchListTile>(find.byType(SwitchListTile))
.toList();
expect(switches[1].onChanged, isNull);
expect(switches[1].value, isTrue);
await tester.tap(find.text('禁用 P2P'));
await tester.pumpAndSettle();
final next = tester
.widgetList<SwitchListTile>(find.byType(SwitchListTile))
.toList();
expect(next[1].onChanged, isNotNull);
expect(next[1].value, isTrue);
});
testWidgets('rule editor rejects wildcard domains', (tester) async {
await tester.pumpWidget(const MaterialApp(home: RuleEditor()));
await tester.enterText(find.byType(TextField), '*.example.com');
await tester.tap(find.text('保存规则'));
await tester.pumpAndSettle();
expect(find.text('请输入有效域名或 CIDR,不接受星号语法'), findsOneWidget);
});
final library = Platform.environment['MESHPORT_LIBRARY'];
test(
'network draft preserves supported options and forces encrypted single-stack host',
() async {
final draft = NetworkProfile({
'runtime_mode': 'unified_vpn',
'ipv4': '10.77.0.11/24',
'network_name': 'test',
'network_secret': 'test-only',
'flags': {'disable_p2p': true},
'listeners': ['udp://0.0.0.0:11010'],
'stun_servers': [],
'optimization': {'mode': 'direct'},
});
final client = await MeshPortClient.open(libraryPath: library);
try {
final toml = await draft.toToml(client);
expect(toml, contains('no_tun = true'));
expect(toml, contains('disable_p2p = true'));
expect(toml, contains('enable_encryption = true'));
expect(toml, contains('stun_servers = []'));
} finally {
await client.close();
}
},
skip: library == null ? 'Requires native Rust library' : false,
);
}
@@ -0,0 +1,93 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
void main() {
testWidgets('IPv4 subnet rule offers all four policies and saves mesh', (
tester,
) async {
Map<String, dynamic>? saved;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) {
return TextButton(
onPressed: () async {
saved = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(builder: (_) => const RuleEditor()),
);
},
child: const Text('open'),
);
},
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
await tester.tap(find.byType(DropdownButtonFormField<String>).first);
await tester.pumpAndSettle();
await tester.tap(find.text('IP CIDR').last);
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), '192.168.50.0/24');
await tester.tap(find.byType(DropdownButtonFormField<String>).last);
await tester.pumpAndSettle();
for (final label in ['代理', '直连', '组网', '拒绝']) {
expect(find.text(label), findsWidgets);
}
await tester.tap(find.text('组网').last);
await tester.pumpAndSettle();
expect(find.textContaining('不会自动发布远端网段'), findsOneWidget);
await tester.tap(find.text('保存规则'));
await tester.pumpAndSettle();
expect(saved, {
'type': 'ip_cidr',
'value': '192.168.50.0/24',
'action': 'mesh',
});
});
testWidgets('mesh rule refuses unsupported IPv6 subnet', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: RuleEditor(
rule: {'type': 'ip_cidr', 'value': 'fd00::/64', 'action': 'mesh'},
),
),
);
await tester.tap(find.text('保存规则'));
await tester.pumpAndSettle();
expect(find.text('组网目前仅支持 IPv4 网段'), findsOneWidget);
});
test('mesh policies and legacy reject survive profile persistence', () {
final profile = ProxyProfile()
..feature = 'combined'
..mode = 'bypass_cn'
..defaultAction = 'mesh'
..rules = [
{'type': 'ip_cidr', 'value': '192.168.50.0/24', 'action': 'mesh'},
{'type': 'domain', 'value': 'blocked.test', 'action': 'reject'},
]
..ruleSets = [
{
'tag': 'group-sites',
'enabled': true,
'action': 'mesh',
'rules': [
{
'domain': ['mesh.test'],
},
],
},
];
final restored = ProxyProfile.fromJson(profile.toJson());
expect(restored.runtime()['rules'], profile.rules);
expect(restored.runtime()['rule_sets'], profile.ruleSets);
expect(restored.defaultAction, 'mesh');
expect(routingPolicyLabel('reject'), '拒绝');
expect(routingPolicyLabel('mesh'), '组网');
});
}
@@ -0,0 +1,127 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/lab_screen.dart';
void main() {
const channel = MethodChannel('meshport/system_vpn');
final binding = TestWidgetsFlutterBinding.ensureInitialized();
// Isolate native startup from bundled personal profiles and external peers.
const localProfile = '''
ipv4 = '10.79.0.10/24'
listeners = []
stun_servers = []
stun_servers_v6 = []
[network_identity]
network_name = 'ui-local-draft'
network_secret = 'test-only'
[flags]
no_tun = true
use_smoltcp = true
disable_p2p = true
[runtime]
mode = 'application'
''';
setUp(
() => binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
(call) async => call.method == 'load_profile' ? localProfile : null,
),
);
tearDown(
() =>
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null),
);
testWidgets(
'form connect starts real native engine and can stop it',
(tester) async {
tester.view.physicalSize = const Size(1400, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const MaterialApp(home: LabScreen()));
final lab = tester.state(find.byType(LabScreen)) as dynamic;
List<String> logs() => (lab.logs as List).cast<String>();
Finder field(String label) => find.byWidgetPredicate(
(widget) =>
widget is TextField && widget.decoration?.labelText == label,
);
Future<void> waitForLog(String text) async {
for (var i = 0; i < 60 && !logs().any((l) => l.contains(text)); i++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 50)),
);
await tester.pump();
}
expect(logs(), contains(contains(text)));
}
await waitForLog('原生库已加载');
// Startup restores profiles first; let it finish before overriding them.
await waitForLog('穿透');
// Mesh-only, in-app engine: no helper, VPN permission or proxy node.
lab.runtimeMode = 'application';
lab.proxyProfile.feature = 'mesh';
lab.proxyProfile.entry = 'application';
await tester.tap(find.text('组网').last);
await tester.pumpAndSettle();
await tester.tap(find.text('基础配置'));
await tester.pumpAndSettle();
await tester.enterText(field('网络名称'), 'ui-local-test');
await tester.enterText(field('网络密钥'), 'test-only');
await tester.enterText(field('虚拟 IPv4 / 前缀'), '10.79.0.11/24');
await tester.tap(find.text('保存草稿'));
await waitForLog('网络配置已保存到');
for (var i = 0; i < 40 && find.text('保存中…').evaluate().isNotEmpty; i++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 50)),
);
await tester.pump();
}
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.text('概览').last);
await tester.pumpAndSettle();
await tester.tap(find.text('连接').last);
await tester.pump(const Duration(milliseconds: 500));
for (
var i = 0;
i < 40 && !logs().any((l) => l.contains('[启动组网引擎] 成功'));
i++
) {
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
expect(logs(), contains(contains('[启动组网引擎] 成功')));
for (
var i = 0;
i < 40 && find.text('引擎运行中 · 0 个节点').evaluate().isEmpty;
i++
) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump();
}
expect(find.text('引擎运行中 · 0 个节点'), findsOneWidget);
expect(find.textContaining('当前设备'), findsOneWidget);
expect(find.textContaining('节点 ID'), findsOneWidget);
await tester.tap(find.text('断开连接'));
for (var i = 0; i < 40 && find.text('尚未连接').evaluate().isEmpty; i++) {
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
expect(find.text('尚未连接'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
},
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
);
}
@@ -1,76 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/lab_screen.dart';
void main() {
testWidgets(
'TOML import starts real native engine and can stop it',
(tester) async {
await tester.pumpWidget(const MaterialApp(home: LabScreen()));
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 500));
});
await tester.pump();
expect(find.textContaining('原生库已加载'), findsOneWidget);
await tester.tap(find.text('设置').last);
await tester.pumpAndSettle();
await tester.tap(find.text('导入'));
await tester.pumpAndSettle();
await tester.tap(find.text('粘贴 TOML 并连接'));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField).last, '''
ipv4 = "10.79.0.11"
listeners = []
stun_servers = []
stun_servers_v6 = []
[network_identity]
network_name = "ui-local-test"
network_secret = "test-only"
[flags]
default_protocol = "udp"
''');
await tester.tap(find.text('校验并连接').last);
await tester.pump(const Duration(milliseconds: 500));
await tester.pumpAndSettle();
for (
var i = 0;
i < 40 && find.textContaining('导入配置并启动引擎').evaluate().isEmpty;
i++
) {
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
expect(find.textContaining('导入配置并启动引擎'), findsOneWidget);
await tester.tap(find.text('概览').last);
await tester.pumpAndSettle();
for (
var i = 0;
i < 40 && find.text('引擎运行中 · 0 个节点').evaluate().isEmpty;
i++
) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump();
}
expect(find.text('引擎运行中 · 0 个节点'), findsOneWidget);
expect(find.textContaining('当前设备'), findsOneWidget);
expect(find.textContaining('节点 ID'), findsOneWidget);
await tester.tap(find.text('断开连接'));
for (var i = 0; i < 40 && find.text('尚未连接').evaluate().isEmpty; i++) {
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
expect(find.text('尚未连接'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
},
skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'),
);
}
@@ -0,0 +1,57 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
void main() {
test('recovers old unlimited sentinel and preserves exact u64 limits', () {
final p = NetworkProfile({
'flags': {'foreign_relay_bps_limit': 18446744073709552000.0},
});
expect(
(p.values['flags'] as Map)['foreign_relay_bps_limit'],
'18446744073709551615',
);
expect(
NetworkProfile.unsignedLimit('18446744073709551614'),
'18446744073709551614',
);
expect(NetworkProfile.unsignedLimit(1024), '1024');
for (final v in [-1, 1.5, '18446744073709551616', 9007199254740992.0]) {
expect(() => NetworkProfile.unsignedLimit(v), throwsFormatException);
}
});
test(
'native projected config regenerates valid TOML after editing entry',
() async {
final client = await MeshPortClient.open(
libraryPath: Platform.environment['MESHPORT_LIBRARY'],
);
try {
final original =
"ipv4 = '192.168.20.4/24'\nlisteners = []\n[network_identity]\nnetwork_name = 'test-only'\nnetwork_secret = 'test-only'\n";
final projected = await client.request({
'op': 'validate',
'toml': original,
'include_profile': true,
});
final p = NetworkProfile(
Map<String, dynamic>.from(projected['profile']),
);
p.values['runtime_mode'] = 'unified_vpn';
final toml = await p.toToml(client);
await client.validate(toml);
expect(
toml,
contains('foreign_relay_bps_limit = "18446744073709551615"'),
);
expect(toml, contains('mode = "application"'));
} finally {
await client.close();
}
},
skip: Platform.environment['MESHPORT_LIBRARY'] == null
? 'Requires native Rust library'
: false,
);
}
+74 -48
View File
@@ -1,3 +1,4 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -21,6 +22,8 @@ void main() {
case 'delete_profile':
stored = null;
return null;
case 'save_proxy_profile':
return null;
default:
throw StateError('Unexpected call: ${call.method}');
}
@@ -31,30 +34,42 @@ void main() {
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null),
);
Future<void> waitFor(WidgetTester tester, Finder finder) async {
for (var i = 0; i < 60 && finder.evaluate().isEmpty; i++) {
// The overview shows only the newest log lines; read the full log list.
List<String> logs(WidgetTester tester) =>
((tester.state(find.byType(LabScreen, skipOffstage: false)) as dynamic)
.logs
as List)
.cast<String>();
Future<void> waitForLog(WidgetTester tester, String text) async {
for (
var i = 0;
i < 100 && !logs(tester).any((line) => line.contains(text));
i++
) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 50)),
);
await tester.pump();
}
expect(finder, findsWidgets);
expect(logs(tester), contains(contains(text)));
}
Future<void> openSettings(WidgetTester tester) async {
Future<void> openApp(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: LabScreen()));
await waitFor(tester, find.textContaining('原生库已加载'));
await waitFor(
tester,
find.byWidgetPredicate(
(widget) =>
widget is Text &&
(widget.data?.contains('已载入默认配置') == true ||
widget.data?.contains('已载入默认网络配置') == true ||
widget.data?.contains('已自动载入保存的网络配置') == true),
),
);
await tester.tap(find.text('设置').last);
await waitForLog(tester, '原生库已加载');
await waitForLog(tester, '载入');
}
Future<void> openPage(WidgetTester tester, String tab, String entry) async {
await tester.tap(find.text(tab).last);
await tester.pumpAndSettle();
await tester.tap(find.text(entry));
await tester.pumpAndSettle();
}
Future<void> back(WidgetTester tester) async {
await tester.pageBack();
await tester.pumpAndSettle();
}
@@ -69,45 +84,36 @@ void main() {
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await openSettings(tester);
await openApp(tester);
await openPage(tester, '组网', '基础配置');
await tester.enterText(field('网络名称'), '我的网络');
await tester.enterText(field('网络密钥'), 'test-only-secret');
await tester.enterText(field('节点名称'), 'saved-node');
await tester.enterText(field('虚拟 IPv4'), '10.79.0.11/24');
await tester.tap(find.text('保存配置'));
await waitFor(tester, find.textContaining('网络配置已保存到 macOS 钥匙串'));
await tester.enterText(field('虚拟 IPv4 / 前缀'), '10.79.0.11/24');
await tester.tap(find.text('保存草稿'));
await waitForLog(tester, '网络配置已保存到');
expect(stored, contains('我的网络'));
expect(find.text('尚未连接'), findsNothing); // The settings page is selected.
await tester.pumpWidget(const SizedBox.shrink());
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await openSettings(tester);
await waitFor(tester, find.textContaining('已自动载入保存的网络配置'));
expect(tester.widget<TextField>(field('网络名称')).controller!.text, '我的网络');
expect(
tester.widget<TextField>(field('网络密钥')).controller!.text,
'test-only-secret',
);
expect(
tester.widget<TextField>(field('节点名称')).controller!.text,
'saved-node',
);
expect(
tester.widget<TextField>(field('虚拟 IPv4')).controller!.text,
'10.79.0.11/24',
);
await tester.tap(find.text('概览').last);
await tester.pumpAndSettle();
expect(find.text('尚未连接'), findsOneWidget);
await tester.tap(find.text('设置').last);
await tester.pumpAndSettle();
await openApp(tester);
await waitForLog(tester, '已自动载入保存的网络配置');
await openPage(tester, '组网', '基础配置');
String text(String label) =>
tester.widget<TextField>(field(label)).controller!.text;
expect(text('网络名称'), '我的网络');
expect(text('网络密钥'), 'test-only-secret');
expect(text('节点名称'), 'saved-node');
expect(text('虚拟 IPv4 / 前缀'), '10.79.0.11/24');
await back(tester);
await openPage(tester, '设置', '默认配置');
await tester.tap(find.text('删除已保存配置'));
await waitFor(tester, find.textContaining('已删除保存的配置'));
await waitForLog(tester, '已删除保存的配置');
expect(stored, isNull);
await tester.pumpWidget(const SizedBox.shrink());
},
skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'),
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
);
testWidgets(
@@ -126,14 +132,34 @@ network_secret = "test-only"
disable_udp_hole_punching = true
''';
final original = stored;
await openSettings(tester);
await waitFor(tester, find.textContaining('已自动载入保存的网络配置'));
await tester.ensureVisible(find.text('保存配置'));
await openApp(tester);
await waitForLog(tester, '已自动载入保存的网络配置');
await openPage(tester, '设置', '默认配置');
await tester.tap(find.text('保存配置'));
await waitFor(tester, find.textContaining('网络配置已保存到 macOS 钥匙串'));
await waitForLog(tester, '网络配置已保存到');
expect(stored, original);
await tester.pumpWidget(const SizedBox.shrink());
},
skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'),
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
);
testWidgets(
'legacy profile is migrated and written back on restore',
(tester) async {
stored = '''
hostname = "legacy-node"
ipv4 = "10.79.0.11/24"
subnet_routes = ["192.168.21.0/24"]
[network_identity]
network_name = "legacy"
network_secret = "test-only"
''';
await openApp(tester);
await waitForLog(tester, '已自动载入保存的网络配置');
expect(stored, isNot(contains('subnet_routes')));
expect(stored, contains('legacy-node'));
await tester.pumpWidget(const SizedBox.shrink());
},
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
);
}
@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/proxy_node_editor.dart';
void main() {
testWidgets('subscription edit saves manual copy and preserves TLS options', (
tester,
) async {
ProxyNode? saved;
final node = ProxyNode(
id: 'subscription-node',
name: 'TLS node',
source: 'subscription-1',
options: {
'type': 'trojan',
'server': 'proxy.example.com',
'server_port': 443,
'password': 'test-secret',
'tls': {
'enabled': true,
'server_name': 'proxy.example.com',
'alpn': ['h2'],
'utls': {'enabled': true, 'fingerprint': 'firefox'},
},
},
);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () async {
saved = await Navigator.push<ProxyNode>(
context,
MaterialPageRoute(
builder: (_) => ProxyNodeEditor(node: node),
),
);
},
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
final password = tester.widget<TextField>(find.byType(TextField).at(3));
expect(password.obscureText, isTrue);
await tester.tap(find.text('保存节点'));
await tester.pumpAndSettle();
expect(saved?.source, 'manual');
expect(saved?.id, isNot(node.id));
expect(saved?.options['tls']['utls']['fingerprint'], 'firefox');
expect(saved?.options['tls']['alpn'], ['h2']);
expect(tester.takeException(), isNull);
});
testWidgets('invalid server cannot be saved', (tester) async {
await tester.pumpWidget(const MaterialApp(home: ProxyNodeEditor()));
await tester.tap(find.text('保存节点'));
await tester.pumpAndSettle();
expect(find.text('代理服务器或端口无效'), findsOneWidget);
});
}
@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/detail_pages.dart';
import 'package:meshport_lab/features/lab_screen.dart';
void main() {
testWidgets('overview offers explicit speed measurement after connection', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
expect(find.text('代理测速'), findsOneWidget);
expect(find.text('连接代理后可测速'), findsOneWidget);
expect(
tester
.widget<FilledButton>(find.widgetWithText(FilledButton, '开始测速'))
.onPressed,
isNull,
);
});
testWidgets('proxy log view excludes unrelated mesh events', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: LogsPageBody(
logs: const [
'12:00:00 代理 · outbound connection',
'12:00:01 穿透 · peer connected',
],
onClear: () {},
),
),
),
);
expect(find.text('12:00:01 穿透 · peer connected'), findsOneWidget);
await tester.tap(find.text('代理日志'));
await tester.pump();
expect(find.text('12:00:01 穿透 · peer connected'), findsNothing);
expect(find.text('12:00:00 代理 · outbound connection'), findsOneWidget);
});
}
@@ -0,0 +1,104 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
void main() {
test(
'full JSON extracts nodes without importing route/DNS and deduplicates',
() {
final value = jsonEncode({
'inbounds': [
{'type': 'tun'},
],
'route': {'final': 'bad'},
'dns': {'servers': []},
'outbounds': [
{'type': 'direct', 'tag': 'D'},
{
'type': 'socks',
'tag': 'A',
'server': '127.0.0.1',
'server_port': 1080,
},
{
'type': 'socks',
'tag': 'B',
'server': '127.0.0.1',
'server_port': 1080,
},
],
});
final preview = importProxyNodes(value);
expect(preview.nodes.length, 1);
expect(preview.unsupported, 1);
expect(preview.nodes.single.options.containsKey('route'), false);
},
);
test('URI/Base64 supports credentials and TLS without logging inputs', () {
final input =
'vless://00000000-0000-0000-0000-000000000001@example.test:443?security=tls&sni=example.test&type=ws&path=%2Fmesh#Node';
final node = importProxyNodes(
base64.encode(utf8.encode(input)),
).nodes.single;
expect(node.options['type'], 'vless');
expect(node.options['tls']['enabled'], true);
expect(node.options['transport']['path'], '/mesh');
final ss = importProxyNodes(
'ss://${base64.encode(utf8.encode('aes-128-gcm:test-only'))}@example.test:8388#SS',
).nodes.single;
expect(ss.options['method'], 'aes-128-gcm');
expect(ss.options['password'], 'test-only');
});
test(
'rejects invalid credential fields, oversize input and injected dialer',
() {
for (final raw in [
'{"type":"socks","server":"a.test","server_port":0}',
'{"type":"vless","server":"a.test","server_port":443,"uuid":"invalid"}',
'{"type":"socks","server":"a.test","server_port":1080,"detour":"meshport"}',
]) {
expect(() => importProxyNodes(raw), throwsFormatException);
}
expect(
() => importProxyNodes('x' * (1024 * 1024 + 1)),
throwsFormatException,
);
},
);
test(
'profile round trip preserves subscription provenance and selection',
() {
final p = ProxyProfile();
p.nodes = importProxyNodes(
'socks5://user:test-only@example.test:1080#Node',
source: 'source-1',
).nodes;
p.selectedId = p.nodes.single.id;
p.mode = 'global';
p.subscriptions = [
{
'id': 'source-1',
'name': 'Source',
'url': 'https://example.test/sub?token=test-only',
},
];
final loaded = ProxyProfile.fromJson(
jsonDecode(jsonEncode(p.toJson())) as Map<String, dynamic>,
);
expect(loaded.selectedId, p.selectedId);
expect(loaded.nodes.single.source, 'source-1');
expect(loaded.runtime()['proxy']['password'], 'test-only');
expect(loaded.mode, 'global');
},
);
test('subscription requires HTTPS without auth URL', () async {
await expectLater(
fetchSubscription('http://example.test/sub', source: 's'),
throwsFormatException,
);
await expectLater(
fetchSubscription('https://user:password@example.test/sub', source: 's'),
throwsFormatException,
);
});
}
@@ -0,0 +1,387 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:singbox_flutter/singbox_flutter.dart';
class FakeProxy implements ProxyEngine {
final List<String> events;
String state = 'Stopped';
bool failStart = false;
Map<String, dynamic>? lastProfile;
FakeProxy(this.events);
@override
Future<Map<String, dynamic>> start({
required int port,
required String meshSocks,
required List<String> prefixes,
Map<String, dynamic>? profile,
}) async {
lastProfile = profile;
events.add('proxy.start:${prefixes.join(',')}');
if (failStart) throw StateError('occupied port');
state = 'Running';
return {'state': state};
}
@override
Future<Map<String, dynamic>> status() async => {'state': state};
@override
Future<void> stop() async {
events.add('proxy.stop');
state = 'Stopped';
}
@override
Future<void> close() async {
events.add('proxy.close');
}
}
class Fixture {
final events = <String>[];
late final proxy = FakeProxy(events);
late final mesh = MeshPortClient.fromTransport(
request: request,
close: () async {},
);
late final session = MeshProxySession(mesh: mesh, proxy: proxy);
String state = 'Stopped', mode = 'application';
bool bridge = false;
// SDK projection: canonical overlay network plus accepted subnets.
String? overlay = '10.77.0.0/24';
List<String> routes = ['192.168.21.0/24'];
List<String> get cidrs => {?overlay, ...routes}.toList()..sort();
int generation = 1;
var _routesChanged = Completer<void>();
void _wake() {
_routesChanged.complete();
_routesChanged = Completer<void>();
}
/// Publishes a route change the way the SDK watch does.
void announceRoutes(List<String> next) {
routes = next;
generation++;
_wake();
}
Future<Map<String, dynamic>> request(Map<String, dynamic> input) async {
final op = input['op'] as String;
if (op == 'wait_routes') {
// Long poll: not logged so lifecycle event assertions stay exact.
if (state == 'Running' && input['after_generation'] == generation) {
await _routesChanged.future;
}
final running = state == 'Running';
return {
'ok': true,
'data': {
'running': running,
'changed': !running || input['after_generation'] != generation,
'route_generation': running ? generation : null,
'mesh_cidrs': running ? cidrs : [],
},
};
}
events.add('mesh.$op');
if (op == 'start_bridged') {
if (mode != 'application') {
return {'ok': false, 'error': 'bridged routing requires application'};
}
if (state != 'Stopped') return {'ok': false, 'error': 'already started'};
}
final data = switch (op) {
'start_bridged' => (() {
state = 'Running';
bridge = true;
return <String, dynamic>{
'listen': '127.0.0.1:50001',
'route_generation': generation,
};
})(),
'stop' => (() {
state = 'Stopped';
_wake();
return <String, dynamic>{};
})(),
'socks_stop' => (() {
bridge = false;
return <String, dynamic>{};
})(),
'status' => {
'state': state,
'platform_network': {'mesh_cidrs': state == 'Running' ? cidrs : []},
'health': {
'engine_running': state == 'Running',
'bridge_running': state == 'Running' && bridge,
'mesh_routable': state == 'Running' && bridge,
},
},
_ => <String, dynamic>{},
};
return {'ok': true, 'data': data};
}
}
void main() {
test(
'joint lifecycle, canonical routes, update and ordered cleanup',
() async {
final f = Fixture();
await f.session.start('test');
expect(f.session.state, 'Running');
expect(f.session.endpoint, '127.0.0.1:10818');
final starts = f.events.where((e) => e.startsWith('proxy.start')).length;
await f.session.refresh();
expect(f.events.where((e) => e.startsWith('proxy.start')).length, starts);
f.routes = ['192.168.22.0/24'];
await f.session.refresh();
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.22.0/24');
expect(f.proxy.lastProfile?['protected_cidrs'], [
'10.77.0.0/24',
'192.168.21.0/24',
'192.168.22.0/24',
]);
f.events.clear();
await f.session.stop();
expect(f.events, ['proxy.stop', 'mesh.socks_stop', 'mesh.stop']);
await f.session.start('test');
await f.session.close();
expect(f.events.last, 'proxy.close');
await expectLater(f.session.start('test'), throwsStateError);
},
);
test('route changes are applied from the SDK watch without a poll', () async {
final f = Fixture();
await f.session.start('test');
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.21.0/24');
f.announceRoutes(['192.168.23.0/24']);
for (var i = 0; i < 50 && !f.events.last.contains('192.168.23.0'); i++) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.23.0/24');
expect(f.session.state, 'Running');
f.events.clear();
await f.session.stop();
expect(f.events, ['proxy.stop', 'mesh.socks_stop', 'mesh.stop']);
await f.session.close();
});
test('failed engine startup rolls back and permits retry', () async {
final f = Fixture();
f.proxy.failStart = true;
await expectLater(f.session.start('test'), throwsStateError);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
expect(f.events.sublist(f.events.length - 3), [
'proxy.stop',
'mesh.socks_stop',
'mesh.stop',
]);
f.proxy.failStart = false;
await f.session.start('test');
await f.session.close();
});
test(
'queue prevents concurrent duplicate starts; system mode is refused',
() async {
final f = Fixture();
final first = f.session.start('test');
final duplicate = f.session.start('test');
await expectLater(duplicate, throwsStateError);
await first;
expect(f.events.where((e) => e == 'mesh.start_bridged').length, 1);
await f.session.stop();
f.mode = 'system_vpn';
await expectLater(f.session.start('test'), throwsStateError);
await f.session.close();
},
);
test(
'wait for DHCP then start; unexpected engine failure cleans mesh',
() async {
final f = Fixture();
f.overlay = null;
f.routes = [];
await f.session.start('test');
expect(f.session.state, 'AwaitingAddress');
f.overlay = '10.77.0.0/24';
await f.session.refresh();
expect(f.session.state, 'Running');
f.proxy.state = 'Failed';
await expectLater(f.session.refresh(), throwsStateError);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
await f.session.close();
},
);
test('mesh prefixes are read from the SDK projection only', () {
expect(
meshPrefixes({
'ipv4': '10.77.0.11/24',
'platform_network': {
'subnet_routes': ['0.0.0.0/0'],
'mesh_cidrs': ['10.77.0.0/24', '192.168.21.0/24'],
},
}),
['10.77.0.0/24', '192.168.21.0/24'],
);
expect(meshPrefixes({'ipv4': '10.77.0.11/24'}), isEmpty);
expect(
() => meshPrefixes({
'platform_network': {
'mesh_cidrs': [7],
},
}),
throwsStateError,
);
});
test('a busy context is refused without stopping its network', () async {
final f = Fixture();
f.state = 'Running';
await expectLater(f.session.start('test'), throwsStateError);
expect(f.events.where((e) => e == 'mesh.stop'), isEmpty);
expect(f.state, 'Running');
await f.session.close();
});
test(
'mesh-only session fails when the SDK reports the bridge down',
() async {
final f = Fixture();
await f.session.start('test');
f.bridge = false;
await expectLater(
f.session.refresh(),
throwsA(
isA<StateError>().having(
(e) => e.message,
'message',
'Mesh bridge stopped unexpectedly',
),
),
);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
await f.session.close();
},
);
test(
'proxy-only session does not start mesh or require network credentials',
() async {
final f = Fixture();
final session = MeshProxySession(
mesh: f.mesh,
proxy: f.proxy,
profile: {'feature': 'proxy', 'mode': 'direct'},
);
await session.start('invalid mesh config');
expect(session.state, 'Running');
expect(
f.events.where(
(e) => e.startsWith('mesh.start') || e == 'mesh.validate',
),
isEmpty,
);
expect(f.proxy.lastProfile?['feature'], 'proxy');
await session.close();
},
);
test(
'combined keeps proxy available and protects mesh when native network stops',
() async {
final f = Fixture();
final session = MeshProxySession(
mesh: f.mesh,
proxy: f.proxy,
profile: {'feature': 'combined', 'mode': 'global'},
);
await session.start('test');
f.state = 'Stopped';
await session.refresh();
expect(session.state, 'Partial');
expect(session.endpoint, isNotNull);
expect(f.proxy.lastProfile?['protected_cidrs'], [
'10.77.0.0/24',
'192.168.21.0/24',
]);
await session.close();
},
);
final path = Platform.environment['MESHPORT_PROXY_LIBRARY'];
test(
'native Go ABI loads from Dart, releases listeners and closes context',
() async {
final listener = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = listener.port;
await listener.close();
final engine = await NativeProxyEngine.open(libraryPath: path);
expect((await engine.status())['state'], 'Stopped');
await engine.start(
port: port,
meshSocks: '127.0.0.1:9',
prefixes: ['10.77.0.0/24'],
);
expect((await engine.status())['state'], 'Running');
final socket = await Socket.connect('127.0.0.1', port);
await engine.close();
expect(
await socket
.fold<int>(0, (count, bytes) => count + bytes.length)
.timeout(const Duration(seconds: 2)),
0,
);
socket.destroy();
final reused = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
port,
);
await reused.close();
await expectLater(engine.status(), throwsStateError);
},
skip: path == null
? 'Set MESHPORT_PROXY_LIBRARY after building native library'
: false,
);
final meshPath = Platform.environment['MESHPORT_LIBRARY'];
test(
'Rust and Go coexist in one Dart process with joint native cleanup',
() async {
final mesh = await MeshPortClient.open(libraryPath: meshPath);
final engine = await NativeProxyEngine.open(libraryPath: path);
final reserve = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = reserve.port;
await reserve.close();
final session = MeshProxySession(mesh: mesh, proxy: engine, port: port);
try {
await session.start(
"ipv4 = '10.253.82.11/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = []\n[network_identity]\nnetwork_name = 'native-lifecycle-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true\n",
);
expect(session.state, 'Running');
expect((await mesh.socksBridgeStatus())['running'], true);
final socket = await Socket.connect('127.0.0.1', port);
await session.stop();
expect(
await socket
.fold<int>(0, (n, b) => n + b.length)
.timeout(const Duration(seconds: 2)),
0,
);
socket.destroy();
expect((await mesh.status())['state'], 'Stopped');
expect((await mesh.socksBridgeStatus())['running'], false);
final reuse = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
port,
);
await reuse.close();
} finally {
await session.close();
await mesh.close();
}
},
skip: path == null || meshPath == null
? 'Set both native library paths'
: false,
);
}
@@ -0,0 +1,279 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/proxy_speed_test.dart';
void main() {
test(
'speed conversion uses decimal Mbps and preserves first-byte timing',
() {
const result = ProxySpeedResult(
1250000,
Duration(seconds: 1),
Duration(milliseconds: 20),
);
expect(result.mbps, 10);
expect(result.mbps / 8, 1.25);
expect(result.firstByte.inMilliseconds, 20);
expect(
const ProxySpeedResult(1, Duration.zero, Duration.zero).mbps.isFinite,
isTrue,
);
},
);
test('invalid proxy ports are rejected before starting a request', () async {
for (final port in [0, -1, 65536]) {
await expectLater(ProxySpeedTest().run(port: port), throwsArgumentError);
}
});
test('an empty response does not produce a speed result', () async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => proxy.close(force: true));
proxy.listen((request) => request.response.close());
await expectLater(
ProxySpeedTest().run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/empty'),
),
throwsStateError,
);
});
test('redirect responses are not followed', () async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => proxy.close(force: true));
var calls = 0;
proxy.listen((request) async {
calls++;
request.response.statusCode = HttpStatus.found;
request.response.headers.set(
HttpHeaders.locationHeader,
'http://speed-test.invalid/other',
);
await request.response.close();
});
await expectLater(
ProxySpeedTest().run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/redirect'),
),
throwsA(isA<HttpException>()),
);
expect(calls, 1);
});
test(
'overlapping runs are rejected and a completed tester can be reused',
() async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final arrived = Completer<void>();
final release = Completer<void>();
addTearDown(() async {
if (!release.isCompleted) release.complete();
await proxy.close(force: true);
});
proxy.listen((request) async {
if (!arrived.isCompleted) arrived.complete();
await release.future;
request.response.add(List.filled(4096, 42));
await request.response.close();
});
final speed = ProxySpeedTest();
final resource = Uri.parse('http://speed-test.invalid/reuse');
final first = speed.run(port: proxy.port, resource: resource);
await arrived.future.timeout(const Duration(seconds: 3));
await expectLater(
speed.run(port: proxy.port, resource: resource),
throwsStateError,
);
release.complete();
expect((await first).bytes, 4096);
expect(
(await speed.run(port: proxy.port, resource: resource)).bytes,
4096,
);
},
);
test(
'a timed-out partial download reports only the received bytes',
() async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final release = Completer<void>();
addTearDown(() async {
if (!release.isCompleted) release.complete();
await proxy.close(force: true);
});
proxy.listen((request) async {
try {
request.response.add(List.filled(65536, 42));
await request.response.flush();
await release.future;
await request.response.close();
} on IOException {
// The test intentionally closes the client before the response ends.
}
});
final result = await ProxySpeedTest().run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/slow'),
limit: const Duration(milliseconds: 500),
);
expect(result.bytes, 65536);
expect(result.mbps, greaterThan(0));
expect(result.firstByte, lessThanOrEqualTo(result.elapsed));
},
);
test(
'timeout before any data fails and cancellation permits a fresh run',
() async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final release = Completer<void>();
addTearDown(() async {
if (!release.isCompleted) release.complete();
await proxy.close(force: true);
});
proxy.listen((request) async {
try {
if (request.uri.path == '/no-data') await release.future;
request.response.add(List.filled(4096, 42));
await request.response.close();
} on IOException {
// The no-data request is intentionally interrupted.
}
});
final speed = ProxySpeedTest();
await expectLater(
speed.run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/no-data'),
limit: const Duration(milliseconds: 200),
),
throwsA(anyOf(isA<IOException>(), isA<StateError>())),
);
await expectLater(
speed.run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/cancel'),
onProgress: (_, _) => speed.cancel(),
),
throwsStateError,
);
expect(
(await speed.run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/fresh'),
)).bytes,
4096,
);
},
);
test(
'large responses stop at the transfer cap instead of reading to EOF',
() async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => proxy.close(force: true));
final chunk = List.filled(1024 * 1024, 42);
proxy.listen((request) async {
try {
for (var i = 0; i < 40; i++) {
request.response.add(chunk);
await request.response.flush();
}
await request.response.close();
} on IOException {
// The cap intentionally closes the response mid-stream.
}
});
final result = await ProxySpeedTest().run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/large'),
);
// Network chunks can cross the cap; overshoot is bounded by a received chunk.
expect(
result.bytes,
inInclusiveRange(
ProxySpeedTest.maxBytes,
ProxySpeedTest.maxBytes + chunk.length,
),
);
expect(result.bytes, lessThan(40 * chunk.length));
},
);
test('download uses explicit proxy without resolving the target', () async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => proxy.close(force: true));
var calls = 0;
proxy.listen((request) async {
calls++;
expect(request.uri.host, 'speed-test.invalid');
request.response.add(List.filled(65536, 42));
await request.response.close();
});
final result = await ProxySpeedTest().run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/download'),
);
expect(calls, 1);
expect(result.bytes, 65536);
expect(result.mbps, greaterThan(0));
});
test('unavailable proxy never falls back to direct origin', () async {
final origin = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => origin.close(force: true));
var calls = 0;
origin.listen((request) {
calls++;
request.response.close();
});
final reserved = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = reserved.port;
await reserved.close();
await expectLater(
ProxySpeedTest().run(
port: port,
resource: Uri.parse('http://127.0.0.1:${origin.port}/'),
),
throwsA(isA<SocketException>()),
);
expect(calls, 0);
});
test(
'cancellation and error responses do not produce a speed result',
() async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => proxy.close(force: true));
proxy.listen((request) async {
if (request.uri.path == '/failure') {
request.response.statusCode = 503;
} else {
request.response.add(List.filled(65536, 42));
}
await request.response.close();
});
final speed = ProxySpeedTest();
await expectLater(
speed.run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/failure'),
),
throwsA(isA<HttpException>()),
);
await expectLater(
speed.run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/download'),
onProgress: (_, _) => speed.cancel(),
),
throwsStateError,
);
},
);
}
@@ -0,0 +1,71 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/app.dart';
import 'package:meshport_lab/features/configuration_pages.dart';
import 'package:meshport_lab/features/lab_screen.dart';
import 'package:meshport_lab/features/proxy_node_editor.dart';
void main() {
for (final width in [360.0, 800.0]) {
testWidgets('main tabs fit ${width}px with larger text', (tester) async {
tester.view.physicalSize = Size(width, 850);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
theme: meshPortTheme(),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(1.4)),
child: child!,
),
home: const LabScreen(initializeNative: false),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
for (final label in ['代理', '组网', '设置', '概览']) {
await tester.tap(find.text(label).last);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull, reason: label);
if (label == '代理') {
await tester.ensureVisible(find.text('高级设置'));
await tester.tap(find.text('高级设置'));
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('DNS 设置'));
expect(
tester.takeException(),
isNull,
reason: 'expanded advanced settings',
);
expect(find.textContaining('代理 DNS:'), findsOneWidget);
}
}
});
}
testWidgets('forms keep fields apart at phone width', (tester) async {
tester.view.physicalSize = const Size(360, 850);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
for (final page in <Widget>[
DnsPage(profile: ProxyProfile(), changed: () {}),
const ProxyNodeEditor(),
const RuleEditor(),
NetworkConfigPage(section: '基础配置', initial: const {}, save: (_) async {}),
]) {
await tester.pumpWidget(MaterialApp(theme: meshPortTheme(), home: page));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
final fields = find.byType(TextField).evaluate().toList();
for (var i = 1; i < fields.length; i++) {
final previous = tester.getRect(find.byWidget(fields[i - 1].widget));
final current = tester.getRect(find.byWidget(fields[i].widget));
expect(current.top - previous.bottom, greaterThanOrEqualTo(12));
}
}
});
}
@@ -0,0 +1,40 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/runtime_diagnostics.dart';
void main() {
test('diagnostics redact nested credentials and retain replaced secrets', () {
final redactor = DiagnosticRedactor();
redactor.remember({
'network_secret': 'mesh-secret',
'nodes': [
{
'options': {
'username': 'proxy-user',
'password': 'proxy-password',
'uuid': '00000000-0000-0000-0000-000000000001',
},
},
],
});
redactor.remember({'password': 'replacement-password'});
final text = redactor.sanitize(
'mesh-secret proxy-user proxy-password replacement-password '
'00000000-0000-0000-0000-000000000001 '
'socks://other-user:other-pass@proxy.example:1080 '
'https://example.test/sub?token=subscription-secret',
);
for (final secret in [
'mesh-secret',
'proxy-user',
'proxy-password',
'replacement-password',
'00000000-0000-0000-0000-000000000001',
'other-user',
'other-pass',
'subscription-secret',
]) {
expect(text, isNot(contains(secret)));
}
expect(text, contains('proxy.example:1080'));
});
}
@@ -0,0 +1,150 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:meshport_lab/features/lab_screen.dart';
void main() {
test('sharing links show decoded Unicode names', () {
for (final fragment in ['演示节点', '%E6%BC%94%E7%A4%BA%E8%8A%82%E7%82%B9']) {
expect(
importProxyNodes('socks5://127.0.0.1:1080#$fragment').nodes.single.name,
'演示节点',
);
}
});
test('blank and legacy DNS use default while custom resolver survives', () {
final p = ProxyProfile();
p.addNodes(importProxyNodes('socks://127.0.0.1:1080').nodes);
p.proxyDnsServer = ' ';
expect(p.runtime()['proxy_dns_server'], ProxyProfile.defaultProxyDns);
expect(p.runtime()['dns_protection'], true);
expect(p.validateConnection, returnsNormally);
final legacy = p.toJson();
(legacy['runtime'] as Map)['proxy_dns_server'] = '';
expect(
ProxyProfile.fromJson(legacy).proxyDnsServer,
ProxyProfile.defaultProxyDns,
);
p.proxyDnsServer = 'tls://resolver.example';
expect(ProxyProfile.fromJson(p.toJson()).proxyDnsServer, p.proxyDnsServer);
});
test('only initial single node is selected automatically', () {
final p = ProxyProfile();
p.addNodes(importProxyNodes('socks://127.0.0.1:1080').nodes);
final selected = p.selectedId;
expect(selected, p.nodes.single.id);
p.addNodes(importProxyNodes('socks://127.0.0.1:1081').nodes);
expect(p.selectedId, selected);
final multiple = ProxyProfile();
multiple.addNodes(
importProxyNodes('socks://127.0.0.1:1080\nsocks://127.0.0.1:1081').nodes,
);
expect(multiple.selectedId, isNull);
final subscription = ProxyProfile();
replaceSubscription(
subscription,
's',
importProxyNodes('socks://127.0.0.1:1080', source: 's'),
DateTime.now(),
);
expect(subscription.selectedId, subscription.nodes.single.id);
replaceSubscription(
subscription,
's',
importProxyNodes('socks://127.0.0.1:1081', source: 's'),
DateTime.now(),
);
expect(subscription.selectedId, isNull);
});
const channel = MethodChannel('meshport/system_vpn');
final binding = TestWidgetsFlutterBinding.ensureInitialized();
tearDown(
() =>
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null),
);
Future<void> openProxy(WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
await tester.tap(find.text('代理').last);
await tester.pumpAndSettle();
expect(find.text('仅代理'), findsOneWidget);
expect(find.text('网络入口'), findsNothing);
expect(find.text('编辑 DNS'), findsNothing);
}
Future<void> chooseMode(WidgetTester tester, String mode) async {
final field = find.byWidgetPredicate(
(w) =>
w is DropdownButtonFormField<String> &&
w.decoration.labelText == '上网模式',
);
await tester.ensureVisible(field);
await tester.tap(field);
await tester.pumpAndSettle();
await tester.tap(find.text(mode).last);
await tester.pumpAndSettle();
}
testWidgets(
'automatic saves serialize rapid edits and keep latest value',
(tester) async {
final first = Completer<void>();
final saves = <Map<String, dynamic>>[];
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
call,
) async {
if (call.method == 'save_proxy_profile') {
saves.add(
jsonDecode(call.arguments as String) as Map<String, dynamic>,
);
if (saves.length == 1) await first.future;
}
return null;
});
await openProxy(tester);
await chooseMode(tester, '直连');
await chooseMode(tester, '全局代理');
expect(saves.length, 1);
first.complete();
await tester.pumpAndSettle();
expect(saves.length, 2);
expect((saves.last['runtime'] as Map)['mode'], 'global');
expect(find.text('正在自动保存…'), findsNothing);
expect(find.text('重试保存'), findsNothing);
},
skip: !Platform.isMacOS,
);
testWidgets(
'failed automatic save offers retry and clears after success',
(tester) async {
var fail = true;
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
call,
) async {
if (call.method == 'save_proxy_profile' && fail) {
throw PlatformException(code: 'KEYCHAIN_SAVE');
}
return null;
});
await openProxy(tester);
await chooseMode(tester, '直连');
expect(find.text('重试保存'), findsOneWidget);
fail = false;
await tester.ensureVisible(find.text('重试保存'));
await tester.tap(find.text('重试保存'));
await tester.pumpAndSettle();
expect(find.text('重试保存'), findsNothing);
expect(tester.takeException(), isNull);
},
skip: !Platform.isMacOS,
);
}
@@ -1,9 +1,136 @@
import 'dart:convert';
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
void main() {
test(
'macOS session reuses authorized IPC after stop and cleans up on exit',
() async {
var launches = 0;
final paths = <String>[];
final sockets = <Socket>[];
var state = 'Stopped';
var idleChecks = 0;
final session = MacSystemVpnSession(
keepAlive: const Duration(milliseconds: 10),
open: () => openMacSystemVpn(
launch: (address, uid) async {
launches++;
paths.add(address);
final socket = await Socket.connect(
InternetAddress(address, type: InternetAddressType.unix),
0,
);
sockets.add(socket);
socket
.cast<List<int>>()
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((line) {
final op = (jsonDecode(line) as Map<String, dynamic>)['op'];
if (op == 'start') state = 'Running';
if (op == 'stop') state = 'Stopped';
if (op == 'status' && state == 'Stopped') idleChecks++;
socket.write(
'${jsonEncode({
'ok': true,
'data': {'state': state},
})}\n',
);
});
},
),
);
try {
final first = await session.acquire();
await first.request({'op': 'start'});
await session.release(first);
expect(state, 'Stopped');
expect(await Directory(File(paths.single).parent.path).exists(), true);
await Future<void>.delayed(const Duration(milliseconds: 40));
expect(idleChecks, greaterThan(0));
final second = await session.acquire();
expect(identical(first, second), true);
expect(launches, 1);
await second.request({'op': 'start'});
await session.release(second);
await session.close();
expect(state, 'Stopped');
expect(await Directory(File(paths.single).parent.path).exists(), false);
await expectLater(session.acquire(), throwsStateError);
} finally {
await session.close();
for (final socket in sockets) {
socket.destroy();
}
}
},
skip: !Platform.isMacOS,
);
test(
'dead helper is replaced and cancelled authorization can be retried',
() async {
var opens = 0, closed = 0;
var failed = false;
final session = MacSystemVpnSession(
open: () async {
opens++;
if (opens == 1) throw StateError('authorization cancelled');
return MeshPortClient.fromTransport(
request: (request) async {
if (failed && opens == 2) throw StateError('helper disconnected');
return {
'ok': true,
'data': {'state': 'Stopped'},
};
},
close: () async {
closed++;
},
);
},
);
try {
await expectLater(session.acquire(), throwsStateError);
final first = await session.acquire();
await session.release(first);
failed = true;
final replacement = await session.acquire();
expect(identical(first, replacement), false);
expect(opens, 3);
expect(closed, 1);
} finally {
await session.close();
}
expect(closed, 2);
},
);
test(
'closing while authorization is pending does not leave a helper',
() async {
final pending = Completer<MeshPortClient>();
var closes = 0;
final session = MacSystemVpnSession(open: () => pending.future);
final opening = session.acquire();
final rejected = expectLater(opening, throwsStateError);
final closing = session.close();
pending.complete(
MeshPortClient.fromTransport(
request: (_) async => {'ok': true, 'data': {}},
close: () async {
closes++;
},
),
);
await rejected;
await closing;
expect(closes, 1);
},
);
test(
'Unix control serializes replies and removes socket on close',
() async {
+34 -8
View File
@@ -20,7 +20,7 @@ void main() {
'version': 'test-core',
},
'peers': [],
'routes': [],
'nodes': [],
},
),
),
@@ -53,13 +53,30 @@ void main() {
'tx_bytes_per_second': 512.0,
},
],
'routes': [
{'peer_id': 1, 'hostname': 'game-server', 'ipv4': '10.77.0.2'},
'nodes': [
{
'peer_id': 1,
'hostname': 'game-server',
'ipv4': '10.77.0.2',
'path': 'direct',
'direct_available': true,
'latency_ms': 23.4,
'latency_source': 'link_rtt',
'metered': true,
'rx_bytes': 2048,
'tx_bytes': 1024,
'rx_bytes_per_second': 1024.0,
'tx_bytes_per_second': 512.0,
},
{
'peer_id': 2,
'hostname': 'relay-target',
'estimated_latency_ms': 89,
'next_hop_peer_id': 1,
'path': 'relay',
'direct_available': false,
'latency_ms': 89,
'latency_source': 'route_estimate',
'metered': false,
},
],
},
@@ -85,14 +102,18 @@ void main() {
'peers': [
{'peer_id': 1, 'direct': true, 'latency_ms': 166.5},
],
'routes': [
'nodes': [
{
'peer_id': 1,
'hostname': 'DIG-US',
'next_hop_peer_id': 2,
'estimated_latency_ms': 108,
'udp_nat_type': 'FullCone',
'version': '2.4.5',
'path': 'relay',
'direct_available': true,
'latency_ms': 108,
'latency_source': 'route_estimate',
'metered': true,
},
],
},
@@ -121,12 +142,17 @@ void main() {
'latency_ms': 7.497,
},
],
'routes': [
'nodes': [
{
'peer_id': 3157594741,
'hostname': 'Redmi_AX6',
'next_hop_peer_id': 3157594741,
'estimated_latency_ms': 7,
'path': 'direct',
'direct_available': true,
'hole_punched': true,
'latency_ms': 7.497,
'latency_source': 'link_rtt',
'metered': true,
},
],
},
+93 -3
View File
@@ -3,6 +3,63 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/lab_screen.dart';
void main() {
testWidgets('connection explains missing node and clears stale errors', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
await tester.tap(find.text('代理').last);
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('连接').last);
await tester.tap(find.text('连接').last);
await tester.pumpAndSettle();
expect(find.textContaining('请先添加代理节点'), findsOneWidget);
await tester.ensureVisible(find.text('诊断与日志'));
await tester.tap(find.text('诊断与日志'));
await tester.pumpAndSettle();
expect(find.textContaining('[校验代理配置] 失败'), findsOneWidget);
expect(find.textContaining('入口=unified_vpn'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('全局代理').last);
await tester.tap(find.text('全局代理').last);
await tester.pumpAndSettle();
await tester.tap(find.text('直连').last);
await tester.pumpAndSettle();
expect(find.textContaining('请先添加代理节点'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('China bypass can be selected and switched to global', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
await tester.tap(find.text('代理').last);
await tester.pumpAndSettle();
final mode = find.byWidgetPredicate(
(w) =>
w is DropdownButtonFormField<String> &&
w.decoration.labelText == '上网模式',
);
await tester.ensureVisible(mode);
await tester.tap(mode);
await tester.pumpAndSettle();
await tester.tap(find.text('绕过中国大陆').last);
await tester.pumpAndSettle();
expect(find.textContaining('中国大陆 IP 和普通私网直连'), findsOneWidget);
await tester.tap(mode);
await tester.pumpAndSettle();
await tester.tap(find.text('全局代理').last);
await tester.pumpAndSettle();
expect(find.textContaining('中国大陆 IP 和普通私网直连'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('Starts disconnected and exposes networking configuration', (
tester,
) async {
@@ -10,10 +67,43 @@ void main() {
const MaterialApp(home: LabScreen(initializeNative: false)),
);
expect(find.text('尚未连接'), findsOneWidget);
await tester.tap(find.text('设置').last);
await tester.tap(find.text('组网').last);
await tester.pumpAndSettle();
await tester.tap(find.text('基础配置'));
await tester.pumpAndSettle();
expect(find.text('网络密钥'), findsOneWidget);
expect(find.text('校验并连接'), findsOneWidget);
expect(find.text('保存配置'), findsOneWidget);
expect(find.text('保存草稿'), findsOneWidget);
});
testWidgets('proxy import requires preview and preserves draft separation', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
await tester.tap(find.text('代理').last);
await tester.pumpAndSettle();
expect(find.text('上网模式'), findsOneWidget);
await tester.ensureVisible(find.text('导入与预览'));
await tester.tap(find.text('导入与预览'));
await tester.pumpAndSettle();
await tester.enterText(
find.byType(TextField).last,
'socks5://127.0.0.1:1080#Preview',
);
await tester.tap(find.text('解析并预览'));
await tester.pumpAndSettle();
expect(find.text('导入预览'), findsOneWidget);
expect(find.text('Preview'), findsOneWidget);
await tester.tap(find.text('确认导入'));
await tester.pumpAndSettle();
expect(find.text('Preview'), findsOneWidget);
expect(find.byIcon(Icons.radio_button_checked), findsOneWidget);
expect(find.text('网络入口'), findsNothing);
expect(find.text('编辑 DNS'), findsNothing);
await tester.ensureVisible(find.text('高级设置'));
await tester.tap(find.text('高级设置'));
await tester.pumpAndSettle();
expect(find.text('网络入口'), findsOneWidget);
expect(find.text('编辑 DNS'), findsOneWidget);
});
}
@@ -0,0 +1,3 @@
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() => integrationDriver(timeout: const Duration(minutes: 15));
@@ -47,6 +47,9 @@ Map<String, dynamic> _call(String path, int handle, String request) {
}
}
/// Lowest native capability revision this binding drives (`abi_info`).
const int minimumCapabilityRevision = 2;
class MeshPortClient {
final String libraryPath;
final int _handle;
@@ -79,9 +82,25 @@ class MeshPortClient {
)();
});
if (handle == 0) throw StateError('Could not create MeshPort context');
return MeshPortClient._(path, handle);
final client = MeshPortClient._(path, handle);
int? revision;
try {
revision = (await client.abiInfo())['revision'] as int?;
} catch (_) {}
if (revision == null || revision < minimumCapabilityRevision) {
await client.close();
throw StateError(
'MeshPort native library at $path is too old '
'(capability revision ${revision ?? 'unknown'}, '
'need $minimumCapabilityRevision); rebuild meshport-ffi',
);
}
return client;
}
/// `{abi, revision, operations}` of the loaded native library.
Future<Map<String, dynamic>> abiInfo() => request({'op': 'abi_info'});
Future<Map<String, dynamic>> request(Map<String, dynamic> request) async {
if (_closed) throw StateError('MeshPort context is closed');
final path = libraryPath, handle = _handle, text = jsonEncode(request);
@@ -95,18 +114,87 @@ class MeshPortClient {
return response['data'] as Map<String, dynamic>;
}
Future<void> validate(String toml) async {
await request({'op': 'validate', 'toml': toml});
/// Returns the overlay projection. [checkLocalOverlap] also rejects an
/// overlay that collides with an existing interface on this device.
Future<Map<String, dynamic>> validate(
String toml, {
bool checkLocalOverlap = false,
}) => request({
'op': 'validate',
'toml': toml,
if (checkLocalOverlap) 'check_local_overlap': true,
});
/// Builds the SDK-accepted TOML from a structured profile draft. Mode,
/// transport and encryption invariants are applied by the SDK.
Future<String> buildConfig(Map<String, dynamic> profile) async =>
(await request({'op': 'build_config', 'profile': profile}))['toml']
as String;
/// Removes options earlier releases saved; returns [toml] unchanged when
/// nothing needed migrating.
Future<String> migrateConfig(String toml) async =>
(await request({'op': 'migrate_config', 'toml': toml}))['toml'] as String;
Future<void> start(String toml, {bool checkLocalOverlap = false}) async {
await request({
'op': 'start',
'toml': toml,
if (checkLocalOverlap) 'check_local_overlap': true,
});
}
Future<void> start(String toml) async {
await request({'op': 'start', 'toml': toml});
}
/// Starts an application-mode network and its local TCP/UDP bridge as one
/// operation; a failure leaves neither running. Returns `listen`, `overlay`,
/// `mesh_cidrs` and `route_generation`.
Future<Map<String, dynamic>> startBridged(
String toml, {
int port = 0,
int maxSessions = 128,
bool checkLocalOverlap = false,
bool requireStaticOverlay = false,
}) => request({
'op': 'start_bridged',
'toml': toml,
'port': port,
'max_sessions': maxSessions,
if (checkLocalOverlap) 'check_local_overlap': true,
if (requireStaticOverlay) 'require_static_overlay': true,
});
Future<void> stop() async {
await request({'op': 'stop'});
}
/// Long-polls mesh routes: returns as soon as `route_generation` differs
/// from [afterGeneration] or the network stops, otherwise after [timeout]
/// with `changed: false`. Runs outside the context's serial lock, so other
/// requests proceed meanwhile. Returns `running`, `changed`,
/// `route_generation`, `mesh_cidrs` and `subnet_routes`.
Future<Map<String, dynamic>> waitRoutes({
int? afterGeneration,
Duration timeout = const Duration(seconds: 25),
}) => request({
'op': 'wait_routes',
if (afterGeneration != null) 'after_generation': afterGeneration,
'timeout_ms': timeout.inMilliseconds,
});
/// Local IPv4 TCP/UDP bridge for a host proxy engine. Application mode only.
/// Data travels on native sockets, outside the serial JSON I/O interface.
Future<Map<String, dynamic>> startSocksBridge({
int port = 0,
int maxSessions = 128,
}) =>
request({'op': 'socks_start', 'port': port, 'max_sessions': maxSessions});
Future<void> stopSocksBridge() async {
await request({'op': 'socks_stop'});
}
Future<Map<String, dynamic>> socksBridgeStatus() =>
request({'op': 'socks_status'});
/// Opt in to bounded process-wide punch tracing. Does not replace host logging.
Future<Map<String, dynamic>> enableDiagnostics() =>
request({'op': 'diagnostics_enable'});
@@ -4,6 +4,102 @@ import 'dart:ffi';
import 'dart:io';
import 'client.dart';
/// Reuses one authenticated helper while its owning app is running. Stopping
/// the engine releases VPN resources; closing this session also closes IPC.
/// No service is installed and no credentials are stored by this class.
class MacSystemVpnSession {
MacSystemVpnSession({
required this.open,
this.keepAlive = const Duration(seconds: 30),
});
final Future<MeshPortClient> Function() open;
final Duration keepAlive;
MeshPortClient? _client;
Future<MeshPortClient>? _opening;
Timer? _heartbeat;
bool _disposed = false, _checking = false;
Future<MeshPortClient> acquire() async {
if (_disposed) throw StateError('VPN authorization session is closed');
_heartbeat?.cancel();
final pending = _opening ??= _acquire();
try {
final client = await pending;
if (_disposed) throw StateError('VPN authorization session is closed');
return client;
} finally {
if (identical(_opening, pending)) _opening = null;
}
}
Future<MeshPortClient> _acquire() async {
final cached = _client;
if (cached != null) {
try {
await cached.status();
return cached;
} catch (_) {
_client = null;
try {
await cached.close();
} catch (_) {}
}
}
final next = await open();
if (_disposed) {
await next.close();
throw StateError('VPN authorization session is closed');
}
return _client = next;
}
Future<void> release(MeshPortClient client) async {
if (!identical(client, _client) || _disposed) {
await client.close();
return;
}
try {
await client.stop();
} catch (_) {
_client = null;
try {
await client.close();
} catch (_) {}
rethrow;
}
if (_disposed || !identical(_client, client)) return;
_heartbeat?.cancel();
_heartbeat = Timer.periodic(keepAlive, (_) async {
if (_checking || _disposed || !identical(_client, client)) return;
_checking = true;
try {
await client.status();
} catch (_) {
if (identical(_client, client)) {
_client = null;
_heartbeat?.cancel();
}
try {
await client.close();
} catch (_) {}
} finally {
_checking = false;
}
});
}
Future<void> close() async {
_disposed = true;
_heartbeat?.cancel();
try {
await _opening;
} catch (_) {}
final client = _client;
_client = null;
await client?.close();
}
}
/// Android's host supplies VpnService authorization and a serialized control
/// channel. Keeping Flutter APIs out of this library permits non-Flutter hosts.
Future<MeshPortClient> openAndroidSystemVpn({
@@ -0,0 +1,4 @@
/// Optional proxy engine bindings; does not load native code until open().
library;
export 'src/proxy_engine.dart';
@@ -0,0 +1,147 @@
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'package:ffi/ffi.dart';
abstract interface class ProxyEngine {
Future<Map<String, dynamic>> start({
required int port,
required String meshSocks,
required List<String> prefixes,
Map<String, dynamic>? profile,
});
Future<Map<String, dynamic>> status();
Future<void> stop();
Future<void> close();
}
String _libraryPath() {
if (Platform.isMacOS) {
return '${File(Platform.resolvedExecutable).parent.parent.path}/Frameworks/libmeshport_proxy.dylib';
}
if (Platform.isAndroid) return 'libmeshport_proxy.so';
throw UnsupportedError('Proxy engine currently supports macOS and Android');
}
Map<String, dynamic> _invoke(String path, int handle, String text) {
final library = DynamicLibrary.open(path);
final call = library
.lookupFunction<
Pointer<Utf8> Function(Uint64, Pointer<Utf8>),
Pointer<Utf8> Function(int, Pointer<Utf8>)
>('meshport_proxy_call');
final free = library
.lookupFunction<
Void Function(Pointer<Utf8>),
void Function(Pointer<Utf8>)
>('meshport_proxy_string_free');
final input = text.toNativeUtf8();
try {
final output = call(handle, input);
if (output == nullptr) throw StateError('Native engine response is null');
try {
return jsonDecode(output.toDartString()) as Map<String, dynamic>;
} finally {
free(output);
}
} finally {
calloc.free(input);
}
}
/// Calls run outside the UI isolate. Close is queued after in-flight operations.
class NativeProxyEngine implements ProxyEngine {
final String libraryPath;
final int _handle;
bool _closed = false;
Future<void> _tail = Future.value();
NativeProxyEngine._(this.libraryPath, this._handle);
static Future<NativeProxyEngine> open({String? libraryPath}) async {
final path = libraryPath ?? _libraryPath();
final handle = await Isolate.run(() {
final lib = DynamicLibrary.open(path);
final abi = lib.lookupFunction<Uint32 Function(), int Function()>(
'meshport_proxy_abi_version',
)();
if (abi != 1) throw StateError('Unsupported proxy engine ABI: $abi');
return lib.lookupFunction<Uint64 Function(), int Function()>(
'meshport_proxy_context_new',
)();
});
if (handle == 0) throw StateError('Could not create proxy engine context');
final engine = NativeProxyEngine._(path, handle);
try {
await engine._request({
'op': 'configure_cache',
'directory': Directory.systemTemp.path,
});
} catch (_) {
await engine.close();
rethrow;
}
return engine;
}
Future<T> _queue<T>(Future<T> Function() work) {
final result = _tail.then((_) => work());
_tail = result.then<void>((_) {}, onError: (Object _, StackTrace __) {});
return result;
}
Future<Map<String, dynamic>> _request(Map<String, dynamic> request) {
if (_closed) return Future.error(StateError('Proxy engine is closed'));
final path = libraryPath, handle = _handle, text = jsonEncode(request);
return _queue(() async {
final response = await Isolate.run(() => _invoke(path, handle, text));
if (response['ok'] != true)
throw StateError(
response['error'] as String? ?? 'Proxy engine operation failed',
);
return response['data'] as Map<String, dynamic>;
});
}
@override
Future<Map<String, dynamic>> start({
required int port,
required String meshSocks,
required List<String> prefixes,
Map<String, dynamic>? profile,
}) => _request({
'op': 'start',
'config': {
...?profile,
'listen_port': port,
'mesh_socks': meshSocks,
'mesh_cidrs': prefixes,
},
});
Future<Map<String, dynamic>> probeNode(Map<String, dynamic> options) =>
_request({
'op': 'probe_node',
'config': {'proxy': options},
});
@override
Future<Map<String, dynamic>> status() => _request({'op': 'status'});
@override
Future<void> stop() async {
await _request({'op': 'stop'});
}
@override
Future<void> close() {
if (_closed) return _tail;
_closed = true;
final path = libraryPath, handle = _handle;
return _queue(
() => Isolate.run(
() => DynamicLibrary.open(path)
.lookupFunction<Void Function(Uint64), void Function(int)>(
'meshport_proxy_context_free',
)(handle),
),
);
}
}
@@ -0,0 +1,8 @@
name: singbox_flutter
description: Managed native sing-box lifecycle bindings for MeshPort clients.
version: 0.1.0
publish_to: none
environment:
sdk: ^3.11.0
dependencies:
ffi: ^2.1.4
@@ -0,0 +1,197 @@
//! Structured profile <-> TOML. Hosts edit a JSON draft; the SDK owns the
//! mode invariants and the exact configuration text it will accept.
use anyhow::{Context, Result, bail};
use serde_json::Value;
/// Keys removed from saved configurations by earlier releases.
const LEGACY_KEYS: [&str; 1] = ["subnet_routes"];
/// Builds a validated configuration from a form draft. Any `runtime_mode` other
/// than `system_vpn` (including a host's unified VPN) runs the mesh in
/// application mode; transport and encryption invariants are not host choices.
pub fn build_config(profile: &Value) -> Result<String> {
let profile = profile.as_object().context("profile must be an object")?;
let text = |key: &str, default: &str| -> Result<Value> {
match profile.get(key) {
None | Some(Value::Null) => Ok(Value::from(default)),
Some(value @ Value::String(_)) => Ok(value.clone()),
Some(_) => bail!("{key} must be a string"),
}
};
let system = profile.get("runtime_mode").and_then(Value::as_str) == Some("system_vpn");
let mut optimization = match profile.get("optimization") {
None | Some(Value::Null) => serde_json::Map::new(),
Some(Value::Object(map)) => map.clone(),
Some(_) => bail!("optimization must be an object"),
};
optimization
.entry("mode")
.or_insert_with(|| Value::from("adaptive"));
let latency_first = matches!(
optimization.get("mode").and_then(Value::as_str),
Some("adaptive" | "latency")
);
let mut flags = match profile.get("flags") {
None | Some(Value::Null) => serde_json::Map::new(),
Some(Value::Object(map)) => map.clone(),
Some(_) => bail!("flags must be an object"),
};
flags.insert("no_tun".into(), Value::from(!system));
flags.insert("use_smoltcp".into(), Value::from(!system));
flags.insert("enable_encryption".into(), Value::from(true));
flags.insert(
"enable_ipv6".into(),
profile
.get("enable_ipv6")
.filter(|v| !v.is_null())
.cloned()
.unwrap_or(Value::from(true)),
);
flags.insert("latency_first".into(), Value::from(latency_first));
let mut root = serde_json::Map::new();
root.insert("hostname".into(), text("hostname", "MeshPort")?);
if profile.get("dhcp").and_then(Value::as_bool) == Some(true) {
root.insert("dhcp".into(), Value::from(true));
} else {
root.insert("ipv4".into(), text("ipv4", "")?);
}
root.insert(
"listeners".into(),
profile
.get("listeners")
.filter(|v| !v.is_null())
.cloned()
.unwrap_or(Value::Array(vec![])),
);
for key in ["stun_servers", "stun_servers_v6"] {
if let Some(value) = profile.get(key).filter(|v| !v.is_null()) {
root.insert(key.into(), value.clone());
}
}
let peers = match profile.get("peers") {
None | Some(Value::Null) => vec![],
Some(Value::Array(peers)) => peers
.iter()
.map(|uri| serde_json::json!({"uri": uri}))
.collect(),
Some(_) => bail!("peers must be an array"),
};
if !peers.is_empty() {
root.insert("peer".into(), Value::Array(peers));
}
root.insert(
"network_identity".into(),
serde_json::json!({
"network_name": text("network_name", "")?,
"network_secret": text("network_secret", "")?,
}),
);
root.insert("flags".into(), Value::Object(drop_nulls(flags)));
root.insert(
"runtime".into(),
serde_json::json!({"mode": if system { "system_vpn" } else { "application" }}),
);
root.insert(
"optimization".into(),
Value::Object(drop_nulls(optimization)),
);
let value = toml::Value::try_from(Value::Object(root))
.map_err(|_| anyhow::anyhow!("profile contains values TOML cannot represent"))?;
let output =
toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?;
super::parse_config(&output)?;
Ok(output)
}
fn drop_nulls(map: serde_json::Map<String, Value>) -> serde_json::Map<String, Value> {
map.into_iter().filter(|(_, v)| !v.is_null()).collect()
}
/// Removes options earlier releases saved but this SDK no longer accepts.
/// Returns the input unchanged (formatting preserved) when nothing is removed.
pub fn migrate_config(input: &str) -> Result<(String, bool)> {
let mut value: toml::Value =
toml::from_str(input).map_err(|_| anyhow::anyhow!("invalid TOML configuration"))?;
let table = value
.as_table_mut()
.context("configuration must be a TOML table")?;
let mut changed = false;
for key in LEGACY_KEYS {
changed |= table.remove(key).is_some();
if let Some(runtime) = table.get_mut("runtime").and_then(|v| v.as_table_mut()) {
changed |= runtime.remove(key).is_some();
}
}
if !changed {
return Ok((input.to_owned(), false));
}
let output =
toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?;
Ok((output, true))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ConfigLoader;
use serde_json::json;
fn draft() -> Value {
json!({
"runtime_mode": "unified_vpn",
"ipv4": "10.77.0.11/24",
"network_name": "test",
"network_secret": "test-only",
"flags": {"disable_p2p": true, "foreign_relay_bps_limit": "18446744073709551615", "no_tun": false},
"listeners": ["udp://0.0.0.0:11010"],
"stun_servers": [],
"peers": ["tcp://192.0.2.1:11010"],
"optimization": {"mode": "direct"},
"unknown_projection_field": true,
})
}
#[test]
fn host_modes_force_invariants_and_round_trip() {
let toml = build_config(&draft()).unwrap();
let config = crate::parse_config(&toml).unwrap();
let flags = config.get_flags();
assert!(flags.no_tun && flags.use_smoltcp && flags.enable_encryption);
assert!(flags.disable_p2p && !flags.latency_first && flags.enable_ipv6);
assert_eq!(flags.foreign_relay_bps_limit, u64::MAX);
assert_eq!(config.get_peers().len(), 1);
assert!(toml.contains("stun_servers = []"));
assert!(toml.contains("mode = \"application\""));
let mut system = draft();
system["runtime_mode"] = json!("system_vpn");
let config = crate::parse_config(&build_config(&system).unwrap()).unwrap();
assert!(!config.get_flags().no_tun && !config.get_flags().use_smoltcp);
}
#[test]
fn dhcp_and_defaults() {
let toml = build_config(&json!({"dhcp": true, "ipv4": "", "network_name": "n"})).unwrap();
let config = crate::parse_config(&toml).unwrap();
assert!(config.get_dhcp() && config.get_flags().latency_first);
assert_eq!(config.get_hostname(), "MeshPort");
assert!(build_config(&json!({"network_name": "n", "ipv4": 7})).is_err());
assert!(build_config(&json!({"network_name": ""})).is_err());
}
#[test]
fn legacy_subnet_routes_are_removed_only_when_present() {
let base = "ipv4 = '10.77.0.11'\n[network_identity]\nnetwork_name = 'test'\n";
assert_eq!(migrate_config(base).unwrap(), (base.to_owned(), false));
for legacy in [
format!("subnet_routes = ['192.168.21.0/24']\n{base}"),
format!("{base}[runtime]\nmode = 'system_vpn'\nsubnet_routes = ['192.168.21.0/24']\n"),
] {
assert!(crate::parse_config(&legacy).is_err());
let (migrated, changed) = migrate_config(&legacy).unwrap();
assert!(changed && !migrated.contains("subnet_routes"));
crate::parse_config(&migrated).unwrap();
}
}
}
+274 -34
View File
@@ -16,8 +16,50 @@ pub use easytier_core::peers::meshport_optimization::{Mode, OptimizationPolicy};
#[cfg(target_os = "android")]
pub mod android;
mod config_builder;
mod system_routes;
pub use config_builder::{build_config, migrate_config};
pub use system_routes::mesh_cidrs;
/// Rejects a static overlay that overlaps an address already on this host.
/// DHCP configurations have no overlay yet and pass.
pub fn check_local_overlap(config: &TomlConfig) -> Result<()> {
match config.get_ipv4() {
Some(ip) => system_routes::check_local_overlap(ip.address(), ip.network_length()),
None => Ok(()),
}
}
/// Address plan for the host's virtual interface, derived from a static overlay.
pub fn overlay_projection(config: &TomlConfig) -> serde_json::Value {
config.get_ipv4().map_or(serde_json::Value::Null, |ip| {
overlay_json(ip.address(), ip.network_length())
})
}
fn overlay_json(address: std::net::Ipv4Addr, prefix: u8) -> serde_json::Value {
let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0);
let network = std::net::Ipv4Addr::from(u32::from(address) & mask);
serde_json::json!({
"address": address.to_string(),
"prefix": prefix,
"network": format!("{network}/{prefix}"),
"routable": system_routes::routable_overlay(address, prefix).is_some(),
})
}
/// Destinations to route through the mesh. `generation` increases on every
/// change of `cidrs` so hosts compare one number instead of the sets.
/// `stopped` is set once, with empty routes, when the network stops.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
pub struct MeshRoutes {
pub generation: u64,
pub cidrs: Vec<String>,
pub subnet_routes: Vec<String>,
pub stopped: bool,
}
pub const REVISION: &str = "7af7bdc16a41d64d58743d15023a63b3eed2102c";
/// Strict mode-aware allowlist. Unknown options fail rather than disappear.
@@ -252,6 +294,117 @@ pub struct Engine {
events: Mutex<Option<EventBusSubscriber>>,
journal: Mutex<Vec<serde_json::Value>>,
event_sequence: Mutex<u64>,
routes: tokio::sync::watch::Sender<MeshRoutes>,
route_task: Mutex<Option<tokio::task::JoinHandle<()>>>,
}
impl Drop for Engine {
fn drop(&mut self) {
if let Some(task) = self.route_task.get_mut().ok().and_then(Option::take) {
task.abort();
}
}
}
async fn current_routes(instance: &NativeCoreInstance) -> (Vec<String>, Vec<String>) {
let accepted = instance
.packet_plane()
.proxy_cidr_diff(&Default::default())
.await
.map(|d| d.current.into_iter().collect::<Vec<_>>())
.unwrap_or_default();
let overlay = instance
.node_snapshot()
.await
.ipv4_addr
.map(|ip| (ip.address(), ip.network_length()));
(
system_routes::mesh_cidrs(overlay, &accepted),
accepted.iter().map(|r| r.to_string()).collect(),
)
}
fn publish_routes(
sender: &tokio::sync::watch::Sender<MeshRoutes>,
cidrs: Vec<String>,
subnet_routes: Vec<String>,
) {
sender.send_if_modified(|current| {
if current.cidrs == cidrs && current.subnet_routes == subnet_routes {
return false;
}
current.generation += 1;
current.cidrs = cidrs;
current.subnet_routes = subnet_routes;
true
});
}
/// Joins link and route views into one row per remote node. A node counts as
/// direct only when it has a direct transport and is its own next hop; the
/// measured link RTT applies only then, otherwise the route estimate does.
fn merge_nodes(
local_peer_id: Option<u64>,
peers: &[serde_json::Value],
routes: &[serde_json::Value],
) -> Vec<serde_json::Value> {
let mut order = Vec::new();
let mut rows: HashMap<u64, serde_json::Value> = HashMap::new();
for route in routes {
if let Some(id) = route["peer_id"].as_u64()
&& rows.insert(id, route.clone()).is_none()
{
order.push(id);
}
}
for peer in peers {
if let Some(id) = peer["peer_id"].as_u64() {
rows.entry(id).or_insert_with(|| {
order.push(id);
serde_json::json!({"peer_id": id})
});
}
}
order
.into_iter()
.filter(|id| Some(*id) != local_peer_id)
.map(|id| {
let route = &rows[&id];
let peer = peers.iter().find(|p| p["peer_id"].as_u64() == Some(id));
let direct_available = peer.is_some_and(|p| p["direct"] == true);
let next_hop = route["next_hop_peer_id"].as_u64();
let direct = direct_available && next_hop.is_none_or(|hop| hop == id);
let measured = peer
.filter(|_| direct)
.and_then(|p| p["latency_ms"].as_f64());
let estimated = route["estimated_latency_ms"].as_f64();
let mut node = route.clone();
node["path"] = serde_json::json!(if direct { "direct" } else { "relay" });
node["direct_available"] = serde_json::json!(direct_available);
node["hole_punched"] =
serde_json::json!(direct && peer.is_some_and(|p| p["hole_punched"] == true));
node["latency_ms"] = serde_json::json!(measured.or(estimated));
node["latency_source"] = serde_json::json!(if measured.is_some() {
Some("link_rtt")
} else if estimated.is_some() {
Some("route_estimate")
} else {
None
});
node["metered"] = serde_json::json!(peer.is_some());
if let Some(peer) = peer {
for key in [
"rx_bytes",
"tx_bytes",
"rx_bytes_per_second",
"tx_bytes_per_second",
] {
node[key] = peer[key].clone();
}
}
node
})
.collect()
}
#[derive(Default)]
@@ -275,6 +428,9 @@ impl Engine {
{
bail!("system_vpn requires a platform VPN build and platform authorization");
}
if mode == RuntimeMode::SystemVpn {
check_local_overlap(&config)?;
}
let optimization = optimization_config(input)?;
let instance = create_native_instance(config.clone())?;
instance
@@ -293,6 +449,21 @@ impl Engine {
instance.stop().await;
return Err(error);
}
let (routes, _) = tokio::sync::watch::channel(MeshRoutes::default());
let (cidrs, subnet_routes) = current_routes(&instance).await;
publish_routes(&routes, cidrs, subnet_routes);
let route_task = tokio::spawn({
let instance = instance.clone();
let routes = routes.clone();
async move {
let mut tick = tokio::time::interval(std::time::Duration::from_secs(1));
loop {
tick.tick().await;
let (cidrs, subnet_routes) = current_routes(&instance).await;
publish_routes(&routes, cidrs, subnet_routes);
}
}
});
Ok(Self {
instance,
config,
@@ -303,8 +474,14 @@ impl Engine {
events: Mutex::new(events),
journal: Mutex::new(Vec::new()),
event_sequence: Mutex::new(0),
routes,
route_task: Mutex::new(Some(route_task)),
})
}
/// Notifies on every change of the destinations to route through the mesh.
pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver<MeshRoutes> {
self.routes.subscribe()
}
pub fn redact_diagnostic(&self, text: &str) -> String {
let secret = self
.config
@@ -326,6 +503,20 @@ impl Engine {
self.instance.attach_tun_fd(fd)
}
pub async fn stop(&self) {
if let Some(task) = self.route_task.lock().unwrap().take() {
task.abort();
}
// Wake route watchers: a stopped network routes nothing.
self.routes.send_if_modified(|routes| {
if routes.stopped {
return false;
}
routes.generation += 1;
routes.cidrs.clear();
routes.subnet_routes.clear();
routes.stopped = true;
true
});
self.instance.stop().await;
*self.interface_name.lock().unwrap() = None;
}
@@ -412,18 +603,10 @@ impl Engine {
.await,
);
}
let subnet_routes = self
.instance
.packet_plane()
.proxy_cidr_diff(&Default::default())
.await
.map(|d| {
d.current
.into_iter()
.map(|r| r.to_string())
.collect::<Vec<_>>()
})
.unwrap_or_default();
let (cidrs, subnet_routes) = current_routes(&self.instance).await;
publish_routes(&self.routes, cidrs, subnet_routes);
let mesh_routes = self.routes.borrow().clone();
let subnet_routes = mesh_routes.subnet_routes.clone();
let mut traffic = self.traffic.lock().unwrap();
let now = Instant::now();
let seconds = traffic
@@ -471,6 +654,22 @@ impl Engine {
traffic.sampled_at = Some(now);
let flags = self.config.get_flags();
let latency_first = flags.latency_first;
let route_rows = routes.iter().map(|r| {
let path_latency = if latency_first {r.path_latency_latency_first.unwrap_or(r.path_latency)} else {r.path_latency};
serde_json::json!({"peer_id": r.peer_id, "hostname": r.hostname,
"ipv4": r.ipv4_addr.as_ref().map(|v| v.to_string()),
"advertised_subnets": r.proxy_cidrs,
"cost": effective_hops.get(&r.peer_id).copied().flatten().map(|hop| if hop == r.peer_id {1} else if latency_first {r.cost_latency_first.unwrap_or(r.cost)} else {r.cost}),
"version": r.version,
"udp_nat_type": r.stun_info.as_ref().map(|s| format!("{:?}", easytier::proto::common::NatType::try_from(s.udp_nat_type).unwrap_or_default())),
"disable_p2p": r.feature_flag.as_ref().map(|f| f.disable_p2p),
"need_p2p": r.feature_flag.as_ref().map(|f| f.need_p2p),
"next_hop_peer_id": effective_hops.get(&r.peer_id).copied().flatten(),
"candidate_next_hop_peer_id": if latency_first { r.next_hop_peer_id_latency_first.unwrap_or(r.next_hop_peer_id) } else { r.next_hop_peer_id },
"estimated_latency_ms": if path_latency > 0 {Some(path_latency)} else {None}
})
}).collect::<Vec<_>>();
let nodes = merge_nodes(Some(u64::from(node.peer_id)), &peer_stats, &route_rows);
let interface_name = self.interface_name.lock().unwrap().clone();
serde_json::json!({
"state": format!("{:?}", self.instance.state()),
@@ -513,21 +712,8 @@ impl Engine {
"tx_bytes_per_second": seconds.filter(|s| *s > 0.0).map(|s| total_tx_delta as f64 / s),
"scope": "tunnel_including_control"
},
"routes": routes.iter().map(|r| {
let path_latency = if latency_first {r.path_latency_latency_first.unwrap_or(r.path_latency)} else {r.path_latency};
serde_json::json!({"peer_id": r.peer_id, "hostname": r.hostname,
"ipv4": r.ipv4_addr.as_ref().map(|v| v.to_string()),
"advertised_subnets": r.proxy_cidrs,
"cost": effective_hops.get(&r.peer_id).copied().flatten().map(|hop| if hop == r.peer_id {1} else if latency_first {r.cost_latency_first.unwrap_or(r.cost)} else {r.cost}),
"version": r.version,
"udp_nat_type": r.stun_info.as_ref().map(|s| format!("{:?}", easytier::proto::common::NatType::try_from(s.udp_nat_type).unwrap_or_default())),
"disable_p2p": r.feature_flag.as_ref().map(|f| f.disable_p2p),
"need_p2p": r.feature_flag.as_ref().map(|f| f.need_p2p),
"next_hop_peer_id": effective_hops.get(&r.peer_id).copied().flatten(),
"candidate_next_hop_peer_id": if latency_first { r.next_hop_peer_id_latency_first.unwrap_or(r.next_hop_peer_id) } else { r.next_hop_peer_id },
"estimated_latency_ms": if path_latency > 0 {Some(path_latency)} else {None}
})
}).collect::<Vec<_>>(),
"routes": route_rows,
"nodes": nodes,
"application_only": self.mode == RuntimeMode::Application,
"runtime_mode": self.mode,
"platform_network": {
@@ -536,7 +722,9 @@ impl Engine {
"route_scope": if !subnet_routes.is_empty() { "overlay_and_remote_subnets" } else { "overlay_only" },
"subnet_route_mode": "automatic",
"route_installation": if self.mode == RuntimeMode::SystemVpn { "system" } else { "sdk_only" },
"subnet_routes": subnet_routes, "subnet_routes_scope": "accepted_projection", "dns_changed": false, "default_route_changed": false
"subnet_routes": subnet_routes, "subnet_routes_scope": "accepted_projection", "dns_changed": false, "default_route_changed": false,
"mesh_cidrs": mesh_routes.cidrs, "route_generation": mesh_routes.generation,
"overlay": node.ipv4_addr.map_or(serde_json::Value::Null, |ip| overlay_json(ip.address(), ip.network_length()))
}, "upstream_revision": REVISION
})
}
@@ -635,6 +823,40 @@ mod tests {
);
}
#[test]
fn nodes_classify_path_and_latency_source() {
use serde_json::json;
let peers = vec![
json!({"peer_id": 2, "direct": true, "hole_punched": true, "latency_ms": 12.5, "rx_bytes": 9}),
json!({"peer_id": 3, "direct": true, "latency_ms": 40.0}),
json!({"peer_id": 5, "direct": false}),
];
let routes = vec![
json!({"peer_id": 1, "hostname": "self"}),
json!({"peer_id": 2, "next_hop_peer_id": 2, "estimated_latency_ms": 30}),
json!({"peer_id": 3, "next_hop_peer_id": 2, "estimated_latency_ms": 55}),
json!({"peer_id": 4, "next_hop_peer_id": 2}),
];
let nodes = merge_nodes(Some(1), &peers, &routes);
let ids: Vec<_> = nodes
.iter()
.map(|n| n["peer_id"].as_u64().unwrap())
.collect();
assert_eq!(ids, vec![2, 3, 4, 5]);
assert_eq!(nodes[0]["path"], "direct");
assert_eq!(nodes[0]["latency_ms"], 12.5);
assert_eq!(nodes[0]["latency_source"], "link_rtt");
assert_eq!(nodes[0]["hole_punched"], true);
assert_eq!(nodes[0]["rx_bytes"], 9);
// Direct link exists but traffic is routed through peer 2.
assert_eq!(nodes[1]["path"], "relay");
assert_eq!(nodes[1]["direct_available"], true);
assert_eq!(nodes[1]["latency_ms"], 55.0);
assert_eq!(nodes[1]["latency_source"], "route_estimate");
assert_eq!(nodes[2]["metered"], false);
assert!(nodes[2]["latency_source"].is_null());
assert_eq!(nodes[3]["path"], "relay");
}
#[test]
fn optimization_configuration_is_strict_and_controls_effective_flags() {
let input = format!(
"{BASE}\n[optimization]\nmode = 'adaptive'\nmin_improvement_ms = 20\nrelay_peer_ids = [10,20]"
@@ -708,7 +930,15 @@ mod tests {
let server = create_native_instance(server_config.clone()).unwrap();
server.start().await.unwrap();
let client = Engine::start(&format!("ipv4 = '10.253.80.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{identity}")).await.unwrap();
let mut watch = client.watch_mesh_routes();
assert_eq!(watch.borrow_and_update().cidrs, vec!["10.253.80.0/24"]);
let result = tokio::time::timeout(Duration::from_secs(20), async {
// The watch fires on acceptance without anyone polling snapshots.
watch
.wait_for(|r| r.cidrs == ["10.253.79.0/24", "10.253.80.0/24"])
.await
.unwrap();
let learned_generation = watch.borrow().generation;
loop {
let snapshot = client.snapshot().await;
let routes = snapshot["platform_network"]["subnet_routes"]
@@ -781,16 +1011,26 @@ mod tests {
})
.await
.unwrap();
while !client.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
let withdrawn = watch
.wait_for(|r| r.cidrs == ["10.253.80.0/24"])
.await
.unwrap()
.is_empty()
{
tokio::time::sleep(Duration::from_millis(100)).await;
}
.generation;
assert!(withdrawn > learned_generation);
assert!(
client.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.is_empty()
);
})
.await;
let mut on_stop = client.watch_mesh_routes();
let before_stop = on_stop.borrow_and_update().generation;
client.stop().await;
assert!(on_stop.has_changed().unwrap());
let stopped = on_stop.borrow().clone();
assert!(stopped.stopped && stopped.cidrs.is_empty() && stopped.generation > before_stop);
server.stop().await;
assert!(result.is_ok(), "automatic subnet test timed out");
}
@@ -24,6 +24,52 @@ pub fn allowed(route: &Ipv4Cidr, overlay: Ipv4Addr, prefix: u8) -> bool {
local_interfaces_allow(route)
}
/// Overlay network when it can carry routed host traffic: a private IPv4 /16-/32.
pub fn routable_overlay(address: Ipv4Addr, prefix: u8) -> Option<Ipv4Cidr> {
if !(16..=32).contains(&prefix) || !address.is_private() {
return None;
}
let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0);
Ipv4Cidr::new(Ipv4Addr::from(u32::from(address) & mask), prefix).ok()
}
/// The canonical, sorted set of destinations hosts must send through the mesh:
/// the routable overlay network plus accepted advertised subnets.
pub fn mesh_cidrs(overlay: Option<(Ipv4Addr, u8)>, accepted: &[Ipv4Cidr]) -> Vec<String> {
let mut result = std::collections::BTreeSet::new();
if let Some(cidr) = overlay.and_then(|(address, prefix)| routable_overlay(address, prefix)) {
result.insert(cidr);
}
result.extend(accepted.iter().copied());
// Always spell the prefix length; host routes would otherwise print bare.
result
.into_iter()
.map(|cidr| format!("{}/{}", cidr.first_address(), cidr.network_length()))
.collect()
}
/// Fails when the overlay overlaps an address already configured on this host,
/// such as the physical LAN or another VPN. Reads interfaces fresh, uncached.
pub fn check_local_overlap(address: Ipv4Addr, prefix: u8) -> anyhow::Result<()> {
use network_interface::{Addr, NetworkInterface, NetworkInterfaceConfig};
let interfaces = NetworkInterface::show()
.map_err(|_| anyhow::anyhow!("cannot inspect existing interfaces"))?;
let conflict = interfaces
.into_iter()
.flat_map(|iface| iface.addr)
.any(|addr| match addr {
Addr::V4(v4) => v4
.netmask
.is_some_and(|mask| overlaps(address, prefix, v4.ip, u32::from(mask))),
_ => false,
});
anyhow::ensure!(
!conflict,
"overlay overlaps an existing interface; choose another subnet or stop the conflicting VPN"
);
Ok(())
}
type InterfaceNetworks = Vec<(Ipv4Addr, u32)>;
type InterfaceCache = Option<(std::time::Instant, Option<InterfaceNetworks>)>;
fn local_interfaces_allow(route: &Ipv4Cidr) -> bool {
@@ -76,6 +122,25 @@ mod tests {
assert!(permitted(&"10.5.0.1/32".parse().unwrap(), overlay, 24));
}
#[test]
fn mesh_cidrs_are_canonical_sorted_and_skip_unroutable_overlays() {
let accepted: Vec<Ipv4Cidr> = vec!["192.168.21.0/24".parse().unwrap()];
assert_eq!(
mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 24)), &accepted),
vec!["10.77.0.0/24", "192.168.21.0/24"]
);
assert_eq!(
mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 32)), &[]),
vec!["10.77.0.11/32"]
);
for (address, prefix) in [("8.8.8.8", 24), ("10.0.0.1", 8)] {
assert_eq!(
mesh_cidrs(Some((address.parse().unwrap(), prefix)), &accepted),
vec!["192.168.21.0/24"]
);
}
assert!(mesh_cidrs(None, &[]).is_empty());
}
#[test]
fn detects_physical_subnet_overlap() {
let local = "10.10.8.54".parse().unwrap();
assert!(overlaps(
+5
View File
@@ -10,6 +10,7 @@ crate-type = ["cdylib", "staticlib", "rlib"]
[dependencies]
meshport.workspace = true
meshport-easytier.workspace = true
meshport-socks.workspace = true
anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
@@ -19,3 +20,7 @@ tracing-subscriber = { version = "0.3", default-features = false, features = ["s
[features]
default = []
system-vpn = ["meshport/system-vpn"]
[dev-dependencies]
easytier = { workspace = true, features = ["proxy-packet"] }
easytier-core.workspace = true
+470 -12
View File
@@ -15,6 +15,33 @@ use std::{
};
use tokio::runtime::Runtime;
static NEXT: AtomicU64 = AtomicU64::new(1);
/// Additive JSON operation set within ABI v1. Bump when hosts must rely on a
/// newly added operation or field; hosts reject libraries below what they need.
const CAPABILITY_REVISION: u32 = 2;
const OPERATIONS: &[&str] = &[
"abi_info",
"build_config",
"migrate_config",
"validate",
"start",
"start_bridged",
"stop",
"status",
"wait_routes",
"socks_start",
"socks_stop",
"socks_status",
"diagnostics_enable",
"probe",
"quality_sample",
"tcp_connect",
"tcp_write",
"tcp_read",
"udp_bind",
"udp_send",
"udp_receive",
"resource_close",
];
#[cfg(target_os = "android")]
#[unsafe(no_mangle)]
pub extern "C" fn meshport_set_android_socket_protector(
@@ -26,12 +53,18 @@ static CONTEXTS: LazyLock<Mutex<HashMap<u64, Arc<Context>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
struct Context {
runtime: Runtime,
network: Mutex<Option<Network>>,
network: Mutex<Option<Arc<Network>>>,
socks: Mutex<Option<meshport_socks::Bridge>>,
tcp: tokio::sync::Mutex<HashMap<u64, meshport::TcpStream>>,
udp: tokio::sync::Mutex<HashMap<u64, meshport::UdpSocket>>,
}
impl Drop for Context {
fn drop(&mut self) {
if let Ok(slot) = self.socks.get_mut()
&& let Some(mut bridge) = slot.take()
{
let _ = self.runtime.block_on(bridge.stop());
}
if let Ok(slot) = self.network.get_mut()
&& let Some(n) = slot.take()
{
@@ -60,6 +93,7 @@ pub extern "C" fn meshport_context_new() -> u64 {
Arc::new(Context {
runtime,
network: Mutex::new(None),
socks: Mutex::new(None),
tcp: tokio::sync::Mutex::new(HashMap::new()),
udp: tokio::sync::Mutex::new(HashMap::new()),
}),
@@ -71,26 +105,134 @@ pub extern "C" fn meshport_context_new() -> u64 {
#[unsafe(no_mangle)]
pub extern "C" fn meshport_context_free(id: u64) {
// Drop outside registry lock; in-flight calls retain an Arc until completion.
let _ = catch_unwind(|| {
let context = CONTEXTS.lock().unwrap().remove(&id);
let _ = catch_unwind(AssertUnwindSafe(|| {
let Some(context) = CONTEXTS.lock().unwrap().remove(&id) else {
return;
};
// Stop now rather than when the last Arc drops: a `wait_routes` call
// holds one without the serial lock, and stopping is what wakes it.
if let Ok(mut network) = context.network.lock() {
let _ = stop_all(&context, &mut network);
}
drop(context);
});
}));
}
fn start_socks(context: &Context, n: &Arc<Network>, request: &Value) -> anyhow::Result<String> {
let mut slot = context.socks.lock().unwrap();
anyhow::ensure!(slot.is_none(), "SOCKS bridge already started");
let port = match request.get("port") {
Some(value) => u16::try_from(
value
.as_u64()
.ok_or_else(|| anyhow::anyhow!("invalid port"))?,
)?,
None => 0,
};
let max_sessions = match request.get("max_sessions") {
Some(value) => usize::try_from(
value
.as_u64()
.ok_or_else(|| anyhow::anyhow!("invalid session limit"))?,
)?,
None => 128,
};
let options = meshport_socks::Options {
listen: std::net::SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, port),
max_sessions,
..Default::default()
};
let bridge = context
.runtime
.block_on(meshport_socks::Bridge::start(n.clone(), options))?;
let address = bridge.local_addr().to_string();
*slot = Some(bridge);
Ok(address)
}
fn stop_all(context: &Context, network: &mut Option<Arc<Network>>) -> anyhow::Result<()> {
let bridge = context.socks.lock().unwrap().take();
let result = match bridge {
Some(mut bridge) => context.runtime.block_on(bridge.stop()),
None => Ok(()),
};
context.tcp.blocking_lock().clear();
context.udp.blocking_lock().clear();
if let Some(n) = network.take() {
context.runtime.block_on(n.stop());
}
result
}
fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
let op = request["op"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing op"))?;
if op == "abi_info" {
return Ok(json!({"abi": 1, "revision": CAPABILITY_REVISION, "operations": OPERATIONS}));
}
// Long poll for route changes. Runs outside the serial context lock so a
// host can wait on one thread while issuing other requests on another.
if op == "wait_routes" {
let timeout_ms = request["timeout_ms"].as_u64().unwrap_or(25000);
anyhow::ensure!(
(1..=30000).contains(&timeout_ms),
"timeout_ms must be 1 to 30000"
);
let after = match request.get("after_generation") {
None | Some(Value::Null) => None,
Some(value) => Some(
value
.as_u64()
.ok_or_else(|| anyhow::anyhow!("invalid after_generation"))?,
),
};
let network = context
.network
.lock()
.map_err(|_| anyhow::anyhow!("context lock poisoned"))?
.clone();
let Some(network) = network else {
return Ok(json!({"running": false, "changed": after.is_some(),
"route_generation": null, "mesh_cidrs": [], "subnet_routes": []}));
};
let mut watch = network.watch_mesh_routes();
let changed = context.runtime.block_on(async {
tokio::time::timeout(
Duration::from_millis(timeout_ms),
watch.wait_for(|r| r.stopped || after.is_none_or(|a| r.generation != a)),
)
.await
.is_ok()
});
let routes = watch.borrow().clone();
return Ok(json!({"running": !routes.stopped,
"changed": changed && after.is_some_and(|a| a != routes.generation),
"route_generation": routes.generation, "mesh_cidrs": routes.cidrs,
"subnet_routes": routes.subnet_routes}));
}
if op == "diagnostics_enable" {
return Ok(json!({"enabled": diagnostics::enable(), "scope": "process"}));
}
if op == "build_config" {
return Ok(json!({"toml": meshport::build_config(&request["profile"])?}));
}
if op == "migrate_config" {
let input = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
let (toml, changed) = meshport::migrate_config(input)?;
return Ok(json!({"toml": toml, "changed": changed}));
}
if op == "validate" {
use meshport_easytier::ConfigLoader;
let input = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
let config = meshport::validate_config(input)?;
if request["check_local_overlap"].as_bool() == Some(true) {
meshport::check_local_overlap(&config)?;
}
let flags = config.get_flags();
let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"}});
let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"},
"overlay": meshport::overlay_projection(&config)});
// Only return credentials when the local caller explicitly requests a
// form projection. Ordinary validation remains free of credentials.
if request["include_profile"].as_bool() == Some(true) {
@@ -105,7 +247,22 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
"peers": config.get_peers().iter().map(|peer| peer.uri.to_string()).collect::<Vec<_>>(),
"enable_ipv6": flags.enable_ipv6,
"latency_first": flags.latency_first,
"optimization": optimization
"optimization": optimization,
"listeners": config.get_listener_uris().iter().map(|uri| uri.to_string()).collect::<Vec<_>>(),
"stun_servers": config.get_stun_servers(),
"stun_servers_v6": config.get_stun_servers_v6(),
"flags": {
"default_protocol": flags.default_protocol,
"disable_p2p": flags.disable_p2p,
"disable_tcp_hole_punching": flags.disable_tcp_hole_punching,
"disable_udp_hole_punching": flags.disable_udp_hole_punching,
"disable_sym_hole_punching": flags.disable_sym_hole_punching,
"p2p_only": flags.p2p_only,
"lazy_p2p": flags.lazy_p2p,
"need_p2p": flags.need_p2p,
"private_mode": flags.private_mode,
"foreign_relay_bps_limit": flags.foreign_relay_bps_limit.to_string()
}
});
}
return Ok(result);
@@ -136,17 +293,87 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
let config = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
*network = Some(context.runtime.block_on(Network::start(config))?);
if request["check_local_overlap"].as_bool() == Some(true) {
meshport::check_local_overlap(&meshport::validate_config(config)?)?;
}
*network = Some(Arc::new(context.runtime.block_on(Network::start(config))?));
Ok(json!({"engine_started": true}))
}
// Application-mode network plus SOCKS bridge as one step, for hosts that
// route traffic into the mesh. Either both run or neither does.
"start_bridged" => {
use meshport_easytier::ConfigLoader;
anyhow::ensure!(
network.is_none(),
"already started; stop before applying a new configuration"
);
let input = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
let config = meshport::validate_config(input)?;
anyhow::ensure!(
config.get_flags().no_tun,
"bridged routing requires application-mode MeshPort"
);
let overlay = meshport::overlay_projection(&config);
anyhow::ensure!(
!overlay.is_null() || request["require_static_overlay"].as_bool() != Some(true),
"static mesh IPv4 required for bridged routing"
);
anyhow::ensure!(
overlay.is_null() || overlay["routable"] == true,
"bridged routing requires a private IPv4 overlay with prefix /16 through /32"
);
if request["check_local_overlap"].as_bool() == Some(true) {
meshport::check_local_overlap(&config)?;
}
let n = Arc::new(context.runtime.block_on(Network::start(input))?);
*network = Some(n.clone());
let listen = match start_socks(context, &n, &request) {
Ok(listen) => listen,
Err(error) => {
let _ = stop_all(context, &mut network);
return Err(error);
}
};
let routes = n.watch_mesh_routes().borrow().clone();
Ok(
json!({"engine_started": true, "listen": listen, "overlay": overlay,
"mesh_cidrs": routes.cidrs, "route_generation": routes.generation}),
)
}
"stop" => {
context.tcp.blocking_lock().clear();
context.udp.blocking_lock().clear();
if let Some(n) = network.take() {
context.runtime.block_on(n.stop());
stop_all(context, &mut network)?;
Ok(json!({"stopped": true}))
}
"socks_start" => {
let n = network
.as_ref()
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
let address = start_socks(context, n, &request)?;
Ok(
json!({"running": true, "listen": address, "tcp": true, "udp": true, "ipv4_only": true, "dns_resolution": false}),
)
}
"socks_stop" => {
if let Some(mut bridge) = context.socks.lock().unwrap().take() {
context.runtime.block_on(bridge.stop())?;
}
Ok(json!({"stopped": true}))
}
"socks_status" => {
let slot = context.socks.lock().unwrap();
Ok(match slot.as_ref() {
Some(bridge) => {
let s = bridge.snapshot();
json!({"running": s.running, "listen": bridge.local_addr().to_string(),
"active_sessions": s.active_sessions, "accepted_sessions": s.accepted_sessions,
"completed_sessions": s.completed_sessions, "failed_sessions": s.failed_sessions,
"refused_at_capacity": s.refused_at_capacity, "dropped_udp_packets": s.dropped_udp_packets})
}
None => json!({"running": false, "active_sessions": 0}),
})
}
"status" => match network.as_ref() {
Some(n) => {
let mut snapshot = context.runtime.block_on(n.snapshot());
@@ -160,9 +387,24 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
})
.collect::<Vec<_>>();
snapshot["diagnostic_traces"] = json!(traces);
let engine_running = snapshot["state"] == "Running";
let bridge_running = context
.socks
.lock()
.unwrap()
.as_ref()
.is_some_and(|b| b.snapshot().running);
// mesh_routable: traffic a host routes to mesh_cidrs via the
// bridge can currently be delivered.
snapshot["health"] = json!({"engine_running": engine_running,
"bridge_running": bridge_running,
"mesh_routable": engine_running && bridge_running});
Ok(snapshot)
}
None => Ok(json!({"state": "Stopped", "peer_count": 0, "application_only": true})),
None => Ok(
json!({"state": "Stopped", "peer_count": 0, "application_only": true,
"health": {"engine_running": false, "bridge_running": false, "mesh_routable": false}}),
),
},
"quality_sample" => {
let network = network
@@ -390,6 +632,10 @@ mod tests {
&json!({"op": "validate", "toml": config, "include_profile": true}).to_string(),
);
assert_eq!(projected["ok"], true);
assert_eq!(
projected["data"]["profile"]["flags"]["foreign_relay_bps_limit"],
"18446744073709551615"
);
assert_eq!(
projected["data"]["profile"]["network_secret"],
"test-only-secret"
@@ -401,4 +647,216 @@ mod tests {
);
meshport_context_free(id);
}
#[test]
fn config_build_and_migration_are_sdk_operations() {
let id = meshport_context_new();
let built = call(
id,
&json!({"op": "build_config", "profile": {"runtime_mode": "unified_vpn",
"ipv4": "10.79.0.11/24", "network_name": "n", "network_secret": "s"}})
.to_string(),
);
assert_eq!(built["ok"], true);
let toml = built["data"]["toml"].as_str().unwrap();
let validated = call(id, &json!({"op": "validate", "toml": toml}).to_string());
assert_eq!(validated["data"]["runtime_mode"], "application");
assert_eq!(validated["data"]["overlay"]["network"], "10.79.0.0/24");
let legacy = format!("{toml}\nsubnet_routes = ['192.168.21.0/24']\n");
let migrated = call(
id,
&json!({"op": "migrate_config", "toml": legacy}).to_string(),
);
assert_eq!(migrated["data"]["changed"], true);
let migrated = migrated["data"]["toml"].as_str().unwrap();
assert_eq!(
call(id, &json!({"op": "validate", "toml": migrated}).to_string())["ok"],
true
);
meshport_context_free(id);
}
#[test]
fn bridged_start_is_atomic_and_reports_routes_and_health() {
let id = meshport_context_new();
let base = "listeners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'bridged-ffi-test'\nnetwork_secret = 'test-only'\n";
let system = format!("ipv4 = '10.253.84.11/24'\n{base}[runtime]\nmode = 'system_vpn'\n");
let wide = format!("ipv4 = '10.253.84.11/8'\n{base}");
let dhcp = format!("dhcp = true\n{base}");
for (config, static_required) in [(system, false), (wide, false), (dhcp, true)] {
let refused = call(
id,
&json!({"op": "start_bridged", "toml": config,
"require_static_overlay": static_required})
.to_string(),
);
assert_eq!(refused["ok"], false, "{config}");
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped");
}
// Bridge failure (invalid session limit) rolls the network back.
let config = format!("ipv4 = '10.253.84.11/24'\n{base}");
let failed = call(
id,
&json!({"op": "start_bridged", "toml": config, "max_sessions": 0}).to_string(),
);
assert_eq!(failed["ok"], false);
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped");
let started = call(
id,
&json!({"op": "start_bridged", "toml": config}).to_string(),
);
assert_eq!(started["ok"], true, "{started}");
assert_eq!(started["data"]["mesh_cidrs"], json!(["10.253.84.0/24"]));
assert!(started["data"]["route_generation"].as_u64().unwrap() >= 1);
assert!(std::net::TcpStream::connect(started["data"]["listen"].as_str().unwrap()).is_ok());
let status = call(id, r#"{"op":"status"}"#)["data"].clone();
assert_eq!(status["health"]["mesh_routable"], true);
assert_eq!(
status["platform_network"]["mesh_cidrs"],
json!(["10.253.84.0/24"])
);
assert_eq!(
status["platform_network"]["overlay"]["address"],
"10.253.84.11"
);
let generation = started["data"]["route_generation"].as_u64().unwrap();
let idle = call(
id,
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 200})
.to_string(),
);
assert_eq!(idle["data"]["changed"], false, "{idle}");
assert_eq!(idle["data"]["running"], true);
assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true);
let status = call(id, r#"{"op":"status"}"#)["data"].clone();
assert_eq!(status["health"]["engine_running"], true);
assert_eq!(status["health"]["mesh_routable"], false);
// A waiter does not hold the context: status still answers, and stop
// wakes it with empty routes well before its timeout.
let waiter = std::thread::spawn(move || {
let at = std::time::Instant::now();
let reply = call(
id,
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000})
.to_string(),
);
(reply, at.elapsed())
});
std::thread::sleep(Duration::from_millis(200));
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true);
let (woken, waited) = waiter.join().unwrap();
assert!(waited < Duration::from_secs(10), "{waited:?}");
assert_eq!(woken["data"]["running"], false, "{woken}");
assert_eq!(woken["data"]["changed"], true);
assert_eq!(woken["data"]["mesh_cidrs"], json!([]));
assert_eq!(
call(id, r#"{"op":"wait_routes","timeout_ms":0}"#)["ok"],
false
);
let info = call(id, r#"{"op":"abi_info"}"#)["data"].clone();
assert_eq!(info["abi"], 1);
assert!(info["revision"].as_u64().unwrap() >= 2);
assert!(
info["operations"]
.as_array()
.unwrap()
.iter()
.any(|o| o == "wait_routes")
);
assert_eq!(
call(id, r#"{"op":"status"}"#)["data"]["health"]["mesh_routable"],
false
);
// Freeing without stop also stops the network and wakes a waiter.
let started = call(
id,
&json!({"op": "start_bridged", "toml": config}).to_string(),
);
assert_eq!(started["ok"], true, "{started}");
let generation = started["data"]["route_generation"].as_u64().unwrap();
let waiter = std::thread::spawn(move || {
let at = std::time::Instant::now();
let reply = call(
id,
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000})
.to_string(),
);
(reply, at.elapsed())
});
std::thread::sleep(Duration::from_millis(200));
meshport_context_free(id);
let (woken, waited) = waiter.join().unwrap();
assert!(waited < Duration::from_secs(10), "{waited:?}");
assert_eq!(woken["data"]["running"], false, "{woken}");
}
#[test]
fn socks_control_lifecycle_and_context_cleanup() {
use std::io::{Read, Write};
let id = meshport_context_new();
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
let config = "ipv4 = '10.253.83.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'socks-ffi-test'\nnetwork_secret = 'test-only'\n";
assert_eq!(
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
true
);
assert_eq!(
call(id, r#"{"op":"socks_start","port":65536}"#)["ok"],
false
);
assert_eq!(
call(id, r#"{"op":"socks_start","max_sessions":0}"#)["ok"],
false
);
let started = call(id, r#"{"op":"socks_start"}"#);
assert_eq!(started["ok"], true);
let address = started["data"]["listen"].as_str().unwrap();
let mut control = std::net::TcpStream::connect(address).unwrap();
control
.set_read_timeout(Some(Duration::from_secs(3)))
.unwrap();
control.write_all(&[5, 1, 0]).unwrap();
let mut reply = [0; 2];
control.read_exact(&mut reply).unwrap();
assert_eq!(reply, [5, 0]);
// A native session waiting for its request does not hold the ABI lock.
assert_eq!(
call(id, r#"{"op":"socks_status"}"#)["data"]["active_sessions"],
1
);
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true);
assert_eq!(control.read(&mut [0]).unwrap(), 0);
assert!(std::net::TcpStream::connect(address).is_err());
assert_eq!(
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
false
);
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], true);
assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true);
assert_eq!(
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
false
);
assert_eq!(
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
true
);
let restarted = call(id, r#"{"op":"socks_start"}"#);
let address = restarted["data"]["listen"].as_str().unwrap();
let mut control = std::net::TcpStream::connect(address).unwrap();
control
.set_read_timeout(Some(Duration::from_secs(3)))
.unwrap();
control.write_all(&[5, 1, 0]).unwrap();
control.read_exact(&mut reply).unwrap();
meshport_context_free(id);
assert_eq!(control.read(&mut [0]).unwrap(), 0);
// No lingering listener after context destruction.
std::net::TcpListener::bind(address).unwrap();
}
}
+77
View File
@@ -0,0 +1,77 @@
use easytier::instance::factory::create_native_instance;
use easytier_core::config::toml::TomlConfig;
use serde_json::{Value, json};
use std::ffi::{CStr, CString};
fn call(id: u64, request: Value) -> Value {
let input = CString::new(request.to_string()).unwrap();
unsafe {
let reply = meshport_ffi::meshport_call(id, input.as_ptr());
let result = serde_json::from_slice(CStr::from_ptr(reply).to_bytes()).unwrap();
meshport_ffi::meshport_string_free(reply);
result
}
}
use std::time::Duration;
use tokio::net::UdpSocket;
#[test]
fn ffi_udp_through_adjacent_mapped_subnet() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let _entered = runtime.enter();
let setup = async {
let port = UdpSocket::bind("127.0.0.1:0")
.await
.unwrap()
.local_addr()
.unwrap()
.port();
let identity =
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
let server_config = TomlConfig::new_from_str(&format!(
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
)).unwrap();
let server = create_native_instance(server_config).unwrap();
server.start().await.unwrap();
let client = format!(
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
);
(server, client)
};
let (server, client) = runtime.block_on(setup);
drop(_entered);
let id = meshport_ffi::meshport_context_new();
assert_eq!(call(id, json!({"op":"start", "toml":client}))["ok"], true);
let deadline = std::time::Instant::now();
loop {
if call(id, json!({"op":"status"}))["data"]["platform_network"]["subnet_routes"]
.as_array()
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
{
break;
}
assert!(deadline.elapsed() < Duration::from_secs(15));
std::thread::sleep(Duration::from_millis(100));
}
let (target, echo): (std::net::SocketAddr, _) = runtime.block_on(async {
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
.parse()
.unwrap();
let echo = tokio::spawn(async move {
let mut buffer = [0; 128];
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
udp.send_to(&buffer[..n], source).await.unwrap();
});
(target, echo)
});
let result = call(
id,
json!({"op":"probe", "target":target.to_string(), "protocol":"UDP", "echo":true, "timeout_ms":3000}),
);
echo.abort();
call(id, json!({"op":"stop"}));
meshport_ffi::meshport_context_free(id);
runtime.block_on(server.stop());
assert_eq!(result["ok"], true, "FFI UDP failed: {result}");
}
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "meshport-socks"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
[dependencies]
meshport.workspace = true
anyhow.workspace = true
tokio.workspace = true
[dev-dependencies]
meshport-easytier.workspace = true
easytier = { workspace = true, features = ["smoltcp", "proxy-packet"] }
easytier-core.workspace = true
tokio = { workspace = true, features = ["signal", "process"] }
serde_json.workspace = true
futures = "0.3"
parking_lot = "0.12"
smoltcp = { version = "0.14", default-features = false }
tokio-util = { version = "0.7", features = ["rt"] }
tracing = "0.1"
bytes = "1"
aes-gcm = "0.10"
libloading = "0.8"
@@ -0,0 +1,43 @@
//! Run with an application-mode TOML file; never prints its credentials.
use anyhow::{Context, Result};
use meshport::Network;
use meshport_socks::{Bridge, Options};
use std::{
net::{Ipv4Addr, SocketAddrV4},
sync::Arc,
};
#[tokio::main]
async fn main() -> Result<()> {
let mut arguments = std::env::args().skip(1);
let path = arguments
.next()
.context("usage: local_bridge CONFIG.toml [PORT]")?;
let port = arguments
.next()
.map(|s| s.parse::<u16>())
.transpose()?
.unwrap_or(0);
anyhow::ensure!(arguments.next().is_none(), "too many arguments");
let config = std::fs::read_to_string(path).context("cannot read configuration")?;
let network = Arc::new(Network::start(&config).await?);
let result = async {
let mut bridge = Bridge::start(
network.clone(),
Options {
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, port),
..Default::default()
},
)
.await?;
println!("MeshPort SOCKS5 IPv4 TCP/UDP: {}", bridge.local_addr());
println!("Waiting for Ctrl-C; engine startup does not guarantee remote reachability.");
let signal = tokio::signal::ctrl_c().await;
bridge.stop().await?;
signal?;
Ok::<_, anyhow::Error>(())
}
.await;
network.stop().await;
result
}
+395
View File
@@ -0,0 +1,395 @@
//! Local IPv4 SOCKS5 bridge to the MeshPort application data plane.
//! No DNS or ordinary internet fallback. This is a restricted internal bridge,
//! not a public SOCKS service (no GSSAPI, password authentication, or BIND).
mod protocol;
use anyhow::{Result, ensure};
use meshport::Network;
use protocol::*;
use std::{
collections::HashSet,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::{
Arc,
atomic::{AtomicU64, AtomicUsize, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt, copy, split},
net::{TcpListener, TcpStream, UdpSocket},
sync::{Semaphore, watch},
task::{JoinHandle, JoinSet},
time::{Instant, sleep_until, timeout},
};
#[derive(Clone, Debug)]
pub struct Options {
pub listen: SocketAddrV4,
pub max_sessions: usize,
pub handshake_timeout: Duration,
pub connect_timeout: Duration,
/// Grace period for the remaining direction after either side reaches EOF.
pub tcp_close_timeout: Duration,
pub udp_idle_timeout: Duration,
pub udp_io_timeout: Duration,
pub max_udp_targets: usize,
}
impl Default for Options {
fn default() -> Self {
Self {
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0),
max_sessions: 128,
handshake_timeout: Duration::from_secs(5),
connect_timeout: Duration::from_secs(10),
tcp_close_timeout: Duration::from_secs(30),
udp_idle_timeout: Duration::from_secs(120),
udp_io_timeout: Duration::from_secs(5),
max_udp_targets: 64,
}
}
}
#[derive(Default)]
struct Counters {
active: AtomicUsize,
accepted: AtomicU64,
completed: AtomicU64,
failed: AtomicU64,
refused_at_capacity: AtomicU64,
dropped_udp: AtomicU64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Snapshot {
pub running: bool,
pub active_sessions: usize,
pub accepted_sessions: u64,
pub completed_sessions: u64,
pub failed_sessions: u64,
pub refused_at_capacity: u64,
pub dropped_udp_packets: u64,
}
struct Active(Arc<Counters>);
impl Drop for Active {
fn drop(&mut self) {
self.0.active.fetch_sub(1, Ordering::Relaxed);
}
}
/// Owns the listener and its sessions, but not the supplied network.
/// Stop the bridge before stopping the network. Dropping aborts all sessions;
/// `stop` additionally waits for resources to be released.
pub struct Bridge {
address: SocketAddrV4,
shutdown: watch::Sender<bool>,
task: Option<JoinHandle<std::io::Result<()>>>,
counters: Arc<Counters>,
}
impl Bridge {
pub async fn start(network: Arc<Network>, options: Options) -> Result<Self> {
ensure!(
options.listen.ip().is_loopback(),
"SOCKS bridge must bind IPv4 loopback"
);
ensure!(
options.max_sessions > 0 && options.max_sessions <= 4096,
"invalid session limit"
);
ensure!(
options.max_udp_targets > 0 && options.max_udp_targets <= 1024,
"invalid UDP target limit"
);
ensure!(
!options.handshake_timeout.is_zero()
&& !options.connect_timeout.is_zero()
&& !options.tcp_close_timeout.is_zero()
&& !options.udp_idle_timeout.is_zero()
&& !options.udp_io_timeout.is_zero(),
"timeouts must be positive"
);
let status = network.snapshot().await;
ensure!(
status["application_only"] == true,
"SOCKS bridge requires application mode"
);
ensure!(status["state"] == "Running", "network is not running");
let listener = TcpListener::bind(options.listen).await?;
let SocketAddr::V4(address) = listener.local_addr()? else {
unreachable!()
};
let counters = Arc::new(Counters::default());
let (shutdown, rx) = watch::channel(false);
let task = tokio::spawn(serve(listener, network, options, rx, counters.clone()));
Ok(Self {
address,
shutdown,
task: Some(task),
counters,
})
}
pub fn local_addr(&self) -> SocketAddrV4 {
self.address
}
pub fn snapshot(&self) -> Snapshot {
let c = &self.counters;
Snapshot {
running: self.task.as_ref().is_some_and(|task| !task.is_finished()),
active_sessions: c.active.load(Ordering::Relaxed),
accepted_sessions: c.accepted.load(Ordering::Relaxed),
completed_sessions: c.completed.load(Ordering::Relaxed),
failed_sessions: c.failed.load(Ordering::Relaxed),
refused_at_capacity: c.refused_at_capacity.load(Ordering::Relaxed),
dropped_udp_packets: c.dropped_udp.load(Ordering::Relaxed),
}
}
pub async fn stop(&mut self) -> Result<()> {
self.shutdown.send_replace(true);
if let Some(task) = self.task.take() {
task.await??;
}
Ok(())
}
}
impl Drop for Bridge {
fn drop(&mut self) {
self.shutdown.send_replace(true);
if let Some(task) = &self.task {
task.abort();
}
}
}
async fn serve(
listener: TcpListener,
network: Arc<Network>,
options: Options,
mut shutdown: watch::Receiver<bool>,
counters: Arc<Counters>,
) -> std::io::Result<()> {
let permits = Arc::new(Semaphore::new(options.max_sessions));
let mut sessions = JoinSet::new();
let result = loop {
tokio::select! {
biased;
_ = shutdown.changed() => break Ok(()),
_ = sessions.join_next(), if !sessions.is_empty() => {},
accepted = listener.accept() => {
let (stream, peer) = match accepted { Ok(v) => v, Err(e) => break Err(e) };
let Ok(permit) = permits.clone().try_acquire_owned() else {
counters.refused_at_capacity.fetch_add(1, Ordering::Relaxed);
drop(stream);
continue;
};
let SocketAddr::V4(peer) = peer else { continue; };
counters.active.fetch_add(1, Ordering::Relaxed);
counters.accepted.fetch_add(1, Ordering::Relaxed);
let active = Active(counters.clone());
let c = counters.clone();
let network = network.clone();
let options = options.clone();
sessions.spawn(async move {
let _permit = permit;
let _active = active;
if session(stream, peer, network, options, &c).await.is_err() {
c.failed.fetch_add(1, Ordering::Relaxed);
} else {
c.completed.fetch_add(1, Ordering::Relaxed);
}
});
}
}
};
drop(listener);
sessions.shutdown().await;
result
}
fn empty_address() -> SocketAddrV4 {
SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)
}
async fn session(
mut stream: TcpStream,
peer: SocketAddrV4,
network: Arc<Network>,
options: Options,
counters: &Counters,
) -> Result<()> {
let request = timeout(options.handshake_timeout, async {
ensure!(negotiate(&mut stream).await?, "no acceptable SOCKS method");
Ok::<_, anyhow::Error>(request(&mut stream).await?)
})
.await??;
let request = match request {
Ok(request) => request,
Err(code) => {
reply(&mut stream, code, empty_address()).await?;
anyhow::bail!("unsupported SOCKS request");
}
};
if request.command == 1 {
if !valid_target(request.address) {
reply(&mut stream, DENIED, empty_address()).await?;
anyhow::bail!("invalid mesh destination");
}
let result = timeout(
options.connect_timeout,
network.connect_tcp(request.address.into(), options.connect_timeout),
)
.await;
let mut overlay = match result {
Ok(Ok(stream)) => stream,
error => {
let code = match &error {
Ok(Err(e))
if e.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::ConnectionRefused) =>
{
REFUSED
}
_ => HOST_UNREACHABLE,
};
reply(&mut stream, code, empty_address()).await?;
anyhow::bail!("mesh connection unavailable");
}
};
let SocketAddr::V4(bound) = overlay.local_addr() else {
unreachable!()
};
reply(&mut stream, SUCCESS, bound).await?;
relay_tcp(&mut stream, &mut overlay, options.tcp_close_timeout).await?;
return Ok(());
}
if !request.address.ip().is_unspecified() && request.address.ip() != peer.ip() {
reply(&mut stream, DENIED, empty_address()).await?;
anyhow::bail!("UDP source differs from control connection");
}
let setup = timeout(options.connect_timeout, async {
let SocketAddr::V4(local) = stream.local_addr()? else {
unreachable!()
};
let relay = UdpSocket::bind(SocketAddrV4::new(*local.ip(), 0)).await?;
let overlay = network.bind_udp(0, options.connect_timeout).await?;
Ok::<_, anyhow::Error>((relay, overlay))
})
.await;
let (relay, overlay) = match setup {
Ok(Ok(v)) => v,
_ => {
reply(&mut stream, FAILURE, empty_address()).await?;
anyhow::bail!("UDP setup failed");
}
};
let SocketAddr::V4(bound) = relay.local_addr()? else {
unreachable!()
};
reply(&mut stream, SUCCESS, bound).await?;
udp_session(
stream,
peer,
request.address.port(),
relay,
overlay,
options,
counters,
)
.await
}
async fn relay_tcp(
local: &mut TcpStream,
remote: &mut meshport::TcpStream,
close_timeout: Duration,
) -> Result<()> {
let (mut local_read, mut local_write) = split(local);
let (mut remote_read, mut remote_write) = split(remote);
let (closed, mut closure) = watch::channel(false);
let upload = async {
copy(&mut local_read, &mut remote_write).await?;
// Notify before native shutdown: a FIN ACK may never arrive after
// a route disappears. Permit pending response data a bounded grace.
closed.send_replace(true);
remote_write.shutdown().await
};
let download = async {
copy(&mut remote_read, &mut local_write).await?;
closed.send_replace(true);
local_write.shutdown().await
};
let forwarding = async { tokio::try_join!(upload, download) };
tokio::pin!(forwarding);
tokio::select! {
result = &mut forwarding => { result?; }
_ = closure.changed() => { timeout(close_timeout, forwarding).await??; }
}
Ok(())
}
async fn udp_session(
mut control: TcpStream,
peer: SocketAddrV4,
source_port: u16,
relay: UdpSocket,
overlay: meshport::UdpSocket,
options: Options,
counters: &Counters,
) -> Result<()> {
let mut endpoint = (source_port != 0).then_some(SocketAddrV4::new(*peer.ip(), source_port));
let mut targets = HashSet::new();
let mut local_buffer = vec![0; 65535];
let mut remote_buffer = vec![0; 65535];
let mut control_buffer = [0; 1];
let mut idle = Instant::now() + options.udp_idle_timeout;
loop {
tokio::select! {
// Association lifetime is tied to its TCP control channel.
result = control.read(&mut control_buffer) => {
result?;
return Ok(()); // EOF or unexpected control payload closes it.
}
_ = sleep_until(idle) => return Ok(()),
result = relay.recv_from(&mut local_buffer) => {
let (len, source) = result?;
let SocketAddr::V4(source) = source else { continue; };
let decoded = udp_request(&local_buffer[..len]);
if source.ip() != peer.ip() || endpoint.is_some_and(|e| e != source) || decoded.is_none() {
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
continue;
}
let (target, payload) = decoded.unwrap();
if !targets.contains(&target) && targets.len() >= options.max_udp_targets {
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
continue;
}
endpoint = Some(source);
// Count attempted destinations too: the native socket can register
// a flow before a send fails. This bounds its resource growth.
targets.insert(target);
match timeout(options.udp_io_timeout, overlay.send_to(payload, target.into())).await {
Ok(Ok(n)) if n == payload.len() => idle = Instant::now() + options.udp_idle_timeout,
_ => { counters.dropped_udp.fetch_add(1, Ordering::Relaxed); }
}
}
result = overlay.recv_from(&mut remote_buffer) => {
let (len, source) = result?;
let SocketAddr::V4(source) = source else { continue; };
let Some(endpoint) = endpoint else { continue; };
if !targets.contains(&source) { continue; }
let Some(frame) = udp_reply(source, &remote_buffer[..len]) else {
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
continue;
};
timeout(options.udp_io_timeout, relay.send_to(&frame, endpoint)).await??;
idle = Instant::now() + options.udp_idle_timeout;
}
}
}
}
+134
View File
@@ -0,0 +1,134 @@
use std::net::{Ipv4Addr, SocketAddrV4};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
pub(crate) const SUCCESS: u8 = 0;
pub(crate) const FAILURE: u8 = 1;
pub(crate) const DENIED: u8 = 2;
pub(crate) const HOST_UNREACHABLE: u8 = 4;
pub(crate) const REFUSED: u8 = 5;
pub(crate) const COMMAND_UNSUPPORTED: u8 = 7;
pub(crate) const ADDRESS_UNSUPPORTED: u8 = 8;
pub(crate) struct Request {
pub command: u8,
pub address: SocketAddrV4,
}
pub(crate) async fn negotiate<S: AsyncRead + AsyncWrite + Unpin>(
s: &mut S,
) -> std::io::Result<bool> {
let mut header = [0; 2];
s.read_exact(&mut header).await?;
if header[0] != 5 || header[1] == 0 {
return Ok(false);
}
let mut methods = vec![0; header[1] as usize];
s.read_exact(&mut methods).await?;
let accepted = methods.contains(&0);
s.write_all(&[5, if accepted { 0 } else { 255 }]).await?;
Ok(accepted)
}
/// Unsupported address types are deliberately not resolved using system DNS.
pub(crate) async fn request<S: AsyncRead + Unpin>(
s: &mut S,
) -> std::io::Result<Result<Request, u8>> {
let mut header = [0; 4];
s.read_exact(&mut header).await?;
if header[0] != 5 || header[2] != 0 {
return Ok(Err(FAILURE));
}
if !matches!(header[1], 1 | 3) {
return Ok(Err(COMMAND_UNSUPPORTED));
}
if header[3] != 1 {
return Ok(Err(ADDRESS_UNSUPPORTED));
}
let mut address = [0; 6];
s.read_exact(&mut address).await?;
Ok(Ok(Request {
command: header[1],
address: decode_address(&address),
}))
}
fn decode_address(bytes: &[u8]) -> SocketAddrV4 {
SocketAddrV4::new(
Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]),
u16::from_be_bytes([bytes[4], bytes[5]]),
)
}
pub(crate) fn address_bytes(address: SocketAddrV4) -> [u8; 6] {
let [a, b, c, d] = address.ip().octets();
let [hi, lo] = address.port().to_be_bytes();
[a, b, c, d, hi, lo]
}
pub(crate) async fn reply<S: AsyncWrite + Unpin>(
s: &mut S,
code: u8,
address: SocketAddrV4,
) -> std::io::Result<()> {
let mut bytes = vec![5, code, 0, 1];
bytes.extend_from_slice(&address_bytes(address));
s.write_all(&bytes).await
}
pub(crate) fn valid_target(address: SocketAddrV4) -> bool {
address.port() != 0
&& !address.ip().is_unspecified()
&& !address.ip().is_multicast()
&& !address.ip().is_broadcast()
&& !address.ip().is_loopback()
}
pub(crate) fn udp_request(bytes: &[u8]) -> Option<(SocketAddrV4, &[u8])> {
// No fragmentation, domain resolution, IPv6, or reserved bits.
if bytes.len() < 10 || bytes[..4] != [0, 0, 0, 1] || bytes.len() > 65507 {
return None;
}
let address = decode_address(&bytes[4..10]);
valid_target(address).then_some((address, &bytes[10..]))
}
pub(crate) fn udp_reply(address: SocketAddrV4, payload: &[u8]) -> Option<Vec<u8>> {
if payload.len() > 65497 {
return None;
}
let mut bytes = Vec::with_capacity(10 + payload.len());
bytes.extend_from_slice(&[0, 0, 0, 1]);
bytes.extend_from_slice(&address_bytes(address));
bytes.extend_from_slice(payload);
Some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn udp_rejects_malformed_fragmented_and_non_mesh_addresses() {
let target = "10.77.0.2:7007".parse().unwrap();
let frame = udp_reply(target, b"hello").unwrap();
assert_eq!(udp_request(&frame), Some((target, &b"hello"[..])));
for length in 0..10 {
assert!(udp_request(&frame[..length]).is_none());
}
for (index, value) in [(0, 1), (1, 1), (2, 1), (3, 3), (3, 4)] {
let mut bad = frame.clone();
bad[index] = value;
assert!(udp_request(&bad).is_none());
}
for address in [
"0.0.0.0:1",
"127.0.0.1:1",
"224.0.0.1:1",
"255.255.255.255:1",
"10.0.0.1:0",
] {
assert!(udp_request(&udp_reply(address.parse().unwrap(), b"x").unwrap()).is_none());
}
assert!(udp_reply(target, &vec![0; 65498]).is_none());
}
}
+732
View File
@@ -0,0 +1,732 @@
use easytier::instance::factory::create_native_instance;
use easytier_core::config::toml::{ConfigLoader, TomlConfig};
use meshport::Network;
use meshport_socks::{Bridge, Options};
use std::{
net::SocketAddrV4,
path::{Path, PathBuf},
process::Stdio,
sync::Arc,
time::{Duration, SystemTime},
};
use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
net::{TcpListener, TcpStream, UdpSocket},
task::JoinSet,
time::{sleep, timeout},
};
const WAIT: Duration = Duration::from_secs(15);
#[path = "support/queue_drop_counter.rs"]
mod queue_drop_counter;
#[path = "support/wire_stats.rs"]
mod wire_stats;
struct ExternalEngine {
child: tokio::process::Child,
config_path: PathBuf,
listen: SocketAddrV4,
}
impl Drop for ExternalEngine {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.config_path);
}
}
impl ExternalEngine {
async fn start(
binary: &Path,
bridge: SocketAddrV4,
network: &Network,
extra_cidrs: &[&str],
) -> Self {
let reserved = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let listen: SocketAddrV4 = reserved.local_addr().unwrap().to_string().parse().unwrap();
let stamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_nanos();
let config_path = std::env::temp_dir().join(format!(
"meshport-singbox-{}-{stamp}.json",
std::process::id()
));
let snapshot = network.snapshot().await;
let mut prefixes = snapshot["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.clone();
prefixes.push(snapshot["ipv4"].clone());
prefixes.extend(extra_cidrs.iter().map(|cidr| serde_json::json!(cidr)));
let config = serde_json::json!({"listen_port": listen.port(), "mesh_socks": bridge.to_string(), "mesh_cidrs": prefixes});
std::fs::write(&config_path, config.to_string()).unwrap();
drop(reserved);
let child = tokio::process::Command::new(binary)
.arg(&config_path)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()
.unwrap();
let mut engine = Self {
child,
config_path,
listen,
};
let mut readiness = String::new();
timeout(
WAIT,
BufReader::new(engine.child.stdout.take().unwrap()).read_line(&mut readiness),
)
.await
.unwrap()
.unwrap();
let ready: serde_json::Value = serde_json::from_str(&readiness).unwrap();
assert_eq!(ready["state"], "Running");
engine
}
async fn stop(&mut self) {
let id = self.child.id().unwrap();
let status = std::process::Command::new("/bin/kill")
.args(["-TERM", &id.to_string()])
.status()
.unwrap();
assert!(status.success());
assert!(
timeout(WAIT, self.child.wait())
.await
.unwrap()
.unwrap()
.success()
);
assert!(TcpStream::connect(self.listen).await.is_err());
}
}
fn config(ip: &str, bootstrap: Option<u16>) -> String {
let peer = bootstrap
.map(|port| format!("[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n"))
.unwrap_or_default();
format!(
"ipv4 = '{ip}/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = []\n{peer}[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n"
)
}
async fn negotiate(addr: SocketAddrV4) -> TcpStream {
let mut s = TcpStream::connect(addr).await.unwrap();
// Deliberately split protocol fields across writes.
s.write_all(&[5]).await.unwrap();
s.write_all(&[1, 0]).await.unwrap();
let mut reply = [0; 2];
s.read_exact(&mut reply).await.unwrap();
assert_eq!(reply, [5, 0]);
s
}
async fn request(s: &mut TcpStream, command: u8, target: SocketAddrV4) -> (u8, SocketAddrV4) {
let mut bytes = vec![5, command, 0, 1];
bytes.extend_from_slice(&target.ip().octets());
bytes.extend_from_slice(&target.port().to_be_bytes());
s.write_all(&bytes).await.unwrap();
let mut reply = [0; 10];
s.read_exact(&mut reply).await.unwrap();
assert_eq!([reply[0], reply[2], reply[3]], [5, 0, 1]);
(
reply[1],
SocketAddrV4::new(
[reply[4], reply[5], reply[6], reply[7]].into(),
u16::from_be_bytes([reply[8], reply[9]]),
),
)
}
fn frame(target: SocketAddrV4, payload: &[u8]) -> Vec<u8> {
let mut bytes = vec![0, 0, 0, 1];
bytes.extend_from_slice(&target.ip().octets());
bytes.extend_from_slice(&target.port().to_be_bytes());
bytes.extend_from_slice(payload);
bytes
}
async fn wait_no_sessions(bridge: &Bridge) {
timeout(WAIT, async {
while bridge.snapshot().active_sessions != 0 {
sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_tcp_udp_over_learned_subnet_and_withdrawal() {
overlay_check(None).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires the built Go engine; run sh scripts/test-singbox-bridge.sh"]
async fn singbox_to_meshport_tcp_udp_and_withdrawal() {
let binary = std::env::var_os("MESHPORT_SINGBOX_BIN").expect("MESHPORT_SINGBOX_BIN required");
overlay_check(Some(PathBuf::from(binary))).await;
}
async fn overlay_check(engine_binary: Option<PathBuf>) {
let port = std::net::UdpSocket::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
// A real remote gateway maps its advertised private subnet to an OS echo
// server. Unlike the SDK UDP listener, this accepts unknown first packets.
let server_config = TomlConfig::new_from_str(&format!(
"ipv4 = '10.253.81.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '127.0.0.0/24'\nmapped_cidr = '10.253.79.0/24'\n[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true"
)).unwrap();
let server = create_native_instance(server_config.clone()).unwrap();
server.start().await.unwrap();
let network = Arc::new(
Network::start(&config("10.253.80.11", Some(port)))
.await
.unwrap(),
);
timeout(WAIT, async {
while !network.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.iter()
.any(|r| r == "10.253.79.0/24")
{
sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
let tcp_target: SocketAddrV4 = format!("10.253.79.1:{}", tcp.local_addr().unwrap().port())
.parse()
.unwrap();
let tcp_echo = tokio::spawn(async move {
let mut children = JoinSet::new();
loop {
tokio::select! {
accepted = tcp.accept() => {
let (mut s, _) = accepted.unwrap();
children.spawn(async move {
let mut buffer = [0; 4096];
loop {
let n = s.read(&mut buffer).await.unwrap();
if n == 0 { break; }
s.write_all(&buffer[..n]).await.unwrap();
}
});
}
_ = children.join_next(), if !children.is_empty() => {}
}
}
});
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let udp_target: SocketAddrV4 = format!("10.253.79.1:{}", udp.local_addr().unwrap().port())
.parse()
.unwrap();
let udp_echo = tokio::spawn(async move {
let mut buffer = [0; 65535];
loop {
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
udp.send_to(&buffer[..n], source).await.unwrap();
}
});
let mut bridge = Bridge::start(
network.clone(),
Options {
tcp_close_timeout: Duration::from_secs(1),
..Options::default()
},
)
.await
.unwrap();
let mut engine = match engine_binary {
Some(binary) => {
Some(ExternalEngine::start(&binary, bridge.local_addr(), &network, &[]).await)
}
None => None,
};
let entry = engine.as_ref().map_or(bridge.local_addr(), |e| e.listen);
let result = timeout(Duration::from_secs(45), async {
// An established TCP connection blocked on read does not serialize
// the other connections or either UDP association.
let mut idle = negotiate(entry).await;
assert_eq!(request(&mut idle, 1, tcp_target).await.0, 0);
let mut clients = JoinSet::new();
for i in 0..4 {
let addr = entry;
clients.spawn(async move {
let mut s = negotiate(addr).await;
assert_eq!(request(&mut s, 1, tcp_target).await.0, 0);
let payload = vec![i; 32768];
s.write_all(&payload).await.unwrap();
let mut received = vec![0; payload.len()];
s.read_exact(&mut received).await.unwrap();
assert_eq!(received, payload);
s.shutdown().await.unwrap();
});
}
while let Some(result) = clients.join_next().await {
result.unwrap();
}
let mut associations = Vec::new();
for payload in [b"first-session".as_slice(), b"second-session".as_slice()] {
let local = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let mut control = negotiate(entry).await;
let (code, relay) = request(&mut control, 3, "0.0.0.0:0".parse().unwrap()).await;
assert_eq!(code, 0);
local
.send_to(&frame(udp_target, payload), relay)
.await
.unwrap();
associations.push((control, local, relay, payload));
}
for (_, local, _, payload) in &associations {
let mut buffer = [0; 256];
let (n, _) = timeout(WAIT, local.recv_from(&mut buffer))
.await
.unwrap()
.unwrap();
assert_eq!(&buffer[..n], frame(udp_target, payload));
}
// The direct bridge enforces endpoint pinning. The outer engine's
// inbound association policy is independently owned by sing-box.
let intruder = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let (control, local, relay, _) = associations.remove(0);
let mut buffer = [0; 128];
if engine.is_none() {
intruder
.send_to(&frame(udp_target, b"injected"), relay)
.await
.unwrap();
assert!(
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
.await
.is_err()
);
let mut fragmented = frame(udp_target, b"fragmented");
fragmented[2] = 1;
local.send_to(&fragmented, relay).await.unwrap();
assert!(
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
.await
.is_err()
);
}
drop(control);
let (remaining_control, remaining_local, remaining_relay, _) = associations.remove(0);
drop(idle);
if engine.is_none() {
assert!(bridge.snapshot().dropped_udp_packets >= 2);
}
// Removal propagates through the real route plane. A fresh SOCKS
// request fails rather than reaching the ordinary network.
server_config.clear_proxy_cidrs();
let updated =
easytier_core::instance::CoreInstanceConfig::from_toml(&server_config).unwrap();
server
.update_runtime_config(easytier_core::config::runtime::CoreInstanceRuntimeConfig {
services: updated.connectivity.runtime,
peer: Arc::new(updated.peer.snapshot),
})
.await
.unwrap();
timeout(WAIT, async {
while !network.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.is_empty()
{
sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
let mut rejected = negotiate(entry).await;
let code = request(&mut rejected, 1, tcp_target).await.0;
if engine.is_some() && code == 0 {
// sing-box acknowledges SOCKS before its asynchronous outbound
// dial. A route failure must then close, never deliver data.
let closed = timeout(WAIT, rejected.read(&mut buffer)).await.unwrap();
assert!(matches!(closed, Ok(0) | Err(_)));
} else {
assert_ne!(code, 0);
}
remaining_local
.send_to(&frame(udp_target, b"after-withdrawal"), remaining_relay)
.await
.unwrap();
assert!(
timeout(
Duration::from_millis(400),
remaining_local.recv_from(&mut buffer)
)
.await
.is_err()
);
drop(remaining_control);
drop(rejected);
if engine.is_none() {
wait_no_sessions(&bridge).await;
}
})
.await;
if let Some(engine) = &mut engine {
engine.stop().await;
}
bridge.stop().await.unwrap();
assert_eq!(bridge.snapshot().active_sessions, 0);
assert!(!bridge.snapshot().running);
assert!(TcpStream::connect(bridge.local_addr()).await.is_err());
bridge.stop().await.unwrap();
// Explicit stop releases the address, allowing a new bridge lifecycle.
let mut restarted = Bridge::start(
network.clone(),
Options {
listen: bridge.local_addr(),
..Options::default()
},
)
.await
.unwrap();
restarted.stop().await.unwrap();
network.stop().await;
server.stop().await;
tcp_echo.abort();
udp_echo.abort();
result.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn limits_protocol_errors_timeout_and_shutdown() {
let network = Arc::new(Network::start(&config("10.253.82.11", None)).await.unwrap());
assert!(
Bridge::start(
network.clone(),
Options {
listen: "0.0.0.0:0".parse().unwrap(),
..Options::default()
}
)
.await
.is_err()
);
let mut bridge = Bridge::start(
network.clone(),
Options {
max_sessions: 2,
handshake_timeout: Duration::from_millis(300),
udp_idle_timeout: Duration::from_millis(300),
..Options::default()
},
)
.await
.unwrap();
let result = timeout(WAIT, async {
let mut auth = TcpStream::connect(bridge.local_addr()).await.unwrap();
auth.write_all(&[5, 1, 2]).await.unwrap();
let mut selection = [0; 2];
auth.read_exact(&mut selection).await.unwrap();
assert_eq!(selection, [5, 255]);
assert_eq!(auth.read(&mut [0]).await.unwrap(), 0);
wait_no_sessions(&bridge).await;
for (bytes, code) in [
(&[5, 2, 0, 1][..], 7),
(&[5, 1, 0, 3][..], 8),
(&[5, 1, 0, 4][..], 8),
(&[4, 1, 0, 1][..], 1),
(&[5, 1, 1, 1][..], 1),
] {
let mut s = negotiate(bridge.local_addr()).await;
s.write_all(bytes).await.unwrap();
let mut response = [0; 10];
s.read_exact(&mut response).await.unwrap();
assert_eq!(response[1], code);
assert_eq!(s.read(&mut [0]).await.unwrap(), 0);
wait_no_sessions(&bridge).await;
}
let mut wrong_source = negotiate(bridge.local_addr()).await;
assert_eq!(
request(&mut wrong_source, 3, "127.0.0.2:1".parse().unwrap())
.await
.0,
2
);
drop(wrong_source);
wait_no_sessions(&bridge).await;
let mut control = negotiate(bridge.local_addr()).await;
assert_eq!(
request(&mut control, 3, "0.0.0.0:0".parse().unwrap())
.await
.0,
0
);
assert_eq!(control.read(&mut [0]).await.unwrap(), 0); // idle association expiry
wait_no_sessions(&bridge).await;
let mut incomplete = TcpStream::connect(bridge.local_addr()).await.unwrap();
incomplete.write_all(&[5]).await.unwrap();
assert_eq!(incomplete.read(&mut [0]).await.unwrap(), 0);
wait_no_sessions(&bridge).await;
// Exhaust both slots with incomplete handshakes.
let _a = TcpStream::connect(bridge.local_addr()).await.unwrap();
let _b = TcpStream::connect(bridge.local_addr()).await.unwrap();
timeout(Duration::from_millis(200), async {
while bridge.snapshot().active_sessions < 2 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let mut rejected = TcpStream::connect(bridge.local_addr()).await.unwrap();
assert_eq!(rejected.read(&mut [0]).await.unwrap(), 0);
assert_eq!(bridge.snapshot().refused_at_capacity, 1);
bridge.stop().await.unwrap();
assert_eq!(bridge.snapshot().active_sessions, 0);
})
.await;
bridge.stop().await.unwrap();
network.stop().await;
result.unwrap();
}
// Isolated diagnostic: no system routes, user profiles, STUN or WAN traffic.
// Report timings rather than asserting host-dependent throughput thresholds.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "local throughput diagnostic; run release with --ignored --nocapture"]
async fn subnet_throughput_diagnostic() {
let trace_tcp = std::env::var_os("MESHPORT_TEST_TRACE_TCP").is_some();
let queue_drops = Arc::new(std::sync::atomic::AtomicU64::new(0));
if trace_tcp {
tracing::subscriber::set_global_default(queue_drop_counter::QueueDropCounter(
queue_drops.clone(),
))
.unwrap();
}
let entries =
std::env::var("MESHPORT_TEST_ENTRIES").unwrap_or_else(|_| "sdk,socks,singbox".to_owned());
let entries: Vec<_> = entries.split(',').collect();
assert!(
entries
.iter()
.all(|entry| matches!(*entry, "sdk" | "socks" | "singbox"))
);
if entries.contains(&"singbox") && std::env::var_os("MESHPORT_SINGBOX_BIN").is_none() {
println!("singbox entry skipped: MESHPORT_SINGBOX_BIN not set");
}
let mib = std::env::var("MESHPORT_TEST_MIB")
.map(|v| v.parse::<usize>().expect("size must be MiB"))
.unwrap_or(2);
assert!((1..=64).contains(&mib));
let size = mib * 1024 * 1024;
let delays = std::env::var("MESHPORT_TEST_DELAY_MS")
.map(|v| vec![v.parse::<u64>().expect("delay must be milliseconds")])
.unwrap_or_else(|_| vec![0, 29, 50]);
for delay_ms in delays {
let reserve = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
let port = reserve.local_addr().unwrap().port();
drop(reserve);
let server_config = TomlConfig::new_from_str(&format!(
"ipv4 = '10.253.81.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '127.0.0.0/24'\nmapped_cidr = '10.253.79.0/24'\n[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true\ndisable_p2p = true\nenable_encryption = true"
)).unwrap();
let server = create_native_instance(server_config).unwrap();
server.start().await.unwrap();
let relay = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
let relay_port = relay.local_addr().unwrap().port();
// Only synthetic local test packets are inspected, using the fixture key.
// Real user profiles and production traffic are never captured here.
let wire_stats = Arc::new(std::sync::Mutex::new([
wire_stats::WireStats::default(),
wire_stats::WireStats::default(),
]));
let relay_stats = wire_stats.clone();
let relay_task = tokio::spawn(async move {
use aes_gcm::{AeadInPlace, KeyInit};
use easytier_core::packet::{StandardAeadTail, ZCPacket, ZCPacketType};
use std::hash::Hasher;
// Same deterministic key derivation as the fixture's production
// encryptor; the core encrypt module is intentionally private.
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write(b"test-only");
let mut key = [0u8; 16];
key[..8].copy_from_slice(&hasher.finish().to_be_bytes());
hasher.write(&key[..8]);
key[8..].copy_from_slice(&hasher.finish().to_be_bytes());
let cipher = aes_gcm::Aes128Gcm::new((&key).into());
let remote: std::net::SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
let mut client = None;
let mut pending = std::collections::VecDeque::new();
let mut packet = vec![0u8; 65536];
loop {
let deadline = pending
.front()
.map(|v: &(tokio::time::Instant, Vec<u8>, std::net::SocketAddr)| v.0)
.unwrap_or_else(|| tokio::time::Instant::now() + Duration::from_secs(3600));
tokio::select! {
value = relay.recv_from(&mut packet) => {
let (n, source) = value.unwrap();
if trace_tcp && n >= 24 && packet[4] == 3 && packet[16] == 1 {
let mut copy = ZCPacket::new_from_buf(bytes::BytesMut::from(&packet[..n]), ZCPacketType::UDP);
let encrypted = copy.peer_manager_header().unwrap().is_encrypted();
let len = copy.payload().len() - if encrypted {StandardAeadTail::SIZE} else {0};
if encrypted {
let tag: [u8;16] = copy.payload()[len..len+16].try_into().unwrap();
let nonce: [u8;12] = copy.payload()[len+16..].try_into().unwrap();
cipher.decrypt_in_place_detached((&nonce).into(), &[], &mut copy.mut_payload()[..len], (&tag).into()).unwrap();
}
relay_stats.lock().unwrap()[usize::from(source == remote)].record(&copy.payload()[..len]);
}
let destination = if source == remote {
let Some(client) = client else { continue; };
client
} else { client = Some(source); remote };
pending.push_back((tokio::time::Instant::now() + Duration::from_millis(delay_ms), packet[..n].to_vec(), destination));
}
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
let (_, data, destination) = pending.pop_front().unwrap();
relay.send_to(&data, destination).await.unwrap();
}
}
}
});
let client_config =
config("10.253.80.11", Some(relay_port)) + "[flags]\ndisable_p2p = true\n";
let network = Arc::new(Network::start(&client_config).await.unwrap());
timeout(WAIT, async {
while !network.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.iter()
.any(|r| r == "10.253.79.0/24")
{
sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
let os_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let os_port = os_listener.local_addr().unwrap().port();
let mut sdk_listener = server.data_plane_tcp_bind(0, WAIT).await.unwrap();
let sdk_port = sdk_listener.local_addr().port();
let mut bridge = Bridge::start(network.clone(), Options::default())
.await
.unwrap();
let mut engine = match std::env::var_os("MESHPORT_SINGBOX_BIN") {
Some(binary) => Some(
ExternalEngine::start(
Path::new(&binary),
bridge.local_addr(),
&network,
&["10.253.81.2/32"],
)
.await,
),
None => None,
};
for (kind, target) in [
("sdk", format!("10.253.81.2:{sdk_port}")),
("subnet", format!("10.253.79.1:{os_port}")),
] {
if std::env::var("MESHPORT_TEST_TARGET").is_ok_and(|selected| selected != kind) {
continue;
}
for &entry in &entries {
if entry == "singbox" && engine.is_none() {
continue;
}
for download in [true, false] {
if trace_tcp {
*wire_stats.lock().unwrap() = Default::default();
queue_drops.store(0, std::sync::atomic::Ordering::Relaxed);
}
let (finished, completion) = tokio::sync::oneshot::channel();
let client = async {
let mut socket: Box<dyn DiagnosticIo> = if entry == "sdk" {
Box::new(
network
.connect_tcp(target.parse().unwrap(), WAIT)
.await
.unwrap(),
)
} else {
let address = if entry == "socks" {
bridge.local_addr()
} else {
engine.as_ref().unwrap().listen
};
let mut socket = negotiate(address).await;
assert_eq!(request(&mut socket, 1, target.parse().unwrap()).await.0, 0);
Box::new(socket)
};
let payload = vec![0x5a; size];
let start = std::time::Instant::now();
if download {
socket.write_all(&[1]).await.unwrap();
let mut response = vec![0; size];
socket.read_exact(&mut response).await.unwrap();
assert_eq!(response, payload);
} else {
socket.write_all(&payload).await.unwrap();
assert_eq!(socket.read_u8().await.unwrap(), 1);
}
finished.send(()).unwrap();
println!(
"{kind} entry={entry} added_rtt_ms={} direction={} mib={} mbps={:.2}",
delay_ms * 2,
if download { "download" } else { "upload" },
mib,
size as f64 * 8.0 / start.elapsed().as_secs_f64() / 1e6
);
};
let responder = async {
let mut socket: Box<dyn DiagnosticIo> = if kind == "sdk" {
Box::new(sdk_listener.accept().await.unwrap().0)
} else {
Box::new(os_listener.accept().await.unwrap().0)
};
if download {
assert_eq!(socket.read_u8().await.unwrap(), 1);
socket.write_all(&vec![0x5a; size]).await.unwrap();
} else {
let mut response = vec![0; size];
socket.read_exact(&mut response).await.unwrap();
assert!(response.iter().all(|v| *v == 0x5a));
socket.write_all(&[1]).await.unwrap();
}
completion.await.unwrap();
};
timeout(Duration::from_secs(60), async {
tokio::join!(client, responder);
})
.await
.unwrap();
if trace_tcp {
let stats = wire_stats.lock().unwrap();
println!(
"{}",
serde_json::json!({"mode":"easytier_encrypted_relay", "target":kind,"entry":entry,
"direction":if download {"download"} else {"upload"}, "client_wire_at_relay":stats[0].observation_json(),
"server_wire_at_relay":stats[1].observation_json(),
"udp_session_queue_full_drops":queue_drops.load(std::sync::atomic::Ordering::Relaxed)})
);
}
}
}
}
if let Some(engine) = engine.as_mut() {
engine.stop().await;
}
bridge.stop().await.unwrap();
network.stop().await;
server.stop().await;
relay_task.abort();
let _ = relay_task.await;
}
}
trait DiagnosticIo: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {}
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> DiagnosticIo for T {}
+625
View File
@@ -0,0 +1,625 @@
//! Real Rust SDK + Go FFI in one process; no TUN, WAN, user profiles or STUN.
use anyhow::{Result, ensure};
use easytier::instance::factory::create_native_instance;
use easytier_core::config::toml::TomlConfig;
use meshport::Network;
use meshport_socks::{Bridge, Options};
use serde_json::{Value, json};
use std::{
ffi::{CStr, CString, c_char},
net::{Ipv4Addr, SocketAddrV4},
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::{Duration, Instant},
};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
net::{TcpListener, TcpStream, UdpSocket},
sync::{Barrier, oneshot},
task::{JoinHandle, JoinSet},
time::{sleep, timeout},
};
const CHUNK: usize = 64 * 1024;
const MESH_TAG: u8 = 0x51;
const PROXY_TAG: u8 = 0xa7;
const WAIT: Duration = Duration::from_secs(15);
trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
struct NativeProxy {
handle: u64,
call: unsafe extern "C" fn(u64, *const c_char) -> *mut c_char,
free_string: unsafe extern "C" fn(*mut c_char),
free: unsafe extern "C" fn(u64),
listen: SocketAddrV4,
}
impl NativeProxy {
fn open() -> Result<Self> {
let path = std::env::var_os("MESHPORT_PROXY_LIBRARY")
.ok_or_else(|| anyhow::anyhow!("MESHPORT_PROXY_LIBRARY required"))?;
// Go runtime threads retain executable addresses: never dlclose this
// library, including on an error path. Contexts still stop/free normally.
let library = std::mem::ManuallyDrop::new(unsafe { libloading::Library::new(path)? });
unsafe {
let version =
*library.get::<unsafe extern "C" fn() -> u32>(b"meshport_proxy_abi_version")?;
ensure!(version() == 1, "proxy ABI mismatch");
let new =
*library.get::<unsafe extern "C" fn() -> u64>(b"meshport_proxy_context_new")?;
let handle = new();
ensure!(handle != 0, "proxy context creation failed");
Ok(Self {
handle,
call: *library.get(b"meshport_proxy_call")?,
free_string: *library.get(b"meshport_proxy_string_free")?,
free: *library.get(b"meshport_proxy_context_free")?,
listen: "127.0.0.1:0".parse()?,
})
}
}
fn request(&self, value: Value) -> Result<Value> {
let input = CString::new(value.to_string())?;
let raw = unsafe { (self.call)(self.handle, input.as_ptr()) };
ensure!(!raw.is_null(), "missing proxy response");
let parsed = unsafe { serde_json::from_slice::<Value>(CStr::from_ptr(raw).to_bytes()) };
unsafe { (self.free_string)(raw) };
let parsed = parsed?;
ensure!(parsed["ok"] == true, "proxy error: {}", parsed["error"]);
Ok(parsed["data"].clone())
}
fn start(&mut self, feature: &str, bridge: SocketAddrV4, proxy: SocketAddrV4) -> Result<()> {
let reserve = std::net::TcpListener::bind("127.0.0.1:0")?;
self.listen = reserve.local_addr()?.to_string().parse()?;
drop(reserve);
let cidrs = if feature == "proxy" {
vec![]
} else {
vec!["10.253.91.0/24", "10.253.93.0/24"]
};
let config = json!({"feature":feature,"mode":"global","listen_port":self.listen.port(),
"mesh_socks":if feature == "proxy" {String::new()} else {bridge.to_string()},"mesh_cidrs":cidrs,
"protected_cidrs":cidrs,
"proxy":if feature=="mesh" {Value::Null} else {json!({"type":"socks","version":"5","server":"127.0.0.1","server_port":proxy.port()})}});
ensure!(
self.request(json!({"op":"start","config":config}))?["state"] == "Running",
"proxy did not start"
);
Ok(())
}
async fn stop(&self) -> Result<()> {
ensure!(
self.request(json!({"op":"stop"}))?["state"] == "Stopped",
"proxy did not stop"
);
ensure!(
TcpStream::connect(self.listen).await.is_err(),
"proxy port still listening"
);
Ok(())
}
}
impl Drop for NativeProxy {
fn drop(&mut self) {
unsafe { (self.free)(self.handle) }
}
}
async fn socks(
entry: SocketAddrV4,
command: u8,
target: SocketAddrV4,
) -> Result<(TcpStream, SocketAddrV4)> {
let mut stream = TcpStream::connect(entry).await?;
stream.write_all(&[5, 1, 0]).await?;
let mut auth = [0; 2];
stream.read_exact(&mut auth).await?;
ensure!(auth == [5, 0], "SOCKS auth failed");
let mut request = vec![5, command, 0, 1];
request.extend(target.ip().octets());
request.extend(target.port().to_be_bytes());
stream.write_all(&request).await?;
let mut reply = [0; 10];
stream.read_exact(&mut reply).await?;
ensure!(
reply[0] == 5 && reply[1] == 0 && reply[3] == 1,
"SOCKS request failed: {:?}",
reply
);
Ok((
stream,
SocketAddrV4::new(
Ipv4Addr::new(reply[4], reply[5], reply[6], reply[7]),
u16::from_be_bytes([reply[8], reply[9]]),
),
))
}
async fn pace(start: Instant, bytes: u64, mbps: u32) {
if mbps > 0 {
let elapsed = Duration::from_secs_f64(bytes as f64 * 8.0 / (mbps as f64 * 1e6));
if let Some(remaining) = elapsed.checked_sub(start.elapsed()) {
sleep(remaining).await;
}
}
}
async fn serve(mut socket: Box<dyn Io>, tag: u8, limit: u32) -> Result<()> {
let direction = socket.read_u8().await?;
let ms = socket.read_u64().await?;
ensure!((500..=10000).contains(&ms), "invalid duration");
let mut payload = vec![tag; CHUNK];
let start = Instant::now();
let mut total = 0u64;
if direction == 1 {
while start.elapsed() < Duration::from_millis(ms) {
socket.write_u32(CHUNK as u32).await?;
socket.write_all(&payload).await?;
total += CHUNK as u64;
pace(start, total, limit).await;
}
socket.write_u32(0).await?;
socket.write_u64(total).await?;
} else {
ensure!(direction == 2, "invalid direction");
loop {
let len = socket.read_u32().await? as usize;
if len == 0 {
break;
}
ensure!(len <= CHUNK, "invalid upload frame");
socket.read_exact(&mut payload[..len]).await?;
ensure!(
payload[..len].iter().all(|v| *v == tag),
"upload data/route corruption"
);
total += len as u64;
}
socket.write_u64(total).await?;
}
socket.flush().await?;
Ok(())
}
struct ProxyStub {
address: SocketAddrV4,
task: JoinHandle<()>,
wrong: Arc<AtomicUsize>,
tcp: Arc<AtomicUsize>,
udp: Arc<AtomicUsize>,
}
impl ProxyStub {
async fn start(limit: u32) -> Result<Self> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let address = listener.local_addr()?.to_string().parse()?;
let wrong = Arc::new(AtomicUsize::new(0));
let tcp = Arc::new(AtomicUsize::new(0));
let udp = Arc::new(AtomicUsize::new(0));
let (w, t, u) = (wrong.clone(), tcp.clone(), udp.clone());
let task = tokio::spawn(async move {
let mut handlers = JoinSet::new();
loop {
tokio::select! {
accepted=listener.accept()=>{let (mut stream,_)=accepted.unwrap();let (w,t,u)=(w.clone(),t.clone(),u.clone());
handlers.spawn(async move {let outcome:Result<()>=async {
let mut auth=[0;3];stream.read_exact(&mut auth).await?;ensure!(auth==[5,1,0],"unexpected upstream auth");stream.write_all(&[5,0]).await?;
let mut request=[0;10];stream.read_exact(&mut request).await?;
ensure!(request[0]==5&&request[3]==1,"unsupported upstream request");
if request[1]==1 {
if request[4..10]!=[198,51,100,77,1,187] {w.fetch_add(1,Ordering::Relaxed);anyhow::bail!("wrong TCP outbound");}
t.fetch_add(1,Ordering::Relaxed);stream.write_all(&[5,0,0,1,127,0,0,1,0,0]).await?;
serve(Box::new(stream),PROXY_TAG,limit).await?;
} else {
ensure!(request[1]==3,"unsupported upstream command");
let relay=UdpSocket::bind("127.0.0.1:0").await?;let port=relay.local_addr()?.port();
let mut reply=vec![5,0,0,1,127,0,0,1];reply.extend(port.to_be_bytes());stream.write_all(&reply).await?;
let mut buffer=[0u8;2048];let mut control=[0;1];loop {tokio::select! {
_=stream.read(&mut control)=>break,
message=relay.recv_from(&mut buffer)=>{let (n,source)=message?;
if n<10 || buffer[..10]!=[0,0,0,1,198,51,100,77,20,233] {w.fetch_add(1,Ordering::Relaxed);anyhow::bail!("wrong UDP outbound");}
u.fetch_add(1,Ordering::Relaxed);relay.send_to(&buffer[..n],source).await?;
}
}}
}
Ok(())
}.await;let _=outcome;});
},
_=handlers.join_next(),if !handlers.is_empty()=>{}
}
}
});
Ok(Self {
address,
task,
wrong,
tcp,
udp,
})
}
async fn stop(&mut self) {
self.task.abort();
let _ = (&mut self.task).await;
}
}
impl Drop for ProxyStub {
fn drop(&mut self) {
self.task.abort();
}
}
struct Flow {
bytes: u64,
start: Instant,
end: Instant,
}
impl Flow {
fn json(
&self,
phase: &str,
lane: &str,
direction: &str,
repeat: usize,
overlap_ms: u128,
) -> Value {
let seconds = self.end.duration_since(self.start).as_secs_f64();
json!({"mode":"combined_flow","phase":phase,"lane":lane,
"direction":direction,"repeat":repeat,"bytes":self.bytes,"seconds":seconds,"mbps":self.bytes as f64*8.0/seconds/1e6,"overlap_ms":overlap_ms})
}
}
async fn transfer(
entry: SocketAddrV4,
target: SocketAddrV4,
download: bool,
tag: u8,
seconds: u64,
limit: u32,
barrier: Option<Arc<Barrier>>,
mut progress: Option<oneshot::Sender<()>>,
) -> Result<Flow> {
timeout(Duration::from_secs(seconds + 15), async {
let (mut socket, _) = socks(entry, 1, target).await?;
if let Some(barrier) = barrier {
barrier.wait().await;
}
let start = Instant::now();
socket.write_u8(if download { 1 } else { 2 }).await?;
socket.write_u64(seconds * 1000).await?;
let mut payload = vec![tag; CHUNK];
let mut bytes = 0u64;
if download {
loop {
let len = socket.read_u32().await? as usize;
if len == 0 {
break;
}
ensure!(len <= CHUNK, "invalid download frame");
socket.read_exact(&mut payload[..len]).await?;
ensure!(
payload[..len].iter().all(|v| *v == tag),
"download data/route corruption"
);
bytes += len as u64;
if let Some(tx) = progress.take() {
let _ = tx.send(());
}
}
ensure!(socket.read_u64().await? == bytes, "download count mismatch");
} else {
while start.elapsed() < Duration::from_secs(seconds) {
socket.write_u32(CHUNK as u32).await?;
socket.write_all(&payload).await?;
bytes += CHUNK as u64;
if let Some(tx) = progress.take() {
let _ = tx.send(());
}
pace(start, bytes, limit).await;
}
socket.write_u32(0).await?;
ensure!(socket.read_u64().await? == bytes, "upload count mismatch");
}
ensure!(bytes > 0, "empty transfer");
Ok(Flow {
bytes,
start,
end: Instant::now(),
})
})
.await?
}
async fn udp_probe(entry: SocketAddrV4, target: SocketAddrV4, tag: u8) -> Result<()> {
timeout(WAIT, async {
let (_control, relay) = socks(entry, 3, "0.0.0.0:0".parse()?).await?;
let local = UdpSocket::bind("127.0.0.1:0").await?;
let mut frame = vec![0, 0, 0, 1];
frame.extend(target.ip().octets());
frame.extend(target.port().to_be_bytes());
frame.extend([tag, 3, 5, 7]);
local.send_to(&frame, relay).await?;
let mut buffer = [0u8; 2048];
let (n, _) = local.recv_from(&mut buffer).await?;
ensure!(buffer[..n] == frame, "UDP data/route corruption");
Ok(())
})
.await?
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "native combined load test; run scripts/test.py combined"]
async fn combined_coexistence() -> Result<()> {
let seconds = std::env::var("MESHPORT_JOINT_SECONDS")
.unwrap_or_else(|_| "2".into())
.parse::<u64>()?;
let repeats = std::env::var("MESHPORT_JOINT_REPEATS")
.unwrap_or_else(|_| "3".into())
.parse::<usize>()?;
let delay = std::env::var("MESHPORT_TEST_DELAY_MS")
.unwrap_or_else(|_| "29".into())
.parse::<u64>()?;
let limit = std::env::var("MESHPORT_JOINT_PROXY_MBPS")
.unwrap_or_else(|_| "100".into())
.parse::<u32>()?;
ensure!(
(1..=5).contains(&seconds) && (1..=10).contains(&repeats) && delay <= 500,
"invalid joint test parameters"
);
let reserved = std::net::UdpSocket::bind("127.0.0.1:0")?;
let port = reserved.local_addr()?.port();
drop(reserved);
let identity =
"[network_identity]\nnetwork_name='combined-fixture'\nnetwork_secret='test-only'\n";
let server = create_native_instance(TomlConfig::new_from_str(&format!(
"ipv4='10.253.91.2/24'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/24'\nmapped_cidr='10.253.93.0/24'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true\ndisable_p2p=true\nenable_encryption=true"
))?)?;
server.start().await?;
let relay = UdpSocket::bind("127.0.0.1:0").await?;
let relay_port = relay.local_addr()?.port();
let relay_task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
let remote: std::net::SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
let mut client = None;
let mut pending = std::collections::VecDeque::new();
let mut buf = vec![0u8; 65536];
loop {
let at = pending
.front()
.map(|(at, _, _): &(tokio::time::Instant, Vec<u8>, std::net::SocketAddr)| *at)
.unwrap_or_else(|| tokio::time::Instant::now() + Duration::from_secs(3600));
tokio::select! {value=relay.recv_from(&mut buf)=>{let(n,source)=value.unwrap();let dest=if source==remote {let Some(client)=client else{continue};client}else{client=Some(source);remote};pending.push_back((tokio::time::Instant::now()+Duration::from_millis(delay),buf[..n].to_vec(),dest));},
_=tokio::time::sleep_until(at),if !pending.is_empty()=>{let(_,data,dest)=pending.pop_front().unwrap();relay.send_to(&data,dest).await.unwrap();}}
}
}));
let network=Arc::new(Network::start(&format!("ipv4='10.253.91.11/24'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{relay_port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true\ndisable_p2p=true")).await?);
timeout(WAIT, async {
while network.snapshot().await["peer_count"].as_u64().unwrap_or(0) == 0 {
sleep(Duration::from_millis(50)).await;
}
})
.await?;
let mut bridge = Bridge::start(network.clone(), Options::default()).await?;
let mut listener = server.data_plane_tcp_bind(0, WAIT).await?;
let mesh: SocketAddrV4 = format!("10.253.91.2:{}", listener.local_addr().port()).parse()?;
let mesh_task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
let mut children = JoinSet::new();
loop {
tokio::select! {
accepted=listener.accept()=>{let Ok((socket,_))=accepted else {break};children.spawn(serve(Box::new(socket),MESH_TAG,0));},
_=children.join_next(),if !children.is_empty()=>{}
}
}
}));
let echo = UdpSocket::bind("127.0.0.1:0").await?;
let mesh_udp: SocketAddrV4 = format!("10.253.93.1:{}", echo.local_addr()?.port()).parse()?;
let echo_task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
let mut buf = [0; 2048];
loop {
let (n, source) = echo.recv_from(&mut buf).await.unwrap();
echo.send_to(&buf[..n], source).await.unwrap();
}
}));
let mut upstream = ProxyStub::start(limit).await?;
let internet: SocketAddrV4 = "198.51.100.77:443".parse()?;
let internet_udp = "198.51.100.77:5353".parse()?;
let mut engine = NativeProxy::open()?;
for round in 1..=repeats {
for download in [true, false] {
let direction = if download { "download" } else { "upload" };
for (phase, feature, lane, target, tag, rate) in [
("mesh_only", "mesh", "mesh", mesh, MESH_TAG, 0),
("proxy_only", "proxy", "proxy", internet, PROXY_TAG, limit),
("combined_idle_mesh", "combined", "mesh", mesh, MESH_TAG, 0),
(
"combined_idle_proxy",
"combined",
"proxy",
internet,
PROXY_TAG,
limit,
),
] {
engine.start(feature, bridge.local_addr(), upstream.address)?;
let flow = transfer(
engine.listen,
target,
download,
tag,
seconds,
rate,
None,
None,
)
.await?;
println!("{}", flow.json(phase, lane, direction, round, 0));
engine.stop().await?;
}
engine.start("combined", bridge.local_addr(), upstream.address)?;
let gate = Arc::new(Barrier::new(2));
let (mtx, mrx) = oneshot::channel();
let (ptx, prx) = oneshot::channel();
let a = transfer(
engine.listen,
mesh,
download,
MESH_TAG,
seconds,
0,
Some(gate.clone()),
Some(mtx),
);
let b = transfer(
engine.listen,
internet,
download,
PROXY_TAG,
seconds,
limit,
Some(gate),
Some(ptx),
);
let probes = async {
mrx.await?;
prx.await?;
let start = Instant::now();
for _ in 0..4 {
let (m, p) = tokio::join!(
udp_probe(engine.listen, mesh_udp, MESH_TAG),
udp_probe(engine.listen, internet_udp, PROXY_TAG)
);
m?;
p?;
}
Ok::<_, anyhow::Error>((start, Instant::now()))
};
let (a, b, probes) = tokio::join!(a, b, probes);
let (a, b, probes) = (a?, b?, probes?);
let overlap = a
.end
.min(b.end)
.duration_since(a.start.max(b.start))
.as_millis();
ensure!(
overlap >= seconds as u128 * 800,
"insufficient concurrent overlap"
);
ensure!(
probes.0 >= a.start.max(b.start) && probes.1 <= a.end.min(b.end),
"UDP probes were not under concurrent TCP load"
);
println!(
"{}",
a.json("concurrent", "mesh", direction, round, overlap)
);
println!(
"{}",
b.json("concurrent", "proxy", direction, round, overlap)
);
engine.stop().await?;
}
}
ensure!(
upstream.wrong.load(Ordering::Relaxed) == 0
&& upstream.tcp.load(Ordering::Relaxed) > 0
&& upstream.udp.load(Ordering::Relaxed) == repeats * 2 * 4,
"route counters mismatch"
);
engine.start("combined", bridge.local_addr(), upstream.address)?;
let (tx, rx) = oneshot::channel();
let healthy = transfer(
engine.listen,
mesh,
true,
MESH_TAG,
seconds,
0,
None,
Some(tx),
);
let fail_proxy = async {
rx.await?;
upstream.stop().await;
ensure!(
transfer(
engine.listen,
internet,
true,
PROXY_TAG,
seconds,
limit,
None,
None
)
.await
.is_err(),
"stopped proxy unexpectedly succeeded"
);
Ok::<_, anyhow::Error>(())
};
let (healthy, failed) = tokio::join!(healthy, fail_proxy);
healthy?;
failed?;
engine.stop().await?;
upstream = ProxyStub::start(limit).await?;
engine.start("combined", bridge.local_addr(), upstream.address)?;
transfer(
engine.listen,
internet,
true,
PROXY_TAG,
seconds,
limit,
None,
None,
)
.await?;
let (tx, rx) = oneshot::channel();
let healthy = transfer(
engine.listen,
internet,
true,
PROXY_TAG,
seconds,
limit,
None,
Some(tx),
);
let fail_mesh = async {
rx.await?;
let before = upstream.tcp.load(Ordering::Relaxed);
bridge.stop().await?;
network.stop().await;
ensure!(
transfer(engine.listen, mesh, true, MESH_TAG, seconds, 0, None, None)
.await
.is_err(),
"stopped mesh unexpectedly succeeded"
);
ensure!(
upstream.tcp.load(Ordering::Relaxed) == before,
"mesh leaked into proxy"
);
Ok::<_, anyhow::Error>(())
};
let (healthy, failed) = tokio::join!(healthy, fail_mesh);
healthy?;
failed?;
ensure!(
engine.request(json!({"op":"status"}))?["state"] == "Running",
"healthy proxy was stopped"
);
engine.stop().await?;
upstream.stop().await;
server.stop().await;
drop(mesh_task);
drop(echo_task);
drop(relay_task);
println!(
"{}",
json!({"mode":"combined_functional","mesh_survives_proxy_stop":true,"proxy_survives_mesh_stop":true,
"no_mesh_to_proxy_fallback":true,"proxy_recovered":true,"ports_released":true,"udp_probes_per_lane":repeats*2*4,
"rtt_ms":delay*2,"duration_seconds":seconds,"proxy_limit_mbps":limit,"repeats":repeats})
);
Ok(())
}
@@ -0,0 +1,48 @@
//! Counts the existing production UDP queue-full trace event in synthetic tests.
use std::sync::{
Arc,
atomic::{AtomicU64, Ordering},
};
pub(crate) struct QueueDropCounter(pub(crate) Arc<AtomicU64>);
impl tracing::Subscriber for QueueDropCounter {
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
metadata.target().ends_with("socket::udp::session")
}
fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
tracing::span::Id::from_u64(1)
}
fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
fn enter(&self, _: &tracing::span::Id) {}
fn exit(&self, _: &tracing::span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
struct Visitor(bool);
impl tracing::field::Visit for Visitor {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
if field.name() == "message"
&& format!("{value:?}").contains("udp session data queue full")
{
self.0 = true;
}
}
}
let mut visitor = Visitor(false);
event.record(&mut visitor);
if visitor.0 {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
}
#[test]
fn counts_only_udp_session_queue_full_events() {
let count = Arc::new(AtomicU64::new(0));
tracing::subscriber::with_default(QueueDropCounter(count.clone()), || {
tracing::trace!(target: "easytier_core::socket::udp::session", "udp session data queue full");
tracing::trace!(target: "easytier_core::socket::udp::session", "other session event");
tracing::trace!(target: "other_target", "udp session data queue full");
});
assert_eq!(count.load(Ordering::Relaxed), 1);
}
@@ -0,0 +1,122 @@
use smoltcp::wire::{Ipv4Packet, TcpPacket};
use std::collections::HashSet;
use tokio::time::Instant;
#[derive(Default)]
pub(crate) struct WireStats {
emitted_packets: usize,
pub(crate) received_packets: usize,
data_packets: usize,
repeated_sequences: usize,
duplicate_acks: usize,
zero_windows: usize,
max_advertised_window: usize,
window_scale: Option<u8>,
last_ack: Option<i32>,
seen: HashSet<(u16, i32, usize)>,
last_data: Option<Instant>,
max_data_gap_ms: u128,
}
#[test]
fn counts_repeated_data_sequences_but_ignores_ip_fragments() {
let mut bytes = vec![0u8; 41];
{
let mut ip = Ipv4Packet::new_unchecked(&mut bytes);
ip.set_version(4);
ip.set_header_len(20);
ip.set_total_len(41);
ip.set_next_header(smoltcp::wire::IpProtocol::Tcp);
}
{
let mut tcp = TcpPacket::new_unchecked(&mut bytes[20..]);
tcp.set_header_len(20);
tcp.set_src_port(1234);
tcp.set_dst_port(5678);
tcp.set_seq_number(smoltcp::wire::TcpSeqNumber(100));
tcp.set_window_len(4096);
}
bytes[40] = 0x5a;
let mut stats = WireStats::default();
stats.record(&bytes);
stats.record(&bytes);
assert_eq!(stats.json()["data_packets"], 2);
assert_eq!(stats.json()["repeated_sequences"], 1);
assert_eq!(stats.json()["max_advertised_window"], 4096);
Ipv4Packet::new_unchecked(&mut bytes).set_more_frags(true);
stats.record(&bytes);
assert_eq!(stats.json()["data_packets"], 2);
}
impl WireStats {
pub(crate) fn record(&mut self, bytes: &[u8]) {
let Ok(ip) = Ipv4Packet::new_checked(bytes) else {
return;
};
if ip.next_header() != smoltcp::wire::IpProtocol::Tcp
|| ip.frag_offset() != 0
|| ip.more_frags()
{
return;
}
let Ok(tcp) = TcpPacket::new_checked(ip.payload()) else {
return;
};
self.emitted_packets += 1;
if tcp.syn() {
self.window_scale = smoltcp::wire::TcpRepr::parse(
&tcp,
&smoltcp::wire::IpAddress::Ipv4(ip.src_addr()),
&smoltcp::wire::IpAddress::Ipv4(ip.dst_addr()),
&smoltcp::phy::ChecksumCapabilities::ignored(),
)
.unwrap()
.window_scale;
}
let window = (tcp.window_len() as usize)
<< if tcp.syn() {
0
} else {
self.window_scale.unwrap_or(0)
};
self.max_advertised_window = self.max_advertised_window.max(window);
if window == 0 {
self.zero_windows += 1;
}
let len = tcp.payload().len();
if len > 0 {
self.data_packets += 1;
if !self.seen.insert((tcp.src_port(), tcp.seq_number().0, len)) {
self.repeated_sequences += 1;
}
let now = Instant::now();
if let Some(last) = self.last_data {
self.max_data_gap_ms = self
.max_data_gap_ms
.max(now.duration_since(last).as_millis());
}
self.last_data = Some(now);
} else if tcp.ack() && !tcp.syn() && !tcp.fin() {
let ack = tcp.ack_number().0;
if self.last_ack == Some(ack) {
self.duplicate_acks += 1;
}
self.last_ack = Some(ack);
}
}
pub(crate) fn observation_json(&self) -> serde_json::Value {
let mut value = self.json();
let map = value.as_object_mut().unwrap();
let observed = map.remove("emitted_packets").unwrap();
map.remove("received_packets");
map.insert("observed_tcp_packets".to_owned(), observed);
value
}
pub(crate) fn json(&self) -> serde_json::Value {
serde_json::json!({"emitted_packets":self.emitted_packets,"received_packets":self.received_packets,
"data_packets":self.data_packets,"repeated_sequences":self.repeated_sequences,
"duplicate_ack_numbers":self.duplicate_acks,"zero_window_packets":self.zero_windows,
"max_advertised_window":self.max_advertised_window,"window_scale":self.window_scale,
"max_data_gap_ms":self.max_data_gap_ms})
}
}
@@ -0,0 +1,226 @@
//! Native TCP-stack isolation over lossless channels or loopback UDP.
//! Includes the production wrapper so reactor/socket behavior stays identical.
#![allow(dead_code, unused_imports)]
mod foundation {
pub mod time {
pub use tokio::time::{Instant, sleep};
}
}
#[path = "../../../vendor/easytier/easytier-core/src/gateway/smoltcp/tokio_smoltcp/mod.rs"]
mod stack;
use smoltcp::{
phy::{DeviceCapabilities, Medium},
wire::{HardwareAddress, Ipv4Packet, TcpPacket},
};
use stack::{BufferSize, Net, NetConfig, channel_device::ChannelDevice};
use std::{
collections::{HashSet, VecDeque},
sync::{Arc, Mutex},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
sync::mpsc,
time::{Instant, timeout},
};
#[path = "support/wire_stats.rs"]
mod wire_stats;
use wire_stats::WireStats;
fn net(
ip: &str,
mtu: usize,
tx_kib: usize,
) -> (
Net,
mpsc::Sender<std::io::Result<Vec<u8>>>,
mpsc::Receiver<Vec<u8>>,
) {
let mut caps = DeviceCapabilities::default();
caps.medium = Medium::Ip;
caps.max_transmission_unit = mtu;
let (device, input, output) = ChannelDevice::new(caps);
let config = NetConfig::new(
smoltcp::iface::Config::new(HardwareAddress::Ip),
format!("{ip}/24").parse().unwrap(),
vec![],
Some(BufferSize {
tcp_rx_size: 1024 * 1024,
tcp_tx_size: tx_kib * 1024,
..Default::default()
}),
);
(Net::new(device, config), input, output)
}
async fn link(
mut output: mpsc::Receiver<Vec<u8>>,
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
delay: Duration,
stats: Arc<Mutex<WireStats>>,
) {
let mut pending = VecDeque::new();
loop {
let deadline = pending
.front()
.map(|(at, _): &(Instant, Vec<u8>)| *at)
.unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));
tokio::select! {
packet = output.recv() => {
let Some(packet) = packet else { return; };
stats.lock().unwrap().record(&packet);
pending.push_back((Instant::now() + delay, packet));
}
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
let (_, packet) = pending.pop_front().unwrap();
if input.send(Ok(packet)).await.is_err() { return; }
stats.lock().unwrap().received_packets += 1;
}
}
}
}
async fn udp_link(
mut output: mpsc::Receiver<Vec<u8>>,
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
delay: Duration,
stats: Arc<Mutex<WireStats>>,
) {
let receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let destination = receiver.local_addr().unwrap();
let sender = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let sender_stats = stats.clone();
let _sender = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
while let Some(packet) = output.recv().await {
sender_stats.lock().unwrap().record(&packet);
assert_eq!(
sender.send_to(&packet, destination).await.unwrap(),
packet.len()
);
}
}));
let mut packet = vec![0u8; 65536];
let mut pending = VecDeque::new();
loop {
let deadline = pending
.front()
.map(|(at, _): &(Instant, Vec<u8>)| *at)
.unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));
tokio::select! {
result = receiver.recv(&mut packet) => {
let len = result.unwrap();
stats.lock().unwrap().received_packets += 1;
pending.push_back((Instant::now()+delay,packet[..len].to_vec()));
}
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
let (_, packet) = pending.pop_front().unwrap();
if input.send(Ok(packet)).await.is_err() { return; }
}
}
}
}
async fn pipe(
udp: bool,
output: mpsc::Receiver<Vec<u8>>,
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
delay: Duration,
stats: Arc<Mutex<WireStats>>,
) {
if udp {
udp_link(output, input, delay, stats).await;
} else {
link(output, input, delay, stats).await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "manual TCP stack diagnostic; run release --ignored --nocapture"]
async fn sdk_tcp_stack_diagnostic() {
let mib = std::env::var("MESHPORT_TEST_MIB")
.map(|v| v.parse::<usize>().unwrap())
.unwrap_or(2);
assert!((1..=64).contains(&mib));
let delay_ms = std::env::var("MESHPORT_TEST_DELAY_MS")
.map(|v| v.parse::<u64>().unwrap())
.unwrap_or(29);
let mtu = std::env::var("MESHPORT_TEST_MTU")
.map(|v| v.parse::<usize>().unwrap())
.unwrap_or(1284);
assert!((576..=1500).contains(&mtu));
let tx_kib = std::env::var("MESHPORT_TEST_TX_KIB")
.map(|v| v.parse::<usize>().unwrap())
.unwrap_or(512);
assert!((16..=1024).contains(&tx_kib));
let mode = std::env::var("MESHPORT_TEST_LINK").unwrap_or_else(|_| "channel".to_owned());
assert!(matches!(mode.as_str(), "channel" | "udp"));
let udp = mode == "udp";
for download in [true, false] {
let (client, client_in, client_out) = net("10.254.90.1", mtu, tx_kib);
let (server, server_in, server_out) = net("10.254.90.2", mtu, tx_kib);
let client_stats = Arc::new(Mutex::new(WireStats::default()));
let server_stats = Arc::new(Mutex::new(WireStats::default()));
let ctask = tokio::spawn(pipe(
udp,
client_out,
server_in,
Duration::from_millis(delay_ms),
client_stats.clone(),
));
let stask = tokio::spawn(pipe(
udp,
server_out,
client_in,
Duration::from_millis(delay_ms),
server_stats.clone(),
));
let mut listener = server
.tcp_bind("10.254.90.2:9000".parse().unwrap())
.await
.unwrap();
let bytes = mib * 1024 * 1024;
let payload = vec![0x5a; bytes];
let transfer = async {
let (connection, accepted) = tokio::join!(
client.tcp_connect("10.254.90.2:9000".parse().unwrap(), 40000),
listener.accept()
);
let mut c = connection.unwrap();
let (mut s, _) = accepted.unwrap();
let start = Instant::now();
if download {
let (sent, _) = tokio::join!(s.write_all(&payload), async {
let mut b = vec![0; bytes];
c.read_exact(&mut b).await.unwrap();
assert_eq!(b, payload);
});
sent.unwrap();
} else {
let (sent, _) = tokio::join!(c.write_all(&payload), async {
let mut b = vec![0; bytes];
s.read_exact(&mut b).await.unwrap();
assert_eq!(b, payload);
});
sent.unwrap();
}
let elapsed = start.elapsed();
tokio::time::sleep(Duration::from_millis(delay_ms * 2 + 100)).await;
println!(
"{}",
serde_json::json!({"mode":mode,"tx_kib":tx_kib,"added_rtt_ms":delay_ms*2,"mtu":mtu,"mib":mib,
"direction":if download {"download"} else {"upload"},"mbps":bytes as f64*8.0/elapsed.as_secs_f64()/1e6,
"client_wire":client_stats.lock().unwrap().json(),"server_wire":server_stats.lock().unwrap().json()})
);
};
let result = timeout(Duration::from_secs(90), transfer).await;
ctask.abort();
stask.abort();
let _ = ctask.await;
let _ = stask.await;
result.unwrap();
}
}
@@ -0,0 +1,4 @@
// Compile the production ordering tests in the SDK workspace as well as the
// upstream workspace, which has a separate dependency lockfile.
#[path = "../../../vendor/easytier/easytier-core/src/peers/conn/selection.rs"]
mod selection;
@@ -0,0 +1,57 @@
use easytier::instance::factory::create_native_instance;
use easytier_core::config::toml::TomlConfig;
use meshport::Network;
use std::time::Duration;
use tokio::net::UdpSocket;
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn udp_through_adjacent_mapped_subnet() {
let port = UdpSocket::bind("127.0.0.1:0")
.await
.unwrap()
.local_addr()
.unwrap()
.port();
let identity =
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
let server_config = TomlConfig::new_from_str(&format!(
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
)).unwrap();
let server = create_native_instance(server_config).unwrap();
server.start().await.unwrap();
let network = Network::start(&format!(
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
)).await.unwrap();
tokio::time::timeout(Duration::from_secs(15), async {
loop {
if network.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
{
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
})
.await
.unwrap();
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
.parse()
.unwrap();
let echo = tokio::spawn(async move {
let mut buffer = [0; 128];
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
udp.send_to(&buffer[..n], source).await.unwrap();
});
let result = network
.probe(target, true, true, Duration::from_secs(3))
.await;
echo.abort();
network.stop().await;
server.stop().await;
assert!(
result.is_ok(),
"adjacent mapped subnet UDP failed: {result:?}"
);
}
+8
View File
@@ -4,6 +4,9 @@ mod system_probe;
use anyhow::{Result, ensure};
use meshport_easytier::Engine;
pub use meshport_easytier::parse_config as validate_config;
pub use meshport_easytier::{
MeshRoutes, build_config, check_local_overlap, migrate_config, overlay_projection,
};
pub use meshport_netstack::{TcpListener, TcpStream, UdpSocket};
use std::{
net::SocketAddr,
@@ -27,6 +30,11 @@ impl Network {
pub async fn stop(&self) {
self.engine.stop().await;
}
/// Destinations to route through this network; changes as advertisements
/// are accepted or withdrawn. Use instead of polling `snapshot`.
pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver<MeshRoutes> {
self.engine.watch_mesh_routes()
}
/// Removes this network's secret from diagnostic text before export.
pub fn redact_diagnostic(&self, text: &str) -> String {
self.engine.redact_diagnostic(text)
+66
View File
@@ -0,0 +1,66 @@
# 客户端自动更新、规则集与导入
更新:2026-10-11。出口仍由用户手动选择;本轮按要求不实现自动测速选出口。
| 功能 | macOS | Android |
| --- | --- | --- |
| 订阅定时更新 | 应用运行期间 | 应用运行期间 |
| 内联 / HTTPS source、binary 规则集 | 已接入引擎 | 已接入引擎 |
| 普通 DNS、DoH、DoT | 已接入引擎 | 已接入引擎 |
| 代理节点 / TOML 文件导入 | NSOpenPanel | 系统文档选择器 |
| 相机扫码 / 二维码图片 | AVFoundation + Vision | 内置 ZXing 扫描与图片解码 |
| 应用启动后自动连接 | 已接入 | 已接入 |
| 登录时启动 | macOS 13+ 系统登录项 | 不支持,未实现 Android 开机广播连接 |
Android 本轮已编译,按用户安排暂不安装真机。macOS 图片二维码入口已实际验证;相机权限、真实登录启动和自动连接恢复仍需要用户环境验证,未为测试开启用户的登录项或自动连接开关。
## 使用入口
- **代理 → 订阅管理 → 编辑订阅**:启用自动更新,选择 15 分钟至 7 天的间隔,返回代理页点击“安全保存配置”。定时器每分钟检查到期项;应用重开也检查逾期项。
- **代理 → 编辑普通规则**:添加、排序、启停规则集。普通规则先匹配,随后规则集,再使用默认出口;组网有效子网和已撤销子网保护始终在前。绕过中国大陆模式同样执行自定义规则及规则集,并优先于私网和大陆 IP 预设。全局 / 直连模式暂停普通规则和规则集。
- **代理 → 编辑 DNS**:启动解析器仍为 IP;直连和代理解析器可填写 IP、`https://主机/dns-query` 或 `tls://主机:853`。DoH 默认 443、DoT 默认 853;TLS 校验保持开启。代理 DNS 经手动所选节点;解析器主机名由独立启动 DNS 解析,避免循环依赖。仅组网模式不接管互联网 DNS。
- **代理 → 导入与预览**:选择文件、相机扫码或二维码图片。只填入草稿,点击“解析并预览”后确认导入。HTTPS 订阅链接可以选择“作为订阅地址添加”。导入普通 sing-box JSON 只提取节点,不能覆盖受管理 TUN、DNS 和组网路由。
- **组网配置**:通过组网页表单填写;原 TOML 导入对话框已移除。保存过的完整 TOML 在未修改表单时原样保留。
- **设置 → 启动与后台**:分别选择自动连接与 macOS 登录启动。登录项需要系统批准时会显示实际状态和系统设置入口;Android 自动连接指打开 APP 后连接,不代表开机后台建立 VPN。
## 更新与缓存行为
普通规则、规则集的匹配策略以及自定义规则模式的默认策略提供四项:**代理、直连、组网、拒绝**。代理使用当前所选节点,直连使用本机网络,拒绝终止匹配连接。组网仅允许已接入的 IPv4 组网目标;需要先启用“代理 + 组网”,并由对端发布对应网段。未接入、已撤销或组网出口不可用时拒绝连接,不回退到代理或直连。
例如让 `192.168.50.0/24` 走组网:在对端发布此子网并确认本机已收到有效路由,再添加普通规则,类型选择 IP 网段、内容填写 `192.168.50.0/24`、策略选择“组网”,保存并重连。本地分流规则不会创建或发布远端路由。受管理的有效组网路由和撤销保护始终优先于普通规则;绕过中国大陆模式也可追加此规则。当前不支持 IPv6 组网网段。
订阅只替换自己的来源节点,保留手动节点、其他订阅及相同节点的 ID。选中节点被删除时清空选择,用户需重新选择,不自动换出口。空响应、仅含不支持节点的响应、网络失败或超出 64 KiB 保存限额,都保留旧配置;失败后 15 分钟重试。编辑期间不自动覆盖草稿。更新成功保存到平台安全存储,当前会话的实际出口保持到显式重连。
远程规则集支持 sing-box source JSON 和 `.srs` binary,初次连接下载、连接期间每 1–168 小时更新。它们可选择直连或所选代理下载。首次下载失败且没有缓存会阻止引擎启动;后续下载或解析失败保留最后一份有效规则。缓存与 FakeIP 一样属于当前引擎私有会话,公告引起的重建可复用,释放会话会清理,不保证 APP 重启后离线使用。
内联 source JSON 可直接编辑或从文件导入,最多 256 条 / 24 KiB。全配置仍受 64 KiB 存储与引擎输入限制。二维码必须有唯一内容;文本文件最多 1 MiB、图片最多 20 MiB / 2000 万像素。文件路径不交给特权 helper,客户端只读取用户选择的内容。
自动连接默认关闭,仅使用已保存的配置和入口,每次 APP 启动尝试一次。没有已保存网络时不靠私用默认文件自动连接;仅代理功能允许使用已保存代理配置独立启动。授权取消、代理节点缺失、现有 VPN 冲突等失败会显示实际错误,不反复抢占 VPN。
## 上游规则集修补与验证
本轮真实并发刷新测试发现 sing-box 1.14.3 规则列表读写未完整同步。项目保留固定版本的最小源码修补,详情见 [补丁说明](../engines/singbox/patches/README.md)。`scripts/go-local.sh` 在忽略目录准备私有模块副本,通过备用 modfile 编译,不修改上游下载缓存;版本或原始文件哈希改变会要求重新审查修补。所有项目 Go 构建脚本均通过该入口执行。
修补同时将远程规则集下载限制为 30 秒、32 MiB、最多五次 HTTPS 重定向,拒绝 HTTP 降级和 URL 用户名密码。配置由 sing-box 原生规则集解析器校验,无法从规则集声明任意 TUN 或出口。
新增测试位于 `advanced_profile_test.dart`、`advanced_pages_test.dart` 与 `advanced_config_test.go`:订阅来源与选择保留、更新到期、配置往返、导入需预览、启动页只读状态、DoT 默认端口、真实 DoH / DoT 请求、规则集组网优先、HTTPS 规则自动刷新及失败保留。TLS 测试仅在隔离测试引擎信任临时测试证书,不修改系统证书。
原生接口依照 [Apple SMAppService](https://developer.apple.com/documentation/servicemanagement/smappservice)、[Android 文档选择器](https://developer.android.com/guide/components/intents-common#Storage) 与 [ZXing Android Embedded](https://github.com/journeyapps/zxing-android-embedded) 接入;后者固定 4.3.0,采用 Apache-2.0 许可证。DNS 采用 sing-box [HTTPS](https://sing-box.sagernet.org/configuration/dns/server/https/) 和 [TLS](https://sing-box.sagernet.org/configuration/dns/server/tls/) 传输。
## 绕过中国大陆预设
代理页的“普通互联网流量模式”新增“绕过中国大陆”。无需配置规则集:引擎使用 SagerNet 的 [geoip-cn 二进制规则集](https://github.com/SagerNet/sing-geoip/tree/rule-set),通过所选代理首次下载并每 24 小时更新。目标大陆 IP 与普通私网直连,其余目标走代理;组网有效前缀与已撤销前缀保护先于普通私网和大陆规则执行。
域名经真实 IP 解析后匹配,包括 FakeIP 恢复域名后的解析;当前引擎仍以 IPv4 为主。判断按目标 IP,不能保证“中国网站”全部直连。远程列表首次下载失败时连接失败,后续更新失败保留会话内有效列表;跨 APP 重启离线缓存尚未接入。
预设先执行自定义规则、规则集,再执行普通私网及大陆 IP 直连,最后使用所选代理;组网路由和失效保护始终在最前。自定义默认动作仅在自定义规则模式生效,绕过中国大陆的兜底始终为所选代理,不覆盖保存内容。`meshport-geoip-cn` 为预设保留的规则集标识,用户规则集不能占用。全局模式不加载大陆 IP 列表,普通流量全部走代理。原有自定义规则和直连模式仍保留;旧配置不自动切换。修改模式后保存,连接或重连生效,已有连接可能中断。
## 代理 DNS 防泄露
客户端默认启用受管理的 DNS 保护,适用于自定义规则、绕过中国大陆与全局代理。用户必须在 DNS 页明确填写代理解析器(IP / DoH / DoT),没有内置代理 DNS 服务商;缺少配置时连接前报错,不停止已有会话。普通域名查询和目标解析经所选代理发送,解析失败不尝试直连或启动解析器。
代理节点、解析器主机名仍可能通过直连启动 DNS 解析;使用 IP 地址能减少必要的启动查询,但 TLS 主机验证保持开启。配置的组网后缀 DNS 和撤销保护继续优先执行。直连模式不保证经代理的 DNS 隐私,仅组网不接管普通 DNS;应用内 SOCKS5 仅处理应用交给它的请求。统一 VPN 捕获的普通 53 端口 DNS 进入内部 DNS 模块,应用自带 DoH/DoT 仍按普通连接策略处理,不声称全设备所有解析都经过指定解析器。
本次没有加入退出 VPN 后的系统防火墙锁定,也未完成平台 IPv6、网络切换和全局 DNS 真机验收。单纯 DoH/DoT 或 FakeIP 不是这些边界的替代。
SDK 的原始 Go JSON 新增可选 `dns_protection`,启用后代理模式要求显式 `proxy_dns_server`;Flutter 客户端核心默认启用,旧保存配置重载时同样启用。未使用该字段的旧原始引擎调用保持兼容。
+36 -8
View File
@@ -7,43 +7,71 @@
构建环境需要 Flutter、JDK 17、Android SDK、NDK 28.2.13676358、CMake 3.22.1,以及 Rust 的 aarch64-linux-android target。
```sh
scripts/build-lab-android.sh --release
scripts/package-lab-android.sh
```
脚本先编译含 system-vpn 功能的 Rust 库,再打包 Flutter APK,输出到 outputs/android。当前使用开发签名,适合本机安装验证。正式发行需配置自己的签名和应用 ID。原生库与 JNI 桥接使用 16 KB ELF 页面对齐;当前真机为 4 KB 页面,16 KB 设备运行尚未验证。
## 签名冲突时使用独立版
无法取得旧版签名时,可执行 `sh scripts/package-lab-android.sh --standalone` 打包“MeshPort 独立版”。其应用 ID 为 `com.meshport.client.standalone`,使用独立持久签名,可与原应用共存;需要重新导入配置,不读取旧应用的私有数据。原应用无需卸载。系统仍只能同时连接一个 VPN。
独立版签名保存在被 Git 忽略的 `work/android-signing/`,构建缓存清理脚本会保留此目录。请备份整个目录,后续独立版升级必须复用该密钥。脚本在密钥或属性文件缺失时拒绝重新生成不完整身份。此签名用于本地分发,不代表已经完成应用商店发布配置。
## 两种模式
- 应用内:通过 meshport_flutter SDK 的 TCP/UDP 接口通信,不创建系统 VPN。
- 系统 VPN:宿主请求用户授权,由前台 VpnService 创建虚拟网卡,将文件描述符交给 Rust 引擎。虚拟网段及符合规则的公告子网自动安装、更新和撤销,不需要填写远端子网。
- 统一 VPN:通过 Android VpnService 建立 TUN,交给 sing-box 接入互联网代理和可选的组网 SOCKS 桥。首次启动默认“仅代理 / 全局代理 / 统一 VPN”;首次导入单个节点自动选中,DNS 默认 `https://cloudflare-dns.com/dns-query`。原有配置与自定义 DNS 保留。设置自动保存,运行中修改需要点击“重连应用修改”。
外层连接通过 VpnService.protect 排除在自己的 VPN 之外。系统模式不配置默认路由或 DNS;IPv6 保留系统通路,当前虚拟网络数据面为 IPv4。其他 Android VPN 与此系统 VPN 不能同时作为当前 VPN 运行。
外层连接通过 VpnService.protect 排除在自己的 VPN 之外。仅组网的系统模式不配置默认路由或 DNS;IPv6 保留系统通路,当前虚拟网络数据面为 IPv4。统一 VPN 的互联网模式接管 IPv4/IPv6 默认路由和 DNS,并跟踪底层物理网络。其他 Android VPN 不能同时作为当前 VPN 运行。
VPN 建立和路由更新会等待 Android ConnectivityService 发布匹配的虚拟地址及路由,再报告就绪,避免新连接提前使用物理源地址。JNI 使用库名链接 Rust 动态库,不携带构建机绝对路径;系统模式启用受保护的 DNS resolver,数字 IP 不经过 DNS 查询。
配置使用 Android Keystore 的 AES-GCM 密钥加密,私有存储仅保存密文与 IV,关闭 Android 备份。启动恢复表单,不自动连接;后台服务仍运行时重新打开界面会恢复该会话。
配置保存到应用私有目录 `filesDir/MeshPort/` 的 `proxy-profile.json` 和 `network-profile.toml`,目录权限 0700、文件权限 0600,使用原子写入,关闭 Android 备份。文件内容为明文,由应用沙箱隔离。旧版 Keystore 加密配置首次读取时迁移;迁移失败可在设置页手动重试,保留旧备份。启动恢复表单,自动连接由独立开关控制;后台服务仍运行时重新打开界面会恢复该会话。
## 真机验证
integration_test/android_network_test.dart 使用隔离网络身份和 USB 转发的本机测试网关,覆盖加密存储、应用内 TCP/UDP、普通系统 Socket 经 VPN 访问自动公告子网,以及公告撤销。
integration_test/android_network_test.dart 使用隔离网络身份和 USB 转发的本机测试网关,覆盖配置保存与恢复、应用内 TCP/UDP、普通系统 Socket 经 VPN 访问自动公告子网,以及公告撤销。
```sh
# 先在项目根目录启动本机夹具
scripts/cargo-local.sh run -p meshport-easytier --example android_test_server
adb reverse tcp:18080 tcp:18080
adb reverse tcp:18081 tcp:18081
cd apps/meshport_lab
flutter test integration_test/android_network_test.dart -d DEVICE_SERIAL
# Use a normal APK and its matching build number; restore it automatically.
sh scripts/test-android-device.sh DEVICE_SERIAL NORMAL_APK BUILD_NUMBER network
```
测试中的系统 VPN 授权必须由用户在手机上完成。测试结束应删除两条 adb reverse 并关闭夹具。测试使用固定地址,不覆盖公网打洞、移动网络切换、长期后台存活或实际游戏负载。
互联网统一 VPN 使用单独的隔离 SOCKS5 夹具,手机与电脑须在同一局域网。仅接受明确指定的手机 IP,测试地址返回确定的 TCP/UDP 回显,公共 HTTPS 和默认 DoH 使用真实上游;不读取或修改用户节点配置。
```sh
python3 scripts/android-proxy-fixture.py --host COMPUTER_LAN_IP --device PHONE_LAN_IP
sh scripts/test-android-device.sh DEVICE_SERIAL NORMAL_APK BUILD_NUMBER proxy COMPUTER_LAN_IP
```
覆盖普通系统 TCP/UDP、TUN DNS、默认加密 DNS、证书验证的 HTTPS、两次启停与断开恢复。实际结果记录在 [开发验证](development-validation.md),脚本存在不代表设备已通过。包装脚本用 `flutter drive --keep-app-running` 避免 Flutter 默认卸载测试 APP;结束或失败时覆盖安装并打开普通 APK,保留已有存储。测试完成后停止夹具。直接使用 `flutter test` 会在结束时卸载测试 APP,不能用于保留用户配置的测试。
## Android 连接日志
APP 的“诊断与日志”记录配置校验、授权、引擎启动与运行错误。Flutter 在输出前隐藏已知凭据,Android 同步到 `MeshPortRuntime`;VPN 服务的阶段事件使用 `MeshPortVPN`,不打印完整配置。可以通过以下命令采集本次连接事件:
```sh
adb -s DEVICE_SERIAL logcat -s MeshPortRuntime:I MeshPortVPN:I AndroidRuntime:E
```
2026-10-10 在 OPPO PJZ110(API 37、4 KB 页面)完整通过:加密配置保存/重新读取/删除、SDK 应用内 TCP/UDP、Java 与 Dart 普通系统 TCP/UDP 经 VPN 通信、公告子网自动安装及撤销。隔离测试不修改用户配置。公网打洞、长期后台运行及移动网络切换尚未验证。
## 自用默认配置
自用配置文件为 `apps/meshport_lab/assets/config/default.private.toml`,不会提交 Git。可以从同目录的 `default.example.toml` 复制后填写网络身份、密钥、虚拟 IP 和初始节点。每台设备应使用不同的静态虚拟 IP。
Android 和 macOS 打包脚本会先执行 `sh scripts/prepare-lab-default.sh`,将私人文件复制为安装包资源 `default.toml`;没有私人文件时使用示例。直接运行 Flutter 命令之前也应先执行该脚本。APK 里的默认配置可以被提取,含密钥的自用安装包不要分发。
开发构建脚本会先执行 `sh scripts/prepare-lab-default.sh`,将私人文件复制为安装包资源 `default.toml`;没有私人文件时使用示例。直接运行 Flutter 命令之前也应先执行该脚本。APK 里的默认配置可以被提取,含密钥的自用安装包不要分发。
客户端优先读取安全存储中已保存的配置;没有可用保存配置时加载安装包默认配置,并默认开启配置保存。默认配置只预填表单,不会自动连接。保存后下次启动会恢复修改后的配置;删除保存配置后,下次启动重新使用安装包默认值。
发布打包使用 `package-lab-android.sh` 或 `package-lab-macos.sh`,仅打入公开示例配置,并恢复本地开发配置。
客户端优先读取应用私有目录中已保存的配置;没有可用保存配置时加载安装包默认配置,并默认开启配置保存。默认配置只预填表单,不会自动连接。保存后下次启动会恢复修改后的配置;删除保存配置后,下次启动重新使用安装包默认值。
最新同步版构建与验证结果见 [Android 最终包验证](../outputs/validation/android-final-sync-20261013.md)。
+6
View File
@@ -1,5 +1,9 @@
# 架构
本文描述当前实现。下一阶段 sing-box 组合客户端方案见 [组网与代理组合架构](next-stage-architecture.md),配套页面见 [移动端 UI V4](ui-design.md)。
已新增可选的应用内 [SOCKS 桥接](socks-bridge.md):通过 Rust 数据面并发转发本机 SOCKS5 TCP/UDP,C ABI/Dart 只负责启动、停止和状态。[sing-box Go 封装与本机联调](singbox-integration.md)已通过;客户端统一 TUN 尚未接入,现有普通 JSON I/O 的串行限制仍保留。
Flutter Lab → Dart SDK → C ABI → MeshPort → EasyTier 原生实例与其 smoltcp 数据面。
当前上游已经提供 `data_plane_tcp_connect`、`data_plane_tcp_bind`、`data_plane_udp_bind`。因此第一版不维护第二套 TCP/IP 栈;netstack crate 是适配边界,可在以后替换实现。
@@ -15,3 +19,5 @@ UI 仅显示实测状态与结果。连接耗时与 echo 往返耗时分开标
选路优化在 vendor/easytier/easytier-core 的连接及下一跳选择层执行,适配层负责严格配置和实际路由快照。质量测量通过公开 Rust/C ABI/Dart API 发起真实 UDP echo,不改系统网络,详见 [优化说明](optimization.md)。
系统模式:Flutter → Dart Unix 控制通道 → macOS 特权 helper → 同一 C ABI → EasyTier TUN;其他应用通过普通系统 socket 使用虚拟网段。详见 [系统组网](system-vpn.md)。
组网规则归 SDK:配置生成与模式约束(`build_config`)、旧配置迁移(`migrate_config`)、虚拟网段与本机接口冲突检查、应用模式网络加桥接的原子启动(`start_bridged`)、路由目标投影(`mesh_cidrs` 与 `route_generation`)、组网可用性(`health`)以及节点直连/中继与延迟来源判定(`nodes`)都在 Rust 中实现。Dart 客户端核心、Android VpnService 与 macOS helper 只安装和展示这些结果,负责平台授权、socket protect、物理网络选择、OS 路由/DNS 守护与 sing-box 配置。质量测量循环仍由 Dart 驱动:ABI v1 每 context 串行,在原生侧运行约 30 秒的采样循环会阻塞同一 context 的状态轮询。
+123
View File
@@ -0,0 +1,123 @@
# 自动化测试
统一入口为 `python3 scripts/test.py`,仅使用 Python 标准库。可以从任意目录运行脚本。原有单项脚本继续可用。
## 日常运行
```sh
python3 scripts/test.py
python3 scripts/test.py --list
python3 scripts/test.py sdk engine
python3 scripts/test.py client
python3 scripts/test.py client --native
python3 scripts/test.py runner
python3 scripts/test.py speed --min-mbps 10
python3 scripts/test.py combined
```
无参数等价于 `all`,覆盖自动化入口自身、Rust workspace、Go race/vet、Go → SDK TCP/UDP 联调、Flutter analyze/全量测试,以及 macOS 配置存储测试。`all` 不包含手动吞吐诊断或速度矩阵。各模块按固定顺序串行运行,不并行争用网络夹具或编译输出。
| 模块 | 范围 | 依赖 |
|---|---|---|
| `runner` | 入口脚本的失败传播、依赖跳过、超时与报告测试 | Python 3.9+ |
| `sdk` | `cargo test --workspace --release --locked`,保留显式忽略的测试 | Rust ≥1.95、protoc |
| `engine` | Go `test -race`、`vet`、构建测试引擎、显式运行真实 Go/SDK 桥接测试 | Go、C 编译器、Python、Rust/protoc |
| `client` | Flutter 依赖解析、analyze、全量测试 | Flutter(Dart ≥3.11) |
| `macos` | `LocalProfileStore` 的 Swift 本地测试 | macOS、Xcode command-line tools |
| `throughput` | 生产 TCP 封装的 channel/UDP 对照、加密 SDK 延迟吞吐诊断 | Rust/protoc |
| `speed` | 多延迟、多轮双向测速,包含 SDK、SOCKS、sing-box,自动汇总与门槛检查 | Rust/protoc、Go、C 编译器 |
| `combined` | 同进程真实 Rust SDK + Go FFI,组网/代理双路负载、UDP、故障隔离和速度对照 | macOS、Rust/protoc、Go、C 编译器 |
Rust、Go 优先复用 `scripts/cargo-local.sh`、`scripts/go-local.sh` 和项目本地工具链。Flutter 使用 PATH 中的 `flutter`。依赖解析或构建可能访问依赖仓库;测试通信使用隔离测试配置与本机夹具。macOS 存储检查在其他平台显示为 SKIP;其他平台是否能通过所有 Rust/Go/Flutter 测试仍需各自验证。
## 原生 Flutter 测试
默认 `client` 清除继承的 `MESHPORT_LIBRARY`、`MESHPORT_PROXY_LIBRARY` 等变量,依赖原生库的用例按现有机制显示为跳过,不误用旧库。`--native` 显式构建 Rust FFI 和 Go 代理库,再把这次构建的路径传给 Flutter 测试。当前原生库构建脚本只支持此入口的 macOS 路径,因此其他平台使用 `--native` 会明确报错。
原生连接 widget 测试使用固定 `load_profile` 夹具:没有外部 peer、监听服务或 STUN,不继承打包的个人默认网络。它启动应用内测试引擎,不请求管理员权限、安装 TUN 或连接用户节点。
## 可选吞吐诊断
```sh
python3 scripts/test.py throughput --rtt-ms 58 --mib 8
```
`--rtt-ms` 是双向合计的附加 RTT,必须是 0–1000 的偶数;每方向加入一半延迟。`--mib` 为每个方向的数据量,范围 1–64,默认 8 MiB。
吞吐模块显式运行两个手动诊断,不使用全局 `--include-ignored`:TCP 封装分别通过保序内存通道和本机 UDP 传输,加密 SDK 路径输出合成测试包的窗口、重复序号及 UDP 会话队列满事件。不会读取真实下载链接或用户配置,也不会创建系统 VPN。会自动解析数据、检查上传/下载完整性、参数一致性和正的有限速度;绝对速度与基线门槛使用下面的 `speed` 模块。
夹具内部还有 60/90 秒的传输保护;很大的 RTT 与数据量组合可能触发该保护。入口的 `--timeout` 不覆盖夹具内部超时。
## 速度矩阵与性能门槛
```sh
python3 scripts/test.py speed --min-mbps 10
python3 scripts/test.py all speed --native --min-mbps 10
python3 scripts/test.py speed --rtts-ms 0,58,100 --repeat 3 --mib 8
```
默认在 0、58、100 ms 附加 RTT 下各运行 3 轮,每方向传输 8 MiB。包含生产 TCP 封装的内存通道/普通 UDP 对照,以及 SDK 直连、SOCKS、sing-box → SOCKS 三条加密组网路径,共 90 个方向测量样本、30 个汇总分组。单独运行 `speed` 会构建所需 Go 引擎;与 `all` 合并时复用引擎构建。与 `throughput` 同时指定时只执行覆盖更完整的速度矩阵。
每个分组记录中位数、最小/最大 Mbps、重复 TCP 数据序号、最大数据包间隔与会话队列满事件。判定规则:
- 缺少某条路径的上传/下载、缺少包级统计、速度非正/非有限、参数不一致或重复样本,即使命令返回 0 也判失败。
- 每组必须完成指定轮数,组中位数不能低于 `--min-mbps`。默认 0,表示不设置跨机器的统一绝对速度要求;上面的 10 Mbps 是显式配置的本地验收值,不是公网速度承诺。
- SDK 会话队列满事件在每组的所有轮次中合计不能超过 `--max-queue-drops`,默认 0。该门槛用于加密 SDK 路径;普通通道没有 SDK 会话队列。
- 不对所有重复序号/零窗口设置硬性零阈值,因为它们不独立等同于实际丢包;原始统计保留供诊断。
基线回归比较:
```sh
python3 scripts/test.py speed --baseline /path/to/previous/metrics.json \
--max-regression-percent 20 --min-mbps 10
```
基线应来自同一机器、可比较的负载和工具链。模式、目标、入口、RTT、每方向数据量和方向必须完全匹配,否则拒绝比较;当前组中位数下降超过指定百分比时失败。基线格式、有限数值和重复分组也会验证。矩阵/门槛参数必须与 `speed` 一起使用,避免只跑功能测试却误认为已检查速度。
这是本机合成链路回归,不覆盖系统 TUN、真实公网节点、真实 NAS 下载或网络切换。实际 App 测速功能另有 HTTP 代理夹具,覆盖 Mbps 换算、首字节时间、空响应、非法端口、重定向、并发重入、超时/部分数据、取消恢复、传输上限和禁止直连回退。
## sing-box 与组网联合测试
```sh
python3 scripts/test.py combined
python3 scripts/test.py combined --rtt-ms 58 --joint-repeat 3 --joint-seconds 2 --proxy-mbps 100
python3 scripts/test.py combined --proxy-mbps 0
```
`combined` 是显式选择的测试,不包含在默认 `all` 中。它构建 Go 共享库,在同一进程加载真实 Go FFI 和 Rust SDK,通过加密 EasyTier UDP 链路连接隔离节点。代理出口使用本地 SOCKS 上游夹具。不会启动系统 TUN、修改系统 VPN 或读取真实代理配置;因此不能据此判断真实运营商、NAS、公网代理或 TUN 路由冲突。
默认模拟组网 RTT 58 ms,每路每次持续至少 2 秒、重复 3 轮。分别对照组网路由配置、代理路由配置、联合配置单路传输、联合配置双路并发,覆盖上传和下载,共 36 个速度样本。SDK 节点在代理基线阶段保持空闲。代理夹具默认限速 100 Mbps,方便比较相同负载;`--proxy-mbps 0` 取消限速,用于主机资源竞争压力测试,可能暴露 CPU/内存带宽竞争。
双路并发要求传输重叠至少为配置时长的 80%,并在两路 TCP 同时传输期间分别完成 24 次 UDP 校验(默认三轮)。TCP/UDP 使用不同路径标记并校验数据,统计上游访问目标,检查组网流量没有进入代理出口。故障注入分别停止代理上游和组网桥接/节点,要求另一条已建立的传输继续成功;同时验证代理上游恢复以及每次停止后监听端口释放。
自动比较各方向中位数:联合配置空闲一路相对单独配置、并发相对联合配置单路、并发相对单独配置。下降超过 `--max-joint-slowdown-percent`(默认 20%)会使测试失败,测量仍保留在报告中。缺失样本、无效速度、重叠不足、UDP 或故障隔离未完成,即使命令返回 0 也会判失败。短时本地测试存在波动,不能替代长时间真实网络测试。
额外输出 `combined-metrics.json` 和 `combined-summary.md`,包含逐轮结果、中位数、变化百分比及功能检查证据。
## 报告与失败处理
默认输出目录:`outputs/validation/automated-tests/<UTC时间>-<随机ID>/`,已加入 Git 忽略规则。
- 每条命令一个 `.log`,终端输出运行阶段、耗时和失败日志末尾。
- `report.json` 记录命令、工作目录、状态、退出码、耗时和日志路径,不保存运行环境变量。
- `junit.xml` 以命令为 testcase,适合 CI 汇总;单元测试内部的通过/跳过数量在对应原始日志中。
- 速度模块另生成 `metrics.json`(逐次测量及分组汇总,可作为基线)和 `speed-summary.md`(易读表格);`speed-check` 的门槛失败同时进入 JSON/JUnit 和最终退出码。
任何失败返回 1;中断返回 130。默认继续其他独立模块,构建失败时跳过依赖它的步骤,最终仍返回失败。`--fail-fast` 在首个失败后跳过剩余步骤。每条命令默认最多运行 900 秒,超时终止命令及其进程组并记录退出码 124;可用 `--timeout 1800` 调整。
```sh
python3 scripts/test.py sdk engine --fail-fast --timeout 1800
python3 scripts/test.py all --log-dir /tmp/meshport-ci-results
```
自定义 `--log-dir` 必须尚不存在,以防覆盖历史记录。入口会清除所有继承的 `MESHPORT_*` 环境变量,再为所选模块设置必要的测试路径和参数,避免旧动态库、真实 profile 或遗留诊断开关影响本轮测试。
## CI 接入
在 CI 中安装所选模块的依赖后运行同一命令,直接使用其退出码判断成功;无论结果如何,收集报告目录中的 JSON、JUnit XML 和 `.log`。例如只验证 SDK 与引擎:
```sh
python3 scripts/test.py sdk engine --log-dir /tmp/meshport-ci-results
```
本次提供的是可供 CI 调用的测试入口,没有添加自动推送、发布或安装应用的步骤。系统 TUN、Android 真机、签名/打包及真实公网测试继续使用原有专项流程,不属于默认自动化回归。
+86
View File
@@ -0,0 +1,86 @@
# 客户端联合运行控制
更新日期:2026-10-10。应用内代理与组网联合运行、节点配置、订阅导入和基础 DNS 已接入。Android 单一 VPN 已实现并交叉编译,真机验证按用户要求暂缓;macOS 统一系统 TUN/helper 已接入,实际测试范围见开发验证记录。此文区分已验证能力和待验证能力,架构图中的最终目标不等于全部完成。
## 模块边界
| 模块 | 职责 |
| --- | --- |
| `crates/meshport-socks` | 回环 SOCKS5 到独立组网 SDK 的 TCP/UDP 桥接 |
| `engines/singbox/bridge` | 受管理代理配置、分流、DNS、生命周期及宿主 TUN 适配 |
| `engines/singbox/cmd/meshport-singbox-ffi` | 数字上下文、JSON 控制、C ABI 与 socket 保护回调 |
| `bindings/flutter/singbox_flutter` | 工作 isolate 中的原生调用、按上下文排队 |
| `packages/meshport_client_core` | 联合会话、配置模型、节点与订阅解析 |
| `apps/meshport_lab` | 概览、代理、组网、设置四个主页面,24 个页面入口及平台安全存储 |
其他应用只依赖 `meshport_flutter`,继续使用独立组网 SDK,无需加载 sing-box。代理功能属于客户端可选层。
## 已实现的配置和界面
- 功能选择:仅组网、仅代理、代理与组网;仅代理不启动 MeshPort,也不要求网络名称或密钥。
- 普通互联网模式:绕过中国大陆、自定义规则、全局、直连。绕过中国大陆使用受管理的大陆 IP 列表,大陆 IP 与普通私网直连,其他走所选代理;保存的自定义规则和默认出口在该预设下暂停。全局和直连暂停普通规则,仍保留组网优先及失效目标保护。
- 节点协议:SOCKS、HTTP、Shadowsocks、VMess、VLESS、Trojan;受支持的 TLS/uTLS/Reality、WebSocket、gRPC 参数由固定上游版本验证。
- 节点按协议编辑,认证字段默认隐藏;订阅节点编辑保存为手动副本。高级传输保留 JSON 编辑入口。
- 导入分享链接、Base64 订阅和 sing-box JSON。只提取支持的节点,完整 JSON 的入口、路由、DNS 不会覆盖受管理配置。导入先预览,再确认。
- HTTPS 订阅添加、更新、删除;更新显式触发,禁止跳转,限制超时和内容大小。删除选中出口前确认,手动节点保留。
- 草稿、保存、运行出口分离。保存不改变连接;运行期间应用草稿需确认重连。macOS Keychain 和 Android KeyStore 加密保存代理配置,组网配置独立保存。
- 普通规则支持域名、域名后缀、CIDR 与 proxy/direct/reject,已使用表单编辑;DNS、组网基础、打洞、高级与线路策略均有独立页面。页面实现和限制见 [界面实现清单](ui-implementation.md)。
- 草稿节点可独立检测 HTTPS 连通性,显示 HTTP 耗时;不保存、不切换运行出口,不创建 TUN。
应用内入口为 `127.0.0.1:10818` SOCKS5,不自动设置 macOS 系统代理或系统路由。系统 VPN 组网原有路径保持独立;统一 VPN 使用 sing-box 唯一 TUN,MeshPort 使用应用内数据面。macOS helper 只加载 App 内固定 Go 动态库,互联网外层绑定物理接口,组网桥接明确绑定 lo0,避免本机回环连接被错误绑定物理网卡。
macOS 统一 VPN 的仅组网模式使用 IPv4 TUN,只安装合规公告及会话保护前缀,可与其他默认路由 VPN 共存;互联网代理模式接管拆分默认路由,检测到其他 TUN 占用时拒绝启动,不删除其他软件路由。统一模式使用静态组网 IPv4。网络切换及长期运行仍需验证。
## 生命周期与保护
组网启动由 SDK `start_bridged` 一步完成 MeshPort 与 Rust SOCKS 桥接(失败由 SDK 一并回滚),再启动 Go 引擎;停止顺序相反。会话只在 `start_bridged` 成功后取得 context 所有权,context 已被占用时不会误停对方网络。网络停止失败保留所有权以便重试。组网配置由 SDK `build_config` 生成,旧版保存的配置经 `migrate_config` 迁移。`close()` 等待队列并释放代理上下文;宿主最终关闭 MeshPort。
宿主状态轮询直接读取 SDK 的 `platform_network.mesh_cidrs`(虚拟网段加已接受公告子网,已规范化),并用 `health.mesh_routable` 判断组网是否可用;客户端不再自行解析或掩码计算前缀。集合变化才重建 Go 配置,无需手动远端子网列表。`MeshProxySession` 启动后另开一个 `wait_routes` 长轮询循环,路由一变化就排队重建,不必等下一次宿主轮询;宿主轮询仍负责健康检查。Android 服务用独立线程长轮询 `wait_routes`,把路由应用投递到服务的 worker 线程。重建关闭已有代理连接,尚非无损热更新。
本次连接期间见过的合规组网前缀形成保护集合。有效前缀先走组网,撤销的已知前缀被拒绝,不能落入普通代理或直连;显式停止会话后清空集合。SDK 数据面也独立验证当前有效公告。
应用内联合模式中,组网暂不可用时普通代理可继续运行,状态为 `Partial`,组网目标保持拒绝。仅组网出现故障则清理会话。Android 单一 VPN 同样按 `health.mesh_routable` 处理:联合(combined)模式下组网停止只撤掉组网路由、代理继续,状态报告 `Partial`(Lab 仍视为已连接,可断开);仅组网模式与系统 VPN 整体停止。该行为尚需真机验证。
Android `MeshVpnService` 的所有状态只在其 worker 线程上修改:Activity 发来的请求、2 秒健康检查、底层网络回调与路由更新都在这一个线程串行执行。请求接口为异步回调,不在 worker 上阻塞等待;每次 worker 任务结束后刷新状态快照,`status` 请求直接返回快照,不会被耗时的重建阻塞。`installed_subnet_routes` 在 Android 与 macOS 辅助进程中含义一致:只含已安装的公告子网,不含虚拟网段。
## DNS
- 启动解析使用明确 IP 的 UDP DNS,默认 `1.1.1.1`,不依赖尚未建立的代理。
- 客户端默认发送 `dns_protection=true`。自定义规则、绕过大陆和全局模式均须显式配置代理 DNS,经所选代理查询,失败不回退;普通目标默认解析器使用代理 DNS。直连模式使用直连 DNS 或启动 DNS。代理节点、解析器地址使用单独的启动解析避免循环依赖。
- 组网 DNS 配置指定后缀及合规组网 IP,经 MeshPort 查询;其服务公告撤销后拒绝对应查询,不回退公共 DNS。
- 组网域名查询及后续连接均保持组网出口优先。
- FakeIP 可选:IPv4 198.18.0.0/15、IPv6 fc00::/18。组网 DNS 规则先匹配且排除 FakeIP,普通 localhost/local/lan 默认排除;支持自定义后缀。真实 TCP 测试验证 FakeIP 反查与代理出口,以及公告重建后保留映射。
- 缓存放入宿主私有临时目录;Go 引擎 stop/start 保留当前会话缓存,最终释放上下文删除文件。重新连接会话会清理缓存,旧连接可能中断。
- macOS 互联网统一模式向 Dynamic Store 增加临时 DNS 补充项,helper 退出时移除,不改写持久网络服务配置;全局 DNS 与现有 TUN 共存不承诺。
- DoH/DoT 与规则集已接入,细节见 [高级客户端功能](advanced-client-features.md);完整 IPv6 端到端验证尚未完成。
## Android 单一 VPN 原型
`MeshVpnService` 持有唯一系统 TUN,MeshPort 使用应用内网络,sing-box 接收宿主提供的重复 FD 并负责 TUN 分流。JNI 为 Rust/Go 外层 socket 提供 `VpnService.protect` 回调,选择非 VPN 底层网络并监听变化;有效公告变化重建配置,组网专用捕获路由随公告更新。
入口标注“待真机验证”。仅组网捕获保护子网;互联网代理模式捕获默认路由。联合模式暂要求静态组网 IPv4。代码和 APK 编译成功不代表底层网络切换、后台运行或实际单一 VPN TCP/UDP 已验证。
## 原生接口和验证
C ABI 提供 version、context_new、call、string_free、context_free,以及宿主 socket 保护回调注册。请求为 NUL 终止 UTF-8,JSON 最大 64 KiB;未知字段、尾随数据与操作拒绝,错误不返回配置凭据。Java JNI 使用标准 UTF-8,避免认证字段中非 ASCII 字符损坏。
```sh
sh scripts/go-local.sh test -race ./...
sh scripts/go-local.sh vet ./...
sh scripts/test-client-runtime.sh
sh scripts/test-singbox-bridge.sh
sh scripts/build-lab-macos.sh
sh scripts/build-lab-android.sh --debug
```
Go 测试包含真实 SOCKS/直连通信、三种模式的组网优先、DNS 域名规则、撤销 DNS 拒绝及 ABI 并发释放。Flutter 测试包含生命周期、失效前缀保护、组网故障后的部分运行、配置导入、节点编辑与真实 Rust/Go 动态库启停。跨语言组网 TCP/UDP 和公告撤销端到端验证见 [引擎接入](singbox-integration.md)。构建产物和本轮验证记录见 [开发验证记录](development-validation.md)。
## 尚未完成
Android 单一 VPN 真机通信与网络切换、macOS 互联网统一模式全局 DNS 和网络切换、相机及真实登录启动恢复、长时间和后台稳定性测试仍需验证。规则集、扫码/文件导入、自动订阅更新与应用启动自动连接已接入,见 [高级客户端功能](advanced-client-features.md)。自动测速选出口按用户要求不实现。原有 Android 独立组网真机测试与本轮新增代理联合模式测试是不同范围。
## 概览测速与代理日志
概览移除测试耗时、测试趋势和快速连接测试入口;原有诊断工具仍可从详情页访问。代理及联合模式增加手动测速卡片,通过本机 127.0.0.1 的受管理 HTTP/SOCKS 混合入口下载 Cloudflare 资源,不回退到直接连接。最多下载 32 MB,15 秒停止,支持取消;重连清除前次结果。显示端到端平均下载 Mbps / MB/s 和首字节耗时。测速占用带宽、遵循当前分流规则;直连模式或命中直连规则时不代表节点性能,结果也不代表 YouTube CDN 吞吐。
代理引擎收集 info 及以上级别的连接、出口和错误事件,原始输出保持写入空设备,只有脱敏事件返回界面。引擎保留最近 128 条,界面保留最近 300 条会话日志;日志页可筛选代理日志并复制当前范围。应用内与统一 VPN 共用该采集路径。不会收集数据包内容,目标地址保留,已知密码、UUID、URL 认证与查询参数隐藏。
+2
View File
@@ -4,6 +4,8 @@ EasyTier 仓库:https://github.com/EasyTier/EasyTier
vendor/easytier 是固定提交的本地定制快照,来源和修改清单见该目录 MESHPORT.md。基础提交:7af7bdc16a41d64d58743d15023a63b3eed2102c。Cargo.lock 固定传递依赖;build 使用 --locked。
原生库能力:C ABI 为 v1,Flutter 绑定要求能力修订号(`abi_info.revision`)≥ 2;`MeshPortClient.open` 在打开时检查,旧库(无 `abi_info` 或修订号更低)会以“native library is too old … rebuild meshport-ffi”的 StateError 拒绝。`fromTransport`(Android VpnService、macOS 辅助进程)由各自宿主保证同版本原生库,不做该检查。
当前本机验证:macOS aarch64、Rust1.99、Flutter3.41.4/Dart3.11.1。
目标平台:macOS/Linux/Windows/iOS/Android。macOS 原生库和客户端已验证。Android ARM64 原生库、JNI 和 APK 已构建,真机配置加密存储、应用内与系统 VPN TCP/UDP,以及公告子网自动接入和撤销已通过。其他 runner 是脚手架,仍需要目标编译、链接、库加载和真机测试。iOS 使用静态链接,并需要保留导出符号。Android 说明见 android.md。
+128
View File
@@ -0,0 +1,128 @@
# 2026-10-11 开发验证记录
## 2026-10-12:互联网统一 VPN 断网排查
实际用户节点的独立 HTTPS 检测返回 HTTP 204;关闭统一 VPN 后普通 HTTPS 同样成功。启用统一 VPN 后,自动采样确认普通域名解析超时、本机 SOCKS 返回网络不可达、固定 IP HTTPS 被重置。退出测试 APP 后物理默认路由和原有 DNS 恢复。
新增按引擎隔离、最多 32 条的运行时警告/错误记录,在内存中脱敏节点认证及 URL 凭据后投影至客户端日志;不将原始上游错误写入 stderr 或日志文件。实际错误明确为启动 DNS 的 `dial udp 1.1.1.1:53: connect: network is unreachable`,随后导致 `cloudflare-dns.com` 与网页解析失败。
修复为在接管全局路由前安装物理接口的 IPv4 scoped default route,供绑定物理接口的启动 DNS 和代理外层 socket 使用。复用既有 scoped route,停止时只删除本次创建且网关/接口仍匹配的路由。APP 已构建、签名验证通过;Rust 路由所有权测试、Go 并发测试及日志脱敏回归通过;Flutter 全量测试 42 项通过、6 项环境测试跳过。产物为 `outputs/macos/MeshPort-0.1.0-unified-vpn-fix.app` 及同目录 ZIP。
**实际运行验收通过**:2026-10-12 04:17(America/Los_Angeles),使用用户原有的 VLESS/Reality 节点、绕过中国大陆及代理加密 DNS 配置,统一 VPN 启用时,物理接口绑定 UDP connect 成功;普通 HTTPS、SOCKS5h HTTPS 和固定 IP HTTPS 均返回 HTTP 204;TUN DNS 返回有效 A 记录。采样后退出测试 APP,原有默认路由和 DNS 恢复,新增 scoped default 已移除,普通 HTTPS 再次返回 HTTP 204。短时验证覆盖本次 IPv4 互联网断网问题;IPv6 端到端、网络切换和长期运行仍需验证。
失败证据保留于本机 `outputs/validation/macos-internet-tun-runtime-failure-20261012.log` 和 `macos-internet-tun-runtime-errors-20261012.log`,原始运行采样不随源码上传。
修复成功证据保留于本机 `outputs/validation/macos-internet-tun-fixed-20261012.log`。
## 2026-10-11:代理连接诊断版
- 修复代理 DNS 缺失时具体错误被替换成通用“操作失败”的问题;代理模式新增出口选择校验,重试清除旧错误。
- 代理页新增“查看连接日志”。记录入口、功能、模式、节点数量、DNS 是否配置,以及配置校验、动态库加载、helper 授权、引擎启动的阶段与耗时。认证值在写入前脱敏,已替换草稿的凭据仍保持隐藏;不输出完整配置。
- Go 引擎初始化/启动失败返回固定的阶段与错误分类,如 `listen_port_in_use`、`permission_denied`、`dns_resolution_failed`;不暴露上游错误中的认证或 URL 内容。
- macOS 通过 `OSLog` 同步记录脱敏事件,subsystem 为 `com.example.meshportLab`,category 为 `Runtime`。真实启动和缺少 DNS 的失败均已在 APP 日志页及系统日志中验证。
- 从固定 EasyTier 提交恢复被 `**/build/` 忽略而遗漏的三个构建源码文件,并修正忽略规则。适配本机 Xcode,macOS 最低版本为 12.0。
- Flutter 全量测试 42 项通过、6 项原生/环境依赖测试跳过;另启用 Rust/Go 动态库的配置往返与联合生命周期测试 11 项通过。Flutter analyze、Go `test -race ./...`、Go vet、APP 深度签名验证均通过。
- 产物:`outputs/macos/MeshPort-0.1.0-proxy-diagnostics.app`,开发调试签名,构建号 `20261012143711`;ZIP 位于同目录。已启动该产物,用户将自行导入真实节点;尚未验证用户代理的互联网通信。
实际日志证据保留于本机 `outputs/validation/proxy-diagnostics-macos-20261011.log`。
本轮继续实现统一 TUN、主要 24 页 UI 和 FakeIP。Android 真机验证按用户要求暂缓,没有安装 APK,也没有替换正在使用的 macOS APP。
| 检查 | 结果和范围 |
| --- | --- |
| Go `test -race ./...` | 12 项顶层测试通过;模式、组网优先、真实 DNS/FakeIP TCP 通信、撤销 DNS、缓存重建、隔离草稿 HTTP 检测、诊断范围隔离及 ABI 生命周期 |
| Go `vet ./...` | 通过 |
| Flutter `analyze` | 无问题 |
| Flutter 客户端测试 | 22 项通过,含原生 Rust/Go 联合启停、Partial、撤销保护、导入、认证隐藏、DNS/规则/组网表单 |
| macOS APP | 构建通过,包含统一 TUN helper;最终开发签名 `codesign --verify --deep --strict` 通过 |
| Android ARM64 APK | 构建通过;APK v2 签名、zipalign 16 KiB 校验通过,JNI/Rust/Go ELF LOAD 对齐均 ≥ 16 KiB |
| macOS 系统 TUN | 普通 OS TCP/UDP 回显、公告子网自动接入、停止删除测试路由及保持默认路由均通过;范围仅为 10.253.88.0/24 测试网 |
| Rust/FFI 映射子网 UDP | 同一 /24 内相邻 /25 的纯 SDK 和 FFI 回归均通过;测试网关必须编译 `proxy-packet`,此前 FFI 超时来自测试构建缺少此组件 |
| Android 联合 VPN 真机 | 未执行;入口明确标注待验证 |
Go/Rust 上游仍存在既有链接或弃用警告,不影响上述成功结果。第一次 Go 回归在沙盒中不能监听本机端口,放开本机测试端口后全部通过;不是功能回归。macOS TUN 首轮发现测试构造需要进入 Tokio runtime,随后修正 smoltcp TCP 回显服务提前关闭,以及错误地把出站 SDK UDP socket 当作入站服务的问题;UDP 自检使用远端映射子网和普通 OS 服务;正式流量通路已明确区分物理出口与 lo0 桥接出口;另修复有效前缀与保护前缀重复生成 TUN 路由,避免公告重建时重复删除导致清理失败,并新增回归测试。helper 自检网关已显式启用 `proxy-packet`,此前 UDP 包到达网关后没有进入子网转发,并非已证实的正式远端网关故障。新增不使用 TUN 的 SDK/FFI 回归覆盖这一场景。TUN 关闭后等待内部地址释放再重建;系统自检已验证重建后路由保留及普通 TCP/UDP 回显,尚不代表长时间稳定性验收。仅组网模式还移除了无对应公告的 IPv6 TUN 地址,避免上游根据空 IPv6 route_address 安装隐式 IPv6 默认路由。
系统自检记录见 [macOS 统一 TUN 日志](../outputs/validation/macos-unified-tun-20261011.log),日志仅含本机测试网络,不包含用户网络配置。
## 构建产物
- macOS:`apps/meshport_lab/build/macos/Build/Products/Debug/MeshPort.app`,构建号 `20261011095231`。
- Android:`outputs/android/MeshPort-0.1.0-1791641256-debug.apk`,ARM64 调试签名。
macOS 是本机开发签名,未公证;Android 是调试 APK,均不是正式发布版本。
## 验证边界
保留用户现有 v2rayN 与已连接 MeshPort,不做全局路由切换。因此 macOS 互联网统一 TUN 的全局 DNS、IPv6、网络切换与长时间运行未实测;不把仅组网的受限路由测试称作全局代理测试。Android 新增联合 VPN 的实际通信、后台和网络切换仍需真机。
公告变化重建 Go 引擎,会中断已有连接,尚无无损热更新。新版概览、代理与 DNS/FakeIP 页面已在 macOS 实际窗口检查,四个导航和编辑入口可达;全部页面的不同尺寸视觉验收仍需继续。
FakeIP 缓存在同一上下文重建时保留,最终释放清理,跨会话重新连接可能影响系统保留的旧 DNS 结果。
页面和限制见 [界面实现清单](ui-implementation.md);使用方法与模块边界见 [客户端运行控制](client-runtime.md)。
## 2026-10-11:高级客户端功能
已追加自动订阅更新、source/binary 与内联规则集、DoH/DoT、macOS/Android 原生文件和二维码导入、应用启动自动连接与 macOS 13+ 登录项设置;自动选出口按要求不实现。使用入口、缓存范围和平台差异见 [高级客户端功能](advanced-client-features.md)。
- Flutter 全量测试:34 项通过,3 项专门环境/UI 开关测试跳过;Rust/Go 动态库生命周期测试实际执行。
- Go 全量 `test -race ./...` 和 `vet ./...` 通过;新增真实 DoH / DoT 解析、规则集组网优先、HTTPS source 自动刷新、下载失败保留有效规则和直连模式暂停代理 DNS / 规则集测试。
- 并发测试暴露 sing-box 1.14.3 远程规则集读取与更新的竞争,已用 [固定版本补丁](../engines/singbox/patches/README.md) 修复,复现测试继续保留。
- macOS:构建、深度签名验证通过;真实图片选择器读取测试 QR,并显示 1 个节点的预览,未保存或连接测试节点。
- Android:ARM64 APK 已编译;相机、文档选择与新自动连接尚未真机验证。本轮未连接手机或安装 APK。
- 未开启用户的登录项、自动连接或相机权限,未替换 `/Applications/MeshPort.app`,保留现有 v2rayN 与 MeshPort 连接。真实登录恢复、相机与公共加密 DNS 在当前网络的可达性需后续验证。
最终高级功能 APP 与 APK 的路径记录在 `outputs/validation/advanced-client-20261011.md`;APP 位于独立输出目录,避免覆盖用户正在查看的开发构建。
## 2026-10-11:macOS 连接配置修复
实际客户端连接失败来自 `foreign_relay_bps_limit`:上游默认 u64::MAX 投影为 JSON 数值后,被 Dart 舍入为浮点数,重新生成 TOML 导致 EasyTier 配置校验失败。FFI 投影和编辑器改为精确十进制字符串,客户端迁移旧的默认无限制值并拒绝其他不精确输入。
- 原生 Rust FFI 投影测试通过;Flutter 原生配置往返与配置页面共 6 项测试通过;Flutter analyze 无问题。
- Rust SDK/helper 与 macOS APP 构建通过,开发签名深度验证通过。
- 修复版:`outputs/macos/MeshPort-0.1.0-config-fix.app`。
- 经用户授权,将旧窗口中的代理配置保存到本机钥匙串;修复版重新启动后实际读到现有节点。当前代理 DNS 尚未填写,实际互联网 SOCKS5 验证等待用户选择 DNS。v2rayN 保持运行,未切换系统路由。
## 2026-10-12:互联网连接修复与配置简化
macOS 互联网统一 VPN 的实际故障是物理出口绑定后的 UDP DNS 请求返回 `network is unreachable`。helper 在安装 TUN 路由前补充并验证物理接口的 scoped default route;复用已有路由,只清理自己创建且仍匹配原网关/接口的路由。此前实测用户节点通过普通 HTTPS、SOCKS5 HTTPS、固定 IP HTTPS 和 TUN DNS 检查,停止后原 DNS、默认路由和互联网访问恢复。本机证据为 `outputs/validation/macos-internet-tun-fixed-20261012.log`。该修复的 IPv6、网络切换和长时间运行仍未验收。
本次简化配置与界面:
- 首次启动默认“仅代理 / 全局代理”,macOS 和 Android 默认统一 VPN。恢复已有功能、节点和自定义 DNS;旧仅组网入口归一为组网功能。
- 代理 DNS 默认 `https://cloudflare-dns.com/dns-query`;缺失或留空均使用此默认值,自定义值保留。直连模式仍使用直连 DNS。
- 首次仅导入一个节点时自动选中;多个节点由用户选择。订阅更新删除原出口时不自动换到另一节点。
- 配置修改自动按顺序保存,失败显示“重试保存”;运行中修改提示“重连应用修改”,由用户执行后才改变运行配置。概览与代理页共用连接动作。
- 仅代理概览只展示连接信息、节点管理、日志和最近事件;网络入口、DNS/FakeIP、分流规则折叠到“高级设置”,组网高级配置同样折叠。分享链接的中文名称正确解码。
验证:Flutter analyze 无问题;启用 Rust/Go 动态库的 Flutter 全量测试 50 项通过,3 项需要专门开关的旧原生/UI 测试跳过。覆盖默认 DNS、首次节点选择、连续编辑保存顺序、保存失败重试、原生生命周期及不同窗口宽度。macOS 隔离预览窗口检查了概览、代理页和导入页布局;自动化输入受本机输入法影响,节点导入/选择通过 widget 测试验收。预览使用 `MESHPORT_UI_PREVIEW=true`,不读写用户配置、不初始化原生连接;交付 APP 未开启此标记。
产物:`outputs/macos/MeshPort-0.1.0-simple.app` 及同名 ZIP,包含 Rust/Go 动态库和 VPN helper;macOS 构建与深度严格签名验证通过。使用本机开发签名,未公证。本轮界面简化未再次切换实际系统 VPN;Android 共用配置逻辑已更新,未进行真机连接验证。
## 2026-10-12:Android 真机统一代理修复
MI 8 Lite(Android 15 / API 35、ARM64、4 KB 页面)完成新一轮真机验证。首次测试等待授权超时后,Flutter 自动卸载了临时 APP;已改用保留测试包并自动恢复普通 APP 的包装脚本,失败和成功均恢复安装,保留用户存储。
统一 VPN 实际复现“引擎 Running 但无法连接”,错误为 `no available network interface`。平台适配器的 Initialize 现在先发布物理接口列表给 sing-box NetworkManager。新增 Go 回归使用真实出站拨号:修复前复现同样错误,修复后 TCP 回显和 TCP/UDP socket 保护调用检查通过;Go 全量 race 与 vet 通过。
- 系统组网 VPN:加密存储、应用内 TCP/UDP、Java/Dart 普通系统 TCP/UDP、公告子网安装与撤销全部通过。
- 互联网统一 VPN:默认 Cloudflare DoH、普通 TCP/UDP、HTTPS 204、两次启动/停止和停止后 HTTPS 恢复全部通过。仅代理启动不依赖组网 TOML;首次单节点自动选择也在真机测试执行。
- Android 增加脱敏 MeshPortRuntime 事件和 VPN 创建、引擎就绪、清理阶段日志;仅代理启动提示改为导入节点后连接。
- 未保存测试节点;已退出测试 VPN、停止两套本机夹具并移除 adb reverse,手机恢复普通 APP。
详细结果和日志见 [Android 验证记录](../outputs/validation/android-client-20261012.md)。测试使用 Wi-Fi 与隔离 SOCKS5 出口;用户自己的代理节点、移动网络切换、长时间后台和 IPv6 上网仍需后续验证。
最终交付 `outputs/android/MeshPort-0.1.0-1791811912-debug.apk`,普通入口,开发签名,已安装并在 MI 8 Lite 前台打开;APK v2 签名、16 KB zipalign 校验通过。最终 Flutter analyze 无问题、50 项回归通过(3 项专门开关测试跳过)。
### Android 扫码方向修复
用户反馈点击相机扫码后变成横屏。ZXing 4.3.0 的 CaptureActivity 库 manifest 默认 `sensorLandscape`;原有 `setOrientationLocked(false)` 只关闭额外锁定,不覆盖 manifest 的横屏要求。宿主 manifest 现在覆盖为 `fullUser`,跟随用户旋转设置,保留原有关闭方向锁定选项。合并 manifest 已确认 CaptureActivity 为 fullUser;构建、签名和 16 KB zipalign 检查通过。`outputs/android/MeshPort-0.1.0-1791812247-debug.apk` 已覆盖安装并打开,保留现有配置。此次只修改方向配置,未自动开启手机相机或扫描用户二维码。
### macOS 关闭窗口与菜单栏驻留
MainFlutterWindow.close 改为隐藏窗口,保留 Flutter 控制器和网络会话;取消最后窗口关闭时退出。AppDelegate 强持有主窗口与状态栏项,顶部图标提供“打开 MeshPort”和“退出 MeshPort”;Dock 重新打开同样恢复原窗口,不创建第二个引擎。关闭主窗口时取消正在进行的相机扫码。
原生 XCTest 两项通过:performClose 隐藏窗口但保留同一控制器,菜单打开动作恢复保留的窗口,退出项明确指向 NSApplication.terminate。修复了原有 RunnerTests 仍引用 meshport_lab.app 的 TEST_HOST 和 scheme 名称。使用隔离预览验证关闭后进程保留、明确退出后进程消失;界面工具无法直接读取状态栏项,其打开动作由原生检查覆盖。未在本轮切换真实 VPN 连接。
普通入口产物 `outputs/macos/MeshPort-0.1.0-menubar.app` 及 ZIP;未开启 MESHPORT_UI_PREVIEW。构建和深度严格签名验证通过,本机开发签名。测试预览已退出,原有配置未改动。
+31 -1
View File
@@ -12,6 +12,21 @@
控制操作:validate/start(toml)、stop、status。
- `validate` 返回 `runtime_mode` 与 `overlay`(静态地址时为 `{address, prefix, network, routable}`,DHCP 为 null;`routable` 表示私有 IPv4 /16~/32)。可选 `check_local_overlap=true` 额外检查虚拟网段是否与本机现有接口重叠。
- `start` 同样接受 `check_local_overlap`。系统模式启动时 SDK 总是执行该检查,宿主不再自行预检。
- `build_config`(profile)由结构化表单草稿生成 SDK 接受的 TOML,返回 `toml`。`runtime_mode` 不是 `system_vpn`(包括宿主的 `unified_vpn`)时生成应用模式;`no_tun`/`use_smoltcp`、`enable_encryption=true`、`latency_first` 由 SDK 决定,宿主不再拼接 TOML。结果已通过 validate 同等校验。
- `migrate_config`(toml)移除旧版保存过、当前不接受的字段(顶层或 runtime 中的 `subnet_routes`),返回 `toml` 与 `changed`;无需迁移时原样返回。
- `abi_info` 返回 `{abi, revision, operations}`。`abi` 仍为 1;`revision` 是同一 ABI 内的能力修订号(当前 2:带 `build_config`/`migrate_config`/`start_bridged`/`wait_routes`/`health` 等),`operations` 列出支持的操作。宿主打开库后先调用它,修订号不足时给出明确错误,而不是在某个操作上才失败。旧库没有该操作,同样视为不满足。
- `start_bridged`(toml,可选 port、max_sessions、check_local_overlap、require_static_overlay)一步完成:校验应用模式、静态地址须可路由、可选要求静态地址与本机冲突检查,再启动网络与 SOCKS 桥接;任一步失败两者都不保留。返回 `engine_started`、`listen`、`overlay`、`mesh_cidrs`、`route_generation`。
`status` 的 `platform_network` 增加 `mesh_cidrs`(虚拟网段(可路由时)加已接受公告子网,规范化、排序,/32 也带后缀)、`route_generation`(`mesh_cidrs` 每次变化递增,宿主只需比较这个数)与 `overlay`。`subnet_routes` 保留,表示已接受公告子网本身。`health` 为 `{engine_running, bridge_running, mesh_routable}`,`mesh_routable` 表示宿主此刻可把 `mesh_cidrs` 流量交给桥接;停止时全部为 false。宿主不再自行计算前缀或判断组网是否可用。
`wait_routes`(可选 `after_generation`,`timeout_ms` 1–30000,默认 25000)长轮询路由变化:`route_generation` 与 `after_generation` 不同或网络停止时立即返回,否则超时返回 `changed:false`。返回 `running`、`changed`、`route_generation`、`mesh_cidrs`、`subnet_routes`。它不占用 context 的串行锁,等待期间 status、stop 等请求照常执行;需在独立线程/isolate 调用。网络停止时 SDK 会递增 generation、清空路由并标记停止,等待方被唤醒并得到 `running:false`。没有网络时立即返回 `running:false`(传了 `after_generation` 时 `changed:true`)。`meshport_context_free` 会立即停止网络并唤醒在途等待,不必等其超时。
`validate` 的 `include_profile=true` 投影将 `flags.foreign_relay_bps_limit` 编码为十进制字符串,以精确保留 u64 范围;宿主重新生成 TOML 时也应使用十进制字符串。默认无限制值为 `"18446744073709551615"`,不能经过浮点数转换。Flutter 会迁移旧配置中被舍入的默认无限制值,其他不精确或越界值要求重新输入。
应用内组网桥接:`socks_start`(可选 port,默认 0;max_sessions,默认 128)、`socks_status`、`socks_stop`。数据转发直接走原生并发任务,不经 JSON 字节 I/O。仅支持 IPv4 回环 SOCKS5 TCP/UDP;域名、IPv6、不支持的命令不做外部回退。stop/context free 先清理桥接再停止网络;socks_stop 不停止组网。需要新版原生库,详见 [SOCKS 桥接](socks-bridge.md)。
Android 系统模式需宿主 VpnService 创建 TUN 后调用 attach_tun(fd)。fd 由宿主持有,原生库不负责关闭;必须在原生实例停止后再关闭,替换网卡时须等新接口 ready 后关闭旧 fd。启动前注册 meshport_set_android_socket_protector,将原生 worker 的外层 socket 交给 VpnService.protect,回调与 JVM 桥接需保持有效。参考客户端 MeshVpnService 和 JNI NativeBridge。
TCP:tcp_connect(target)返回 resource;tcp_write(resource、bytes);tcp_read(resource、max_bytes、timeout_ms)返回 bytes/eof。
@@ -24,12 +39,14 @@ probe:target、protocol(TCP/UDP)、echo、timeout_ms。TCP echo=false 只
单次 JSON 请求 ≤128 KiB,配置 ≤64 KiB;写数据建议按16 KiB分块。UDP bytes ≤65507;TCP read 最大65535。普通 I/O 超时 1–30000 ms,默认5000 ms。连接/绑定超时当前固定5000 ms。
该 ABI 同步且每 context 串行,必须在后台线程执行。停止和释放会等待在途请求完成;当前不提供立即取消。TCP超时后可能已有部分字节发出,不应直接重发整个消息。后续生产版需异步资源接口和结构化错误码。
该 ABI 同步且每 context 串行(`wait_routes` 除外),必须在后台线程执行。停止和释放会等待在途请求完成(`wait_routes` 会被唤醒而非等待);当前不提供立即取消。TCP超时后可能已有部分字节发出,不应直接重发整个消息。后续生产版需异步资源接口和结构化错误码。
## 网络遥测
`status` 增加 `traffic`:`rx_bytes` / `tx_bytes` 为当前引擎运行期间采样到的累计隧道字节,`rx_bytes_per_second` / `tx_bytes_per_second` 是两次状态采样间的平均 B/s。首次采样速率为 null,重启引擎重新计数。包含组网控制、心跳和转发流量,不等于应用有效载荷。计数来自存活连接快照;若连接在两次采样之间消失,最后一次采样后的字节可能未计入。
`nodes` 是 SDK 合并 routes 与 peers 后的节点视图(排除本机,routes 顺序在前):`path`(direct/relay)、`direct_available`、`hole_punched`、`latency_ms` 与 `latency_source`(link_rtt / route_estimate / null)、`metered` 及该节点链路的 rx/tx 字段。直连且有 RTT 时取链路 RTT,否则取路由估算;界面直接展示,不再自行判定。
`peers` 增加默认连接的 `latency_ms`(EasyTier ping RTT;未测出为 null),当前存活连接合计字节及采样速率。`routes` 增加所选路由的 `estimated_latency_ms` 与 `next_hop_peer_id`;估算为路由各链路延迟之和,不是端到端实测 RTT。多连接节点的 RTT 来自默认连接,流量为全部存活连接之和。中继目标未单独归集流量,其流量计入下一跳隧道。
`diagnostics_enable` 显式开启进程级穿透 tracing 采集,返回 enabled 与 scope。SDK 默认不安装全局 subscriber;已有宿主 subscriber 时 enabled=false,宿主应自行开启 EasyTier 穿透日志。启用后不可在本进程中卸载,采集仅匹配 easytier_core::connectivity::hole_punch,最多 200 条、每条 4 KiB;status 增加 diagnostic_traces,含递增 sequence,可跨采样去重。多实例共享采集范围;诊断中含节点地址,导出时当前网络密钥脱敏。
@@ -39,3 +56,16 @@ probe:target、protocol(TCP/UDP)、echo、timeout_ms。TCP echo=false 只
注意上游 directly_connected_conns 只统计非打洞连接,本 SDK 不再直接以其为空推断中继。peers.direct 包括 TCP/UDP 打洞后的物理连接,hole_punched 表示存在上游归类为打洞的存活连接。页面的直连/中继标签仍根据所选下一跳判断,而非仅根据 direct。
`quality_sample` 请求:`resource` 为已绑定 UDP 句柄,`target` 为 IPv4:port,`sequence` 为 u64,`timeout_ms` 为100–5000(默认1000)。返回 success、elapsed_ms、target_peer_id、next_hop_peer_id、next_hop_after、route_changed。超时/I/O错误返回 success=false、elapsed_ms=null;非法句柄或参数走 ABI 错误。复用 socket 并顺序调用,目标须支持原样 echo;状态前后采样不计入 RTT。
### 高级受管理代理配置(2026-10-11)
`direct_dns_server` 可选,`proxy_dns_server` 支持普通 IP DNS、HTTPS DoH、TLS DoT。`dns_server` 保留为独立 IP 启动解析器。直连模式不建立代理 DNS 依赖;代理 DNS 非直连模式需要手动选择代理节点。
`rule_sets` 是最多 32 个受管理条目的数组:`tag`(唯一)、`enabled`、`action`(proxy/direct/reject)。远程条目使用 `url`(HTTPS)、`format`(source/binary)、`download_detour`(direct/proxy)、`update_hours`(1–168,默认 24);内联条目使用 `rules`(sing-box headless 规则)。远程和内联不能混用,不接收特权文件路径。仅规则模式加载规则集,组网保护优先。配置入口仍拒绝未知字段及超过 64 KiB 的请求;不接受完整未管理 sing-box 配置。
订阅的 `auto_update` / `interval_minutes`、代理配置的 `proxy_enabled` 以及平台启动首选项由客户端持久化层管理,不是 EasyTier 组网 SDK 新参数。版本 1 配置可读取旧字段缺失的保存数据。自动连接仍按系统权限实际结果报告状态。
## 代理 DNS 保护
sing-box 引擎配置新增可选布尔字段 `dns_protection`。启用后,非直连互联网模式要求明确的 `proxy_dns_server` 和代理节点,普通解析和默认域名解析器均使用代理 DNS;不配置默认公共解析器,不回退启动 DNS。Flutter ProxyProfile 默认发送此字段,旧 JSON 调用未设置字段时兼容旧行为。代理节点与解析器主机名使用受管理 bootstrap 解析以避免循环;仅组网与直连模式保持独立。宿主应在关闭旧会话之前执行连接校验。
+113
View File
@@ -0,0 +1,113 @@
# 下一阶段架构:组网与代理组合客户端
更新日期:2026-10-10。状态:部分实现。现有实现见 [当前架构](architecture.md),页面和行为依据见 [UI 设计 V4](ui-design.md)及其交互说明。
开发进度:已完成 [MeshPort SOCKS 桥接](socks-bridge.md)及 FFI/Dart 控制入口,并新增 [sing-box Go 封装](singbox-integration.md),通过本机跨语言 TCP/UDP 与公告撤销验证。组网 SDK 原有 JSON I/O 仍串行;已新增 [独立 singbox_flutter 与客户端核心](client-runtime.md),实现应用内联合生命周期和公告变化后的配置重建;普通代理配置、订阅、模式和基础 DNS 已接入;Android 统一 TUN 为待真机验证原型,macOS 统一 TUN/helper、FakeIP 与新版主要页面已接入,测试范围见 [验证记录](development-validation.md)。下文目录与架构图表达最终目标,具体已实现范围以接入文档为准。
## 模块架构
保留 MeshPort 独立组网 SDK。代理引擎与组合会话管理属于客户端扩展,不让其他应用使用组网 SDK 时强制依赖 sing-box。
```mermaid
flowchart TD
UI[Flutter 客户端:概览 / 代理 / 组网 / 设置] --> Core[客户端核心:状态 / 配置 / 订阅 / 路由 / DNS]
Core --> MB[meshport_flutter]
Core --> SB[singbox_flutter]
Core --> Platform[平台权限 / 安全存储 / 网络入口]
MB --> FFI[meshport-ffi:C ABI]
FFI --> SDK[meshport:Rust SDK]
SDK --> Adapter[meshport-easytier / meshport-netstack]
Adapter --> ET[EasyTier 核心与应用内数据面]
SB --> Go[sing-box Go 封装]
Go --> Socks[meshport-socks:组网 SOCKS5 桥接]
Socks --> SDK
Platform --> Android[Android:VPN Service / 原生桥接]
Platform --> Mac[macOS:系统接入 / 特权 helper]
Other[其他项目应用] --> MB
```
客户端核心负责组合状态、配置验证、持久化与生效、公告变化和故障反馈。Rust SDK 负责组网、节点、选路及数据面;Go 封装负责代理引擎运行和接口适配。Flutter 页面不直接拼装内核配置或操作系统路由。
## 组合模式数据路径
```mermaid
flowchart LR
Apps[系统应用 TCP / UDP] --> TUN[一个平台 TUN]
TUN --> Route[sing-box 统一分流]
Route -->|有效组网地址与公告子网| Socks[MeshPort SOCKS5:TCP / UDP]
Socks --> Stack[MeshPort 应用内数据面]
Stack --> ET[EasyTier:直连或中继]
ET --> Remote[远端节点 / 公告局域网]
Route -->|普通代理目标| Proxy[代理出口]
Route -->|普通直连目标| Physical[物理网络]
Proxy --> Physical
ET --> Physical
```
这张图表示目标方案。组合会话只允许一个系统 TUN 所有者,MeshPort 使用应用内数据面,不同时启动现有 EasyTier 系统 TUN。现有独立系统组网模式仍可单独使用。
组网优先规则仅包含合规且有效的目标,不泛化为所有私网地址。两侧引擎的外层连接需绕过自身 TUN,避免循环;代理服务器启动解析也不能依赖尚未建立的同一个代理。Android 的连接保护和底层网络选择、macOS 的物理网络出口处理属于原生平台适配职责。
公告接入、撤销和失联时同步更新有效分流与状态。组网目的地不可静默降级到互联网代理;保护记录及恢复本地访问行为按 V4 交互说明实施。
## 目标目录
“新增”为计划模块,其余保留现有边界;目录名称在落实接口时可调整。
```text
MeshPort/
├── crates/
│ ├── meshport/ # 现有:组网 SDK 公共接口
│ ├── meshport-easytier/ # 现有:EasyTier 适配、选路、公告子网
│ ├── meshport-netstack/ # 现有:应用内 TCP/UDP 数据面
│ ├── meshport-ffi/ # 现有:C ABI
│ └── meshport-socks/ # 新增:组网 SOCKS5 TCP/UDP 桥接
├── engines/
│ └── singbox/ # 新增:Go 引擎封装
│ ├── bridge/ # 启停、状态、统计、出口切换
│ ├── platform/ # TUN 与底层连接接口
│ └── tests/
├── bindings/flutter/
│ ├── meshport_flutter/ # 现有:独立组网 SDK 绑定
│ └── singbox_flutter/ # 新增:代理引擎平台绑定
├── packages/
│ └── meshport_client_core/ # 新增:共用客户端业务逻辑
│ └── lib/
│ ├── runtime/ # 两侧生命周期、组合状态
│ ├── configuration/ # 草稿、保存、运行快照、迁移
│ ├── subscriptions/ # 导入、更新、来源、节点归属
│ ├── routing/ # 组网优先、普通规则、默认出口
│ ├── dns/ # 域名范围、解析出口、失败策略
│ ├── telemetry/ # 状态、流量、测量、脱敏日志
│ └── platform/ # 权限、能力、安全存储接口
├── apps/meshport_lab/ # 现有客户端,逐步重构
│ ├── lib/
│ │ ├── app/ # 导航、主题、依赖组装
│ │ ├── features/
│ │ │ ├── overview/
│ │ │ ├── proxy/
│ │ │ ├── network/
│ │ │ └── settings/
│ │ └── shared/ # 控件、状态视图、确认框
│ ├── android/ # VPN Service、权限、连接保护
│ └── macos/ # 系统接入、helper、安全存储
├── tools/
│ ├── meshport-vpn-helper/ # 现有 macOS 特权入口,按需扩展
│ └── meshport-test-server/ # 现有 TCP/UDP 验证服务
├── tests/integration/ # 新增:组合模式与平台联调
├── scripts/ # Rust/Go 构建、打包、安装
└── docs/ # 架构、设计、配置、验证
```
## 开发顺序与完成条件
| 阶段 | 工作 | 完成条件 |
| --- | --- | --- |
| 1:组网桥接 | SOCKS5 TCP/UDP、连接级并发、取消及资源清理 | 并发连接不被单次读取串行阻塞,目标与会话正确隔离,停止无残留 |
| 2:引擎及平台入口 | Go 封装、Android 单一 VPN 入口,随后 macOS | 仅组网、仅代理、组合模式通信通过;两侧外层流量不循环 |
| 3:配置与状态 | 订阅、草稿/保存/生效、DNS、公告接入及撤销 | 部分失败和权限取消准确呈现,更新可确认,失效组网目标不泄漏到互联网代理 |
| 4:UI 与稳定性 | 按 V4 拆页面、后台与恢复、持续验证 | 网络切换、重连、故障恢复及长时间运行通过真实设备验证 |
当前 ABI 每 context 串行,不能直接作为大量 SOCKS 并发连接的最终数据面;先完善异步提交、取消和连接级并发,或为桥接层提供等价的 Rust 原生并发接口。
初期保留 apps/meshport_lab 的目录与安装标识,减少同时迁移构建脚本、包名和配置存储的风险;正式命名迁移另列任务。实现应固定依赖版本、记录构建特性与上游许可证,并按实际平台能力开放 UI。
+11 -1
View File
@@ -24,7 +24,7 @@ relay_peer_ids = []
没有 optimization 时,保留原 flags.latency_first 的含义:true 使用 adaptive,false/缺省使用 hop。显式 mode 优先决定该 flag。阈值范围:毫秒 0–1000、比例 0–0.9、持续时间 0–300 秒、冷却 0–600 秒。
UDP 优先作用于同一节点已经建立的连接,保留 TCP 作为备用。尚未首次 ping 确认的打洞连接不会抢占已确认连接。连接选择最多每 5 秒刷新;路由选择缓存 2 秒,通过流量或状态采样驱动阈值评估。策略不会凭空建立配置中没有的备用通道。
同一节点已建立的连接先按确认状态、再按实测 RTT 选择;UDP 偏好仅用于 RTT 相同时的选择,不会为了 UDP 放弃延迟更低的 TCP。尚未首次 ping 确认的打洞连接不会抢占已确认连接。连接选择最多每 5 秒刷新;路由选择缓存 2 秒,通过流量或状态采样驱动阈值评估。策略不会凭空建立配置中没有的备用通道,也不保证最低 RTT 的连接具有最高吞吐。
relay_peer_ids 最多 64 项,约束本机普通 peer-map 中上游候选的第一跳,空列表不限制。它不是完整的中继池调度器:上游最优候选不在列表时,不搜索第二优候选;没有直连可能暂时不可达。也不约束远端后续转发或所有 foreign-network 转发。建议第一轮留空。
@@ -38,6 +38,16 @@ relay_peer_ids 最多 64 项,约束本机普通 peer-map 中上游候选的第
当前自动选路比较直连的选中连接 RTT 与上游路径估算,并未将端到端 P95/抖动/丢包自动反馈到路由器,也未强制逐条候选路径探测。先分别使用 direct/adaptive 测量同一 echo 目标,检查结果再调阈值。配置修改需断开重连。
## 用户态子网 TCP 缓冲
SDK 数据面使用接收 1 MiB、发送 512 KiB 的 TCP 缓冲;用户态子网转发使用接收 1 MiB、发送 128 KiB。子网转发原来的收发各 16 KiB,在较高 RTT 下可能限制单连接吞吐。直接使用 512 KiB 发送缓冲时,本地低延迟短下载出现回退,因此子网转发采用较小的发送缓冲。增大缓冲不能解决丢包、重传或链路选路问题。
子网缓冲按 socket 分配,收发合计约 1.125 MiB,尚在握手中的连接也会分配;100 个 socket 的缓冲约占 112.5 MiB,不含其他对象。该修改作用于运行此代码、启用用户态子网转发的网关。仅更新本机 MeshPort 不会扩大远端原版 EasyTier 网关的窗口,内核转发路径也不受此处修改影响。尚需真实远程链路验证,不能仅凭本地模拟结果承诺带宽。
## UDP 接收调度
UDP 接收循环每连续接收 32 个报文主动让出调度,避免突发收包时会话队列的消费任务长时间得不到运行机会。保持原有 128 槽队列和丢包策略,不阻塞共享 UDP socket 等待某个节点。该调整在本地加密 SDK 链路的延迟测试中减少了队列满丢包和重复 TCP 数据序号;仍需实际网络、多节点持续负载验证,不能保证所有丢包或现场延迟问题均被消除。
## 后续范围
独立候选路径探测与端到端反馈、完整专用中继池搜索、拥塞/排队感知、MTU 探测、游戏流优先和跨国长时故障测试尚未实现。此轮没有部署或购买中继服务器。
+66
View File
@@ -0,0 +1,66 @@
# sing-box 引擎接入:第一阶段
更新日期:2026-10-10。本文件记录第一阶段组网桥接的验证路径,下文“本阶段”均指最初 mesh-only 范围。当前已追加普通代理出口、配置与订阅、模式和基础 DNS;Android 单一 VPN 为待真机验证原型。最新范围见 [客户端运行控制](client-runtime.md)。
## 已实现的路径
```mermaid
flowchart LR
Test[本机 SOCKS5 测试客户端] --> Go[sing-box:回环入口与受管理分流]
Go --> Rust[MeshPort SOCKS5:原生并发 TCP/UDP]
Rust --> SDK[应用内 MeshPort / EasyTier]
SDK --> Gateway[远端节点:自动学习的合规公告子网]
Gateway --> Service[TCP / UDP echo 服务]
```
引擎固定使用 sing-box 1.14.3,依赖版本与校验记录在 engines/singbox/go.mod 和 go.sum。项目本地脚本设置独立 Go 模块、构建缓存,工具链最低要求由 go.mod 的 Go 1.25.5 声明决定;没有升级系统 Go 安装。
SOCKS 出口依据 [sing-box 官方接口](https://sing-box.sagernet.org/configuration/outbound/socks/)接入;本阶段只注册所需的本机 SOCKS 能力。模块固定上游版本,不改写下载缓存内的源码;当前规则集并发修补通过项目私有模块副本构建,见 [补丁说明](../engines/singbox/patches/README.md)。上游许可证副本见 [sing-box LICENSE](upstream/sing-box-LICENSE)。
## 模块职责
| 文件 | 作用 |
| --- | --- |
| engines/singbox/bridge/config.go | 从有效组网前缀生成受管理配置;验证回环端点、地址范围和数量 |
| engines/singbox/bridge/engine.go | 引擎启动、停止、状态及失败恢复;重复启动拒绝,停止可重复调用 |
| engines/singbox/bridge/inbound.go | 跟踪已接受但尚未路由的 TCP 控制连接;停止时关闭全部控制连接,最多 128 个 |
| engines/singbox/bridge/outbound.go | TCP 使用上游 SOCKS 出口;UDP 标准化关联握手并复用上游报文封装 |
| engines/singbox/cmd/meshport-singbox | 读取受管理配置、输出一次就绪状态、响应退出信号的开发程序 |
| crates/meshport-socks | 本机 SOCKS 到独立组网 SDK 的桥接 |
只有配置前缀内的 IPv4 流量进入组网出口;其他目标和域名请求显式拒绝,没有普通互联网出口。当前前缀额外限制为私网 /16–/32,不接受所有私网、公共段、IPv6 或默认路由。地址属于允许范围不等于已公告,宿主仍需从 SDK 的合规有效投影生成配置。
mesh_cidrs 直接取自 SDK 状态的 `platform_network.mesh_cidrs`(或 `start_bridged` 返回值),宿主原样传入,不是用户手动远端子网列表,也不再由各宿主重复计算。Go 使用启动时快照;公告撤销由底层 SDK 即时阻止转发。现有客户端核心按有效投影变化自动重建 Go 引擎,无需手动列表;变化会关闭已有代理连接。无损热更新仍待实现;当前客户端核心已保留本次会话中的已知前缀,撤销目标由显式拒绝规则保护。
组网目标没有路由时返回连接失败或关闭连接,UDP 不交给其他出口。域名在分流第一条即拒绝,不做系统 DNS;此处描述最初 mesh-only 配置;当前联合模式已实现组网 DNS 和普通代理解析,FakeIP 已实现,范围见客户端运行控制。
## 联调中修正的问题
- TCP 半关闭时远端 FIN ACK 可能因路由撤销而无法返回,Rust 桥接加入有界收尾时间,避免永久占用会话。
- 引擎停止时,尚未完成 SOCKS 请求的连接还没进入路由连接管理器;Go 接入层在协议处理前跟踪连接,保证停止时主动关闭。
- UDP ASSOCIATE 按 [RFC 1928](https://www.rfc-editor.org/rfc/rfc1928)表达客户端预计使用的来源端点。Go 适配层在尚未分配 UDP 端点时发送 IPv4 0.0.0.0:0,避免将远端私网目标或其服务端口误当作来源。Rust 的来源 IP/端口隔离保持有效;不修改上游版本的握手实现。
Go UDP 握手受上下文取消和最长 5 秒超时控制;仅接受同一桥接 IP 返回的有效 IPv4 回环端点。取得关联后保留 TCP 控制通道,关联关闭会清理控制和 UDP 资源。宿主在上下文取消后仍需调用 Engine.Stop;Snapshot 不将已取消上下文标作 Running。
## 构建与验证
```sh
sh scripts/go-local.sh mod download
sh scripts/go-local.sh test -race ./...
sh scripts/go-local.sh vet ./...
sh scripts/build-singbox.sh
sh scripts/test-singbox-bridge.sh
scripts/cargo-local.sh test -p meshport-socks -p meshport-ffi --locked
```
开发程序输出到 target/debug/meshport-singbox,缓存和二进制均在 Git 忽略目录。配置输入上限 64 KiB,拒绝未知字段和尾随 JSON,不接收任意完整 sing-box 配置;默认关闭内核日志,只输出就绪状态,不打印配置或凭据。
端到端测试自行建立本机真实 EasyTier 网关、客户端和 echo 服务,自动学习测试公告;网关将测试私网映射到回环地址。它启动 Go 引擎,然后验证四个并发 TCP 连接、空闲 TCP 与两组 UDP 会话、公告撤销后的 TCP/UDP 失败及程序停止。测试不需要管理员 VPN 权限,不改系统路由,不读取个人网络配置。
第一阶段 Go 引擎有 3 项测试(配置约束、拒绝未配置目标/域名、启停与恢复),通过 race 检查;新增代理策略测试见客户端验证记录。Rust 桥接/FFI 常规测试 7 项通过。跨语言端到端测试默认显式忽略,由 test-singbox-bridge.sh 构建引擎后单独执行,已通过。Rust Clippy 与 Go vet 通过。
本次验证平台为开发机 macOS ARM64。链接器仍报告上游/工具链的重复 objc 与 race 对象符号表警告,编译与测试成功;不据此宣称已通过 Android 或实际系统 VPN 验证。
## 后续进度
以 [客户端运行控制](client-runtime.md) 和 [开发验证记录](development-validation.md) 为准。macOS 统一 TUN 的限定子网 TCP/UDP 与清理自检已通过;Android 联合模式仍需真机验证。新增高级功能范围见 [高级客户端功能](advanced-client-features.md)。
+77
View File
@@ -0,0 +1,77 @@
# 应用内组网 SOCKS 桥接
更新日期:2026-10-10。下一阶段第一批实现:新增 `crates/meshport-socks`,并提供 C ABI 与 Dart 控制入口。[sing-box 本机引擎联调](singbox-integration.md)已完成;统一 TUN 和新 UI 尚未接入,现有客户端不会自动启动此桥接。
## 接入方式
```text
本机代理引擎/测试程序 → 回环 SOCKS5 → Rust MeshPort 数据面 → EasyTier → 虚拟地址/合规公告子网
```
每个连接/关联在 Tokio 独立任务中运行,转发直接使用 Rust 数据面,不通过串行 JSON 字节读写。现有 ABI 的普通 TCP/UDP 读写操作仍是每 context 串行;本次没有将它们改为异步 ABI。
按 [RFC 1928](https://www.rfc-editor.org/rfc/rfc1928)的报文格式实现受限的本机桥接:CONNECT 与 UDP ASSOCIATE,IPv4 地址、无认证协商。没有 GSSAPI、用户名密码、BIND、IPv6、域名解析或 UDP 分片,不能作为完整公开 SOCKS 服务使用。不支持的 TCP 请求返回协议错误;不支持的 UDP 报文丢弃。
- 仅允许 IPv4 回环监听,默认动态端口;调用者持有同一应用内 `Network`。
- SDK 公共 TCP 数据面采用 OverlayOnly,未找到组网路由时失败,不调用普通互联网直连。UDP 使用组网数据面,不提供外部回退。
- 公告子网仍由现有 SDK 自动学习、过滤与撤销;无需手动填写远端 CIDR。
- 域名需上层按 DNS 策略解析到 IPv4,再交给桥接;桥接不使用系统 DNS,避免意外域名泄漏。
- UDP 关联绑定 TCP 控制连接来源 IP,按请求端口或首个合法数据报固定来源端口;仅向本关联已发送过的目标接收返回数据。
- 关联在控制连接关闭、空闲超时或桥接停止后释放。TCP 在任一方向 EOF 后给另一方向有限的收尾时间,防止路由失效后无限等待 FIN ACK。
- 本机无认证监听不隔离同一设备上的其他进程;后续正式集成若需要隔离,应增加认证或平台内通道,不能把回环监听视为秘密凭据保护。
## Rust
```rust,ignore
let network = std::sync::Arc::new(meshport::Network::start(&toml).await?);
let mut bridge = meshport_socks::Bridge::start(
network.clone(),
meshport_socks::Options::default(),
).await?;
let endpoint = bridge.local_addr();
// 将 endpoint 配置为宿主代理引擎的组网 SOCKS 出口。
bridge.stop().await?;
network.stop().await;
```
生命周期顺序:启动组网 → 启动桥接 → 启动宿主代理;停止时先停宿主代理,再停止桥接,最后停止组网。`Bridge::stop` 等待子任务清理,可重复调用;Drop 发起取消但不能同步保证异步任务已回收。
默认限制:128 个会话,握手 5 秒,连接/UDP 建立 10 秒,TCP 半关闭收尾 30 秒,UDP 空闲 120 秒、单次发送 5 秒,每关联最多 64 个尝试目标。超限不排队创建无限任务;关联目标集合包含发送失败的尝试,避免底层 flow 无限增长。Rust Options 可调整,启动时校验范围和非零超时。
SOCKS IPv4 UDP 封装增加 10 字节,当前每个数据报最多承载 65497 字节。大于此值的远端响应会丢弃;这不表示实际线路 MTU 支持同样大的无分片报文。TCP/UDP 协议和 MTU 限制不提供 ICMP 转发。
## C ABI / Flutter
新增控制请求(保留 ABI 版本 1):
```json
{"op":"socks_start","port":0,"max_sessions":128}
{"op":"socks_status"}
{"op":"socks_stop"}
```
`socks_start` 返回 running、listen、tcp、udp、ipv4_only、dns_resolution。已有桥接时启动失败;系统 VPN 模式或未启动网络时启动失败。`socks_status` 返回运行状态、当前/累计会话、完成/失败会话、容量拒绝及 UDP 丢弃数量;这些是桥接计数,不是链路丢包率或应用流量。
`stop` 和 context free 会先停止桥接,再停止组网,关闭监听与所有会话;`socks_stop` 保留组网实例。容量拒绝的连接不计入 accepted;取消的会话不会计入 completed/failed,因此累计值不要求严格相加相等。
```dart
await client.start(applicationToml);
final bridge = await client.startSocksBridge();
final endpoint = bridge['listen'];
final status = await client.socksBridgeStatus();
await client.stopSocksBridge();
await client.stop();
```
运行这些方法需要重新构建原生 FFI 库。只更新 Dart 而加载旧库会返回未知操作,不会产生可用桥接。平台宿主的单一 TUN 与外层连接保护留给下一批实现。
## 验证
```sh
scripts/cargo-local.sh test -p meshport-socks -p meshport-ffi --locked
scripts/cargo-local.sh run -p meshport-socks --example local_bridge -- /path/to/application.toml
```
测试使用本机真实 EasyTier 引导节点与远端网关,网关将公告私网映射到回环 TCP/UDP echo 服务,不修改系统路由,不读取私人配置。覆盖:并发 TCP、空闲 TCP 不阻塞其他会话、双 UDP 关联隔离、来源端口限制、分片拒绝、公告学习与撤销、协议错误、容量/握手/空闲超时、重启及 FFI/context 清理。
这批验证只覆盖开发机本地网络。Android 原生构建与真机、macOS 实际组合 VPN、远程高延迟与长时间压测仍需后续验证。
+42
View File
@@ -0,0 +1,42 @@
# MeshPort 稳定性验证
当前已完成短时 macOS 联网及 Android 真机 TCP/UDP、DNS、HTTPS、启停和清理验证;尚未完成长时间后台与物理网络切换验收。短时通过不能替代稳定性验收。
## 测试安排
| 阶段 | 操作 | 观察与通过条件 |
| --- | --- | --- |
| 启停回归 | 同一配置连接/断开 50 次,组网、代理、联合模式分别执行 | 无崩溃、无遗留 VPN;每次可重新连接;断开后普通上网恢复 |
| 连续通信 | 连续运行 1 小时,每 30 秒执行 HTTPS 请求、组网 TCP 和 UDP 回显 | 记录成功率、延迟和错误阶段;与未使用 MeshPort 的网络基线比较,区分公网故障与 APP 故障 |
| 后台运行 | 连续 8 小时,包含锁屏、切换 APP、恢复前台 | 后台连接符合预期;恢复后状态准确,能通信或明确报告连接失败;无永久卡在“已连接但无网” |
| 网络变化 | Wi-Fi 断开/恢复、两个 Wi-Fi 间切换、有移动数据的设备切换 Wi-Fi/移动网络,各 10 次 | 记录恢复时间;可自动恢复或明确提示重连;代理出站不进入自身 VPN |
| 故障恢复 | 关闭测试代理/组网网关、使 DNS 不可达,再恢复服务 | 有可定位的日志;失败不偷偷切换出口或泄漏组网流量;恢复或重连后可用 |
| 资源与清理 | 比较启动前、运行中、重复启停后、停止后的资源 | 排除启动预热与缓存后,内存、线程、FD 不持续增长;停止后无测试 TUN、路由或 DNS 遗留 |
先执行短时测试,再逐步延长。不要用全部无响应的数据推断 APP 故障;应保留同一网络上的基线、测试节点可达性和发生时间。
## 使用现有测试
- 应用内 UDP 质量页可记录 RTT、P95、抖动和未响应率,需要远端回显服务;它不能代表系统 VPN 的稳定性。
- Android 系统组网与统一代理真机脚本见 [Android 文档](android.md)。使用 `scripts/test-android-device.sh`,结束时自动恢复普通 APP,避免 Flutter 直接测试后卸载用户 APP。
- 当前统一代理真机脚本只重复两次启停;50 次、8 小时后台及网络切换仍需单独执行并记录。
- macOS 检查连接前后的默认路由、物理 scoped route 和 DNS;只清理测试会话拥有的路由。
## Android 采样
```sh
# 记录脱敏运行阶段,不采集全部系统日志。
adb -s DEVICE_SERIAL logcat -s MeshPortRuntime:I MeshPortVPN:I AndroidRuntime:E
# 在各阶段重复采样,比对 PSS、线程和 FD 趋势。
adb -s DEVICE_SERIAL shell dumpsys meminfo com.example.meshport_lab
adb -s DEVICE_SERIAL shell pidof com.example.meshport_lab
adb -s DEVICE_SERIAL shell ls /proc/APP_PID/fd
adb -s DEVICE_SERIAL shell ls /proc/APP_PID/task
```
部分设备限制读取 `/proc`,这时记录可获取的 meminfo 与进程状态;不要为了采样关闭设备安全保护。原始日志留在本机 `outputs/validation`,Git 只提交不含私人配置的验证摘要。
## 验收记录
每次记录 APP 构建号、系统版本、入口与功能、节点协议、网络类型、时长、请求数量/失败数量、延迟、内存趋势、恢复时间和遗留资源检查。测试报告区分“已通过”“失败”“未执行”;只有三种入口及目标平台的相关场景完成后,才对对应范围给出稳定性结论。
+6 -4
View File
@@ -22,15 +22,15 @@ Rust 的 `system-vpn` feature 是显式编译开关;默认 SDK 构建保持应
## 启动和生命周期
运行 `scripts/run-lab-macos.sh`,它构建并启动包含动态库与 helper 的开发应用。系统模式启动时 macOS 请求管理员授权;Flutter UI 不提权,独立 helper 创建网络接口。控制通道是当前用户私有临时目录中的 Unix socket,helper 校验对端 UID,限制请求大小与允许的操作。断开连接、控制通道关闭或空闲超时后停止引擎;临时目录由 Dart 清理。虚拟网段在启动前检查冲突。自动公告子网只允许私有 IPv4 /16 至 /32,最多 32 项(CIDR 排序后截取);过滤默认路由、公网、过宽网段、虚拟网段及本机接口重叠。接口缓存每 2 秒更新,系统路由定期重新同步;安装失败重试,公告撤回删除路由。
运行 `scripts/run-lab-macos.sh`,它构建并启动包含动态库与 helper 的开发应用。系统模式启动时 macOS 请求管理员授权;Flutter UI 不提权,独立 helper 创建网络接口。控制通道是当前用户私有临时目录中的 Unix socket,helper 校验对端 UID,限制请求大小与允许的操作。断开连接停止引擎,但应用存活期间保留已授权 helper 和控制通道,使用每 30 秒一次的空闲心跳支持下次连接复用授权。退出应用关闭控制通道并清理 helper;控制通道异常关闭或空闲超时也会停止引擎,临时目录由 Dart 清理。虚拟网段在启动前检查冲突。自动公告子网只允许私有 IPv4 /16 至 /32,最多 32 项(CIDR 排序后截取);过滤默认路由、公网、过宽网段、虚拟网段及本机接口重叠。接口缓存每 2 秒更新,系统路由定期重新同步;安装失败重试,公告撤回删除路由。helper 是串行的请求/响应进程,由 GUI 状态轮询驱动,因此仍用轮询读取 `mesh_cidrs`,不使用 `wait_routes`;统一模式 status 的 `installed_subnet_routes` 不含虚拟网段,与 Android 一致;仅组网的统一模式在 `health.mesh_routable` 失效时整体停止(与 Android 一致),联合模式则保持代理并报告 `Partial`。
原生调用超过 60 秒时 helper 退出,以关闭 utun 文件描述符;Dart 控制请求超时为 30 秒。
设置页顶部有“配置保存”面板,可在未连接时点击“保存配置”。完整 TOML(包含网络密钥)保存在 macOS Keychain;启动时自动回填表单,不自动连接。已保存的配置可以重新载入或删除。“连接成功后自动保存配置”首次默认关闭,主动保存或加载已有配置后开启。未编辑的导入配置原样保留高级参数;修改表单后使用表单生成的配置。
设置页支持自动保存和独立的自动连接开关。配置保存在 `~/Library/Application Support/MeshPort/`,代理文件为 `proxy-profile.json`,组网文件为 `network-profile.toml`;目录权限 0700、文件权限 0600,内容为明文,使用原子写入。启动时尝试无弹窗迁移旧 Keychain 配置;需要授权时在设置页点击“迁移旧配置”,保留旧备份且不覆盖已有本地配置。未编辑的导入配置保留高级参数;修改表单后使用表单生成的配置。
## 发布边界
这是开发版 helper 方案,使用临时管理员授权与 ad-hoc 签名,尚未完成正式签名、公证或 Network Extension 发布流程;macOS App Sandbox 已为此开发方案关闭。Android VpnService 已接入,并通过隔离真机 TCP/UDP 和自动公告路由验证,详见 [Android](android.md)。iOS Packet Tunnel、移动端长期后台恢复仍待验证。
这是开发版 helper 方案,使用管理员授权。Release 打包优先使用可用的 Apple Development 身份保持签名稳定,没有身份时使用 ad-hoc;尚未完成 Developer ID 签名、公证或 Network Extension 发布流程;macOS App Sandbox 已为此开发方案关闭。Android VpnService 已接入,并通过隔离真机 TCP/UDP 和自动公告路由验证,详见 [Android](android.md)。iOS Packet Tunnel、移动端长期后台恢复仍待验证。
显式特权自检:`sudo target/debug/meshport-vpn-helper --self-test`。自检通过 loopback 建立两个隔离的 EasyTier 节点,使用 10.253.77.0/24 作为客户端虚拟网段,自动学习另一节点发布的 10.253.78.0/24,验证额外子网路由以及普通系统 TCP/UDP 经 utun 回显、默认路由保持不变、公告撤回后的路由删除和停止后的接口删除。最多运行 45 秒;阶段日志写入 `/tmp/meshport-vpn-self-test-<pid>.log`,不写网络密钥。
@@ -42,4 +42,6 @@ macOS 的节点连接使用物理网卡候选,IPv4/IPv6 都排除其他 VPN
保留 v2rayN TUN,先用 `route -n get 192.168.21.201` 检查更具体的 /24 路由是否指向 MeshPort 的 utun。只设置 v2rayN “直连”规则不能建立 EasyTier 子网路由。如路由仍被代理接管,再检查 TUN 路由排除配置;不要依赖变化的 utun 编号设置永久路由。
旧版 runtime.subnet_routes 已移除;Lab 从钥匙串恢复旧版单行配置时会删除该字段并改用自动学习。直接使用 SDK 的旧配置应移除此字段。自动子网是 IPv4;移动端、Windows 的打包与实际互通尚待验证。
旧版 runtime.subnet_routes 已移除;Lab 恢复旧版保存的配置时调用 SDK `migrate_config` 删除该字段并改用自动学习。直接使用 SDK 的旧配置也可调用该操作或手动移除此字段。
虚拟网段与本机现有接口重叠时,系统模式启动由 SDK 拒绝(“overlay overlaps an existing interface”),macOS helper 与 Android 服务不再各自预检。Android 上另一应用仍活动的 VPN 接口若与虚拟网段重叠,同样会被拒绝。自动子网是 IPv4;移动端、Windows 的打包与实际互通尚待验证。
+7 -3
View File
@@ -1,5 +1,7 @@
# 验证记录
日常回归可使用 `python3 scripts/test.py`。模块选择、原生库测试、吞吐诊断及 JSON/JUnit 报告见 [自动化测试](automated-testing.md)。以下为各阶段的历史验证记录。
## Android 阶段(2026-10-10)
ARM64 Rust 原生库、JNI 桥接、Android debug/release APK 构建通过。OPPO PJZ110(API 37,4 KB 页面)已完成 Android Keystore 独立测试存储的保存/重新读取/删除,以及 SDK 经隔离公告子网的 TCP/UDP 回显。系统 VPN 授权后,Java 和 Dart 普通系统 Socket 的 TCP/UDP 回显、公告子网自动安装与撤销全部通过。修复了 JNI 绝对路径依赖、受保护 DNS resolver 功能缺失和 Android 网络注册时序。隔离 USB 夹具不覆盖公网打洞、长期后台运行或移动网络切换。
@@ -20,7 +22,7 @@ ARM64 Rust 原生库、JNI 桥接、Android debug/release APK 构建通过。OPP
- 穿透详细日志 opt-in 采集、保留节点 ID、过滤其他应用模块日志。
- Dart后台isolate → C ABI → Rust → 两节点EasyTier UDP通信,校验字节与来源。
- Flutter widget 初始未连接状态、设置入口。
- Flutter TOML 导入 → 实际原生引擎启动 → 状态显示 → 断开连接。
- Flutter 组网表单填写并保存 → 概览连接 → 实际原生引擎启动 → 状态显示 → 断开连接(`native_connect_test.dart`)。
- C 示例编译并读取原生实例状态。
- Flutter Redmi_AX6 打洞直连显示 7.5 ms 实测 RTT,排除错误中继标签。
- Flutter 节点 RTT、路由估算、流量速率和中继统计范围显示测试;已有直连但实际路由经中继时正确区分。
@@ -36,8 +38,10 @@ scripts/cargo-local.sh clippy --workspace --all-targets --no-deps --locked -- -D
cd apps/meshport_lab
flutter analyze
flutter test
# 包含真实原生引擎的界面测试(先构建 Rust 库)
flutter test --dart-define=MESHPORT_LIBRARY="$(cd ../.. && pwd)/target/debug/libmeshport_ffi.dylib"
# 包含真实原生引擎的测试(先构建 Rust 库)。未设置环境变量时这些测试显示为 skip。
MESHPORT_LIBRARY="$(cd ../.. && pwd)/target/debug/libmeshport_ffi.dylib" \
MESHPORT_PROXY_LIBRARY="$(cd ../.. && pwd)/target/debug/libmeshport_proxy.dylib" \
flutter test
dart run tool/native_smoke.dart ../../target/debug/libmeshport_ffi.dylib
```

Some files were not shown because too many files have changed in this diff Show More