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>
@@ -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,19 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "meshport-socks"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"easytier",
|
||||
"easytier-core",
|
||||
"meshport",
|
||||
"meshport-easytier",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "meshport-test-server"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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 控制与自检。
|
||||
|
||||
@@ -51,3 +51,6 @@ android {
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
// Offline QR decoding and an in-app camera capture Activity.
|
||||
dependencies { implementation("com.journeyapps:zxing-android-embedded:4.3.0") }
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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,34 @@ 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 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)
|
||||
@@ -52,6 +90,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) } }
|
||||
@@ -101,6 +142,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 +192,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()
|
||||
}
|
||||
|
||||
@@ -22,6 +22,13 @@ class MeshVpnService : VpnService() {
|
||||
val worker = ScheduledThreadPoolExecutor(1)
|
||||
private var handle = 0L
|
||||
private var tun: ParcelFileDescriptor? = null
|
||||
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
|
||||
private var ipv4 = ""
|
||||
private var installed = emptyList<String>()
|
||||
private var running = false
|
||||
@@ -37,10 +44,14 @@ class MeshVpnService : VpnService() {
|
||||
.setSmallIcon(R.drawable.ic_stat_meshport).setContentIntent(open).setOngoing(true).build())
|
||||
worker.scheduleWithFixedDelay({
|
||||
if (running) try {
|
||||
if (unified) {
|
||||
check(proxyCall(JSONObject().put("op","status")).getJSONObject("data").getString("state") == "Running")
|
||||
if (!meshEnabled) return@scheduleWithFixedDelay
|
||||
}
|
||||
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)
|
||||
if (next != installed) { if (unified) restartProxy(next) else rebuild(next) }
|
||||
} catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
|
||||
}, 2, 2, TimeUnit.SECONDS)
|
||||
}
|
||||
@@ -59,6 +70,13 @@ class MeshVpnService : VpnService() {
|
||||
try {
|
||||
handle = NativeBridge.newContext()
|
||||
val config = request.getString("toml")
|
||||
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).put("include_profile", true)).getJSONObject("data")
|
||||
check(validation.getString("runtime_mode") == "system_vpn")
|
||||
ipv4 = validation.getJSONObject("profile").getString("ipv4")
|
||||
@@ -73,7 +91,7 @@ class MeshVpnService : VpnService() {
|
||||
"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 ->
|
||||
else (if (unified) unifiedStatus() else native(request)).also { reply ->
|
||||
reply.getJSONObject("data").getJSONObject("platform_network")
|
||||
.put("installed_subnet_routes", org.json.JSONArray(installed)).put("route_installation", "android_vpn")
|
||||
}
|
||||
@@ -142,8 +160,113 @@ class MeshVpnService : VpnService() {
|
||||
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!!))
|
||||
if (meshEnabled) {
|
||||
val validated = native(JSONObject().put("op","validate").put("toml",config)).getJSONObject("data")
|
||||
check(validated.getString("runtime_mode") == "application") { "Unified VPN requires application-mode MeshPort" }
|
||||
native(JSONObject().put("op","start").put("toml",config))
|
||||
val bridge = native(JSONObject().put("op","socks_start")).getJSONObject("data").getString("listen")
|
||||
proxyProfile.put("mesh_socks", bridge)
|
||||
}
|
||||
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"
|
||||
val routes = if (meshEnabled) {
|
||||
val state = native(JSONObject().put("op","status")).getJSONObject("data")
|
||||
val address = state.optString("ipv4").split('/')
|
||||
check(address.size == 2 && address[0].isNotEmpty()) { "Static mesh address required for unified VPN" }
|
||||
val prefix = IpPrefix(InetAddress.getByName(address[0]),address[1].toInt())
|
||||
val virtual = "${prefix.address.hostAddress}/${prefix.prefixLength}"
|
||||
protected.add(virtual)
|
||||
val list = state.getJSONObject("platform_network").getJSONArray("subnet_routes")
|
||||
(0 until list.length()).map { list.getString(it) }
|
||||
} else emptyList()
|
||||
if (internet) {
|
||||
builder.addRoute("0.0.0.0",0).addRoute("::",0).addDnsServer("172.19.0.2")
|
||||
} else {
|
||||
for (route in protected + routes) { val cidr=route.split('/');builder.addRoute(cidr[0],cidr[1].toInt()) }
|
||||
builder.allowFamily(OsConstants.AF_INET6)
|
||||
}
|
||||
tun = builder.establish() ?: error("VPN authorization revoked")
|
||||
proxyHandle = NativeBridge.newProxyContext()
|
||||
check(proxyHandle != 0L)
|
||||
proxyCall(JSONObject().put("op","configure_cache").put("directory",cacheDir.absolutePath))
|
||||
restartProxy(routes)
|
||||
running = true
|
||||
networkCallback = object: ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: android.net.Network) { worker.execute { updatePhysical() } }
|
||||
override fun onLost(network: android.net.Network) { worker.execute { 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(installed) }
|
||||
} catch (_: Exception) { failure="物理网络已断开,请重新连接";shutdown();stopSelf() }
|
||||
}
|
||||
private fun restartProxy(routes: List<String>) {
|
||||
proxyCall(JSONObject().put("op","stop"))
|
||||
val config = JSONObject(proxyProfile.toString())
|
||||
val active = routes.toMutableSet()
|
||||
if (meshEnabled) {
|
||||
val state = native(JSONObject().put("op","status")).getJSONObject("data")
|
||||
val value = state.getString("ipv4").split('/')
|
||||
val prefix = IpPrefix(InetAddress.getByName(value[0]),value[1].toInt())
|
||||
active.add("${prefix.address.hostAddress}/${prefix.prefixLength}")
|
||||
protected.addAll(active)
|
||||
}
|
||||
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 != installed) {
|
||||
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(active.sorted()))
|
||||
.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))
|
||||
installed = 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)
|
||||
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() {
|
||||
running = false
|
||||
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) { NativeBridge.freeContext(handle); handle = 0L }
|
||||
tun?.close(); tun = null; installed = emptyList()
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -7,26 +7,31 @@ 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(),
|
||||
);
|
||||
}
|
||||
|
||||
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,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// The dialog owns its controller until the route has actually been removed.
|
||||
class ConfigImportDialog extends StatefulWidget {
|
||||
@@ -15,16 +16,60 @@ class _ConfigImportDialogState extends State<ConfigImportDialog> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String error = '';
|
||||
Future<void> read(String method) async {
|
||||
try {
|
||||
final value = await const MethodChannel(
|
||||
'meshport/system_vpn',
|
||||
).invokeMethod<String>(method);
|
||||
if (value != null && mounted) {
|
||||
setState(() {
|
||||
editor.text = value;
|
||||
error = '';
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) setState(() => error = '导入失败,请检查权限或文件格式');
|
||||
}
|
||||
}
|
||||
|
||||
@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: '粘贴完整配置。不支持的配置将拒绝导入。'),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => read('import_file'),
|
||||
child: const Text('文件'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => read('scan_qr'),
|
||||
child: const Text('扫码'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => read('import_qr_image'),
|
||||
child: const Text('二维码图片'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (error.isNotEmpty) Text(error),
|
||||
Flexible(
|
||||
child: TextField(
|
||||
controller: editor,
|
||||
maxLines: 12,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '粘贴完整配置。不支持的配置将拒绝导入。',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
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) {
|
||||
final direct =
|
||||
peer?['direct'] == true &&
|
||||
(node['next_hop_peer_id'] == null ||
|
||||
node['next_hop_peer_id'] == node['peer_id']);
|
||||
final measured = direct ? (peer?['latency_ms']) : null;
|
||||
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(
|
||||
'${peer?['direct'] == true ? '有直连可用' : '未发现直连'} · ${peer?['hole_punched'] == true ? '打洞建立' : '未确认打洞'}',
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
title: Text(measured != null ? '链路 RTT' : '路由估算'),
|
||||
subtitle: Text(
|
||||
'${measured ?? node['estimated_latency_ms'] ?? '未测得'}${measured != null || node['estimated_latency_ms'] != null ? ' 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 StatelessWidget {
|
||||
final List<String> logs;
|
||||
final VoidCallback onClear;
|
||||
const LogsPageBody({super.key, required this.logs, required this.onClear});
|
||||
@override
|
||||
Widget build(BuildContext context) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text('仅保留本次应用会话最近 300 条事件,不写日志文件。复制会保留节点地址,但移除认证信息。'),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
children: [
|
||||
OutlinedButton(
|
||||
onPressed: () async {
|
||||
await Clipboard.setData(ClipboardData(text: logs.join('\n')));
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('已复制当前日志')));
|
||||
}
|
||||
},
|
||||
child: const Text('复制当前范围'),
|
||||
),
|
||||
TextButton(onPressed: onClear, child: const Text('清空显示')),
|
||||
],
|
||||
),
|
||||
for (final line in logs)
|
||||
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 秒刷新。'),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
@@ -87,60 +88,63 @@ class NodeTelemetry extends StatelessWidget {
|
||||
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),
|
||||
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 ? '直连' : '中继'}${direct && peer?['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'] ?? '未知'}',
|
||||
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 ((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 (peer != null)
|
||||
Text(
|
||||
'当前链路累计 ↓ ${formatBytes(peer['rx_bytes'] as num?)} ↑ ${formatBytes(peer['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,534 @@
|
||||
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 Future<void> Function() save, connect;
|
||||
final VoidCallback changed;
|
||||
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,
|
||||
});
|
||||
@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);
|
||||
widget.changed();
|
||||
}
|
||||
|
||||
Future<void> act(Future<void> Function() work) async {
|
||||
if (working || widget.busy) return;
|
||||
setState(() => working = true);
|
||||
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.nodes.addAll(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.nodes.add(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.nodes.add(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(() {
|
||||
p.nodes.removeWhere((n) => n.source == source);
|
||||
p.nodes.addAll(replacement);
|
||||
if (removed) p.selectedId = null;
|
||||
sub['updated'] = DateTime.now().toIso8601String();
|
||||
});
|
||||
}
|
||||
|
||||
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: 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 Text(
|
||||
'修改的是草稿。保存不会更改运行出口;连接或重连后生效。应用内模式通过 SOCKS5 127.0.0.1:10818 接入。',
|
||||
),
|
||||
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!),
|
||||
),
|
||||
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 (widget.entry == 'system_vpn' && p.feature != 'mesh')
|
||||
const Text('独立系统组网只支持仅组网;代理功能请选择统一 VPN 或应用内入口。'),
|
||||
Text(
|
||||
p.mode == 'bypass_cn' && p.feature != 'mesh'
|
||||
? '中国大陆 IP 和普通私网直连,其余走所选代理;组网始终优先。内置 IP 规则集通过代理每 24 小时更新,首次下载失败会阻止连接。'
|
||||
: '组网优先始终生效。全局/直连暂停普通规则;仅组网不接管互联网。',
|
||||
),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
FilledButton(
|
||||
onPressed:
|
||||
disabled ||
|
||||
(widget.entry == 'system_vpn' && p.feature != 'mesh')
|
||||
? null
|
||||
: () => act(widget.connect),
|
||||
child: Text(widget.running ? '重连使草稿生效' : '连接'),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: disabled ? null : () => act(widget.save),
|
||||
child: const Text('安全保存配置'),
|
||||
),
|
||||
],
|
||||
),
|
||||
]),
|
||||
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),
|
||||
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),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
section('分流与 DNS', [
|
||||
const Text('受管理规则:有效组网地址 → 组网;已失效的已知组网地址 → 拒绝;随后才应用普通规则与默认出口。'),
|
||||
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: 'reject', child: Text('拒绝')),
|
||||
],
|
||||
onChanged: disabled || p.mode != 'rule' || p.feature == 'mesh'
|
||||
? null
|
||||
: (v) => change(() => p.defaultAction = v!),
|
||||
),
|
||||
Text(
|
||||
'${p.rules.length} 条普通规则 · ${p.mode == 'rule' && p.feature != 'mesh' ? '规则模式执行' : '已暂停'}',
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: disabled
|
||||
? null
|
||||
: () => Navigator.push<void>(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) =>
|
||||
RulesPage(profile: p, changed: widget.changed),
|
||||
),
|
||||
),
|
||||
child: const Text('编辑普通规则'),
|
||||
),
|
||||
Text(
|
||||
'启动 DNS:${p.dnsServer} · 直连 DNS:${p.directDnsServer.isEmpty ? '启动 DNS' : p.directDnsServer} · 代理 DNS:${p.proxyDnsServer.isEmpty ? '待配置 · 代理模式必填' : p.proxyDnsServer}',
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: disabled
|
||||
? null
|
||||
: () => Navigator.push<void>(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) =>
|
||||
DnsPage(profile: p, changed: widget.changed),
|
||||
),
|
||||
),
|
||||
child: const Text('编辑 DNS'),
|
||||
),
|
||||
Text('FakeIP:${p.fakeIP ? '开启' : '关闭'} · 组网域名自动排除,解析失败无公共 DNS 回退。'),
|
||||
]),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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。',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import Cocoa
|
||||
import Security
|
||||
import FlutterMacOS
|
||||
import ServiceManagement
|
||||
import UniformTypeIdentifiers
|
||||
import AVFoundation
|
||||
import Vision
|
||||
import ImageIO
|
||||
|
||||
class MainFlutterWindow: NSWindow {
|
||||
private var vpnChannel: FlutterMethodChannel?
|
||||
private var qrScanner: MeshQRScanner?
|
||||
private var importing = false
|
||||
|
||||
override func awakeFromNib() {
|
||||
let flutterViewController = FlutterViewController()
|
||||
@@ -13,13 +20,17 @@ class MainFlutterWindow: NSWindow {
|
||||
RegisterGeneratedPlugins(registry: flutterViewController)
|
||||
|
||||
vpnChannel = FlutterMethodChannel(name: "meshport/system_vpn", binaryMessenger: flutterViewController.engine.binaryMessenger)
|
||||
vpnChannel?.setMethodCallHandler { call, result in
|
||||
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")
|
||||
let isProxy = call.method.contains("_proxy_profile")
|
||||
let profileQuery: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: "MeshPort.Lab.NetworkProfile",
|
||||
kSecAttrAccount as String: "last-network"
|
||||
kSecAttrService as String: isProxy ? "MeshPort.Lab.ProxyProfile" : "MeshPort.Lab.NetworkProfile",
|
||||
kSecAttrAccount as String: isProxy ? "last-proxy" : "last-network"
|
||||
]
|
||||
if call.method == "save_profile", let config = call.arguments as? String,
|
||||
if profileMethod == "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)
|
||||
@@ -32,7 +43,7 @@ class MainFlutterWindow: NSWindow {
|
||||
else { result(FlutterError(code: "KEYCHAIN_SAVE", message: "Could not save network profile to Keychain", details: status)) }
|
||||
return
|
||||
}
|
||||
if call.method == "load_profile" {
|
||||
if profileMethod == "load_profile" {
|
||||
var query = profileQuery
|
||||
query[kSecReturnData as String] = true
|
||||
query[kSecMatchLimit as String] = kSecMatchLimitOne
|
||||
@@ -43,7 +54,7 @@ class MainFlutterWindow: NSWindow {
|
||||
else { result(FlutterError(code: "KEYCHAIN_LOAD", message: "Could not read network profile", details: status)) }
|
||||
return
|
||||
}
|
||||
if call.method == "delete_profile" {
|
||||
if profileMethod == "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)) }
|
||||
@@ -77,4 +88,159 @@ 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 == "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>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,131 @@
|
||||
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 protects DNS and requires explicit resolver before connecting',
|
||||
() {
|
||||
final p = ProxyProfile();
|
||||
expect(p.runtime()['dns_protection'], true);
|
||||
expect(p.validateConnection, throwsStateError);
|
||||
p.proxyDnsServer = 'tls://resolver.example';
|
||||
expect(p.validateConnection, returnsNormally);
|
||||
p.proxyDnsServer = '';
|
||||
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,84 @@
|
||||
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('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);
|
||||
});
|
||||
test(
|
||||
'network draft preserves supported options and forces encrypted single-stack host',
|
||||
() {
|
||||
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'},
|
||||
});
|
||||
expect(draft.toToml(), contains('no_tun = true'));
|
||||
expect(draft.toToml(), contains('disable_p2p = true'));
|
||||
expect(draft.toToml(), contains('enable_encryption = true'));
|
||||
expect(draft.toToml(), contains('stun_servers = []'));
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
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.toToml(),
|
||||
contains('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';
|
||||
await client.validate(p.toToml());
|
||||
expect(
|
||||
p.toToml(),
|
||||
contains('foreign_relay_bps_limit = "18446744073709551615"'),
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
skip: Platform.environment['MESHPORT_LIBRARY'] == null
|
||||
? 'Requires native Rust library'
|
||||
: false,
|
||||
);
|
||||
}
|
||||
@@ -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,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,296 @@
|
||||
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';
|
||||
String? ip = '10.77.0.11/24';
|
||||
List<String> routes = ['192.168.21.0/24'];
|
||||
Future<Map<String, dynamic>> request(Map<String, dynamic> input) async {
|
||||
final op = input['op'] as String;
|
||||
events.add('mesh.$op');
|
||||
final data = switch (op) {
|
||||
'validate' => {'runtime_mode': mode},
|
||||
'start' => (() {
|
||||
state = 'Running';
|
||||
return <String, dynamic>{};
|
||||
})(),
|
||||
'stop' => (() {
|
||||
state = 'Stopped';
|
||||
return <String, dynamic>{};
|
||||
})(),
|
||||
'socks_start' => {'listen': '127.0.0.1:50001'},
|
||||
'socks_status' => {'running': true},
|
||||
'status' => {
|
||||
'state': state,
|
||||
'ipv4': ip,
|
||||
'platform_network': {
|
||||
'subnet_routes_scope': 'accepted_projection',
|
||||
'subnet_routes': routes,
|
||||
},
|
||||
},
|
||||
_ => <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;
|
||||
f.routes = ['192.168.21.17/24', '192.168.21.0/24'];
|
||||
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('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').length, 1);
|
||||
await f.session.stop();
|
||||
f.mode = 'system_vpn';
|
||||
await expectLater(f.session.start('test'), throwsUnsupportedError);
|
||||
await f.session.close();
|
||||
},
|
||||
);
|
||||
test(
|
||||
'wait for DHCP then start; unexpected engine failure cleans mesh',
|
||||
() async {
|
||||
final f = Fixture();
|
||||
f.ip = null;
|
||||
f.routes = [];
|
||||
await f.session.start('test');
|
||||
expect(f.session.state, 'AwaitingAddress');
|
||||
f.ip = '10.77.0.11/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(
|
||||
'reject public/overbroad projection and ignore untrusted route scope',
|
||||
() {
|
||||
expect(
|
||||
() => effectiveMeshPrefixes({'ipv4': '8.8.8.8/24'}),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(
|
||||
() => effectiveMeshPrefixes({'ipv4': '10.0.0.1/8'}),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(
|
||||
effectiveMeshPrefixes({
|
||||
'ipv4': '10.77.0.11/24',
|
||||
'platform_network': {
|
||||
'subnet_routes': ['0.0.0.0/0'],
|
||||
},
|
||||
}),
|
||||
['10.77.0.0/24'],
|
||||
);
|
||||
},
|
||||
);
|
||||
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 == '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,59 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,33 @@ import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshport_lab/features/lab_screen.dart';
|
||||
|
||||
void main() {
|
||||
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 +37,36 @@ 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.text('安全保存配置'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -107,6 +107,21 @@ class MeshPortClient {
|
||||
await request({'op': 'stop'});
|
||||
}
|
||||
|
||||
/// 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'});
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -26,12 +26,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 +66,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()),
|
||||
}),
|
||||
@@ -105,7 +112,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,10 +158,13 @@ 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))?);
|
||||
*network = Some(Arc::new(context.runtime.block_on(Network::start(config))?));
|
||||
Ok(json!({"engine_started": true}))
|
||||
}
|
||||
"stop" => {
|
||||
if let Some(mut bridge) = context.socks.lock().unwrap().take() {
|
||||
context.runtime.block_on(bridge.stop())?;
|
||||
}
|
||||
context.tcp.blocking_lock().clear();
|
||||
context.udp.blocking_lock().clear();
|
||||
if let Some(n) = network.take() {
|
||||
@@ -147,6 +172,61 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
|
||||
}
|
||||
Ok(json!({"stopped": true}))
|
||||
}
|
||||
"socks_start" => {
|
||||
let n = network
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
|
||||
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(
|
||||
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());
|
||||
@@ -390,6 +470,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 +485,72 @@ mod tests {
|
||||
);
|
||||
meshport_context_free(id);
|
||||
}
|
||||
|
||||
#[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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
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);
|
||||
|
||||
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) -> 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());
|
||||
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();
|
||||
}
|
||||
@@ -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:?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
# 客户端自动更新、规则集与导入
|
||||
|
||||
更新:2026-10-11。出口仍由用户手动选择;本轮按要求不实现自动测速选出口。
|
||||
|
||||
| 功能 | macOS | Android |
|
||||
| --- | --- | --- |
|
||||
| 订阅定时更新 | 应用运行期间 | 应用运行期间 |
|
||||
| 内联 / HTTPS source、binary 规则集 | 已接入引擎 | 已接入引擎 |
|
||||
| 普通 DNS、DoH、DoT | 已接入引擎 | 已接入引擎 |
|
||||
| 代理节点 / TOML 文件导入 | NSOpenPanel | 系统文档选择器 |
|
||||
| 相机扫码 / 二维码图片 | AVFoundation + Vision | 内置 ZXing 扫描与图片解码 |
|
||||
| 应用启动后自动连接 | 已接入 | 已接入 |
|
||||
| 登录时启动 | macOS 13+ 系统登录项 | 不支持,未实现 Android 开机广播连接 |
|
||||
|
||||
Android 本轮已编译,按用户安排暂不安装真机。macOS 图片二维码入口已实际验证;相机权限、真实登录启动和自动连接恢复仍需要用户环境验证,未为测试开启用户的登录项或自动连接开关。
|
||||
|
||||
## 使用入口
|
||||
|
||||
- **代理 → 订阅管理 → 编辑订阅**:启用自动更新,选择 15 分钟至 7 天的间隔,返回代理页点击“安全保存配置”。定时器每分钟检查到期项;应用重开也检查逾期项。
|
||||
- **代理 → 编辑普通规则**:添加、排序、启停规则集。普通规则先匹配,随后规则集,再使用默认出口;组网有效子网和已撤销子网保护始终在前。全局 / 直连模式暂停普通规则和规则集。
|
||||
- **代理 → 编辑 DNS**:启动解析器仍为 IP;直连和代理解析器可填写 IP、`https://主机/dns-query` 或 `tls://主机:853`。DoH 默认 443、DoT 默认 853;TLS 校验保持开启。代理 DNS 经手动所选节点;解析器主机名由独立启动 DNS 解析,避免循环依赖。仅组网模式不接管互联网 DNS。
|
||||
- **代理 → 导入与预览**:选择文件、相机扫码或二维码图片。只填入草稿,点击“解析并预览”后确认导入。HTTPS 订阅链接可以选择“作为订阅地址添加”。导入普通 sing-box JSON 只提取节点,不能覆盖受管理 TUN、DNS 和组网路由。
|
||||
- **组网配置导入**:TOML 导入对话框同样支持文件、相机和二维码图片,校验后由用户点击连接。
|
||||
- **设置 → 启动与后台**:分别选择自动连接与 macOS 登录启动。登录项需要系统批准时会显示实际状态和系统设置入口;Android 自动连接指打开 APP 后连接,不代表开机后台建立 VPN。
|
||||
|
||||
## 更新与缓存行为
|
||||
|
||||
订阅只替换自己的来源节点,保留手动节点、其他订阅及相同节点的 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 列表,普通流量全部走代理。原有自定义规则和直连模式仍保留;旧配置不自动切换。修改模式后保存,连接或重连生效,已有连接可能中断。
|
||||
|
||||
## 代理 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 客户端核心默认启用,旧保存配置重载时同样启用。未使用该字段的旧原始引擎调用保持兼容。
|
||||
@@ -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 是适配边界,可在以后替换实现。
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
# 客户端联合运行控制
|
||||
|
||||
更新日期: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。网络切换及长期运行仍需验证。
|
||||
|
||||
## 生命周期与保护
|
||||
|
||||
组网启动顺序为 MeshPort → Rust SOCKS 桥接 → Go 引擎。停止顺序相反。启动失败回滚已有资源,网络停止失败保留所有权以便重试。`close()` 等待队列并释放代理上下文;宿主最终关闭 MeshPort。
|
||||
|
||||
每 2 秒读取当前虚拟 IPv4 和 `platform_network.subnet_routes`,只采用 `accepted_projection`。规范化后有变化才重建 Go 配置,无需手动远端子网列表。重建关闭已有代理连接,尚非无损热更新。
|
||||
|
||||
本次连接期间见过的合规组网前缀形成保护集合。有效前缀先走组网,撤销的已知前缀被拒绝,不能落入普通代理或直连;显式停止会话后清空集合。SDK 数据面也独立验证当前有效公告。
|
||||
|
||||
应用内联合模式中,组网暂不可用时普通代理可继续运行,状态为 `Partial`,组网目标保持拒绝。仅组网出现故障则清理会话。Android 服务故障目前整体停止,恢复行为尚需真机验证。
|
||||
|
||||
## 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 独立组网真机测试与本轮新增代理联合模式测试是不同范围。
|
||||
@@ -0,0 +1,59 @@
|
||||
# 2026-10-11 开发验证记录
|
||||
|
||||
本轮继续实现统一 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 保持运行,未切换系统路由。
|
||||
@@ -12,6 +12,10 @@
|
||||
|
||||
控制操作:validate/start(toml)、stop、status。
|
||||
|
||||
`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。
|
||||
@@ -39,3 +43,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 解析以避免循环;仅组网与直连模式保持独立。宿主应在关闭旧会话之前执行连接校验。
|
||||
|
||||
@@ -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。
|
||||
@@ -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.subnet_routes 和当前虚拟地址。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)。
|
||||
@@ -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、远程高延迟与长时间压测仍需后续验证。
|
||||
@@ -0,0 +1,59 @@
|
||||
# MeshPort 移动端 UI 设计 V4
|
||||
|
||||
更新日期:2026-10-10。包含 24 个页面和 4 个公共状态示例,覆盖组网与代理组合客户端的目标交互。此文档为下一阶段设计依据,图片中的数据为示例,不表示客户端已经实现全部功能。
|
||||
|
||||
配套文档:[交互规则与验收场景](../outputs/ui/meshport-ui-v4-interactions.md)、[下一阶段架构](next-stage-architecture.md)、[V3 审查记录](../outputs/ui/meshport-ui-v3-review.md)、[图片生成提示词](../outputs/ui/meshport-ui-v4-prompts.md)。
|
||||
|
||||
## 1–4:主页面
|
||||
|
||||
概览、代理、组网、设置。组合模式分别显示两侧状态;代理模式只控制普通互联网流量;统计区分链路测量与路由估算。
|
||||
|
||||

|
||||
|
||||
## 5–8:代理配置
|
||||
|
||||
导入代理配置、订阅管理、代理节点详情、分流规则。订阅是节点来源;选中、检测可用和正在运行是不同状态。普通导入只提取支持的节点,不覆盖受管理的路由和 DNS。
|
||||
|
||||

|
||||
|
||||
## 9–12:组网配置
|
||||
|
||||
基础配置、连接与打洞、高级配置、线路策略。参数按 SDK 能力开放,未支持项禁用;配置保存与运行生效分开,候选中继不表示强制中继。
|
||||
|
||||

|
||||
|
||||
## 13–16:节点与路由
|
||||
|
||||
节点详情、自动接入子网、子网详情、网络诊断。公告子网区分学习与实际生效,接入方式决定状态文案。同 CIDR 多发布者合并展示;列表顶部数字为状态统计,不是筛选标签。
|
||||
|
||||

|
||||
|
||||
## 17–20:应用设置
|
||||
|
||||
DNS 设置、默认配置、启动与后台、运行日志。DNS 定义域名范围、服务器、出口与失败策略;启动、恢复功能选择和自动连接分别控制;日志始终脱敏。
|
||||
|
||||

|
||||
|
||||
## 21–24:引导与编辑
|
||||
|
||||
首次使用、添加代理节点、编辑订阅、编辑分流规则。首次使用按所选功能要求配置,进入首页不隐式连接;节点字段按协议变化,保存和测试草稿分别执行。
|
||||
|
||||

|
||||
|
||||
## 公共状态与确认
|
||||
|
||||
等待 VPN 授权、导入失败、保存后重连、订阅更新导致当前节点失效。它们是当前流程中的状态或确认视图,不是额外导航页面。
|
||||
|
||||

|
||||
|
||||
## 实现约束
|
||||
|
||||
- 统一运行功能排列:仅组网 / 仅代理 / 代理+组网。生成图中个别控件排列、图标、换行以实际组件统一。
|
||||
- 只有所选能力全部就绪才显示全部可用;权限未完成、没有节点、部分失败均有独立状态。
|
||||
- 配置区分草稿、持久化配置和运行快照;重建网络入口前提示现有连接可能中断。
|
||||
- 有效组网目标优先,故障或撤销时不静默交给互联网代理;具体保护、撤销和本地冲突处理见交互规则。
|
||||
- 尚未实现的功能按平台和 SDK 能力禁用,不能接受配置后忽略。
|
||||
|
||||
完整的 24 页修正对应关系和后续功能验收条件见 [V4 交互说明](../outputs/ui/meshport-ui-v4-interactions.md)。
|
||||
|
||||
当前客户端已接入主要页面,实际能力与禁用项见 [界面实现清单](ui-implementation.md)。原型图片仍为目标视觉设计,不代表全部未来功能已经完成。
|
||||
@@ -0,0 +1,36 @@
|
||||
# 移动端与桌面客户端界面实现
|
||||
|
||||
更新:2026-10-10。沿用 V4 的四个主导航,以下是代码中的实际页面,不是设计图上的示例数据。Flutter 同时供 macOS 与 Android 使用;视觉效果仍需设备与不同屏幕尺寸的人工验收。
|
||||
|
||||
| 页码 | 页面 | 入口与已接入功能 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 概览 | 主导航;连接、分功能状态、实际节点 RTT 和流量 |
|
||||
| 2 | 代理 | 主导航;功能、入口、模式、草稿节点与运行出口 |
|
||||
| 3 | 组网 | 主导航;实际节点、配置与诊断入口 |
|
||||
| 4 | 设置 | 主导航;DNS、默认配置、后台、日志、引导与关于 |
|
||||
| 5 | 导入代理配置 | 代理;文本解析、预览、确认、失败保留输入 |
|
||||
| 6 | 订阅管理 | 代理;HTTPS 更新、删除与来源管理 |
|
||||
| 7 | 代理节点详情 | 点击节点;参数与认证隐藏,手动编辑/订阅复制 |
|
||||
| 8 | 分流规则 | 代理;顺序、编辑、删除、默认动作,组网优先固定 |
|
||||
| 9 | 基础配置 | 组网;网络名称、密钥、IP/DHCP、初始节点、运行入口 |
|
||||
| 10 | 连接与打洞 | 组网;协议、监听、P2P、UDP/TCP/对称 NAT 打洞、STUN |
|
||||
| 11 | 高级配置 | 组网;私有模式、惰性 P2P、强制 P2P、外部中继限制 |
|
||||
| 12 | 线路策略 | 组网;优化模式、优势阈值、观察/冷却时间、候选节点 |
|
||||
| 13 | 节点详情 | 点击组网节点;路由、链路 RTT/估算、直连可用性与流量 |
|
||||
| 14 | 自动接入子网 | 组网;公告合并、接受/安装/失效保护状态,无手动列表 |
|
||||
| 15 | 子网详情 | 点击子网;发布者、下一跳、接入状态与拒绝原因边界 |
|
||||
| 16 | 网络诊断 | 组网或设置;SDK 实际 TCP/UDP 测试 |
|
||||
| 17 | DNS 设置 | 设置;启动/代理 DNS、组网后缀 DNS、FakeIP 与排除项 |
|
||||
| 18 | 默认配置 | 设置;配置优先级、恢复内置草稿,需确认 |
|
||||
| 19 | 启动与后台 | 设置;说明已保存配置自动回填、平台后台限制 |
|
||||
| 20 | 运行日志 | 设置;会话内事件、复制与清空,凭据脱敏 |
|
||||
| 21 | 首次使用 | 设置中的使用引导;介绍三种功能与入口,不自动连接 |
|
||||
| 22 | 添加代理节点 | 代理;六种协议表单、TLS/Reality、传输、草稿连通检测 |
|
||||
| 23 | 编辑订阅 | 订阅管理;名称、URL、保存与更新分离 |
|
||||
| 24 | 编辑分流规则 | 分流规则;域名/后缀/CIDR、动作和输入检查 |
|
||||
|
||||
表单保存只修改配置草稿;运行期间应用配置会确认重连,现有连接可能中断。表单未保存退出有确认。HTTP 检测耗时不等于网络 RTT;组网延迟注明来源,控制流量和应用流量不混称。
|
||||
|
||||
扫码、文件选择导入、自动订阅更新、规则集和应用启动自动连接已实现;macOS 13+ 登录启动已接入系统状态与授权入口,Android 不接入开机广播。详见 [高级客户端功能](advanced-client-features.md)。自动选出口按用户要求不实现。引导可从设置进入,尚无首次启动强制流程。关于页与公共授权/错误/重连确认不是额外导航项。
|
||||
|
||||
实现主要文件:`configuration_pages.dart`、`detail_pages.dart`、`proxy_source_pages.dart`、`proxy_node_editor.dart`、`proxy_panel.dart`、`lab_screen.dart`。原型图见 [UI 设计](ui-design.md),平台和验证范围见 [客户端运行控制](client-runtime.md)。
|
||||
@@ -0,0 +1,17 @@
|
||||
Copyright (C) 2022 by nekohasekai <contact-sagernet@sekai.icu>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
In addition, no derivative work may use the name or imply association
|
||||
with this application without prior consent.
|
||||
@@ -0,0 +1,15 @@
|
||||
# MeshPort sing-box 接入
|
||||
|
||||
固定依赖 sing-box 1.14.3。当前提供本机 SOCKS 入口、受管理的 IPv4 组网分流、MeshPort SOCKS 出口及启停控制;完整 APP/TUN、互联网代理配置与订阅尚未接入。
|
||||
|
||||
从项目根目录执行:
|
||||
|
||||
```sh
|
||||
sh scripts/go-local.sh test -race ./...
|
||||
sh scripts/build-singbox.sh
|
||||
sh scripts/test-singbox-bridge.sh
|
||||
```
|
||||
|
||||
Go API:bridge.Engine.Start(context, bridge.Config)、Stop()、Snapshot()。调用方生成有效配置投影并拥有生命周期,停止或上下文取消后需调用 Stop。
|
||||
|
||||
完整接入方式、验证及限制见 [项目文档](../../docs/singbox-integration.md),上游许可证见 [LICENSE 副本](../../docs/upstream/sing-box-LICENSE)。
|
||||
@@ -0,0 +1,228 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
D "github.com/miekg/dns"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing/common/json/badoption"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
box "github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
func TestEncryptedResolversAndRemoteRuleSetsDecode(t *testing.T) {
|
||||
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "rule", DefaultAction: "direct", DirectDNS: "https://dns.example/dns-query", ProxyDNS: "tls://dns.example:853", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 12346}, RuleSets: []RuleSet{{Tag: "private-sites", Enabled: true, URL: "https://rules.example/test.srs", Format: "binary", Action: "proxy", UpdateHours: 6, DownloadDetour: "direct"}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: options})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
var result map[string]any
|
||||
json.Unmarshal(data, &result)
|
||||
servers := result["dns"].(map[string]any)["servers"].([]any)
|
||||
if len(servers) != 3 || servers[1].(map[string]any)["type"] != "https" || servers[2].(map[string]any)["detour"] != "proxy" {
|
||||
t.Fatal("encrypted DNS transport/detour missing")
|
||||
}
|
||||
for _, v := range []string{"http://dns.example/dns-query", "tls://dns.example/path", "https://user:pass@dns.example", "https://dns.example:0", "https://dns.example/dns-query?x=1"} {
|
||||
c.DirectDNS = v
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Fatalf("accepted invalid resolver %q", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInlineRuleSetsRouteAndPreserveMeshPriority(t *testing.T) {
|
||||
mesh, meshCount := socksEcho(t)
|
||||
defer mesh.Close()
|
||||
proxy, proxyCount := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
listener, port := reservePort(t)
|
||||
listener.Close()
|
||||
c := Config{ListenPort: port, Feature: "combined", Mode: "rule", DefaultAction: "reject", MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.23.0.0/24"}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, RuleSets: []RuleSet{{Tag: "test", Enabled: true, Action: "proxy", Rules: []map[string]any{{"ip_cidr": []string{"10.23.0.0/24", "198.51.100.0/24"}}}}}}
|
||||
engine := &Engine{}
|
||||
if err := engine.Start(context.Background(), c); err != nil {
|
||||
t.Fatalf("start: %v / %v", err, engine.startupCause)
|
||||
}
|
||||
defer engine.Close()
|
||||
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), true)
|
||||
echoThrough(t, port, M.ParseSocksaddr("10.23.0.1:1234"), true)
|
||||
if proxyCount.Load() != 1 || meshCount.Load() != 1 {
|
||||
t.Fatal("rule set overrode protected mesh precedence")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoHAndDoTExchangeWithCertificateVerification(t *testing.T) {
|
||||
answer := func(r *D.Msg) *D.Msg {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
return m
|
||||
}
|
||||
var count atomic.Int32
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var data []byte
|
||||
var err error
|
||||
if r.Method == "POST" {
|
||||
data, err = io.ReadAll(io.LimitReader(r.Body, 65536))
|
||||
} else {
|
||||
data, err = base64.RawURLEncoding.DecodeString(r.URL.Query().Get("dns"))
|
||||
}
|
||||
request := new(D.Msg)
|
||||
if err != nil || request.Unpack(data) != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
count.Add(1)
|
||||
reply, _ := answer(request).Pack()
|
||||
w.Header().Set("Content-Type", "application/dns-message")
|
||||
w.Write(reply)
|
||||
}))
|
||||
defer server.Close()
|
||||
listener, err := tls.Listen("tcp4", "127.0.0.1:0", &tls.Config{Certificates: server.TLS.Certificates, MinVersion: tls.VersionTLS12})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dnsServer := &D.Server{Listener: listener, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) { count.Add(1); w.WriteMsg(answer(r)) })}
|
||||
go dnsServer.ActivateAndServe()
|
||||
defer dnsServer.Shutdown()
|
||||
certificate := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}))
|
||||
for _, url := range []string{server.URL + "/dns-query", "tls://" + listener.Addr().String()} {
|
||||
t.Run(url, func(t *testing.T) {
|
||||
upstream, proxyCount := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
socket, port := reservePort(t)
|
||||
socket.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "global", DirectDNS: url, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A test-only trust root is installed in this isolated box, never the OS.
|
||||
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{certificate}}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: opts})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := count.Load()
|
||||
echoThrough(t, port, M.ParseSocksaddr("encrypted.example.test:1234"), true)
|
||||
if count.Load() <= before || proxyCount.Load() != 1 {
|
||||
t.Fatal("encrypted DNS path not used")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteRuleSetRefreshKeepsLastGoodRulesOnFailure(t *testing.T) {
|
||||
var stage atomic.Int32
|
||||
var requests atomic.Int32
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
if stage.Load() == 2 {
|
||||
w.WriteHeader(503)
|
||||
return
|
||||
}
|
||||
prefix := "198.51.100.0/24"
|
||||
if stage.Load() == 1 {
|
||||
prefix = "203.0.113.0/24"
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"version": 3, "rules": []any{map[string]any{"ip_cidr": []string{prefix}}}})
|
||||
}))
|
||||
defer server.Close()
|
||||
upstream, _ := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
socket, port := reservePort(t)
|
||||
socket.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}, RuleSets: []RuleSet{{Tag: "remote", Enabled: true, URL: server.URL + "/rules.json", Format: "source", Action: "proxy", UpdateHours: 1}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}))}}
|
||||
opts.Route.RuleSet[0].RemoteOptions.UpdateInterval = badoption.Duration(100 * time.Millisecond)
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: opts})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer instance.Close()
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), true)
|
||||
stage.Store(1)
|
||||
set, ok := instance.Router().RuleSet("remote")
|
||||
if !ok {
|
||||
t.Fatal("remote set missing")
|
||||
}
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for !set.Match(&adapter.InboundContext{Destination: M.ParseSocksaddr("203.0.113.1:1234")}) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("remote rules did not refresh")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("203.0.113.1:1234"), true)
|
||||
echoThrough(t, port, M.ParseSocksaddr("198.51.100.1:1234"), false)
|
||||
stage.Store(2)
|
||||
before := requests.Load()
|
||||
deadline = time.Now().Add(3 * time.Second)
|
||||
for requests.Load() <= before {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("failed refresh not attempted")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("203.0.113.1:1234"), true)
|
||||
}
|
||||
|
||||
func TestDirectModePausesProxyDNSAndRemoteRuleSets(t *testing.T) {
|
||||
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "direct", ProxyDNS: "tls://dns.example", RuleSets: []RuleSet{{Tag: "remote", Enabled: true, URL: "https://rules.example/test.srs", Format: "binary", Action: "proxy", DownloadDetour: "proxy"}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result map[string]any
|
||||
json.Unmarshal(data, &result)
|
||||
if _, ok := result["route"].(map[string]any)["rule_set"]; ok {
|
||||
t.Fatal("direct mode still loads rule sets")
|
||||
}
|
||||
if len(result["dns"].(map[string]any)["servers"].([]any)) != 1 {
|
||||
t.Fatal("direct mode still depends on proxy DNS")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
D "github.com/miekg/dns"
|
||||
box "github.com/sagernet/sing-box"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
)
|
||||
|
||||
func TestBypassChinaPresetAndGlobalIsolation(t *testing.T) {
|
||||
for _, fake := range []bool{false, true} {
|
||||
c := Config{ListenPort: 12345, Feature: "combined", Mode: "bypass_cn", FakeIP: fake,
|
||||
MeshSOCKS: "127.0.0.1:12346", MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.88.0.0/24"},
|
||||
DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 12347},
|
||||
Rules: []Rule{{Type: "ip_cidr", Value: "0.0.0.0/0", Action: "reject"}},
|
||||
RuleSets: []RuleSet{{Tag: "custom", Enabled: true, Action: "reject", Rules: []map[string]any{{"ip_cidr": []string{"0.0.0.0/0"}}}}}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = sjson.UnmarshalExtendedContext[option.Options](registryContext(context.Background()), data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result map[string]any
|
||||
json.Unmarshal(data, &result)
|
||||
route := result["route"].(map[string]any)
|
||||
if route["final"] != "proxy" {
|
||||
t.Fatal("preset did not force proxy fallback")
|
||||
}
|
||||
sets := route["rule_set"].([]any)
|
||||
set := sets[0].(map[string]any)
|
||||
if len(sets) != 1 || set["tag"] != "meshport-geoip-cn" || set["format"] != "binary" || set["download_detour"] != "proxy" || set["update_interval"] != "24h" {
|
||||
t.Fatal("managed GeoIP update missing")
|
||||
}
|
||||
rules := route["rules"].([]any)
|
||||
// DNS hijack/real-IP resolution precede mesh, withdrawn-prefix protection,
|
||||
// ordinary private addresses and finally the China IP rule.
|
||||
if len(rules) != 6 || rules[1].(map[string]any)["action"] != "resolve" || rules[2].(map[string]any)["outbound"] != "meshport" || rules[3].(map[string]any)["action"] != "reject" || rules[4].(map[string]any)["ip_is_private"] != true || rules[5].(map[string]any)["outbound"] != "direct" {
|
||||
t.Fatal("GeoIP or mesh priority broken")
|
||||
}
|
||||
if len(c.Rules) != 1 || c.RuleSets[0].Tag != "custom" {
|
||||
t.Fatal("preset modified saved custom rules")
|
||||
}
|
||||
c.Mode = "global"
|
||||
data, err = c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
json.Unmarshal(data, &result)
|
||||
route = result["route"].(map[string]any)
|
||||
if _, ok := route["rule_set"]; ok {
|
||||
t.Fatal("global mode still loads GeoIP")
|
||||
}
|
||||
if len(route["rules"].([]any)) != 4 || route["final"] != "proxy" {
|
||||
t.Fatal("global mode contains ordinary bypass rules")
|
||||
}
|
||||
c.Mode = "bypass_cn"
|
||||
c.Proxy = nil
|
||||
if _, err = c.managedJSON(); err == nil {
|
||||
t.Fatal("preset accepted missing proxy node")
|
||||
}
|
||||
c.Feature = "mesh"
|
||||
c.MeshDNS = nil
|
||||
if _, err = c.managedJSON(); fake && err == nil {
|
||||
t.Fatal("mesh-only accepted FakeIP")
|
||||
} else if !fake && err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use documentation IPs and isolated SOCKS counters in place of physical
|
||||
// exits, so real-IP/FakeIP policy is exercised without public connections.
|
||||
func TestBypassChinaRealIPAndFakeIPRouting(t *testing.T) {
|
||||
for _, fake := range []bool{false, true} {
|
||||
direct, dc := socksEcho(t)
|
||||
defer direct.Close()
|
||||
proxy, pc := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
socket, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &D.Server{PacketConn: socket, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
ip := "203.0.113.7"
|
||||
if r.Question[0].Name == "china.test." {
|
||||
ip = "198.51.100.7"
|
||||
}
|
||||
if r.Question[0].Qtype == D.TypeA {
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP(ip)}}
|
||||
}
|
||||
w.WriteMsg(m)
|
||||
})}
|
||||
go server.ActivateAndServe()
|
||||
defer server.Shutdown()
|
||||
listener, port := reservePort(t)
|
||||
listener.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "bypass_cn", FakeIP: fake, DNS: socket.LocalAddr().String(), Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var generated map[string]any
|
||||
json.Unmarshal(data, &generated)
|
||||
route := generated["route"].(map[string]any)
|
||||
route["rule_set"] = []any{map[string]any{"type": "inline", "tag": "meshport-geoip-cn", "rules": []any{map[string]any{"ip_cidr": []string{"198.51.100.0/24"}}}}}
|
||||
outbounds := generated["outbounds"].([]any)
|
||||
outbounds[0] = map[string]any{"type": "socks", "tag": "direct", "server": "127.0.0.1", "server_port": direct.Addr().(*net.TCPAddr).Port}
|
||||
data, _ = json.Marshal(generated)
|
||||
ctx := registryContext(context.Background())
|
||||
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: options})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, domain := range []string{"china.test", "foreign.test"} {
|
||||
target := domain
|
||||
if fake {
|
||||
conn, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dnsConn := &D.Conn{Conn: conn}
|
||||
msg := new(D.Msg)
|
||||
msg.SetQuestion(D.Fqdn(domain), D.TypeA)
|
||||
if err = dnsConn.WriteMsg(msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := dnsConn.ReadMsg()
|
||||
conn.Close()
|
||||
if err != nil || len(answer.Answer) != 1 {
|
||||
t.Fatalf("FakeIP answer: %v / %v", answer, err)
|
||||
}
|
||||
target = answer.Answer[0].(*D.A).A.String()
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), true)
|
||||
}
|
||||
if dc.Load() != 1 || pc.Load() != 1 {
|
||||
t.Fatalf("fake=%v direct=%d proxy=%d", fake, dc.Load(), pc.Load())
|
||||
}
|
||||
instance.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Only node fields may be imported. Route, DNS and TUN ownership remain managed.
|
||||
type Rule struct {
|
||||
Type string `json:"type"`
|
||||
Value string `json:"value"`
|
||||
Action string `json:"action"`
|
||||
}
|
||||
type MeshDNS struct {
|
||||
Suffix string `json:"suffix"`
|
||||
Server string `json:"server"`
|
||||
}
|
||||
type TunConfig struct {
|
||||
FD int `json:"fd"`
|
||||
Name string `json:"name"`
|
||||
Interface string `json:"physical_interface"`
|
||||
Index int `json:"physical_index"`
|
||||
}
|
||||
type RuleSet struct {
|
||||
Tag string `json:"tag"`
|
||||
Enabled bool `json:"enabled"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Format string `json:"format,omitempty"`
|
||||
Rules []map[string]any `json:"rules,omitempty"`
|
||||
Action string `json:"action"`
|
||||
DownloadDetour string `json:"download_detour,omitempty"`
|
||||
UpdateHours int `json:"update_hours,omitempty"`
|
||||
}
|
||||
type Config struct {
|
||||
DNSProtection bool `json:"dns_protection,omitempty"`
|
||||
RuleSets []RuleSet `json:"rule_sets,omitempty"`
|
||||
DirectDNS string `json:"direct_dns_server,omitempty"`
|
||||
ListenPort uint16 `json:"listen_port"`
|
||||
MeshSOCKS string `json:"mesh_socks"`
|
||||
MeshCIDRs []string `json:"mesh_cidrs"`
|
||||
ProtectedCIDRs []string `json:"protected_cidrs,omitempty"`
|
||||
Feature string `json:"feature,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Proxy map[string]any `json:"proxy,omitempty"`
|
||||
Rules []Rule `json:"rules,omitempty"`
|
||||
DefaultAction string `json:"default_action,omitempty"`
|
||||
DNS string `json:"dns_server,omitempty"`
|
||||
ProxyDNS string `json:"proxy_dns_server,omitempty"`
|
||||
MeshDNS []MeshDNS `json:"mesh_dns,omitempty"`
|
||||
FakeIP bool `json:"fakeip,omitempty"`
|
||||
FakeIPExclude []string `json:"fakeip_exclude,omitempty"`
|
||||
DesktopTun bool `json:"desktop_tun,omitempty"`
|
||||
PhysicalInterface string `json:"physical_interface,omitempty"`
|
||||
Tun *TunConfig `json:"tun,omitempty"`
|
||||
}
|
||||
|
||||
// Diagnostics are restricted to the privileged, mesh-only local fixture. They
|
||||
// cannot enable logging of a user's ordinary proxy nodes or network traffic.
|
||||
func (c Config) selfTestTrace() bool {
|
||||
if os.Getenv("MESHPORT_SELF_TEST_TRACE") != "1" || os.Geteuid() != 0 ||
|
||||
!c.DesktopTun || c.Feature != "mesh" || c.Proxy != nil || len(c.MeshCIDRs) == 0 {
|
||||
return false
|
||||
}
|
||||
fixture := netip.MustParsePrefix("10.253.88.0/24")
|
||||
for _, value := range append(append([]string{}, c.MeshCIDRs...), c.ProtectedCIDRs...) {
|
||||
prefix, err := netip.ParsePrefix(value)
|
||||
if err != nil || prefix.Bits() < fixture.Bits() || !fixture.Contains(prefix.Addr()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func prefixes(values []string) ([]string, error) {
|
||||
if len(values) > 128 {
|
||||
return nil, errors.New("too many mesh prefixes")
|
||||
}
|
||||
set := map[string]bool{}
|
||||
for _, v := range values {
|
||||
p, e := netip.ParsePrefix(v)
|
||||
if e != nil || !p.Addr().Is4() || p.Bits() < 16 || !p.Addr().IsPrivate() {
|
||||
return nil, errors.New("invalid or unsupported mesh prefix")
|
||||
}
|
||||
set[p.Masked().String()] = true
|
||||
}
|
||||
result := make([]string, 0, len(set))
|
||||
for p := range set {
|
||||
result = append(result, p)
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result, nil
|
||||
}
|
||||
func domain(v string) bool {
|
||||
if len(v) > 253 || v == "" || strings.ContainsAny(v, " /:@*\r\n") {
|
||||
return false
|
||||
}
|
||||
for _, label := range strings.Split(v, ".") {
|
||||
if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
||||
return false
|
||||
}
|
||||
for _, c := range label {
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func proxyNode(node map[string]any) (map[string]any, error) {
|
||||
kind, _ := node["type"].(string)
|
||||
fields := map[string]string{"socks": "version,username,password", "http": "username,password,tls", "shadowsocks": "method,password", "vmess": "uuid,security,alter_id,tls,transport", "vless": "uuid,flow,tls,transport", "trojan": "password,tls,transport"}
|
||||
extra, ok := fields[kind]
|
||||
if !ok {
|
||||
return nil, errors.New("unsupported proxy protocol")
|
||||
}
|
||||
allowed := ",type,server,server_port," + extra + ","
|
||||
result := map[string]any{"tag": "proxy"}
|
||||
for key, value := range node {
|
||||
if !strings.Contains(allowed, ","+key+",") {
|
||||
return nil, errors.New("unsupported proxy node field")
|
||||
}
|
||||
result[key] = value
|
||||
}
|
||||
host, ok := node["server"].(string)
|
||||
if !ok {
|
||||
return nil, errors.New("proxy server required")
|
||||
}
|
||||
if _, err := netip.ParseAddr(host); err != nil && !domain(host) {
|
||||
return nil, errors.New("invalid proxy server")
|
||||
}
|
||||
raw, _ := json.Marshal(node["server_port"])
|
||||
var port uint16
|
||||
if json.Unmarshal(raw, &port) != nil || port == 0 {
|
||||
return nil, errors.New("invalid proxy port")
|
||||
}
|
||||
// Nested transport/TLS options are validated by the fixed upstream registry;
|
||||
// they cannot supply route, DNS, dialer or arbitrary outbound configuration.
|
||||
if tls, ok := node["tls"].(map[string]any); ok {
|
||||
for k := range tls {
|
||||
if !strings.Contains(",enabled,server_name,alpn,reality,utls,", ","+k+",") {
|
||||
return nil, errors.New("unsupported TLS option")
|
||||
}
|
||||
}
|
||||
}
|
||||
if tr, ok := node["transport"].(map[string]any); ok {
|
||||
for k := range tr {
|
||||
if !strings.Contains(",type,path,headers,service_name,host,", ","+k+",") {
|
||||
return nil, errors.New("unsupported transport option")
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func dnsAddress(value string) (string, uint16, error) {
|
||||
if ip, e := netip.ParseAddr(value); e == nil {
|
||||
return ip.String(), 53, nil
|
||||
}
|
||||
if addr, e := netip.ParseAddrPort(value); e == nil && addr.Port() > 0 {
|
||||
return addr.Addr().String(), addr.Port(), nil
|
||||
}
|
||||
return "", 0, errors.New("DNS server must be an IP with optional port")
|
||||
}
|
||||
|
||||
// Encrypted resolver hostnames use the independent IP bootstrap resolver.
|
||||
func resolver(value, tag, detour string) (map[string]any, error) {
|
||||
result := map[string]any{"tag": tag}
|
||||
if !strings.Contains(value, "://") {
|
||||
host, port, err := dnsAddress(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result["type"], result["server"], result["server_port"] = "udp", host, port
|
||||
} else {
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || (u.Scheme != "https" && u.Scheme != "tls") {
|
||||
return nil, errors.New("invalid encrypted DNS URL")
|
||||
}
|
||||
host := u.Hostname()
|
||||
if _, err := netip.ParseAddr(host); err != nil && !domain(host) {
|
||||
return nil, errors.New("invalid DNS host")
|
||||
}
|
||||
port := uint16(443)
|
||||
kind := "https"
|
||||
if u.Scheme == "tls" {
|
||||
port, kind = 853, "tls"
|
||||
if u.Path != "" && u.Path != "/" {
|
||||
return nil, errors.New("DoT does not accept a path")
|
||||
}
|
||||
}
|
||||
if u.Port() != "" {
|
||||
if _, err := fmt.Sscanf(u.Port(), "%d", &port); err != nil || port == 0 {
|
||||
return nil, errors.New("invalid DNS port")
|
||||
}
|
||||
}
|
||||
result["type"], result["server"], result["server_port"] = kind, host, port
|
||||
result["tls"] = map[string]any{"enabled": true, "server_name": host}
|
||||
if _, err := netip.ParseAddr(host); err != nil {
|
||||
result["domain_resolver"] = map[string]any{"server": "bootstrap"}
|
||||
}
|
||||
if kind == "https" {
|
||||
path := u.EscapedPath()
|
||||
if path == "" {
|
||||
path = "/dns-query"
|
||||
}
|
||||
result["path"] = path
|
||||
}
|
||||
}
|
||||
if detour != "" {
|
||||
result["detour"] = detour
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func (c Config) managedJSON() ([]byte, error) {
|
||||
feature := c.Feature
|
||||
if feature == "" {
|
||||
feature = "mesh"
|
||||
}
|
||||
if feature != "mesh" && feature != "proxy" && feature != "combined" {
|
||||
return nil, errors.New("invalid feature")
|
||||
}
|
||||
mesh := feature != "proxy"
|
||||
internet := feature != "mesh"
|
||||
mode := c.Mode
|
||||
if mode == "" {
|
||||
mode = "rule"
|
||||
}
|
||||
if mode != "rule" && mode != "global" && mode != "direct" && mode != "bypass_cn" {
|
||||
return nil, errors.New("invalid proxy mode")
|
||||
}
|
||||
// A managed preset must not inherit custom rules that could override GeoIP.
|
||||
bypassCN := mode == "bypass_cn"
|
||||
if bypassCN {
|
||||
mode = "rule"
|
||||
c.DefaultAction = "proxy"
|
||||
c.Rules = nil
|
||||
c.RuleSets = []RuleSet{{Tag: "meshport-geoip-cn", Enabled: true,
|
||||
URL: "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/geoip-cn.srs",
|
||||
Format: "binary", Action: "direct", DownloadDetour: "proxy", UpdateHours: 24}}
|
||||
}
|
||||
active, err := prefixes(c.MeshCIDRs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
protected, err := prefixes(c.ProtectedCIDRs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.ListenPort == 0 {
|
||||
return nil, errors.New("listen port required")
|
||||
}
|
||||
outbounds := []any{}
|
||||
if mesh {
|
||||
endpoint, e := netip.ParseAddrPort(c.MeshSOCKS)
|
||||
if e != nil || !endpoint.Addr().Is4() || !endpoint.Addr().IsLoopback() || endpoint.Port() == 0 {
|
||||
return nil, errors.New("mesh SOCKS must be an IPv4 loopback endpoint with a port")
|
||||
}
|
||||
if len(active) == 0 && len(protected) == 0 {
|
||||
return nil, errors.New("effective mesh prefixes required")
|
||||
}
|
||||
meshOutbound := map[string]any{"type": "socks", "tag": "meshport", "server": endpoint.Addr().String(), "server_port": endpoint.Port(), "version": "5", "udp_over_tcp": false}
|
||||
// The Rust bridge is local. The internet default_interface must not
|
||||
// bind this loopback connection to a physical network adapter.
|
||||
if c.DesktopTun {
|
||||
meshOutbound["bind_interface"] = "lo0"
|
||||
}
|
||||
outbounds = append(outbounds, meshOutbound)
|
||||
}
|
||||
if internet {
|
||||
outbounds = append(outbounds, map[string]any{"type": "direct", "tag": "direct"})
|
||||
if c.Proxy != nil {
|
||||
node, e := proxyNode(c.Proxy)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
// Only the proxy endpoint may bootstrap outside the proxy.
|
||||
node["domain_resolver"] = map[string]any{"server": "bootstrap"}
|
||||
outbounds = append(outbounds, node)
|
||||
}
|
||||
}
|
||||
action := c.DefaultAction
|
||||
if action == "" {
|
||||
action = "proxy"
|
||||
}
|
||||
if action != "proxy" && action != "direct" && action != "reject" {
|
||||
return nil, errors.New("invalid default action")
|
||||
}
|
||||
if internet && mode == "global" {
|
||||
action = "proxy"
|
||||
}
|
||||
if internet && mode == "direct" {
|
||||
action = "direct"
|
||||
}
|
||||
routeRules := []any{}
|
||||
dns := map[string]any{}
|
||||
defaultResolver := "bootstrap"
|
||||
if internet {
|
||||
server := c.DNS
|
||||
if server == "" {
|
||||
server = "1.1.1.1"
|
||||
}
|
||||
server, dnsPort, e := dnsAddress(server)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
dnsServers := []any{map[string]any{"type": "udp", "tag": "bootstrap", "server": server, "server_port": dnsPort}}
|
||||
dnsFinal := "bootstrap"
|
||||
if c.DirectDNS != "" {
|
||||
server, e := resolver(c.DirectDNS, "direct-dns", "")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
dnsServers = append(dnsServers, server)
|
||||
dnsFinal = "direct-dns"
|
||||
}
|
||||
if c.DNSProtection && mode != "direct" {
|
||||
if c.Proxy == nil {
|
||||
return nil, errors.New("DNS protection requires a selected proxy node; use direct mode for direct-only traffic")
|
||||
}
|
||||
if c.ProxyDNS == "" {
|
||||
return nil, errors.New("DNS protection requires an explicitly configured proxy DNS server")
|
||||
}
|
||||
}
|
||||
if c.ProxyDNS != "" && mode != "direct" {
|
||||
if c.Proxy == nil {
|
||||
return nil, errors.New("proxy DNS requires proxy node")
|
||||
}
|
||||
server, e := resolver(c.ProxyDNS, "proxy-dns", "proxy")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
dnsServers = append(dnsServers, server)
|
||||
if mode != "direct" {
|
||||
dnsFinal = "proxy-dns"
|
||||
}
|
||||
}
|
||||
dnsRules := []any{}
|
||||
for i, m := range c.MeshDNS {
|
||||
ip, e := netip.ParseAddr(m.Server)
|
||||
activeDNS, knownDNS := false, false
|
||||
for _, v := range active {
|
||||
if netip.MustParsePrefix(v).Contains(ip) {
|
||||
activeDNS = true
|
||||
}
|
||||
}
|
||||
for _, v := range protected {
|
||||
if netip.MustParsePrefix(v).Contains(ip) {
|
||||
knownDNS = true
|
||||
}
|
||||
}
|
||||
if !mesh || !domain(m.Suffix) || e != nil || !(activeDNS || knownDNS) {
|
||||
return nil, errors.New("mesh DNS requires a known mesh server and valid suffix")
|
||||
}
|
||||
if !activeDNS {
|
||||
dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "reject"})
|
||||
continue
|
||||
}
|
||||
tag := "mesh-dns-" + strings.Repeat("x", i+1)
|
||||
dnsServers = append(dnsServers, map[string]any{"type": "udp", "tag": tag, "server": m.Server, "detour": "meshport"})
|
||||
dnsRules = append(dnsRules, map[string]any{"domain_suffix": []string{m.Suffix}, "action": "route", "server": tag})
|
||||
}
|
||||
if c.FakeIP {
|
||||
if len(c.FakeIPExclude) > 128 {
|
||||
return nil, errors.New("too many FakeIP exclusions")
|
||||
}
|
||||
excluded := []string{"localhost", "local", "lan"}
|
||||
for _, v := range c.FakeIPExclude {
|
||||
if !domain(v) {
|
||||
return nil, errors.New("invalid FakeIP exclusion")
|
||||
}
|
||||
excluded = append(excluded, v)
|
||||
}
|
||||
dnsRules = append(dnsRules, map[string]any{"domain_suffix": excluded, "action": "route", "server": dnsFinal})
|
||||
dnsServers = append(dnsServers, map[string]any{"type": "fakeip", "tag": "fakeip", "inet4_range": "198.18.0.0/15", "inet6_range": "fc00::/18"})
|
||||
dnsRules = append(dnsRules, map[string]any{"query_type": []string{"A", "AAAA"}, "action": "route", "server": "fakeip"})
|
||||
}
|
||||
defaultResolver = dnsFinal
|
||||
dns = map[string]any{"servers": dnsServers, "rules": dnsRules, "final": dnsFinal, "strategy": "ipv4_only"}
|
||||
routeRules = append(routeRules, map[string]any{"port": 53, "action": "hijack-dns"}, map[string]any{"action": "resolve", "strategy": "ipv4_only"})
|
||||
} else {
|
||||
routeRules = append(routeRules, map[string]any{"domain_regex": []string{".+"}, "action": "reject"})
|
||||
}
|
||||
if mesh && internet {
|
||||
for _, rule := range c.MeshDNS {
|
||||
routeRules = append(routeRules, map[string]any{"domain_suffix": []string{rule.Suffix}, "action": "route", "outbound": "meshport"})
|
||||
}
|
||||
}
|
||||
|
||||
if mesh && len(active) > 0 {
|
||||
routeRules = append(routeRules, map[string]any{"ip_cidr": active, "action": "route", "outbound": "meshport"})
|
||||
}
|
||||
if mesh && len(protected) > 0 {
|
||||
routeRules = append(routeRules, map[string]any{"ip_cidr": protected, "action": "reject"})
|
||||
}
|
||||
if internet && bypassCN {
|
||||
routeRules = append(routeRules, map[string]any{"ip_is_private": true, "action": "route", "outbound": "direct"})
|
||||
}
|
||||
usedProxy := internet && action == "proxy"
|
||||
if internet && mode == "rule" {
|
||||
if len(c.Rules) > 256 {
|
||||
return nil, errors.New("too many rules")
|
||||
}
|
||||
for _, r := range c.Rules {
|
||||
item := map[string]any{}
|
||||
switch r.Type {
|
||||
case "domain", "domain_suffix":
|
||||
if !domain(r.Value) {
|
||||
return nil, errors.New("invalid rule domain")
|
||||
}
|
||||
item[r.Type] = []string{r.Value}
|
||||
case "ip_cidr":
|
||||
p, e := netip.ParsePrefix(r.Value)
|
||||
if e != nil {
|
||||
return nil, errors.New("invalid rule CIDR")
|
||||
}
|
||||
item[r.Type] = []string{p.Masked().String()}
|
||||
default:
|
||||
return nil, errors.New("unsupported rule type")
|
||||
}
|
||||
switch r.Action {
|
||||
case "reject":
|
||||
item["action"] = "reject"
|
||||
case "direct", "proxy":
|
||||
item["action"] = "route"
|
||||
item["outbound"] = r.Action
|
||||
if r.Action == "proxy" {
|
||||
usedProxy = true
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("invalid rule action")
|
||||
}
|
||||
routeRules = append(routeRules, item)
|
||||
}
|
||||
}
|
||||
ruleSets := []any{}
|
||||
if len(c.RuleSets) > 32 {
|
||||
return nil, errors.New("too many rule sets")
|
||||
}
|
||||
tags := map[string]bool{}
|
||||
for _, set := range c.RuleSets {
|
||||
if !set.Enabled || !internet || mode != "rule" {
|
||||
continue
|
||||
}
|
||||
if !domain(set.Tag) || tags[set.Tag] {
|
||||
return nil, errors.New("invalid or duplicate rule set tag")
|
||||
}
|
||||
tags[set.Tag] = true
|
||||
if set.Action != "proxy" && set.Action != "direct" && set.Action != "reject" {
|
||||
return nil, errors.New("invalid rule set action")
|
||||
}
|
||||
item := map[string]any{"tag": set.Tag}
|
||||
if set.URL != "" {
|
||||
u, err := url.Parse(set.URL)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || len(set.Rules) != 0 {
|
||||
return nil, errors.New("invalid remote rule set URL")
|
||||
}
|
||||
if set.Format != "source" && set.Format != "binary" {
|
||||
return nil, errors.New("invalid rule set format")
|
||||
}
|
||||
hours := set.UpdateHours
|
||||
if hours == 0 {
|
||||
hours = 24
|
||||
}
|
||||
if hours < 1 || hours > 168 {
|
||||
return nil, errors.New("invalid rule set interval")
|
||||
}
|
||||
detour := set.DownloadDetour
|
||||
if detour == "" {
|
||||
detour = "direct"
|
||||
}
|
||||
if detour != "proxy" && detour != "direct" {
|
||||
return nil, errors.New("invalid rule set download detour")
|
||||
}
|
||||
if detour == "proxy" && c.Proxy == nil {
|
||||
return nil, errors.New("rule set download requires proxy")
|
||||
}
|
||||
item["type"], item["format"], item["url"] = "remote", set.Format, set.URL
|
||||
item["update_interval"], item["download_detour"] = fmt.Sprintf("%dh", hours), detour
|
||||
} else {
|
||||
if len(set.Rules) == 0 || len(set.Rules) > 256 {
|
||||
return nil, errors.New("invalid inline rule set")
|
||||
}
|
||||
item["type"], item["rules"] = "inline", set.Rules
|
||||
}
|
||||
if internet && mode == "rule" {
|
||||
ruleSets = append(ruleSets, item)
|
||||
match := map[string]any{"rule_set": []string{set.Tag}, "action": "route", "outbound": set.Action}
|
||||
if set.Action == "reject" {
|
||||
delete(match, "outbound")
|
||||
match["action"] = "reject"
|
||||
}
|
||||
if set.Action == "proxy" {
|
||||
usedProxy = true
|
||||
}
|
||||
routeRules = append(routeRules, match)
|
||||
}
|
||||
}
|
||||
if usedProxy && c.Proxy == nil {
|
||||
return nil, errors.New("selected proxy node required")
|
||||
}
|
||||
final := "meshport"
|
||||
if internet && action != "reject" {
|
||||
final = action
|
||||
} else {
|
||||
routeRules = append(routeRules, map[string]any{"action": "reject"})
|
||||
if internet {
|
||||
final = "direct"
|
||||
}
|
||||
}
|
||||
if c.FakeIP && !internet {
|
||||
return nil, errors.New("FakeIP requires ordinary proxy feature")
|
||||
}
|
||||
inbounds := []any{map[string]any{"type": "socks", "tag": "local", "listen": "127.0.0.1", "listen_port": c.ListenPort}}
|
||||
route := map[string]any{"rules": routeRules, "final": final}
|
||||
if len(ruleSets) > 0 {
|
||||
route["rule_set"] = ruleSets
|
||||
}
|
||||
if internet {
|
||||
route["default_domain_resolver"] = map[string]any{"server": defaultResolver}
|
||||
}
|
||||
if c.DesktopTun {
|
||||
if c.Tun != nil || c.PhysicalInterface == "" || strings.ContainsAny(c.PhysicalInterface, " /\\\t\r\n") {
|
||||
return nil, errors.New("desktop TUN requires physical interface")
|
||||
}
|
||||
route["default_interface"] = c.PhysicalInterface
|
||||
routes := []string{"0.0.0.0/1", "128.0.0.0/1", "::/1", "8000::/1"}
|
||||
if !internet {
|
||||
// Active prefixes also belong to the session's protection set.
|
||||
// Duplicate routes make Darwin delete the same entry twice on close,
|
||||
// which breaks subsequent announcement-driven engine restarts.
|
||||
captureSet := make(map[string]bool)
|
||||
for _, prefix := range append(append([]string{}, active...), protected...) {
|
||||
captureSet[prefix] = true
|
||||
}
|
||||
capture := make([]string, 0, len(captureSet))
|
||||
for prefix := range captureSet {
|
||||
capture = append(capture, prefix)
|
||||
}
|
||||
routes, err = prefixes(capture)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
dnsMode := "native"
|
||||
addresses := []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"}
|
||||
if !internet {
|
||||
dnsMode = "disabled"
|
||||
// No accepted IPv6 mesh prefixes exist yet. Giving Darwin an IPv6
|
||||
// address with auto_route and no IPv6 route_address captures its
|
||||
// IPv6 default route, even in the subnet-only mode.
|
||||
addresses = []string{"172.19.0.1/30"}
|
||||
}
|
||||
inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "address": addresses, "mtu": 1280, "auto_route": true, "route_address": routes, "stack": "system", "dns_mode": dnsMode})
|
||||
}
|
||||
if c.Tun != nil {
|
||||
if c.Tun.FD <= 0 || c.Tun.Name == "" || c.Tun.Interface == "" || c.Tun.Index <= 0 {
|
||||
return nil, errors.New("valid platform TUN and physical network required")
|
||||
}
|
||||
route["auto_detect_interface"] = true
|
||||
inbounds = append(inbounds, map[string]any{"type": "tun", "tag": "unified-tun", "interface_name": c.Tun.Name, "address": []string{"172.19.0.1/30", "fdfe:dcba:9876::1/126"}, "mtu": 1280, "auto_route": false, "stack": "system", "dns_mode": "disabled"})
|
||||
}
|
||||
result := map[string]any{"log": map[string]any{"disabled": !c.selfTestTrace(), "level": "debug"}, "inbounds": inbounds, "outbounds": outbounds, "route": route}
|
||||
if internet {
|
||||
result["dns"] = dns
|
||||
}
|
||||
return json.Marshal(result)
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
box "github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
func TestDNSProtectionRequiresExplicitResolverAndKeepsBootstrapNarrow(t *testing.T) {
|
||||
c := Config{ListenPort: 12345, Feature: "proxy", Mode: "global", DNSProtection: true, Proxy: map[string]any{"type": "socks", "server": "proxy.example", "server_port": 1080}}
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Fatal("silently chose a DNS provider")
|
||||
}
|
||||
c.ProxyDNS = "tls://resolver.example"
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v map[string]any
|
||||
json.Unmarshal(data, &v)
|
||||
if v["dns"].(map[string]any)["final"] != "proxy-dns" || v["route"].(map[string]any)["default_domain_resolver"].(map[string]any)["server"] != "proxy-dns" {
|
||||
t.Fatal("ordinary lookup escapes proxy DNS")
|
||||
}
|
||||
outbounds := v["outbounds"].([]any)
|
||||
if outbounds[1].(map[string]any)["domain_resolver"].(map[string]any)["server"] != "bootstrap" {
|
||||
t.Fatal("proxy endpoint resolution loops")
|
||||
}
|
||||
c.Mode = "direct"
|
||||
c.Proxy = nil
|
||||
c.ProxyDNS = ""
|
||||
if _, err := c.managedJSON(); err != nil {
|
||||
t.Fatal("direct mode required proxy DNS", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSProtectionNoDirectFallbackOnProxyFailure(t *testing.T) {
|
||||
// All addresses and trust are isolated test fixtures, not public DNS providers.
|
||||
fixture := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer fixture.Close()
|
||||
for _, fake := range []bool{false, true} {
|
||||
for _, fail := range []bool{false, true} {
|
||||
var proxiedQueries, bootQueries atomic.Int32
|
||||
proxy, _ := socksFixture(t, func(conn net.Conn) {
|
||||
if fail {
|
||||
return
|
||||
}
|
||||
stream := tls.Server(conn, &tls.Config{Certificates: fixture.TLS.Certificates, MinVersion: tls.VersionTLS12})
|
||||
dc := &D.Conn{Conn: stream}
|
||||
for {
|
||||
request, err := dc.ReadMsg()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
proxiedQueries.Add(1)
|
||||
response := new(D.Msg)
|
||||
response.SetReply(request)
|
||||
response.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: request.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
if dc.WriteMsg(response) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
defer proxy.Close()
|
||||
socket, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bootstrap := &D.Server{PacketConn: socket, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) { bootQueries.Add(1); m := new(D.Msg); m.SetReply(r); w.WriteMsg(m) })}
|
||||
go bootstrap.ActivateAndServe()
|
||||
defer bootstrap.Shutdown()
|
||||
l, port := reservePort(t)
|
||||
l.Close()
|
||||
c := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DefaultAction: "reject", DNS: socket.LocalAddr().String(), DNSProtection: true, FakeIP: fake,
|
||||
ProxyDNS: "tls://127.0.0.1:853", Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}}
|
||||
data, err := c.managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := registryContext(context.Background())
|
||||
opts, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opts.Certificate = &option.CertificateOptions{Store: "none", Certificate: []string{string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.Certificate().Raw}))}}
|
||||
instance, err := box.New(box.Options{Context: ctx, Options: opts})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = instance.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := "private-query.test"
|
||||
if fake {
|
||||
conn, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dc := &D.Conn{Conn: conn}
|
||||
msg := new(D.Msg)
|
||||
msg.SetQuestion("private-query.test.", D.TypeA)
|
||||
if err = dc.WriteMsg(msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := dc.ReadMsg()
|
||||
conn.Close()
|
||||
if err != nil || len(answer.Answer) != 1 {
|
||||
t.Fatalf("FakeIP query: %v / %v", answer, err)
|
||||
}
|
||||
target = answer.Answer[0].(*D.A).A.String()
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(target, "443")), false)
|
||||
instance.Close()
|
||||
if bootQueries.Load() != 0 {
|
||||
t.Fatal("target query leaked to bootstrap DNS")
|
||||
}
|
||||
if !fail && proxiedQueries.Load() == 0 {
|
||||
t.Fatal("proxy DNS wasn't used")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Package bridge provides an explicitly managed sing-box lifecycle. Platform
|
||||
// TUN integration and ordinary internet proxy profiles are separate milestones.
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
"github.com/sagernet/sing/service"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
box "github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/adapter/certificate"
|
||||
"github.com/sagernet/sing-box/adapter/endpoint"
|
||||
"github.com/sagernet/sing-box/adapter/inbound"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
boxservice "github.com/sagernet/sing-box/adapter/service"
|
||||
"github.com/sagernet/sing-box/dns"
|
||||
"github.com/sagernet/sing-box/dns/transport"
|
||||
"github.com/sagernet/sing-box/dns/transport/fakeip"
|
||||
"github.com/sagernet/sing-box/dns/transport/local"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/protocol/direct"
|
||||
"github.com/sagernet/sing-box/protocol/http"
|
||||
"github.com/sagernet/sing-box/protocol/shadowsocks"
|
||||
"github.com/sagernet/sing-box/protocol/trojan"
|
||||
"github.com/sagernet/sing-box/protocol/tun"
|
||||
"github.com/sagernet/sing-box/protocol/vless"
|
||||
"github.com/sagernet/sing-box/protocol/vmess"
|
||||
sjson "github.com/sagernet/sing/common/json"
|
||||
)
|
||||
|
||||
func registryContext(ctx context.Context) context.Context {
|
||||
in := inbound.NewRegistry()
|
||||
registerTrackedInbound(in)
|
||||
tun.RegisterInbound(in)
|
||||
out := outbound.NewRegistry()
|
||||
registerMeshOutbound(out)
|
||||
shadowsocks.RegisterOutbound(out)
|
||||
vmess.RegisterOutbound(out)
|
||||
vless.RegisterOutbound(out)
|
||||
trojan.RegisterOutbound(out)
|
||||
http.RegisterOutbound(out)
|
||||
direct.RegisterOutbound(out) // Required for sing-box's internal defaults.
|
||||
dnsRegistry := dns.NewTransportRegistry()
|
||||
local.RegisterTransport(dnsRegistry)
|
||||
transport.RegisterUDP(dnsRegistry)
|
||||
transport.RegisterHTTPS(dnsRegistry)
|
||||
transport.RegisterTLS(dnsRegistry)
|
||||
fakeip.RegisterTransport(dnsRegistry)
|
||||
return box.Context(ctx, in, out, endpoint.NewRegistry(), dnsRegistry,
|
||||
boxservice.NewRegistry(), certificate.NewRegistry())
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
State string `json:"state"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type Engine struct {
|
||||
selfTestTrace bool
|
||||
startupCause error // Private diagnostic for package tests; never returned over ABI.
|
||||
// Protector must be installed before starting a host TUN.
|
||||
CacheRoot string
|
||||
cacheDir string
|
||||
Protect func(int) error
|
||||
mu sync.Mutex
|
||||
box *box.Box
|
||||
state string
|
||||
cancel context.CancelFunc
|
||||
ctx context.Context
|
||||
desktopTun bool
|
||||
}
|
||||
|
||||
func (e *Engine) Snapshot() Snapshot {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
state := e.state
|
||||
if state == "" {
|
||||
state = "Stopped"
|
||||
}
|
||||
if state == "Running" && e.ctx.Err() != nil {
|
||||
state = "Failed"
|
||||
}
|
||||
return Snapshot{State: state, Version: "1.14.3"}
|
||||
}
|
||||
|
||||
func (e *Engine) Start(parent context.Context, config Config) error {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.box != nil {
|
||||
return errors.New("engine already started; stop before applying configuration")
|
||||
}
|
||||
if parent.Err() != nil {
|
||||
return errors.New("engine context is canceled")
|
||||
}
|
||||
if config.DesktopTun && (runtime.GOOS != "darwin" || os.Geteuid() != 0) {
|
||||
return errors.New("desktop TUN requires macOS privileged helper")
|
||||
}
|
||||
if config.DesktopTun {
|
||||
attached, err := desktopTunAddressAttached()
|
||||
if err != nil {
|
||||
return errors.New("cannot inspect desktop TUN address")
|
||||
}
|
||||
if attached {
|
||||
return errors.New("desktop TUN address already in use")
|
||||
}
|
||||
}
|
||||
data, err := config.managedJSON()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
e.selfTestTrace = config.selfTestTrace()
|
||||
e.desktopTun = config.DesktopTun
|
||||
e.state = "Starting"
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
ctx = registryContext(ctx)
|
||||
if config.Tun != nil {
|
||||
if e.Protect == nil {
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("platform socket protection required")
|
||||
}
|
||||
physical := &control.Interface{Name: config.Tun.Interface, Index: config.Tun.Index, MTU: 1500, Flags: net.FlagUp}
|
||||
ctx = service.ContextWith[adapter.PlatformInterface](ctx, &hostPlatform{config: *config.Tun, protect: e.Protect, monitor: &hostMonitor{physical: physical}})
|
||||
}
|
||||
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
|
||||
if err != nil {
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("invalid managed engine configuration")
|
||||
}
|
||||
if config.FakeIP || len(config.RuleSets) > 0 {
|
||||
if e.cacheDir == "" {
|
||||
e.cacheDir, err = os.MkdirTemp(e.CacheRoot, "meshport-fakeip-")
|
||||
if err != nil {
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("cannot create private DNS cache")
|
||||
}
|
||||
}
|
||||
options.Experimental = &option.ExperimentalOptions{CacheFile: &option.CacheFileOptions{Enabled: true, Path: filepath.Join(e.cacheDir, "fakeip.db"), StoreFakeIP: config.FakeIP}}
|
||||
}
|
||||
instance, err := box.New(box.Options{Options: options, Context: ctx})
|
||||
if err != nil {
|
||||
e.startupCause = err
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("cannot initialize proxy engine")
|
||||
}
|
||||
if err = instance.Start(); err != nil {
|
||||
e.startupCause = err
|
||||
_ = instance.Close()
|
||||
cancel()
|
||||
e.state = "Failed"
|
||||
return errors.New("cannot start proxy engine")
|
||||
}
|
||||
e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running"
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Engine) Stop() error {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.box == nil {
|
||||
e.state = "Stopped"
|
||||
return nil
|
||||
}
|
||||
e.state = "Stopping"
|
||||
err := e.box.Close()
|
||||
e.cancel()
|
||||
e.box, e.cancel, e.ctx = nil, nil, nil
|
||||
if e.desktopTun && err == nil {
|
||||
// Darwin can retain the utun address until its last kernel reference
|
||||
// drains. Reusing that address immediately can attach the new routes
|
||||
// to the retiring interface and remove them when it finally disappears.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
attached, inspectErr := desktopTunAddressAttached()
|
||||
if inspectErr != nil {
|
||||
err = inspectErr
|
||||
break
|
||||
}
|
||||
if !attached {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
err = errors.New("desktop TUN address did not detach")
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
e.state = "Failed"
|
||||
if e.selfTestTrace {
|
||||
fmt.Fprintf(os.Stderr, "self-test cleanup cause: %v\n", err)
|
||||
}
|
||||
return errors.New("proxy engine cleanup failed")
|
||||
}
|
||||
e.state = "Stopped"
|
||||
return nil
|
||||
}
|
||||
|
||||
func desktopTunAddressAttached() (bool, error) {
|
||||
addresses, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, address := range addresses {
|
||||
ip, _, err := net.ParseCIDR(address.String())
|
||||
if err == nil && ip.Equal(net.ParseIP("172.19.0.1")) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Close releases the session's private cache only after the engine is stopped.
|
||||
func (e *Engine) Close() error {
|
||||
err := e.Stop()
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.cacheDir != "" {
|
||||
removeErr := os.RemoveAll(e.cacheDir)
|
||||
e.cacheDir = ""
|
||||
if err == nil {
|
||||
err = removeErr
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func reservePort(t *testing.T) (net.Listener, uint16) {
|
||||
t.Helper()
|
||||
l, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l, uint16(l.Addr().(*net.TCPAddr).Port)
|
||||
}
|
||||
|
||||
func TestUnconfiguredTargetsAndDomainsAreRejected(t *testing.T) {
|
||||
bridgeListener, _ := reservePort(t)
|
||||
defer bridgeListener.Close()
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
if err := engine.Start(context.Background(), Config{ListenPort: port, MeshSOCKS: bridgeListener.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Stop()
|
||||
for _, destination := range []M.Socksaddr{
|
||||
M.SocksaddrFrom(netip.MustParseAddr("127.0.0.1"), uint16(bridgeListener.Addr().(*net.TCPAddr).Port)),
|
||||
M.SocksaddrFrom(netip.MustParseAddr("10.78.0.1"), 1234),
|
||||
M.ParseSocksaddr("must-not-resolve.invalid:1234"),
|
||||
} {
|
||||
conn, err := net.Dial("tcp4", entry.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, destination, "", "")
|
||||
conn.Close()
|
||||
if err == nil {
|
||||
t.Fatal("unconfigured target accepted:", destination)
|
||||
}
|
||||
if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
|
||||
t.Fatal("rejection timed out:", destination)
|
||||
}
|
||||
}
|
||||
bridgeListener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))
|
||||
if conn, err := bridgeListener.Accept(); err == nil {
|
||||
conn.Close()
|
||||
t.Fatal("rejected request reached mesh bridge")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigurationRejectsUnsupportedEndpointsAndPrefixes(t *testing.T) {
|
||||
base := Config{ListenPort: 1080, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.0/24"}}
|
||||
for _, endpoint := range []string{"example.com:1080", "0.0.0.0:1080", "10.0.0.1:1080", "127.0.0.1:0", "[::1]:1080"} {
|
||||
c := base
|
||||
c.MeshSOCKS = endpoint
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Errorf("accepted endpoint %s", endpoint)
|
||||
}
|
||||
}
|
||||
for _, prefix := range []string{"0.0.0.0/0", "10.0.0.0/8", "1.1.1.0/24", "127.0.0.0/24", "fd00::/64", "invalid"} {
|
||||
c := base
|
||||
c.MeshCIDRs = []string{prefix}
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Errorf("accepted prefix %s", prefix)
|
||||
}
|
||||
}
|
||||
c := base
|
||||
c.MeshCIDRs = nil
|
||||
if _, err := c.managedJSON(); err == nil {
|
||||
t.Error("accepted empty projection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineLifecycleAndFailedStartRecovery(t *testing.T) {
|
||||
occupied, port := reservePort(t)
|
||||
defer occupied.Close()
|
||||
c := Config{ListenPort: port, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.11/24", "10.77.0.0/24"}}
|
||||
var engine Engine
|
||||
if engine.Snapshot().State != "Stopped" {
|
||||
t.Fatal("initial state")
|
||||
}
|
||||
if engine.Start(context.Background(), c) == nil {
|
||||
t.Fatal("started on occupied port")
|
||||
}
|
||||
if engine.Snapshot().State != "Failed" {
|
||||
t.Fatal("failed start state")
|
||||
}
|
||||
occupied.Close()
|
||||
if err := engine.Start(context.Background(), c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Stop()
|
||||
if engine.Snapshot().State != "Running" {
|
||||
t.Fatal("running state")
|
||||
}
|
||||
if engine.Start(context.Background(), c) == nil {
|
||||
t.Fatal("duplicate start accepted")
|
||||
}
|
||||
conn, err := net.Dial("tcp4", occupied.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
if _, err := conn.Write([]byte{5, 1, 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var reply [2]byte
|
||||
if _, err := io.ReadFull(conn, reply[:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reply != [2]byte{5, 0} {
|
||||
t.Fatal("unexpected negotiation", reply)
|
||||
}
|
||||
if err := engine.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if engine.Snapshot().State != "Stopped" {
|
||||
t.Fatal("stop state")
|
||||
}
|
||||
if n, err := conn.Read(reply[:]); n != 0 {
|
||||
t.Fatal("active connection retained after stop")
|
||||
} else if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
|
||||
t.Fatal("active connection only closed by client timeout")
|
||||
}
|
||||
l, err := net.Listen("tcp4", occupied.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal("listener leaked:", err)
|
||||
}
|
||||
l.Close()
|
||||
if err := engine.Start(context.Background(), c); err != nil {
|
||||
t.Fatal("restart:", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/inbound"
|
||||
"github.com/sagernet/sing-box/common/listener"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/protocol/socks"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
// Track accepted controls before SOCKS negotiation, including connections that
|
||||
// have not entered sing-box's routed connection manager yet.
|
||||
type connectionSet struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
connections map[*trackedConnection]struct{}
|
||||
}
|
||||
|
||||
type trackedConnection struct {
|
||||
net.Conn
|
||||
owner *connectionSet
|
||||
}
|
||||
|
||||
func (c *trackedConnection) Close() error {
|
||||
err := c.Conn.Close()
|
||||
c.owner.mu.Lock()
|
||||
delete(c.owner.connections, c)
|
||||
c.owner.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *connectionSet) track(conn net.Conn) *trackedConnection {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed || len(s.connections) >= 128 {
|
||||
return nil
|
||||
}
|
||||
c := &trackedConnection{Conn: conn, owner: s}
|
||||
s.connections[c] = struct{}{}
|
||||
return c
|
||||
}
|
||||
|
||||
func (s *connectionSet) closeAll() {
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
connections := make([]*trackedConnection, 0, len(s.connections))
|
||||
for conn := range s.connections {
|
||||
connections = append(connections, conn)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, conn := range connections {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
type trackedInbound struct {
|
||||
*socks.Inbound
|
||||
listener *listener.Listener
|
||||
connections connectionSet
|
||||
}
|
||||
|
||||
func registerTrackedInbound(registry *inbound.Registry) {
|
||||
inbound.Register[option.SocksInboundOptions](registry, C.TypeSOCKS,
|
||||
func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SocksInboundOptions) (adapter.Inbound, error) {
|
||||
delegate, err := socks.NewInbound(ctx, router, logger, tag, options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tracked := &trackedInbound{Inbound: delegate.(*socks.Inbound), connections: connectionSet{connections: make(map[*trackedConnection]struct{})}}
|
||||
// The delegate only handles the protocol. This listener owns the
|
||||
// accepted TCP controls; its options also constrain UDP association
|
||||
// allocation through the delegate's original packet-listener helper.
|
||||
tracked.listener = listener.New(listener.Options{Context: ctx, Logger: logger, Network: []string{N.NetworkTCP}, Listen: options.ListenOptions, ConnectionHandler: tracked})
|
||||
return tracked, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (h *trackedInbound) Start(stage adapter.StartStage, scope *adapter.Scope) error {
|
||||
if stage != adapter.StartStateStart {
|
||||
return nil
|
||||
}
|
||||
if err := h.listener.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
scope.Add(func() error {
|
||||
err := h.listener.Close()
|
||||
h.connections.closeAll()
|
||||
return err
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *trackedInbound) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
|
||||
tracked := h.connections.track(conn)
|
||||
if tracked == nil {
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
h.Inbound.NewConnection(ctx, tracked, metadata, onClose)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/outbound"
|
||||
"github.com/sagernet/sing-box/common/dialer"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
boxsocks "github.com/sagernet/sing-box/protocol/socks"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
)
|
||||
|
||||
type meshOutbound struct {
|
||||
adapter.Outbound
|
||||
dialer N.Dialer
|
||||
server M.Socksaddr
|
||||
logger log.ContextLogger
|
||||
}
|
||||
|
||||
func registerMeshOutbound(registry *outbound.Registry) {
|
||||
outbound.Register[option.SOCKSOutboundOptions](registry, C.TypeSOCKS,
|
||||
func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SOCKSOutboundOptions) (adapter.Outbound, error) {
|
||||
delegate, err := boxsocks.NewOutbound(ctx, router, logger, tag, options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tag != "meshport" {
|
||||
return delegate, nil
|
||||
}
|
||||
d, err := dialer.New(ctx, options.DialerOptions, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &meshOutbound{Outbound: delegate, dialer: d, server: options.ServerOptions.Build(), logger: logger}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (o *meshOutbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
if N.NetworkName(network) == N.NetworkUDP {
|
||||
return o.associate(ctx, destination)
|
||||
}
|
||||
return o.Outbound.DialContext(ctx, network, destination)
|
||||
}
|
||||
|
||||
func (o *meshOutbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
return o.associate(ctx, destination)
|
||||
}
|
||||
|
||||
// RFC 1928 UDP ASSOCIATE names the client's expected UDP endpoint, not the
|
||||
// remote destination. That endpoint is not yet allocated, so request 0.0.0.0:0.
|
||||
// Keep this normalization in our adapter instead of weakening the Rust bridge's
|
||||
// source IP/port isolation to accept another client's private-address heuristic.
|
||||
func (o *meshOutbound) associate(ctx context.Context, destination M.Socksaddr) (packet *socks.AssociatePacketConn, err error) {
|
||||
control, err := o.dialer.DialContext(ctx, N.NetworkTCP, o.server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = control.Close()
|
||||
}
|
||||
}()
|
||||
stopCancel := context.AfterFunc(ctx, func() { _ = control.Close() })
|
||||
defer func() {
|
||||
if !stopCancel() {
|
||||
if packet != nil {
|
||||
_ = packet.Close()
|
||||
packet = nil
|
||||
}
|
||||
err = ctx.Err()
|
||||
}
|
||||
}()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
|
||||
deadline = d
|
||||
}
|
||||
if err = control.SetDeadline(deadline); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reader := varbin.StubReader(control)
|
||||
if err = socks5.WriteAuthRequest(control, socks5.AuthRequest{Methods: []byte{socks5.AuthTypeNotRequired}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
auth, err := socks5.ReadAuthResponse(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if auth.Method != socks5.AuthTypeNotRequired {
|
||||
return nil, errors.New("mesh bridge rejected authentication method")
|
||||
}
|
||||
if err = socks5.WriteRequest(control, socks5.Request{Command: socks5.CommandUDPAssociate, Destination: M.SocksaddrFrom(netip.IPv4Unspecified(), 0)}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.logger.DebugContext(ctx, "mesh UDP association requested")
|
||||
response, err := socks5.ReadResponse(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.ReplyCode != socks5.ReplyCodeSuccess || !response.Bind.Addr.Is4() || response.Bind.Addr != o.server.Addr || response.Bind.Port == 0 {
|
||||
return nil, errors.New("mesh bridge rejected UDP association or returned an invalid endpoint")
|
||||
}
|
||||
if err = control.SetDeadline(time.Time{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udp, err := o.dialer.DialContext(ctx, N.NetworkUDP, response.Bind)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.logger.DebugContext(ctx, "mesh UDP association ready: ", udp.LocalAddr(), " -> ", response.Bind)
|
||||
return socks.NewAssociatePacketConn(udp, destination, control), nil
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
"github.com/sagernet/sing/common/x/list"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// This adapter owns a duplicate of the host's TUN. It never creates OS routes.
|
||||
// All optional platform capabilities explicitly remain unavailable.
|
||||
type hostPlatform struct {
|
||||
config TunConfig
|
||||
protect func(int) error
|
||||
monitor *hostMonitor
|
||||
}
|
||||
|
||||
func (p *hostPlatform) Initialize(adapter.NetworkManager) error { return nil }
|
||||
func (p *hostPlatform) UsePlatformAutoDetectInterfaceControl() bool { return true }
|
||||
func (p *hostPlatform) AutoDetectInterfaceControl(fd int) error {
|
||||
if p.protect == nil {
|
||||
return errors.New("socket protector missing")
|
||||
}
|
||||
return p.protect(fd)
|
||||
}
|
||||
func (p *hostPlatform) UsePlatformInterface() bool { return true }
|
||||
func (p *hostPlatform) OpenInterface(o *tun.Options, _ option.TunPlatformOptions) (tun.Tun, error) {
|
||||
fd, e := unix.Dup(p.config.FD)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
unix.CloseOnExec(fd)
|
||||
o.FileDescriptor = fd
|
||||
o.Name = p.config.Name
|
||||
p.monitor.RegisterMyInterface(o.Name)
|
||||
result, e := tun.New(*o)
|
||||
if e != nil {
|
||||
unix.Close(fd)
|
||||
}
|
||||
return result, e
|
||||
}
|
||||
func (*hostPlatform) ProcessPlatformOptions(option.TunPlatformOptions) error { return nil }
|
||||
func (*hostPlatform) UsePlatformDefaultInterfaceMonitor() bool { return true }
|
||||
func (p *hostPlatform) CreateDefaultInterfaceMonitor(logger.Logger) tun.DefaultInterfaceMonitor {
|
||||
return p.monitor
|
||||
}
|
||||
func (*hostPlatform) UsePlatformNetworkInterfaces() bool { return true }
|
||||
func (p *hostPlatform) NetworkInterfaces() ([]adapter.NetworkInterface, error) {
|
||||
return []adapter.NetworkInterface{{Interface: *p.monitor.physical}, {Interface: control.Interface{Name: "lo", Index: 1, MTU: 65536, Flags: net.FlagUp | net.FlagLoopback, Addresses: []netip.Prefix{netip.MustParsePrefix("127.0.0.1/8")}}}}, nil
|
||||
}
|
||||
func (*hostPlatform) UnderNetworkExtension() bool { return false }
|
||||
func (*hostPlatform) NetworkExtensionIncludeAllNetworks() bool { return false }
|
||||
func (*hostPlatform) ClearDNSCache() {}
|
||||
func (*hostPlatform) RequestPermissionForWIFIState() error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) ReadWIFIState(context.Context) adapter.WIFIState { return adapter.WIFIState{} }
|
||||
func (*hostPlatform) UsePlatformConnectionOwnerFinder() bool { return false }
|
||||
func (*hostPlatform) FindConnectionOwner(*adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) UsePlatformWIFIMonitor() bool { return false }
|
||||
func (*hostPlatform) UsePlatformNotification() bool { return false }
|
||||
func (*hostPlatform) SendNotification(*adapter.Notification) error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) CancelNotification(string, int32) error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) MyInterfaceAddress() []netip.Addr {
|
||||
return []netip.Addr{netip.MustParseAddr("172.19.0.1"), netip.MustParseAddr("fdfe:dcba:9876::1")}
|
||||
}
|
||||
func (*hostPlatform) UsePlatformNeighborResolver() bool { return false }
|
||||
func (*hostPlatform) StartNeighborMonitor(adapter.NeighborUpdateListener) error {
|
||||
return errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) CloseNeighborMonitor(adapter.NeighborUpdateListener) error { return nil }
|
||||
func (*hostPlatform) UsePlatformShell() bool { return false }
|
||||
func (*hostPlatform) CheckPlatformShell() error { return errors.New("unsupported") }
|
||||
func (*hostPlatform) OpenShellSession(*adapter.PlatformUser, string, []string, string, int32, int32) (adapter.ShellSession, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) LookupUser(string) (*adapter.PlatformUser, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
func (*hostPlatform) LookupSFTPServer() (string, error) { return "", errors.New("unsupported") }
|
||||
func (*hostPlatform) ReadSystemSSHHostKey() ([]byte, error) { return nil, errors.New("unsupported") }
|
||||
func (*hostPlatform) TailscaleHostname() string { return "" }
|
||||
func (*hostPlatform) UsePlatformBridge() bool { return false }
|
||||
func (*hostPlatform) CreateBridge(adapter.BridgeOptions) (adapter.BridgeSession, error) {
|
||||
return nil, errors.New("unsupported")
|
||||
}
|
||||
|
||||
type hostMonitor struct {
|
||||
physical *control.Interface
|
||||
mu sync.Mutex
|
||||
names []string
|
||||
callbacks list.List[tun.DefaultInterfaceUpdateCallback]
|
||||
}
|
||||
|
||||
func (*hostMonitor) Start() error { return nil }
|
||||
func (*hostMonitor) Close() error { return nil }
|
||||
func (m *hostMonitor) DefaultInterface() *control.Interface { return m.physical }
|
||||
func (*hostMonitor) OverrideAndroidVPN() bool { return true }
|
||||
func (*hostMonitor) AndroidVPNEnabled() bool { return false }
|
||||
func (m *hostMonitor) RegisterCallback(c tun.DefaultInterfaceUpdateCallback) *list.Element[tun.DefaultInterfaceUpdateCallback] {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.callbacks.PushBack(c)
|
||||
}
|
||||
func (m *hostMonitor) UnregisterCallback(e *list.Element[tun.DefaultInterfaceUpdateCallback]) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.callbacks.Remove(e)
|
||||
}
|
||||
func (m *hostMonitor) RegisterMyInterface(n string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.names = append(m.names, n)
|
||||
}
|
||||
func (m *hostMonitor) MyInterfaces() []string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return append([]string{}, m.names...)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
D "github.com/miekg/dns"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
)
|
||||
|
||||
// A real SOCKS5 fixture echoes through the selected outlet; a request counter
|
||||
// distinguishes route selection from mere successful engine startup.
|
||||
func socksEcho(t *testing.T) (net.Listener, *atomic.Int32) {
|
||||
return socksFixture(t, func(c net.Conn) { io.Copy(c, c) })
|
||||
}
|
||||
func socksFixture(t *testing.T, handler func(net.Conn)) (net.Listener, *atomic.Int32) {
|
||||
l, _ := reservePort(t)
|
||||
counter := &atomic.Int32{}
|
||||
go func() {
|
||||
for {
|
||||
c, e := l.Accept()
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
var greeting [2]byte
|
||||
if _, e := io.ReadFull(c, greeting[:]); e != nil {
|
||||
return
|
||||
}
|
||||
methods := make([]byte, int(greeting[1]))
|
||||
if _, e := io.ReadFull(c, methods); e != nil {
|
||||
return
|
||||
}
|
||||
c.Write([]byte{5, 0})
|
||||
var req [4]byte
|
||||
if _, e := io.ReadFull(c, req[:]); e != nil {
|
||||
return
|
||||
}
|
||||
n := 4
|
||||
if req[3] == 3 {
|
||||
var size [1]byte
|
||||
if _, e := io.ReadFull(c, size[:]); e != nil {
|
||||
return
|
||||
}
|
||||
n = int(size[0])
|
||||
} else if req[3] == 4 {
|
||||
n = 16
|
||||
}
|
||||
if _, e := io.ReadFull(c, make([]byte, n+2)); e != nil {
|
||||
return
|
||||
}
|
||||
counter.Add(1)
|
||||
c.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 1})
|
||||
handler(c)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return l, counter
|
||||
}
|
||||
func echoThrough(t *testing.T, port uint16, target M.Socksaddr, want bool) {
|
||||
t.Helper()
|
||||
c, e := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, e = socks.ClientHandshake5(c, socks5.CommandConnect, target, "", "")
|
||||
if !want {
|
||||
if e == nil {
|
||||
c.Write([]byte("x"))
|
||||
var b [1]byte
|
||||
n, readErr := c.Read(b[:])
|
||||
if n != 0 || readErr == nil {
|
||||
t.Fatal("protected target passed")
|
||||
}
|
||||
if ne, ok := readErr.(net.Error); ok && ne.Timeout() {
|
||||
t.Fatal("rejection timed out")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.Write([]byte("route-echo"))
|
||||
result := make([]byte, 10)
|
||||
if _, e := io.ReadFull(c, result); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if string(result) != "route-echo" {
|
||||
t.Fatal(string(result))
|
||||
}
|
||||
}
|
||||
func jsonNumber(n int) string { raw, _ := json.Marshal(n); return string(raw) }
|
||||
func TestModesAndMeshPriority(t *testing.T) {
|
||||
proxy, count := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
mesh, meshCount := socksEcho(t)
|
||||
defer mesh.Close()
|
||||
direct, _ := reservePort(t)
|
||||
defer direct.Close()
|
||||
go func() {
|
||||
for {
|
||||
c, e := direct.Accept()
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
go func() { defer c.Close(); io.Copy(c, c) }()
|
||||
}
|
||||
}()
|
||||
for _, mode := range []string{"rule", "global", "direct"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
config := Config{ListenPort: port, Feature: "combined", Mode: mode, MeshSOCKS: mesh.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}, ProtectedCIDRs: []string{"10.88.0.0/24"}, Proxy: map[string]any{"type": "socks", "version": "5", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, Rules: []Rule{{Type: "ip_cidr", Value: "127.0.0.0/8", Action: "direct"}}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Stop()
|
||||
before := count.Load()
|
||||
beforeMesh := meshCount.Load()
|
||||
echoThrough(t, port, M.SocksaddrFrom(netip.MustParseAddr("127.0.0.1"), uint16(direct.Addr().(*net.TCPAddr).Port)), true)
|
||||
expected := int32(0)
|
||||
if mode == "global" {
|
||||
expected = 1
|
||||
}
|
||||
if count.Load()-before != expected {
|
||||
t.Fatal("wrong internet outlet")
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("10.77.0.2:1234"), true)
|
||||
if meshCount.Load()-beforeMesh != 1 {
|
||||
t.Fatal("mesh priority lost")
|
||||
}
|
||||
before = count.Load()
|
||||
echoThrough(t, port, M.ParseSocksaddr("10.88.0.2:1234"), false)
|
||||
if count.Load() != before {
|
||||
t.Fatal("protected destination leaked to proxy")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestDNSAndDomainRule(t *testing.T) {
|
||||
upstream, count := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
dnsSock, e := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
dnsServer := &D.Server{PacketConn: dnsSock, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
w.WriteMsg(m)
|
||||
})}
|
||||
go dnsServer.ActivateAndServe()
|
||||
defer dnsServer.Shutdown()
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
config := Config{ListenPort: port, Feature: "proxy", Mode: "rule", DNS: dnsSock.LocalAddr().String(), DefaultAction: "reject", Proxy: map[string]any{"type": "socks", "version": "5", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}, Rules: []Rule{{Type: "domain_suffix", Value: "example.test", Action: "proxy"}}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Stop()
|
||||
echoThrough(t, port, M.ParseSocksaddr("sub.example.test:1234"), true)
|
||||
if count.Load() != 1 {
|
||||
t.Fatal("domain rule not selected")
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr("blocked.invalid:1234"), false)
|
||||
if count.Load() != 1 {
|
||||
t.Fatal("default reject bypassed")
|
||||
}
|
||||
}
|
||||
func TestImportedNodeCannotReplaceManagedDialer(t *testing.T) {
|
||||
for _, field := range []string{"detour", "bind_interface", "routing_mark", "domain_resolver", "tag", "route"} {
|
||||
node := map[string]any{"type": "socks", "server": "example.test", "server_port": 1080, field: "unmanaged"}
|
||||
if _, e := proxyNode(node); e == nil {
|
||||
t.Fatal("injected field accepted", field)
|
||||
}
|
||||
}
|
||||
var engine Engine
|
||||
config := Config{ListenPort: 10818, Feature: "proxy", Mode: "direct", Tun: &TunConfig{FD: 123, Name: "tun0", Interface: "eth0", Index: 2}}
|
||||
if e := engine.Start(context.Background(), config); e == nil {
|
||||
engine.Stop()
|
||||
t.Fatal("unprotected platform TUN accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithdrawnMeshDNSIsRejectedWithoutFallback(t *testing.T) {
|
||||
upstream, count := socksEcho(t)
|
||||
defer upstream.Close()
|
||||
entry, port := reservePort(t)
|
||||
entry.Close()
|
||||
var engine Engine
|
||||
config := Config{ListenPort: port, Feature: "combined", Mode: "global", MeshSOCKS: "127.0.0.1:9", ProtectedCIDRs: []string{"10.77.0.0/24"}, MeshDNS: []MeshDNS{{Suffix: "mesh.test", Server: "10.77.0.2"}}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": upstream.Addr().(*net.TCPAddr).Port}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Stop()
|
||||
echoThrough(t, port, M.ParseSocksaddr("secret.mesh.test:1234"), false)
|
||||
if count.Load() != 0 {
|
||||
t.Fatal("mesh DNS failed open to proxy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFakeIPMappingAndMeshExclusion(t *testing.T) {
|
||||
dnsSock, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dnsServer := &D.Server{PacketConn: dnsSock, Handler: D.HandlerFunc(func(w D.ResponseWriter, r *D.Msg) {
|
||||
m := new(D.Msg)
|
||||
m.SetReply(r)
|
||||
m.Answer = []D.RR{&D.A{Hdr: D.RR_Header{Name: r.Question[0].Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: 60}, A: net.ParseIP("203.0.113.7")}}
|
||||
w.WriteMsg(m)
|
||||
})}
|
||||
go dnsServer.ActivateAndServe()
|
||||
defer dnsServer.Shutdown()
|
||||
proxy, count := socksEcho(t)
|
||||
defer proxy.Close()
|
||||
listener, port := reservePort(t)
|
||||
listener.Close()
|
||||
engine := &Engine{}
|
||||
config := Config{ListenPort: port, Feature: "combined", Mode: "global", MeshSOCKS: "127.0.0.1:9", DNS: dnsSock.LocalAddr().String(), ProtectedCIDRs: []string{"10.77.0.0/24"}, Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}, FakeIP: true, MeshDNS: []MeshDNS{{Suffix: "mesh.test", Server: "10.77.0.2"}}}
|
||||
if e := engine.Start(context.Background(), config); e != nil {
|
||||
t.Fatalf("%v: %v", e, engine.startupCause)
|
||||
}
|
||||
defer engine.Close()
|
||||
query := func(domain string) *D.Msg {
|
||||
t.Helper()
|
||||
c, err := net.Dial("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(int(port))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
_, err = socks.ClientHandshake5(c, socks5.CommandConnect, M.ParseSocksaddr("1.1.1.1:53"), "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn := &D.Conn{Conn: c}
|
||||
msg := new(D.Msg)
|
||||
msg.SetQuestion(D.Fqdn(domain), D.TypeA)
|
||||
if e := conn.WriteMsg(msg); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
reply, e := conn.ReadMsg()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return reply
|
||||
}
|
||||
reply := query("public.test")
|
||||
if len(reply.Answer) != 1 {
|
||||
t.Fatalf("missing FakeIP answer: %v", reply)
|
||||
}
|
||||
address, ok := reply.Answer[0].(*D.A)
|
||||
if !ok || !netip.MustParsePrefix("198.18.0.0/15").Contains(netip.MustParseAddr(address.A.String())) {
|
||||
t.Fatal("not a FakeIP answer")
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(address.A.String(), "443")), true)
|
||||
if count.Load() != 1 {
|
||||
t.Fatal("FakeIP connection did not use selected proxy")
|
||||
}
|
||||
if err := engine.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := engine.Start(context.Background(), config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
echoThrough(t, port, M.ParseSocksaddr(net.JoinHostPort(address.A.String(), "443")), true)
|
||||
if count.Load() != 2 {
|
||||
t.Fatal("FakeIP mapping lost across managed rebuild")
|
||||
}
|
||||
// Known withdrawn mesh domains must reject before the generic FakeIP rule.
|
||||
reply = query("host.mesh.test")
|
||||
if len(reply.Answer) != 0 || reply.Rcode == D.RcodeSuccess {
|
||||
t.Fatal("withdrawn mesh domain leaked to FakeIP")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/protocol/socks"
|
||||
"github.com/sagernet/sing/protocol/socks/socks5"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ProbeResult struct {
|
||||
Method string `json:"method"`
|
||||
ElapsedMS float64 `json:"elapsed_ms"`
|
||||
StatusCode int `json:"status_code"`
|
||||
}
|
||||
|
||||
// A draft probe owns an isolated loopback engine and never installs a TUN or
|
||||
// changes the running instance. The public ABI fixes its HTTPS test destination.
|
||||
func ProbeNode(parent context.Context, node map[string]any, dnsServer string, target string) (ProbeResult, error) {
|
||||
ctx, cancel := context.WithTimeout(parent, 10*time.Second)
|
||||
defer cancel()
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("cannot reserve probe port")
|
||||
}
|
||||
port := uint16(listener.Addr().(*net.TCPAddr).Port)
|
||||
listener.Close()
|
||||
var engine Engine
|
||||
defer engine.Close()
|
||||
if err := engine.Start(ctx, Config{ListenPort: port, Feature: "proxy", Mode: "global", Proxy: node, DNS: dnsServer}); err != nil {
|
||||
return ProbeResult{}, errors.New("invalid draft proxy configuration")
|
||||
}
|
||||
transport := &http.Transport{DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
c, err := (&net.Dialer{}).DialContext(ctx, "tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(port))))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.SetDeadline(time.Now().Add(8 * time.Second))
|
||||
_, err = socks.ClientHandshake5(c, socks5.CommandConnect, M.ParseSocksaddr(address), "", "")
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}, TLSHandshakeTimeout: 8 * time.Second, DisableKeepAlives: true}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("invalid probe target")
|
||||
}
|
||||
started := time.Now()
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("HTTPS connectivity check failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
_, err = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
|
||||
if err != nil {
|
||||
return ProbeResult{}, errors.New("connectivity response failed")
|
||||
}
|
||||
result := ProbeResult{Method: "HTTP connectivity", ElapsedMS: float64(time.Since(started).Microseconds()) / 1000, StatusCode: response.StatusCode}
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return result, errors.New("connectivity target returned a non-success status")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDraftHTTPProbeIsIsolated(t *testing.T) {
|
||||
proxy, count := socksFixture(t, func(c net.Conn) {
|
||||
request, err := http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if request.Host != "203.0.113.7" || request.Method != "GET" {
|
||||
t.Error("unexpected draft request")
|
||||
}
|
||||
fmt.Fprint(c, "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
|
||||
})
|
||||
defer proxy.Close()
|
||||
l, port := reservePort(t)
|
||||
l.Close()
|
||||
var running Engine
|
||||
if err := running.Start(context.Background(), Config{ListenPort: port, MeshSOCKS: "127.0.0.1:9", MeshCIDRs: []string{"10.77.0.0/24"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer running.Close()
|
||||
node := map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": proxy.Addr().(*net.TCPAddr).Port}
|
||||
result, err := ProbeNode(context.Background(), node, "", "http://203.0.113.7/probe")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.StatusCode != 204 || result.ElapsedMS <= 0 || count.Load() != 1 {
|
||||
t.Fatal("probe did not use selected draft node")
|
||||
}
|
||||
if running.Snapshot().State != "Running" {
|
||||
t.Fatal("probe changed running engine")
|
||||
}
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := ProbeNode(canceled, node, "", "http://203.0.113.7/probe"); err == nil {
|
||||
t.Fatal("canceled probe accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDesktopTunCaptureRoutesDoNotDuplicateProtection(t *testing.T) {
|
||||
data, err := (Config{ListenPort: 10818, Feature: "mesh", MeshSOCKS: "127.0.0.1:19001", MeshCIDRs: []string{"10.253.88.0/25"}, ProtectedCIDRs: []string{"10.253.88.0/25", "10.253.88.128/25"}, DesktopTun: true, PhysicalInterface: "en0"}).managedJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal(data, &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inbounds := config["inbounds"].([]any)
|
||||
addresses := inbounds[1].(map[string]any)["address"].([]any)
|
||||
if len(addresses) != 1 || addresses[0] != "172.19.0.1/30" {
|
||||
t.Fatalf("mesh-only TUN must not create implicit IPv6 default routes: %v", addresses)
|
||||
}
|
||||
routes := inbounds[1].(map[string]any)["route_address"].([]any)
|
||||
if len(routes) != 2 || routes[0] != "10.253.88.0/25" || routes[1] != "10.253.88.128/25" {
|
||||
t.Fatalf("unsafe capture routes: %v", routes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraceCannotLogOrdinaryNetworkProfiles(t *testing.T) {
|
||||
t.Setenv("MESHPORT_SELF_TEST_TRACE", "1")
|
||||
fixture := Config{Feature: "mesh", DesktopTun: true, MeshCIDRs: []string{"10.253.88.0/25"}}
|
||||
for _, change := range []func(*Config){
|
||||
func(c *Config) { c.MeshCIDRs = []string{"192.168.20.0/24"} },
|
||||
func(c *Config) { c.ProtectedCIDRs = []string{"192.168.21.0/24"} },
|
||||
func(c *Config) { c.MeshCIDRs = []string{"10.253.0.0/16"} },
|
||||
func(c *Config) { c.Feature = "combined" },
|
||||
func(c *Config) { c.DesktopTun = false },
|
||||
func(c *Config) { c.Proxy = map[string]any{"type": "socks"} },
|
||||
func(c *Config) { c.MeshCIDRs = nil },
|
||||
} {
|
||||
config := fixture
|
||||
change(&config)
|
||||
if config.selfTestTrace() {
|
||||
t.Fatal("self-test tracing accepted an ordinary network profile")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// C ABI owns numeric contexts and malloc-allocated UTF-8 JSON responses.
|
||||
package main
|
||||
|
||||
/*
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include "protector.h"
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
"meshport.local/singbox/bridge"
|
||||
)
|
||||
|
||||
type engineContext struct {
|
||||
mu sync.Mutex
|
||||
engine bridge.Engine
|
||||
closed bool
|
||||
}
|
||||
|
||||
var registry = struct {
|
||||
sync.Mutex
|
||||
contexts map[uint64]*engineContext
|
||||
}{contexts: make(map[uint64]*engineContext)}
|
||||
var next atomic.Uint64
|
||||
|
||||
type request struct {
|
||||
Directory string `json:"directory,omitempty"`
|
||||
Op string `json:"op"`
|
||||
Config *bridge.Config `json:"config,omitempty"`
|
||||
}
|
||||
|
||||
func dispatch(id uint64, data []byte) (any, error) {
|
||||
if len(data) > 65536 {
|
||||
return nil, errors.New("request too large")
|
||||
}
|
||||
var input request
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&input); err != nil {
|
||||
return nil, errors.New("invalid engine request")
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
return nil, errors.New("trailing request data")
|
||||
}
|
||||
registry.Lock()
|
||||
slot := registry.contexts[id]
|
||||
registry.Unlock()
|
||||
if slot == nil {
|
||||
return nil, errors.New("engine context is closed")
|
||||
}
|
||||
slot.mu.Lock()
|
||||
defer slot.mu.Unlock()
|
||||
if slot.closed {
|
||||
return nil, errors.New("engine context is closed")
|
||||
}
|
||||
switch input.Op {
|
||||
case "configure_cache":
|
||||
if slot.engine.Snapshot().State != "Stopped" || input.Directory == "" || !filepath.IsAbs(input.Directory) {
|
||||
return nil, errors.New("valid stopped-engine cache directory required")
|
||||
}
|
||||
info, err := os.Lstat(input.Directory)
|
||||
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return nil, errors.New("invalid cache directory")
|
||||
}
|
||||
slot.engine.CacheRoot = input.Directory
|
||||
case "probe_node":
|
||||
if input.Config == nil || input.Config.Proxy == nil {
|
||||
return nil, errors.New("draft node required")
|
||||
}
|
||||
return bridge.ProbeNode(context.Background(), input.Config.Proxy, input.Config.DNS, "https://www.gstatic.com/generate_204")
|
||||
case "start":
|
||||
if input.Config == nil {
|
||||
return nil, errors.New("managed configuration required")
|
||||
}
|
||||
if err := slot.engine.Start(context.Background(), *input.Config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "stop":
|
||||
if err := slot.engine.Stop(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "status":
|
||||
default:
|
||||
return nil, errors.New("unknown engine operation")
|
||||
}
|
||||
return slot.engine.Snapshot(), nil
|
||||
}
|
||||
func freeContext(id uint64) {
|
||||
registry.Lock()
|
||||
slot := registry.contexts[id]
|
||||
delete(registry.contexts, id)
|
||||
registry.Unlock()
|
||||
if slot != nil {
|
||||
slot.mu.Lock()
|
||||
defer slot.mu.Unlock()
|
||||
slot.closed = true
|
||||
_ = slot.engine.Close()
|
||||
}
|
||||
}
|
||||
|
||||
//export meshport_proxy_set_socket_protector
|
||||
func meshport_proxy_set_socket_protector(pointer C.uintptr_t) { C.proxy_set_protector(pointer) }
|
||||
|
||||
//export meshport_proxy_abi_version
|
||||
func meshport_proxy_abi_version() C.uint32_t { return 1 }
|
||||
|
||||
//export meshport_proxy_context_new
|
||||
func meshport_proxy_context_new() C.uint64_t {
|
||||
id := next.Add(1)
|
||||
registry.Lock()
|
||||
slot := &engineContext{}
|
||||
slot.engine.Protect = func(fd int) error {
|
||||
if C.proxy_protect(C.int(fd)) == 0 {
|
||||
return errors.New("platform socket protection failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
registry.contexts[id] = slot
|
||||
registry.Unlock()
|
||||
return C.uint64_t(id)
|
||||
}
|
||||
|
||||
//export meshport_proxy_context_free
|
||||
func meshport_proxy_context_free(id C.uint64_t) { freeContext(uint64(id)) }
|
||||
|
||||
//export meshport_proxy_call
|
||||
func meshport_proxy_call(id C.uint64_t, input *C.char) (output *C.char) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
output = C.CString(`{"ok":false,"error":"native engine failure"}`)
|
||||
}
|
||||
}()
|
||||
if input == nil {
|
||||
return C.CString(`{"ok":false,"error":"null request"}`)
|
||||
}
|
||||
result, err := dispatch(uint64(id), []byte(C.GoString(input)))
|
||||
envelope := map[string]any{"ok": err == nil}
|
||||
if err != nil {
|
||||
envelope["error"] = err.Error()
|
||||
} else {
|
||||
envelope["data"] = result
|
||||
}
|
||||
encoded, _ := json.Marshal(envelope)
|
||||
return C.CString(string(encoded))
|
||||
}
|
||||
|
||||
//export meshport_proxy_string_free
|
||||
func meshport_proxy_string_free(input *C.char) { C.free(unsafe.Pointer(input)) }
|
||||
func main() {}
|
||||
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestContext() uint64 {
|
||||
id := next.Add(1)
|
||||
registry.Lock()
|
||||
registry.contexts[id] = &engineContext{}
|
||||
registry.Unlock()
|
||||
return id
|
||||
}
|
||||
func TestABIRequestLifecycle(t *testing.T) {
|
||||
id := newTestContext()
|
||||
defer freeContext(id)
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
listener.Close()
|
||||
input, _ := json.Marshal(map[string]any{"op": "start", "config": map[string]any{"listen_port": port, "mesh_socks": "127.0.0.1:9", "mesh_cidrs": []string{"10.77.0.0/24"}}})
|
||||
if _, err := dispatch(id, input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := dispatch(id, input); err == nil {
|
||||
t.Fatal("duplicate start accepted")
|
||||
}
|
||||
for _, bad := range []string{`{"op":"status","extra":true}`, `{"op":"status"} {}`, `{"op":"start"}`, `{"op":"wrong"}`} {
|
||||
if _, err := dispatch(id, []byte(bad)); err == nil {
|
||||
t.Fatal("bad request accepted", bad)
|
||||
}
|
||||
}
|
||||
var wait sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wait.Add(1)
|
||||
go func() { defer wait.Done(); _, _ = dispatch(id, []byte(`{"op":"status"}`)) }()
|
||||
}
|
||||
freeContext(id)
|
||||
wait.Wait()
|
||||
if _, err := dispatch(id, []byte(`{"op":"status"}`)); err == nil {
|
||||
t.Fatal("freed context accepted")
|
||||
}
|
||||
probe, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(port)))
|
||||
if err != nil {
|
||||
t.Fatal("listener leaked", err)
|
||||
}
|
||||
probe.Close()
|
||||
}
|
||||
func jsonNumber(port int) string { data, _ := json.Marshal(port); return string(data) }
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "protector.h"
|
||||
#include <stdatomic.h>
|
||||
static _Atomic(uintptr_t) protector;
|
||||
void proxy_set_protector(uintptr_t value) { atomic_store(&protector, value); }
|
||||
int proxy_protect(int fd) {
|
||||
uintptr_t value = atomic_load(&protector);
|
||||
if (!value) return 0;
|
||||
return ((int (*)(int))value)(fd);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#include <stdint.h>
|
||||
void proxy_set_protector(uintptr_t pointer);
|
||||
int proxy_protect(int fd);
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"meshport.local/singbox/bridge"
|
||||
)
|
||||
|
||||
func run() error {
|
||||
if len(os.Args) != 2 {
|
||||
return fmt.Errorf("usage: meshport-singbox MANAGED-CONFIG.json")
|
||||
}
|
||||
file, err := os.Open(os.Args[1])
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot read managed configuration")
|
||||
}
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
if err != nil || info.Size() > 65536 {
|
||||
return fmt.Errorf("managed configuration exceeds size limit or cannot be read")
|
||||
}
|
||||
decoder := json.NewDecoder(io.LimitReader(file, 65537))
|
||||
decoder.DisallowUnknownFields()
|
||||
var config bridge.Config
|
||||
if err = decoder.Decode(&config); err != nil {
|
||||
return fmt.Errorf("invalid managed configuration")
|
||||
}
|
||||
var extra any
|
||||
if decoder.Decode(&extra) != io.EOF {
|
||||
return fmt.Errorf("invalid trailing configuration")
|
||||
}
|
||||
var engine bridge.Engine
|
||||
if err = engine.Start(context.Background(), config); err != nil {
|
||||
return err
|
||||
}
|
||||
defer engine.Stop()
|
||||
// One machine-readable readiness line, no configuration/credentials/log dump.
|
||||
if err = json.NewEncoder(os.Stdout).Encode(engine.Snapshot()); err != nil {
|
||||
return err
|
||||
}
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
defer signal.Stop(stop)
|
||||
<-stop
|
||||
return engine.Stop()
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
module meshport.local/singbox
|
||||
|
||||
go 1.25.5
|
||||
|
||||
require (
|
||||
github.com/sagernet/sing v0.9.7-0.20260929150544-0ad23b637bd4
|
||||
github.com/sagernet/sing-box v1.14.3
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||
github.com/caddyserver/certmagic v0.25.3-0.20260421143802-60d9d8b415d6 // indirect
|
||||
github.com/caddyserver/zerossl v0.1.5 // indirect
|
||||
github.com/database64128/netx-go v0.1.1 // indirect
|
||||
github.com/database64128/tfo-go/v2 v2.3.2 // indirect
|
||||
github.com/florianl/go-nfqueue/v2 v2.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.2.5 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||
github.com/gofrs/uuid/v5 v5.5.1 // indirect
|
||||
github.com/google/btree v1.1.3 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/hashicorp/yamux v0.1.2 // indirect
|
||||
github.com/jsimonetti/rtnetlink v1.4.1 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/libdns/acmedns v0.5.0 // indirect
|
||||
github.com/libdns/alidns v1.0.6 // indirect
|
||||
github.com/libdns/cloudflare v0.2.2 // indirect
|
||||
github.com/libdns/libdns v1.1.1 // indirect
|
||||
github.com/logrusorgru/aurora v2.0.3+incompatible // indirect
|
||||
github.com/mdlayher/netlink v1.11.2 // indirect
|
||||
github.com/mdlayher/socket v0.6.0 // indirect
|
||||
github.com/metacubex/utls v1.8.7 // indirect
|
||||
github.com/mholt/acmez/v3 v3.1.6 // indirect
|
||||
github.com/miekg/dns v1.1.72 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/sagernet/bbolt v0.0.0-20260915102804-500ee1e84832 // indirect
|
||||
github.com/sagernet/fswatch v0.1.2 // indirect
|
||||
github.com/sagernet/gvisor v0.0.0-20260727.0-sing-box-mod.1 // indirect
|
||||
github.com/sagernet/netlink v0.0.0-20260814022025-64455d367bbf // indirect
|
||||
github.com/sagernet/nftables v0.3.0-mod.4 // indirect
|
||||
github.com/sagernet/quic-go v0.61.0-sing-box-mod.9 // indirect
|
||||
github.com/sagernet/sing-mux v0.3.10-0.20260929204512-caf09fe32475 // indirect
|
||||
github.com/sagernet/sing-quic v0.7.2-0.20261002084117-75c3ac4fa12b // indirect
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9-0.20260929204512-65740e0f0e3e // indirect
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.2-0.20260929152114-a69d1086332b // indirect
|
||||
github.com/sagernet/sing-snell v0.0.0-20260904135315-bc5a12ac736f // indirect
|
||||
github.com/sagernet/sing-tun v0.9.7-0.20261009020158-bca4bf029237 // indirect
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260817040617-28bd42667eca // indirect
|
||||
github.com/sagernet/sing-vmess v0.2.9-0.20260929152519-9b95ab8c9478 // indirect
|
||||
github.com/sagernet/smux v1.5.50-sing-box-mod.1 // indirect
|
||||
github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 // indirect
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.1 // indirect
|
||||
go.uber.org/zap/exp v0.3.0 // indirect
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
|
||||
golang.org/x/crypto v0.54.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
|
||||
golang.org/x/mod v0.37.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect
|
||||
google.golang.org/grpc v1.79.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
lukechampine.com/blake3 v1.3.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,184 @@
|
||||
code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=
|
||||
code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM=
|
||||
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||
github.com/caddyserver/certmagic v0.25.3-0.20260421143802-60d9d8b415d6 h1:LYSB6VgWzKtNrcxElw3c97BP40Oc7bizKxA9K1Vi/5k=
|
||||
github.com/caddyserver/certmagic v0.25.3-0.20260421143802-60d9d8b415d6/go.mod h1:llW/CvsNmza8S6hmsuggsZeiX+uS27dkqY27wDIuBWg=
|
||||
github.com/caddyserver/zerossl v0.1.5 h1:dkvOjBAEEtY6LIGAHei7sw2UgqSD6TrWweXpV7lvEvE=
|
||||
github.com/caddyserver/zerossl v0.1.5/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cilium/ebpf v0.12.3 h1:8ht6F9MquybnY97at+VDZb3eQQr8ev79RueWeVaEcG4=
|
||||
github.com/cilium/ebpf v0.12.3/go.mod h1:TctK1ivibvI3znr66ljgi4hqOT8EYQjz1KWBfb1UVgM=
|
||||
github.com/database64128/netx-go v0.1.1 h1:dT5LG7Gs7zFZBthFBbzWE6K8wAHjSNAaK7wCYZT7NzM=
|
||||
github.com/database64128/netx-go v0.1.1/go.mod h1:LNlYVipaYkQArRFDNNJ02VkNV+My9A5XR/IGS7sIBQc=
|
||||
github.com/database64128/tfo-go/v2 v2.3.2 h1:UhZMKiMq3swZGUiETkLBDzQnZBPSAeBMClpJGlnJ5Fw=
|
||||
github.com/database64128/tfo-go/v2 v2.3.2/go.mod h1:GC3uB5oa4beGpCUbRb2ZOWP73bJJFmMyAVgQSO7r724=
|
||||
github.com/florianl/go-nfqueue/v2 v2.1.0 h1:Fywt30TY/evxyDySpXjxQ1jsRW7nQbLpOhELqpr4068=
|
||||
github.com/florianl/go-nfqueue/v2 v2.1.0/go.mod h1:8PKUM5rYoVFO5IZV1bifx4/b0jHAglKkHXr9PRwzi4Y=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
|
||||
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/gofrs/uuid/v5 v5.5.1 h1:z1Ce19/JwNidXpy3tOQc3241lnJLKdKyq/xlNvlD4Ng=
|
||||
github.com/gofrs/uuid/v5 v5.5.1/go.mod h1:bbAA98EoIlxyRHIVg6ektCSsZ5n8mSbwgEhvhMYlZgg=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
|
||||
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=
|
||||
github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
|
||||
github.com/jsimonetti/rtnetlink v1.4.1 h1:JfD4jthWBqZMEffc5RjgmlzpYttAVw1sdnmiNaPO3hE=
|
||||
github.com/jsimonetti/rtnetlink v1.4.1/go.mod h1:xJjT7t59UIZ62GLZbv6PLLo8VFrostJMPBAheR6OM8w=
|
||||
github.com/jsimonetti/rtnetlink/v2 v2.2.0 h1:/KfZ310gOAFrXXol5VwnFEt+ucldD/0dsSRZwpHCP9w=
|
||||
github.com/jsimonetti/rtnetlink/v2 v2.2.0/go.mod h1:lbjDHxC+5RJ08lzPeA90Ls2pEoId3F08MoEMlhfHxeI=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU=
|
||||
github.com/letsencrypt/challtestsrv v1.4.2/go.mod h1:GhqMqcSoeGpYd5zX5TgwA6er/1MbWzx/o7yuuVya+Wk=
|
||||
github.com/letsencrypt/pebble/v2 v2.10.0 h1:Wq6gYXlsY6ubqI3hhxsTzdyotvfdjFBxuwYqCLCnj/U=
|
||||
github.com/letsencrypt/pebble/v2 v2.10.0/go.mod h1:Sk8cmUIPcIdv2nINo+9PB4L+ZBhzY+F9A1a/h/xmWiQ=
|
||||
github.com/libdns/acmedns v0.5.0 h1:5pRtmUj4Lb/QkNJSl1xgOGBUJTWW7RjpNaIhjpDXjPE=
|
||||
github.com/libdns/acmedns v0.5.0/go.mod h1:X7UAFP1Ep9NpTwWpVlrZzJLR7epynAy0wrIxSPFgKjQ=
|
||||
github.com/libdns/alidns v1.0.6 h1:/Ii428ty6WHFJmE24rZxq2taq++gh7rf9jhgLfp8PmM=
|
||||
github.com/libdns/alidns v1.0.6/go.mod h1:RECwyQ88e9VqQVtSrvX76o1ux3gQUKGzMgxICi+u7Ec=
|
||||
github.com/libdns/cloudflare v0.2.2 h1:XWHv+C1dDcApqazlh08Q6pjytYLgR2a+Y3xrXFu0vsI=
|
||||
github.com/libdns/cloudflare v0.2.2/go.mod h1:w9uTmRCDlAoafAsTPnn2nJ0XHK/eaUMh86DUk8BWi60=
|
||||
github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U=
|
||||
github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
|
||||
github.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8=
|
||||
github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4=
|
||||
github.com/mdlayher/netlink v1.11.2 h1:HKh2jqe+omdSWcQ88nrT7INE61B0NXfiSPFdgL4YbNI=
|
||||
github.com/mdlayher/netlink v1.11.2/go.mod h1:uT2Yc/QLaZubzDpZIBi9d4GoeLwtp3x1AMeqSRrK2sA=
|
||||
github.com/mdlayher/socket v0.6.0 h1:ScZPaAGyO1icQnbFrhPM8mnXyMu9qukC1K4ZoM2IQKU=
|
||||
github.com/mdlayher/socket v0.6.0/go.mod h1:q7vozUAnxSqnjHc12Fik5yUKIzfZ8ITCfMkhOtE9z18=
|
||||
github.com/metacubex/utls v1.8.7 h1:Cp+yWkNTFkSihETgGWq34hlVFds5HpYWVOR1xovUVTs=
|
||||
github.com/metacubex/utls v1.8.7/go.mod h1:kncGGVhFaoGn5M3pFe3SXhZCzsbCJayNOH4UEqTKTko=
|
||||
github.com/mholt/acmez/v3 v3.1.6 h1:eGVQNObP0pBN4sxqrXeg7MYqTOWyoiYpQqITVWlrevk=
|
||||
github.com/mholt/acmez/v3 v3.1.6/go.mod h1:5nTPosTGosLxF3+LU4ygbgMRFDhbAVpqMI4+a4aHLBY=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/sagernet/bbolt v0.0.0-20260915102804-500ee1e84832 h1:KDXMGbzqLmDdKcld0T3wuMuqf1iezZq+DemgtZ/vhtQ=
|
||||
github.com/sagernet/bbolt v0.0.0-20260915102804-500ee1e84832/go.mod h1:7/qFPFH5fqK5XQeY8EA1Qpaly08Av77p38Zt50ieQww=
|
||||
github.com/sagernet/fswatch v0.1.2 h1:/TT7k4mkce1qFPxamLO842WjqBgbTBiXP2mlUjp9PFk=
|
||||
github.com/sagernet/fswatch v0.1.2/go.mod h1:5BpGmpUQVd3Mc5r313HRpvADHRg3/rKn5QbwFteB880=
|
||||
github.com/sagernet/gvisor v0.0.0-20260727.0-sing-box-mod.1 h1:IdQ7yTKkB2wv8txwshxUroPlO4npOYAV71xb7xQ7Lys=
|
||||
github.com/sagernet/gvisor v0.0.0-20260727.0-sing-box-mod.1/go.mod h1:9O3SQskYuCfdHNvHEsWuEAgoyKEF74PiWp4NsNUia8g=
|
||||
github.com/sagernet/netlink v0.0.0-20260814022025-64455d367bbf h1:b/3rm+KvxzuYRcnMdLq/hmcqX6/2B8k24l6SDHL2Piw=
|
||||
github.com/sagernet/netlink v0.0.0-20260814022025-64455d367bbf/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=
|
||||
github.com/sagernet/nftables v0.3.0-mod.4 h1:vnOtcDYeSXv2e5RoRuGH0lrpttQFJ8iC4ICS2nhlDSo=
|
||||
github.com/sagernet/nftables v0.3.0-mod.4/go.mod h1:8kslHG4VvYNihcco+i6uxIX7qbT8A56T0y5q7U44ZaQ=
|
||||
github.com/sagernet/quic-go v0.61.0-sing-box-mod.9 h1:Lojx77uC63TxZO38Z1OSo6aOoBSXY+ueH0/IKKeTZuI=
|
||||
github.com/sagernet/quic-go v0.61.0-sing-box-mod.9/go.mod h1:hmLC8GJPp+BrpBgrgJnacvI4fZGIhasuy1ROJJ8GR4E=
|
||||
github.com/sagernet/sing v0.9.7-0.20260929150544-0ad23b637bd4 h1:d4WT3KO4zhp9qzPHUZCKqCP+ZmP1GXBsAmReqlnE4zA=
|
||||
github.com/sagernet/sing v0.9.7-0.20260929150544-0ad23b637bd4/go.mod h1:K3Owt3xPhHugvlnlPPxZJ/exXdaJfEPOTNorGk4AXjo=
|
||||
github.com/sagernet/sing-box v1.14.3 h1:cBg8TP5SPWoMAlWqTqbSNdHGKPUciZisjQbLtqFlMZA=
|
||||
github.com/sagernet/sing-box v1.14.3/go.mod h1:Yei01EtPLnLTpLho05THCbqUwfidsaE/0vm1oSu+XQA=
|
||||
github.com/sagernet/sing-mux v0.3.10-0.20260929204512-caf09fe32475 h1:aG0DqHEOjax7DyfE1GTAXZotOg3QGVCz3/8rCSua2kg=
|
||||
github.com/sagernet/sing-mux v0.3.10-0.20260929204512-caf09fe32475/go.mod h1:jricpwCOndDsTEM1TM3piJvhL/2Mm7OhLkm+JadJJ1Q=
|
||||
github.com/sagernet/sing-quic v0.7.2-0.20261002084117-75c3ac4fa12b h1:2Jx/URJAPt32MEbLmAR5nzH87tO6NQZLRfRFvFqBWuk=
|
||||
github.com/sagernet/sing-quic v0.7.2-0.20261002084117-75c3ac4fa12b/go.mod h1:rJFeVxbEej2iuyeCJ3drKW+p5rOgtLIW3XhZ6ty7Fig=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9-0.20260929204512-65740e0f0e3e h1:LKgE/uuqp/D2kgxYViOz8vf4slaCUfpFywXjtuwD5gU=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9-0.20260929204512-65740e0f0e3e/go.mod h1:lo7TWEMDcN5/h5B8S0ew+r78ZODn6SwVaFhvB6H+PTI=
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.2-0.20260929152114-a69d1086332b h1:VH65QNqSHat2b+N3Rlzo5Qe44gRmQGwzY5atuy3D0A8=
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.2-0.20260929152114-a69d1086332b/go.mod h1:RnXS0lExcDAovvDeniJ4IKa2IuChrdipolPYWBv9hWQ=
|
||||
github.com/sagernet/sing-snell v0.0.0-20260904135315-bc5a12ac736f h1:tbTCI+iis5sTmua7a6Q7vebcSRURok/LGgnEafnQAsc=
|
||||
github.com/sagernet/sing-snell v0.0.0-20260904135315-bc5a12ac736f/go.mod h1:et8Lws4f5QbOrY65DmjevHGup3mijJkhswkto6cwciM=
|
||||
github.com/sagernet/sing-tun v0.9.7-0.20261009020158-bca4bf029237 h1:B9tUcRf1FAatPyzN8sKEvIHMvKNkFMBZikeIOL4gqtQ=
|
||||
github.com/sagernet/sing-tun v0.9.7-0.20261009020158-bca4bf029237/go.mod h1:3EgPst7agntRO7D6GOsiZ1l9FoqdLeuWmKT5TnWkmf0=
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260817040617-28bd42667eca h1:5wA+IE0Fq1CGVLOgSpm0gKKZ03HzugcJ2JyhmDqeX6A=
|
||||
github.com/sagernet/sing-usbip v0.0.0-20260817040617-28bd42667eca/go.mod h1:ADAZZU85MnM91XNhd2TdZRTaIbA7RjTZuQ1KCHcUbNg=
|
||||
github.com/sagernet/sing-vmess v0.2.9-0.20260929152519-9b95ab8c9478 h1:q2eQn4nq8oWGxRm9zXesXSlPr9GEgPrOGzf4iPtzG9A=
|
||||
github.com/sagernet/sing-vmess v0.2.9-0.20260929152519-9b95ab8c9478/go.mod h1:P11scgTxMxVVQ8dlM27yNm3Cro40mD0+gHbnqrNGDuY=
|
||||
github.com/sagernet/smux v1.5.50-sing-box-mod.1 h1:XkJcivBC9V4wBjiGXIXZ229aZCU1hzcbp6kSkkyQ478=
|
||||
github.com/sagernet/smux v1.5.50-sing-box-mod.1/go.mod h1:NjhsCEWedJm7eFLyhuBgIEzwfhRmytrUoiLluxs5Sk8=
|
||||
github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 h1:6uUiZcDRnZSAegryaUGwPC/Fj13JSHwiTftrXhMmYOc=
|
||||
github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854/go.mod h1:LtfoSK3+NG57tvnVEHgcuBW9ujgE8enPSgzgwStwCAA=
|
||||
github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
|
||||
github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
|
||||
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||
github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
|
||||
github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
|
||||
github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=
|
||||
github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=
|
||||
github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
|
||||
go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
|
||||
go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
|
||||
go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
|
||||
go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
|
||||
go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
|
||||
go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
|
||||
go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
|
||||
go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
|
||||
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY=
|
||||
google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
lukechampine.com/blake3 v1.3.0 h1:sJ3XhFINmHSrYCgl958hscfIa3bw8x4DqMP3u1YvoYE=
|
||||
lukechampine.com/blake3 v1.3.0/go.mod h1:0OFRp7fBtAylGVCO40o87sbupkyIGgbpv1+M1k1LM6k=
|
||||
@@ -0,0 +1,13 @@
|
||||
# Pinned sing-box rule-set patch
|
||||
|
||||
Upstream: sing-box **v1.14.3**, GPL-3.0-or-later; license copy in `docs/upstream/sing-box-LICENSE`.
|
||||
|
||||
`rule_set_remote.go.txt` is the pinned source with MeshPort's small changes:
|
||||
|
||||
- Match, merge, string rendering, cleanup and close synchronize rule-list access with the existing RWMutex. Upstream already locked replacement and metadata, but did not lock all readers/clear operations. The remote refresh integration test reproduced this with `go test -race`.
|
||||
- Remote downloads have a 30-second deadline, a 32 MiB response limit and at most five HTTPS redirects. HTTP downgrade and URL authentication are rejected.
|
||||
- Failed fetch or parsing leaves the last good rules intact.
|
||||
|
||||
`sh scripts/go-local.sh ...` prepares an 11 MiB private module copy under ignored `work/singbox-patched`, verifies the original rule source hash, and uses an alternate modfile. The shared download cache, tracked `go.mod` and dependency checksums are unchanged. All project Go build/test scripts use this wrapper. Invoke it for development builds too; raw `go build` uses the unpatched upstream module.
|
||||
|
||||
The `.txt` suffix prevents Go from treating the patch directory as a standalone package. Review and rebase this patch explicitly when updating the pinned version.
|
||||
@@ -0,0 +1,360 @@
|
||||
// MeshPort patch of sing-box v1.14.3: synchronized rule snapshots and bounded HTTPS fetch.
|
||||
// Copyright (C) 2022 nekohasekai; licensed under GPL-3.0-or-later.
|
||||
// Upstream license: docs/upstream/sing-box-LICENSE.
|
||||
package rule
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/srs"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
"github.com/sagernet/sing/common/x/list"
|
||||
"github.com/sagernet/sing/service"
|
||||
"github.com/sagernet/sing/service/filemanager"
|
||||
"github.com/sagernet/sing/service/pause"
|
||||
|
||||
"go4.org/netipx"
|
||||
)
|
||||
|
||||
var _ adapter.RuleSet = (*RemoteRuleSet)(nil)
|
||||
|
||||
type RemoteRuleSet struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
logger logger.ContextLogger
|
||||
outbound adapter.OutboundManager
|
||||
tag string
|
||||
url string
|
||||
urlHash [32]byte
|
||||
initialPath string
|
||||
options option.RuleSet
|
||||
updateInterval time.Duration
|
||||
httpClient *http.Client
|
||||
access sync.RWMutex
|
||||
rules []adapter.HeadlessRule
|
||||
metadata adapter.RuleSetMetadata
|
||||
lastUpdated time.Time
|
||||
lastEtag string
|
||||
cacheFile adapter.CacheFile
|
||||
pauseManager pause.Manager
|
||||
callbacks list.List[adapter.RuleSetUpdateCallback]
|
||||
refs atomic.Int32
|
||||
}
|
||||
|
||||
func NewRemoteRuleSet(ctx context.Context, logger logger.ContextLogger, tag string, options option.RuleSet) (*RemoteRuleSet, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
var updateInterval time.Duration
|
||||
if options.RemoteOptions.UpdateInterval > 0 {
|
||||
updateInterval = time.Duration(options.RemoteOptions.UpdateInterval)
|
||||
} else {
|
||||
updateInterval = 24 * time.Hour
|
||||
}
|
||||
var initialPath string
|
||||
if options.RemoteOptions.InitialPath != "" {
|
||||
initialPath = filemanager.BasePath(ctx, strings.ReplaceAll(options.RemoteOptions.InitialPath, C.RuleSetTagPlaceholder, tag))
|
||||
initialPath, _ = filepath.Abs(initialPath)
|
||||
}
|
||||
url := strings.ReplaceAll(options.RemoteOptions.URL, C.RuleSetTagPlaceholder, tag)
|
||||
return &RemoteRuleSet{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
outbound: service.FromContext[adapter.OutboundManager](ctx),
|
||||
logger: logger,
|
||||
tag: tag,
|
||||
url: url,
|
||||
urlHash: sha256.Sum256([]byte(url)),
|
||||
initialPath: initialPath,
|
||||
options: options,
|
||||
updateInterval: updateInterval,
|
||||
pauseManager: service.FromContext[pause.Manager](ctx),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Name() string {
|
||||
return s.tag
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) String() string {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return strings.Join(F.MapToString(s.rules), " ")
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) StartContext(ctx context.Context, startContext *adapter.HTTPStartContext) error {
|
||||
s.cacheFile = service.FromContext[adapter.CacheFile](s.ctx)
|
||||
transport, err := s.resolveTransport()
|
||||
if err != nil {
|
||||
return E.Cause(err, "create rule-set http client")
|
||||
}
|
||||
startContext.Register(transport)
|
||||
s.httpClient = &http.Client{Transport: transport, Timeout: 30 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if req.URL.Scheme != "https" || req.URL.User != nil || len(via) >= 5 {
|
||||
return E.New("rule-set redirect must remain HTTPS and within five hops")
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
if s.cacheFile != nil {
|
||||
savedSet := s.cacheFile.LoadRuleSet(s.tag)
|
||||
if savedSet != nil {
|
||||
if len(savedSet.URLHash) > 0 && !bytes.Equal(savedSet.URLHash, s.urlHash[:]) {
|
||||
s.logger.Info("cached rule-set was downloaded from another URL, will refetch")
|
||||
} else {
|
||||
err = s.loadBytes(savedSet.Content)
|
||||
if err != nil {
|
||||
s.logger.Warn(E.Cause(err, "restore cached rule-set, will refetch"))
|
||||
} else {
|
||||
s.lastUpdated = savedSet.LastUpdated
|
||||
s.lastEtag = savedSet.LastEtag
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var loadedFromInitialPath bool
|
||||
if s.lastUpdated.IsZero() && s.initialPath != "" {
|
||||
var content []byte
|
||||
content, err = filemanager.ReadFile(s.ctx, s.initialPath)
|
||||
if err == nil {
|
||||
err = s.loadBytes(content)
|
||||
}
|
||||
if err != nil {
|
||||
s.logger.Warn(E.Cause(err, "load initial rule-set from ", s.initialPath))
|
||||
} else {
|
||||
loadedFromInitialPath = true
|
||||
}
|
||||
}
|
||||
if s.lastUpdated.IsZero() && !loadedFromInitialPath {
|
||||
err = s.fetch(ctx, true)
|
||||
if err != nil {
|
||||
return E.Cause(err, "initial rule-set: ", s.tag)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Metadata() adapter.RuleSetMetadata {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return s.metadata
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) ExtractIPSet() []*netipx.IPSet {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return common.FlatMap(s.rules, extractIPSetFromRule)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) IncRef() {
|
||||
s.refs.Add(1)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) DecRef() {
|
||||
if s.refs.Add(-1) < 0 {
|
||||
panic("rule-set: negative refs")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Cleanup() {
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
if s.refs.Load() == 0 {
|
||||
s.rules = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) RegisterCallback(callback adapter.RuleSetUpdateCallback) *list.Element[adapter.RuleSetUpdateCallback] {
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
return s.callbacks.PushBack(callback)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) UnregisterCallback(element *list.Element[adapter.RuleSetUpdateCallback]) {
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
s.callbacks.Remove(element)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) loadBytes(content []byte) error {
|
||||
var (
|
||||
ruleSet option.PlainRuleSetCompat
|
||||
err error
|
||||
)
|
||||
switch s.options.Format {
|
||||
case C.RuleSetFormatSource:
|
||||
ruleSet, err = json.UnmarshalExtended[option.PlainRuleSetCompat](content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case C.RuleSetFormatBinary:
|
||||
ruleSet, err = srs.Read(bytes.NewReader(content), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return E.New("unknown rule-set format: ", s.options.Format)
|
||||
}
|
||||
plainRuleSet, err := ruleSet.Upgrade()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rules := make([]adapter.HeadlessRule, len(plainRuleSet.Rules))
|
||||
for i, ruleOptions := range plainRuleSet.Rules {
|
||||
rules[i], err = NewHeadlessRule(s.ctx, ruleOptions)
|
||||
if err != nil {
|
||||
return E.Cause(err, "parse rule_set.rules.[", i, "]")
|
||||
}
|
||||
}
|
||||
metadata := buildRuleSetMetadata(plainRuleSet.Rules)
|
||||
err = validateRuleSetMetadataUpdate(s.ctx, s.tag, metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.access.Lock()
|
||||
s.metadata = metadata
|
||||
s.rules = rules
|
||||
callbacks := s.callbacks.Array()
|
||||
s.access.Unlock()
|
||||
for _, callback := range callbacks {
|
||||
callback(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) updateOnce() {
|
||||
err := s.fetch(s.ctx, false)
|
||||
if err != nil {
|
||||
s.logger.Error("fetch rule-set ", s.tag, ": ", err)
|
||||
} else {
|
||||
s.Cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) fetch(ctx context.Context, isStart bool) error {
|
||||
s.logger.Debug("updating rule-set ", s.tag, " from URL: ", s.url)
|
||||
request, err := http.NewRequest("GET", s.url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.lastEtag != "" {
|
||||
request.Header.Set("If-None-Match", s.lastEtag)
|
||||
}
|
||||
if !isStart {
|
||||
defer s.httpClient.CloseIdleConnections()
|
||||
}
|
||||
response, err := s.httpClient.Do(request.WithContext(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
switch response.StatusCode {
|
||||
case http.StatusOK:
|
||||
case http.StatusNotModified:
|
||||
s.lastUpdated = time.Now()
|
||||
if s.cacheFile != nil {
|
||||
savedRuleSet := s.cacheFile.LoadRuleSet(s.tag)
|
||||
if savedRuleSet != nil {
|
||||
savedRuleSet.LastUpdated = s.lastUpdated
|
||||
savedRuleSet.URLHash = s.urlHash[:]
|
||||
err = s.cacheFile.SaveRuleSet(s.tag, savedRuleSet)
|
||||
if err != nil {
|
||||
s.logger.Error("save rule-set updated time: ", err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
s.logger.Info("update rule-set ", s.tag, ": not modified")
|
||||
return nil
|
||||
default:
|
||||
return E.New("unexpected status: ", response.Status)
|
||||
}
|
||||
const maxRuleSetBytes = 32 * 1024 * 1024
|
||||
content, err := io.ReadAll(io.LimitReader(response.Body, maxRuleSetBytes+1))
|
||||
if len(content) > maxRuleSetBytes {
|
||||
return E.New("rule-set exceeds 32 MiB")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.loadBytes(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
eTagHeader := response.Header.Get("Etag")
|
||||
if eTagHeader != "" {
|
||||
s.lastEtag = eTagHeader
|
||||
}
|
||||
s.lastUpdated = time.Now()
|
||||
if s.cacheFile != nil {
|
||||
err = s.cacheFile.SaveRuleSet(s.tag, &adapter.SavedBinary{
|
||||
LastUpdated: s.lastUpdated,
|
||||
Content: content,
|
||||
LastEtag: s.lastEtag,
|
||||
URLHash: s.urlHash[:],
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Error("save rule-set cache: ", err)
|
||||
}
|
||||
}
|
||||
s.logger.Info("updated rule-set ", s.tag)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) resolveTransport() (adapter.HTTPTransport, error) {
|
||||
httpClientManager := service.FromContext[adapter.HTTPClientManager](s.ctx)
|
||||
if s.options.RemoteOptions.HTTPClient != nil && !s.options.RemoteOptions.HTTPClient.IsEmpty() {
|
||||
if s.options.RemoteOptions.DownloadDetour != "" { //nolint:staticcheck
|
||||
return nil, E.New("http_client is conflict with deprecated download_detour field")
|
||||
}
|
||||
return httpClientManager.ResolveTransport(s.ctx, s.logger, *s.options.RemoteOptions.HTTPClient)
|
||||
}
|
||||
if s.options.RemoteOptions.DownloadDetour != "" { //nolint:staticcheck
|
||||
deprecated.Report(s.ctx, deprecated.OptionLegacyRuleSetDownloadDetour)
|
||||
return httpClientManager.ResolveTransport(s.ctx, s.logger, option.HTTPClientOptions{
|
||||
DialerOptions: option.DialerOptions{
|
||||
Detour: s.options.RemoteOptions.DownloadDetour, //nolint:staticcheck
|
||||
},
|
||||
DisableEmptyDirectCheck: true,
|
||||
})
|
||||
}
|
||||
defaultTransport := httpClientManager.DefaultTransport()
|
||||
if defaultTransport == nil {
|
||||
return nil, E.New("default http client transport is not initialized")
|
||||
}
|
||||
return defaultTransport, nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Close() error {
|
||||
s.cancel()
|
||||
s.access.Lock()
|
||||
s.rules = nil
|
||||
s.access.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) Match(metadata *adapter.InboundContext) bool {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return matchAnyHeadlessRule(s.rules, metadata)
|
||||
}
|
||||
|
||||
func (s *RemoteRuleSet) mergeableRule() *DefaultHeadlessRule {
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return mergeableRuleIn(s.rules)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# MeshPort 代理与组网移动端原型
|
||||
|
||||
工具:内置 imagegen。图片为设计预览,指标及节点状态为示例数据。
|
||||
|
||||
生成提示词要点:浅色、高保真、简体中文、四个完整手机界面并排,沿用 MeshPort 青蓝色网络节点 Logo、暖白背景、白色圆角卡片、细边框及青色选中状态。
|
||||
|
||||
- 概览:仅组网、仅代理、代理+组网三种运行功能;代理规则、全局、直连切换;独立组网状态;上传下载速度、趋势图、每个节点的延迟及流量;连接控制。
|
||||
- 代理:模式切换、当前节点、节点列表、手动或自动选择、导入配置、更新订阅。
|
||||
- 组网:本机虚拟地址、在线节点、直连与中继路径、各节点延迟和流量、自动接入公告子网、线路策略。
|
||||
- 设置:默认网络、组网和代理配置、保存与恢复配置、启动自动连接、DNS、分流规则、自动接入公告子网、诊断及日志。
|
||||
|
||||
所有页面底部导航统一为概览、代理、组网、设置。全局代理仍保留组网地址通过 MeshPort 的优先规则。消费者界面不显示 JNI、FFI 等实现细节。正式实现时校正生成图片中的个别文字排版和地址,不能将图内数据作为真实连接状态。
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
@@ -0,0 +1,36 @@
|
||||
# MeshPort 移动端完整原型
|
||||
|
||||
> 此版本已由 [V4 修订版](meshport-ui-v4-index.md)替代;保留作为设计历史。
|
||||
|
||||
沿用暖白背景、青蓝色选中状态、卡片布局与 MeshPort 标识。包含既有四个主页面和本轮补充的二十个页面,共二十四个。
|
||||
|
||||
| 原型图 | 页面 |
|
||||
| --- | --- |
|
||||
| [主页面](meshport-proxy-network-mobile-v3.png) | 概览、代理、组网、设置 |
|
||||
| [代理配置与订阅](meshport-ui-v3-proxy.png) | 导入代理配置、订阅管理、代理节点详情、分流规则 |
|
||||
| [组网配置](meshport-ui-v3-network-config.png) | 基础配置、连接与打洞、高级配置、线路策略 |
|
||||
| [节点与路由](meshport-ui-v3-network-details.png) | 节点详情、自动接入子网、子网详情、网络诊断 |
|
||||
| [应用设置](meshport-ui-v3-settings.png) | DNS 设置、默认配置、启动与后台、运行日志 |
|
||||
| [引导与编辑](meshport-ui-v3-editors.png) | 首次使用、添加代理节点、编辑订阅、编辑分流规则 |
|
||||
|
||||
## 页面入口
|
||||
|
||||
- 概览:运行功能与代理模式快捷切换;节点进入节点详情,当前代理进入代理节点详情。
|
||||
- 代理:配置导入进入导入页;配置管理进入订阅管理;节点详情进入节点编辑;分流规则进入单条规则编辑。
|
||||
- 组网:网络配置进入基础、连接和高级配置;节点进入详情;公告子网进入列表及详情;线路策略独立编辑;连通性检查进入诊断。
|
||||
- 设置:默认配置、DNS、后台运行、网络诊断和日志分别进入对应子页。
|
||||
- 首次使用:选择运行功能、导入缺失配置,然后进入首页;VPN 授权保留系统确认流程。
|
||||
|
||||
## 实现边界
|
||||
|
||||
这些图片是目标交互设计,不表示所有开关已实现。实现时以 SDK 的有效配置字段、实际内核能力和平台权限为准;暂不支持的选项需禁用并说明原因。
|
||||
|
||||
组网地址和符合规则的公告子网始终优先通过 MeshPort;全局代理不能覆盖这一规则。外层连接需排除自身隧道以避免循环。
|
||||
|
||||
自动学习远端子网与发布本地子网是两个不同功能,不能把远端子网填写为本机发布项。默认配置只是预填;启动自动连接为单独的显式选择。
|
||||
|
||||
订阅首版可支持 sing-box JSON;其他订阅格式需要额外转换能力。规则编辑中的通配符是用户界面表达,需转换为对应的域名规则。
|
||||
|
||||
线路阈值、版本、延迟、流量和测试结果均为示例。生成图中的个别文字、图标和布局需在实现时校正。Android 后台与开机启动、macOS 登录启动应按各平台能力分别处理。
|
||||
|
||||
[完整生成提示词](meshport-ui-v3-prompts.md)
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
@@ -0,0 +1,24 @@
|
||||
# MeshPort 完整移动端原型生成提示词
|
||||
|
||||
工具:内置 imagegen。所有页面均为设计预览,数据为虚构示例。
|
||||
|
||||
## Board A
|
||||
|
||||
High-fidelity mobile UI prototype board for MeshPort. Four complete Android phone screens side by side, wide landscape, straight-on, generous gutters, all full screens including bottom actions visible. Chinese text sharp readable. Same visual system as preceding MeshPort prototypes: warm ivory background #F8F7F3, white rounded cards, fine grey borders, pale cyan selected controls, dark charcoal typography, teal #137A88 accents, restrained shadows, compact practical layouts. Rounded blue-teal square logo with white M connected nodes. Each screen status bar 18:17. No dark theme, no purple, no technical implementation jargon, no credentials. All data fictional. Each screen has back chevron, short Chinese heading and relevant save or add action. Subpages do NOT need bottom navigation; use full content area and fixed bottom action where appropriate. Labels above each phone name its page. All toggles and form controls usable-looking, no overflowing text. Board A: 代理配置与订阅. Screen 1 导入代理配置: top segmented 订阅链接 / 配置文件 / 扫码; 订阅链接 selected. Form cards 配置名称 自用代理; 订阅地址 https://example.com/sub; helper 支持订阅链接与 sing-box JSON. Secondary action 从剪贴板粘贴. Checkbox 自动更新 enabled; interval 每 24 小时. Small preview 检测到 8 个节点 with three example rows 日本·东京 VLESS, 香港 Trojan, 新加坡 Shadowsocks. Bottom button 导入配置. Screen 2 订阅管理: toolbar plus. Card 自用代理 8 个节点; 更新于 今天 18:05; next update 明天 18:05; actions 更新 / 编辑, enable toggle. Another card 备用代理 3 个节点 已停用 toggleoff. Small informational banner 更新失败时保留现有配置. Footer 最近更新记录 with 成功 更新了 8 个节点 and timestamp. Screen 3 代理节点详情: header 日本·东京; top latency85ms card, 协议 VLESS, 可用 pill; select button 使用此节点. Form readonly-labelled rows 服务器 jp.example.com; 端口443; 传输 TCP; TLS 已启用; server name jp.example.com; 身份凭据 •••••••• with eye icon. Small recent latency sparkline with min78ms max96ms. Footer 测试连接 and 编辑节点. Screen4 分流规则: header with add. Sticky information card 组网地址优先通过 MeshPort; do not let movable internet rules override mesh. Tabs 域名 / IP / 规则集, 规则集 selected. List 国内网站 → 直连 enabled; 广告过滤 → 拦截 enabled; 其他网站 → 当前代理 enabled. section 默认出口 当前代理 chevron. Bottom 导入规则集. Show drag handles only on configurable internet rules.
|
||||
|
||||
## Board B
|
||||
|
||||
High-fidelity mobile UI prototype board for MeshPort. Four complete Android phone screens side by side, wide landscape, straight-on, generous gutters, all full screens including bottom actions visible. Chinese text sharp readable. Same visual system as preceding MeshPort prototypes: warm ivory background #F8F7F3, white rounded cards, fine grey borders, pale cyan selected controls, dark charcoal typography, teal #137A88 accents, restrained shadows, compact practical layouts. Rounded blue-teal square logo with white M connected nodes. Each screen status bar 18:17. No dark theme, no purple, no technical implementation jargon, no credentials. All data fictional. Each screen has back chevron, short Chinese heading and relevant save or add action. Subpages do NOT need bottom navigation; use full content area and fixed bottom action where appropriate. Labels above each phone name its page. All toggles and form controls usable-looking, no overflowing text. Board B: 组网配置. FOUR screen titles 基础配置 / 连接与打洞 / 高级配置 / 线路策略. All are form subpages with back arrow and 保存 top right, no bottom navigation. Screen1 基础配置: cyan intro 网络配置 GameNet. label fields 网络名称 GameNet; 网络密钥 •••••••• eye; 节点名称 MeshPort-Android; 虚拟 IPv4 192.168.20.6 / 24 (prefix separate small control); 自动分配地址 disabled switch grey helper 当前系统模式使用静态地址. Section 组网方式 selected 手动 with 公共节点 and 独立 options; 初始节点 list tcp://relay-us.example.com:52015 and tcp://relay-jp.example.com:52015 with remove icons; outline 添加初始节点. Bottom 导入 TOML配置 and 保存配置. Screen2 连接与打洞: group 连接 with 首选协议 UDP chevron, 监听地址 row udp://0.0.0.0:11010 and 添加监听地址. group NAT 穿透 four ON toggles 启用 P2P / UDP 打洞 / TCP 打洞 / 对称 NAT 打洞; UPnP toggleOFF. group STUN 默认服务器 selected, 自定义服务器 chevron, IPv6 STUN chevron. Cyan footer label NAT 状态 UDP PortRestricted / TCP Unknown; 测试 NAT button. Screen3 高级配置: group 安全与性能 toggle 私有网络模式 ON, 加密传输 ON, 多线程 ON, 仅使用物理网卡 ON; group 协议 toggle IPv6 ON, KCP 代理 OFF, QUIC 代理 OFF; note 代理协议能力以所选内核构建为准. group 网络服务 rows 发布本地子网 chevron; 出口节点 OFF; 系统转发 OFF; 网络内 DNS OFF. Bottom subtle expert action 查看完整 TOML. Screen4 线路策略: cyan selected recommendation card 自适应 with text 质量接近优先直连,明显改善才用中继. Radio alternatives 直连优先 / 延迟优先 / 指定中继. Group 调整参数 rows 中继改善门槛 30 ms; 切换确认次数 3 次; 最短保持时间30秒; UDP优先 switchON. Group 候选中继 rows 自动发现 selected, 手动选择 chevron. Information strip 参数为示例,实际阈值以测试确定. Small summary 当前路径 直连 → DIG-US 167ms. Attractive readable full phones, clean exact Chinese text.
|
||||
|
||||
## Board C
|
||||
|
||||
High-fidelity mobile UI prototype board for MeshPort. Four complete Android phone screens side by side, wide landscape, straight-on, generous gutters, all full screens including bottom actions visible. Chinese text sharp readable. Same visual system as preceding MeshPort prototypes: warm ivory background #F8F7F3, white rounded cards, fine grey borders, pale cyan selected controls, dark charcoal typography, teal #137A88 accents, restrained shadows, compact practical layouts. Rounded blue-teal square logo with white M connected nodes. Each screen status bar 18:17. No dark theme, no purple, no technical implementation jargon, no credentials. All data fictional. Each screen has back chevron, short Chinese heading and relevant save or add action. Subpages do NOT need bottom navigation; use full content area and fixed bottom action where appropriate. Labels above each phone name its page. All toggles and form controls usable-looking, no overflowing text. Board C: 节点、路由与诊断. Four complete phone subpages: 节点详情 / 自动接入子网 / 子网详情 / 网络诊断. Screen1 节点详情 for Redmi_AX6. Cyan hero card green 在线, 192.168.20.3, 7 ms big and small 链路 RTT. compact metrics 直连 UDP / 丢包0.0%; ↓82KB/s ↑35KB/s; 累计下载4.9MB 上传5.5MB. Sparkline last60seconds. group 连接信息 rows 当前路径 本机 → Redmi_AX6; 远端地址203.0.113.10:25423; UDP NAT PortRestricted; 内核版本2.6.4. group 公告子网 192.168.21.0/24 已接入 chevron. Footer 测试连通性 button. Screen2 自动接入子网: cyan banner 自动学习节点公告,无需手动填写远端子网. Segmented 已接入2 / 未接入1. accepted cards 192.168.21.0/24, 发布节点 Redmi_AX6, 当前下一跳 Redmi_AX6, green 已接入; 10.80.0.0/24, 发布节点 NAS, 当前下一跳 Redmi_AX6, green 已接入. Group 接入规则 compact rows 私有 IPv4; 前缀 /16 至 /32; 最大32条. explanatory rejected example 192.168.20.0/24 未接入 与虚拟网段重叠, muted amber card. Bottom 刷新公告 secondary button. Screen3 子网详情: hero 192.168.21.0/24 已接入. rows 发布节点Redmi_AX6; 下一跳Redmi_AX6; 模式自动接入; 系统路由已安装; 更新时间18:16. Simple readable linear path vertically 本机192.168.20.6 → Redmi_AX6 192.168.20.3 → 目标设备192.168.21.201. Section 连通性测试 field目标地址192.168.21.201 field端口5900; teal 测试连接. Last result green TCP 可达 12ms, helper 延迟为示例. footer note 节点撤销公告后自动移除此路由, no manual subnet entry toggle. Screen4 网络诊断: target field192.168.21.201:5900; segmented TCP / UDP / 路径, TCP active. count输入10次, timeout3秒. filled 开始检测. Results card green 10/10 成功; 最小7ms 平均12ms 最大18ms 丢包0%. group 当前路径 本机 → Redmi_AX6 → 目标设备. compact checklist 虚拟网卡已就绪 / 公告子网已安装 / 目标端口可达 green checks. bottom 导出诊断报告. No real secrets. Strong visual alignment.
|
||||
|
||||
## Board D
|
||||
|
||||
High-fidelity mobile UI prototype board for MeshPort. Four complete Android phone screens side by side, wide landscape, straight-on, generous gutters, all full screens including bottom actions visible. Chinese text sharp readable. Same visual system as preceding MeshPort prototypes: warm ivory background #F8F7F3, white rounded cards, fine grey borders, pale cyan selected controls, dark charcoal typography, teal #137A88 accents, restrained shadows, compact practical layouts. Rounded blue-teal square logo with white M connected nodes. Each screen status bar 18:17. No dark theme, no purple, no technical implementation jargon, no credentials. All data fictional. Each screen has back chevron, short Chinese heading and relevant save or add action. Subpages do NOT need bottom navigation; use full content area and fixed bottom action where appropriate. Labels above each phone name its page. All toggles and form controls usable-looking, no overflowing text. Board D: 应用设置. Four full mobile settings subpages DNS设置 / 默认配置 / 启动与后台 / 运行日志. Screen1 DNS设置: top save. group 解析策略 segmented 自动 / 自定义, 自定义 selected. Cards 直连DNS 系统 DNS chevron; 代理DNS https://dns.example.com/dns-query chevron; 组网DNS 未配置 chevron helper 仅对组网内域名生效. toggles DNS缓存 ON; FakeIP OFF; helper 组网内域名使用独立解析规则. group 测试解析 input example.com; outlined 测试; results 203.0.113.20 46ms small fictional result. Bottom 恢复默认 secondary. Screen2 默认配置: hero 当前默认配置 自用网络 grey 私人配置. list 组网 GameNet; 虚拟地址192.168.20.6/24; 初始节点2个; 代理配置自用代理. Group 保存与恢复 switches 保存配置 ON; 启动恢复上次配置 ON; 启动自动连接 OFF. Banner 优先读取已保存配置,没有保存配置时使用安装包默认值. Buttons 保存当前配置 teal; 恢复安装包默认值 outline; 删除已保存配置 discreet red text with confirmation icon. footnote 敏感配置保存在设备安全存储中. Screen3 启动与后台: group启动 switches 开机启动 OFF; 打开应用自动连接 OFF; 恢复上次运行功能 ON; group后台 安卓前台通知 已启用 with green check and helper 持续组网时显示通知; 电池优化 未放行 amber and button前往系统设置; 后台运行权限 未检查 chevron. group断线恢复 自动重连 ON; 重试间隔自动退避 chevron; 网络变化时重试ON. blue note VPN授权由系统确认,其他VPN可能中断当前连接. Bottom 检查运行环境. Screen4运行日志: header分享icon. chips 全部 / 组网 / 代理 / 路由 / 错误 with全部 selected; search搜索日志. scrollable log card chronological examples 18:17:08 [路由] 接入192.168.21.0/24, 18:17:07 [组网] Redmi_AX6直连建立, 18:17:06 [代理] 日本·东京可用85ms, 18:17:05 [系统] 虚拟网卡已就绪, 18:17:04 [配置] 载入保存配置, 18:16:59 [代理] 备用节点超时 (amber). Each row short and well-spaced. Group 日志级别 信息 chevron; 隐藏敏感信息 ON. footer 导出日志 outlined and 清空日志 secondary. No passwords, no private URLs, no internal code symbol names.
|
||||
|
||||
## Board E
|
||||
|
||||
High-fidelity mobile UI prototype board for MeshPort. Four complete Android phone screens side by side, wide landscape, straight-on, generous gutters, all full screens including bottom actions visible. Chinese text sharp readable. Same visual system as preceding MeshPort prototypes: warm ivory background #F8F7F3, white rounded cards, fine grey borders, pale cyan selected controls, dark charcoal typography, teal #137A88 accents, restrained shadows, compact practical layouts. Rounded blue-teal square logo with white M connected nodes. Each screen status bar 18:17. No dark theme, no purple, no technical implementation jargon, no credentials. All data fictional. Each screen has back chevron, short Chinese heading and relevant save or add action. Subpages do NOT need bottom navigation; use full content area and fixed bottom action where appropriate. Labels above each phone name its page. All toggles and form controls usable-looking, no overflowing text. Board E: 配置编辑与首次使用. Four full phones with page labels 首次使用 / 添加代理节点 / 编辑订阅 / 编辑分流规则. Screen1首次使用: small logo MeshPort and subtitle 代理与组网,一个客户端. No back button here. Section选择使用方式 three large clean radio cards: 仅组网 helper访问游戏服务器与远端内网; 仅代理 helper按规则代理上网; 代理+组网 selectedcyan helper同时使用代理和虚拟网络. section配置状态 rows 默认组网配置已载入 greencheck; 代理配置待导入 amber plusbutton导入配置. Section系统权限 small card VPN授权未申请 with helper首次连接时由系统请求授权. Checkbox记住我的选择 ON. bottom开始使用 teal. No automatic connection action without VPN authorization. Screen2添加代理节点: header取消 left保存 right. Dropdown协议VLESS chevron. text fields节点名称日本·东京; 服务器jp.example.com; 端口443; 身份ID •••••••••••• with eye. segmented传输 TCP / WebSocket / gRPC, TCPselected. TLS toggleON; dropdown安全方式TLS (can switch toReality); 服务器名称jp.example.com; certificatevalidationON. footer折叠 高级参数 chevron; 测试连接 outline; 创建节点 teal. Display this as a VLESS example, avoid passwords. Screen3编辑订阅: header返回 保存. group基本信息 配置名称自用代理; 订阅地址https://example.com/sub with clipboard icon. group更新 自动更新ON; 更新间隔24小时 chevron; 仅Wi-Fi更新OFF; helper关闭时允许移动网络更新. group保留设置 保留手动节点ON; 保留当前节点选择ON. preview card最近更新成功 8个节点 今天18:05. bottom立即更新 outline; 删除订阅 redtext. Screen4编辑分流规则: header取消 保存. section规则名称 国内网站; 类型 segmented域名 / IP / 规则集, 域名selected. textarea 匹配内容 example.cn on line1 *.example.cn line2. group规则动作 selectedradio 直连, otherradio当前代理, 拦截; row启用规则toggleON. info banner 组网地址优先规则不可被覆盖. Compact预览访问example.cn → 直连. Bottom保存规则 teal. Precise Chinese type and complete viewport. Do not add implementation labels. This is a design-only concept, not a claim that functions are already available.
|
||||
|
||||
|
After Width: | Height: | Size: 1.3 MiB |
@@ -0,0 +1,73 @@
|
||||
# MeshPort 24 页设计逻辑检查
|
||||
|
||||
> 审查后的设计修正已整理为 [V4 原型](meshport-ui-v4-index.md)与 [V4 交互说明](meshport-ui-v4-interactions.md)。下文保留原始审查记录;不代表客户端代码已完成对应修正。
|
||||
|
||||
检查日期:2026-10-10。对象:六张原型图、页面目录、当前客户端配置加载逻辑与 SDK 配置/线路策略代码。图片是静态设计,本文区分明确矛盾与尚未定义的交互;不表示运行中的客户端已经出现这些错误。没有修改图片或客户端。
|
||||
|
||||
结论:页面覆盖与视觉结构可保留,但不能直接把全部控件作为实现规格。应先确定运行状态、配置生效、订阅归属、路由与 DNS 的一致规则。
|
||||
|
||||
## 必须先明确的行为
|
||||
|
||||
1. 运行功能只选择启用哪些能力;代理模式只决定普通上网流量如何处理。仅组网时禁用代理模式和节点选择。代理+组网时分别展示两侧状态,允许显示部分可用。
|
||||
2. 点击连接启动当前选定能力。未准备好代理配置时,提示补齐或明确选择仅组网,不静默改变运行功能。修改运行功能可能重新配置虚拟网卡,不能承诺旧连接全部不中断。
|
||||
3. 只有虚拟网络地址和通过校验、实际生效的公告子网进入组网优先规则,不能将所有私有地址统一交给 MeshPort。公告撤销及故障必须同步更新流量规则与状态;原组网目标不可静默降级到互联网代理。撤销后的本地地址访问行为需另行定义。
|
||||
4. 区分配置来源和运行配置。订阅是节点来源,启用来源不会自动切换当前出口。固定系统规则由客户端维护,不能被导入的完整 JSON 替换。第一版普通导入提取节点;完整配置接管如需支持,应作为明确的高级功能。
|
||||
5. 配置编辑先保留草稿,保存并不等于已经生效。能热更新的部分可立即应用;需重连的参数展示待生效与重新连接。失败保留原运行配置,离开未保存页面提示保存或放弃。
|
||||
6. 仅代理、仅组网、组合模式各自定义 DNS 行为。组网 DNS 需要域名范围、服务器地址、请求出口与不可达行为;启用 FakeIP 时必须排除组网域名,不能只增加一个开关。
|
||||
7. 敏感凭据允许安全保存,但当前自用 APK 的默认配置含可提取密钥,不能声称所有敏感配置都只存在设备安全存储。
|
||||
8. 原型内存在现有 SDK 尚未支持的功能。展示应由能力判断决定:不支持项禁用或隐藏,而不是开启后被忽略。
|
||||
|
||||
## 逐页检查
|
||||
|
||||
| 页码 | 页面 | 问题或未定义项 | 修改建议 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 概览 | 单一“已连接”无法表达组合模式单侧失败;“断开连接”范围不明;流量来源未说明 | 总状态允许部分可用,代理和组网独立显示;主按钮连接/断开当前选定功能;说明总流量口径 |
|
||||
| 2 | 代理 | 手动选择与自动选择的状态缺失;选中节点不等于连接可用 | 自动模式显示实际使用节点并禁用直接点选,或点选明确切回手动;区分选中、检测可用与运行中 |
|
||||
| 3 | 组网 | “在线3/3”分母没有清晰来源;代理 RTT 与组网 RTT 容易比较混用 | 未知总量时显示在线3台;分别标注链路 RTT、路由估算与代理测试耗时 |
|
||||
| 4 | 设置 | 组网/代理配置入口过泛;自动接入开关没有关闭后的说明 | 指向确定页面;关闭自动接入是否撤销既有子网需明确,显示影响及重连要求 |
|
||||
| 5 | 导入代理配置 | 订阅、完整 JSON、扫码的内容格式与合并行为未定义;预览检测可能尚未发生 | 分离导入节点与接管完整配置;先下载/解析预览,再导入;提供失败、空配置和不支持格式状态 |
|
||||
| 6 | 订阅管理 | 多个来源开关可能被误解为多套引擎同时运行;删除正在使用节点没有策略 | 标注开关为参与节点列表;更新/删除前处理当前节点消失,保留手动节点归属及原运行配置 |
|
||||
| 7 | 代理节点详情 | “使用此节点”没有运行时行为;没有区分订阅节点和手动节点 | 显示来源;订阅节点只读或复制为手动节点;选择节点与启动代理分开 |
|
||||
| 8 | 分流规则 | “其他网站”兜底规则与默认出口重复,且可拖动/关闭;全局模式是否执行用户规则不明确 | 兜底只保留一个固定默认出口;系统组网规则置顶锁定;全局/直连时标明哪些普通规则暂停 |
|
||||
| 9 | 基础配置 | 手动、公共节点、独立切换缺少字段联动;公共节点可能混淆为互联网代理;静态 IP 没有冲突处理 | 解释为组网引导节点;按方式显示初始节点字段;验证地址、前缀及已知地址冲突 |
|
||||
| 10 | 连接与打洞 | 关闭 P2P 后其余打洞仍可编辑;监听缺少协议校验;STUN 默认/自定义与 IPv6 画成互斥选项 | P2P 关闭时禁用相关控件但保留值;独立设置 IPv4 与 IPv6 STUN;按平台能力启用 TCP 等选项 |
|
||||
| 11 | 高级配置 | 当前 SDK 不支持图中多线程、仅物理网卡、KCP/QUIC、出口节点、系统转发等配置入口;加密不能关闭 | 当前版本固定显示加密已开启;未支持项禁用;发布本地子网与学习远端子网分开,待 SDK 支持后开放 |
|
||||
| 12 | 线路策略 | “指定中继始终使用”与 SDK 的候选筛选不符;确认次数无对应字段;缺少相对改善比例 | 改为候选中继;使用实际支持的绝对改善、相对改善、持续确认时长、冷却时长;目标节点路径不能用一个全局当前路径替代 |
|
||||
| 13 | 节点详情 | 在线、当前转发路径、存在直连接口是不同事实;固定7ms无测量状态 | 展示当前路径与可用连接;无 RTT 时显示未测得,提供时间和测量方式;统计明确是否包含控制流量 |
|
||||
| 14 | 自动接入子网 | 全部条目都是成功或拒绝,缺少学习后尚未生效的阶段;同 CIDR 多发布节点未定义 | 增加待接入、失败、失效;同 CIDR 合并展示发布者与实际下一跳;应用内模式显示应用内可用 |
|
||||
| 15 | 子网详情 | “系统路由已安装”在应用内或统一 sing-box 分流方案下不一定成立 | 根据接入方式显示系统路由已安装、应用内可用、统一分流已生效;支持查看失败原因与最后生效时间 |
|
||||
| 16 | 网络诊断 | TCP耗时可能被当 RTT;TCP/UDP失败比例被标作丢包;“路径”可能被误解为公网 traceroute | 改为TCP连接耗时、UDP回显耗时及检测失败率;路径明确是组网下一跳;UDP无回显不直接判设备不可达 |
|
||||
| 17 | DNS 设置 | 组网 DNS 只填服务器无法决定域名匹配;代理 DNS 的访问出口与启动解析未定义;FakeIP说明生成错误 | 分开域名范围、服务器和出口;普通DNS/组网DNS按模式生效;纠正缓存与FakeIP说明并预留启动解析 |
|
||||
| 18 | 默认配置 | 安装包默认值与已保存配置的来源展示混用;保存时机文案与现有实现不一致;删除后默认值可能重新出现 | 展示当前来源;自动保存明确成功连接后发生;恢复默认只加载草稿并提示是否保存;删除说明下次加载安装包默认值 |
|
||||
| 19 | 启动与后台 | 开机启动与自动连接联动不明;恢复功能的文案写成恢复连接状态;不同平台权限不同 | 区分启动应用、恢复功能选择、自动连接;按平台显示权限;等待授权时不显示已连接 |
|
||||
| 20 | 运行日志 | 敏感信息过滤范围、导出范围及清空范围未定义;错误可能造成无限日志 | 始终隐藏密钥与订阅令牌;导出前脱敏;区分清空显示与删除历史;限制容量并显示时间范围 |
|
||||
| 21 | 首次使用 | 仅组网时仍要求代理配置;缺默认配置的路径不完整;开始使用是否连接不明确 | 配置条件随运行功能变化;支持导入或手动配置;开始使用进入首页,连接操作另行请求授权 |
|
||||
| 22 | 添加代理节点 | 同一组字段无法适配多协议;TLS开关与安全方式选项重复;保存和创建重复;测试草稿行为缺失 | 按协议生成字段;统一安全方式为无/TLS/Reality等适用选项;只保留一个保存动作,测试不隐式保存 |
|
||||
| 23 | 编辑订阅 | 保存与立即更新的执行顺序不清楚;删除订阅可能删除当前节点 | 立即更新使用已保存地址,或明确先保存再更新;删除确认说明节点影响;自动更新失败保留原节点 |
|
||||
| 24 | 编辑分流规则 | 域名精确、后缀、通配符语义混用;“当前代理”动作在仅组网时如何处理未定义 | 提供精确域名/域名后缀/CIDR/规则集选择;实时校验;不满足运行功能的规则显示暂停;顺序与优先级可见 |
|
||||
|
||||
## 现有 SDK 的明确差异
|
||||
|
||||
- 线路策略支持 adaptive、direct、latency、hop;原型遗漏 hop,且把中继候选列表描绘成强制中继模式。
|
||||
- 实际可调字段包含 min_improvement_ms、min_improvement_ratio、hold_seconds、cooldown_seconds、prefer_udp、relay_peer_ids;没有“切换确认次数”。实现时应使用确认时长,不把秒转换成不可靠的采样次数。
|
||||
- 当前配置解析采用严格白名单。高级页中超出白名单的参数不能直接保存为有效 TOML。
|
||||
- 当前应用保存逻辑在显式保存或开启记住配置且成功连接后触发,不是原型写的退出时保存。应保留明确保存入口,避免依赖平台可能不发生的退出回调。
|
||||
|
||||
## 公共状态和反馈补充
|
||||
|
||||
所有24页应共享以下交互规范,不必为每个状态另加独立导航页:
|
||||
|
||||
- 未配置、未连接、等待系统授权、连接中、运行中、部分可用、重连中、失败与断开中。
|
||||
- 初次加载、空列表、下载/解析失败、格式不支持、检测未完成、数值过期。
|
||||
- 草稿、已保存但未生效、应用中、应用成功、应用失败并保留旧配置。
|
||||
- 删除订阅、删除保存配置、恢复默认、离开未保存表单、重建VPN前的确认与影响提示。
|
||||
- 订阅更新删除了已选节点、虚拟IP冲突、目标子网与本地网段冲突、公告撤销、VPN被其他应用替换。
|
||||
|
||||
不应继续承诺切换运行功能、重建 TUN 或任意配置重载都不影响游戏连接。可以尽量让新规则只作用于新连接,但需分清热更新与必须重启的操作。
|
||||
|
||||
## 官方文档参考
|
||||
|
||||
- [sing-box Selector](https://sing-box.sagernet.org/configuration/outbound/selector/):选择器具有 interrupt_exist_connections 配置,是否中断连接是实现选择,不能作为所有配置切换的统一承诺。
|
||||
- [sing-box Route Rule](https://sing-box.sagernet.org/configuration/route/rule/):域名精确、后缀、正则和 CIDR 是不同的匹配字段,表单必须转换成确定规则。
|
||||
|
||||
建议实施顺序:先修正组合状态与模式切换、公告路由/DNS、订阅来源及配置生效,再调整高级参数、统计口径和页面文案。
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.6 MiB |
@@ -0,0 +1,37 @@
|
||||
# MeshPort 移动端原型 V4
|
||||
|
||||
修订日期:2026-10-10。针对 [V3 的 24 页审查](meshport-ui-v3-review.md)修正交互逻辑,保持暖白背景、青蓝色状态与卡片风格。
|
||||
|
||||
本版本包括 24 个页面及 4 个共享状态示例。图片中的数字、节点和测试结果是示例;这些是目标视觉设计,客户端现已接入主要页面;实际能力与禁用项见 [界面实现清单](../../docs/ui-implementation.md)。交互目标以 [交互说明](meshport-ui-v4-interactions.md)为准,不能将目标图视为运行截图。
|
||||
|
||||
| 页码 | 原型图 | 页面 |
|
||||
| --- | --- | --- |
|
||||
| 1–4 | [主页面](meshport-ui-v4-main.png) | 概览、代理、组网、设置 |
|
||||
| 5–8 | [代理配置](meshport-ui-v4-proxy.png) | 导入代理配置、订阅管理、代理节点详情、分流规则 |
|
||||
| 9–12 | [组网配置](meshport-ui-v4-network-config.png) | 基础配置、连接与打洞、高级配置、线路策略 |
|
||||
| 13–16 | [节点与路由](meshport-ui-v4-network-details.png) | 节点详情、自动接入子网、子网详情、网络诊断 |
|
||||
| 17–20 | [应用设置](meshport-ui-v4-settings.png) | DNS 设置、默认配置、启动与后台、运行日志 |
|
||||
| 21–24 | [引导与编辑](meshport-ui-v4-editors.png) | 首次使用、添加代理节点、编辑订阅、编辑分流规则 |
|
||||
| 共享状态 | [状态与确认](meshport-ui-v4-states.png) | 等待 VPN 授权、导入失败、保存后重连、订阅更新导致当前节点失效 |
|
||||
|
||||
## 页面连接
|
||||
|
||||
- 首次使用 → 按运行功能补齐配置 → 进入概览;连接为独立操作。
|
||||
- 概览 → 当前代理节点详情、组网节点详情;连接和断开作用于所选功能,组合模式显示两侧状态。
|
||||
- 代理 → 导入、订阅管理、节点详情、分流规则;手动节点进入编辑,订阅节点只读并允许复制为手动节点。
|
||||
- 组网 → 基础配置、连接与打洞、高级配置、线路策略、节点详情、子网列表与详情、诊断。
|
||||
- 设置 → DNS、默认配置、启动与后台、日志;诊断复用组网页入口。
|
||||
- 公共确认框或状态视图留在当前流程中,完成或取消后返回原页,不增加底部导航项。
|
||||
|
||||
## 修订要点
|
||||
|
||||
- 组合模式分别显示代理与组网状态,未配置、待授权、部分可用不能标作全部连接成功。
|
||||
- 分开草稿、保存配置和运行配置;明确重连影响及失败处理。
|
||||
- 订阅管理节点来源,选中节点、检测结果与运行出口分开;导入不替换受管理的路由和 DNS。
|
||||
- 公告子网区分学到、接入中、生效、失败和撤销;组网目标不会静默交给互联网代理。
|
||||
- 线路参数按 SDK 能力表达,不支持的高级选项禁用;统计区分 RTT、估算和连接检测耗时。
|
||||
- 补齐 DNS 范围与出口、首次使用联动、隐私文案和共享错误状态。
|
||||
|
||||
生成图中个别图标、文字换行和控件排列需在实际组件实现时统一。子网列表顶部数字是状态统计,不是筛选标签;运行功能的统一排列为“仅组网 / 仅代理 / 代理+组网”。
|
||||
|
||||
[完整生成提示词](meshport-ui-v4-prompts.md)
|
||||
@@ -0,0 +1,150 @@
|
||||
# MeshPort V4 交互说明
|
||||
|
||||
本说明修正 V3 审查中的问题,与 [V4 原型目录](meshport-ui-v4-index.md)配套。范围为设计,不表示 sing-box 集成、所有平台功能或以下状态机已经实现。静态图无法展示的联动按本文执行。
|
||||
|
||||
## 1. 运行功能、模式与状态
|
||||
|
||||
底部导航固定为概览、代理、组网、设置。运行功能固定顺序为仅组网、仅代理、代理+组网;代理模式为规则、全局、直连,决定普通互联网流量处理,不覆盖生效的组网目标。
|
||||
|
||||
| 运行功能 | 启动条件 | 控件与状态 |
|
||||
| --- | --- | --- |
|
||||
| 仅组网 | 有效组网配置 | 禁用代理模式、出口切换;允许浏览和编辑代理草稿 |
|
||||
| 仅代理 | 有效代理配置和适用出口 | 组网显示未启用,不启动组网引擎 |
|
||||
| 代理+组网 | 两侧配置有效 | 分别显示引擎、权限和接入状态;只有两侧就绪才显示全部可用 |
|
||||
|
||||
组合模式缺配置时,点击连接提示“补齐配置 / 仅启动已配置功能 / 取消”。第二项必须由用户选择;保留组合功能选择,总状态为部分可用,不静默切换设置。尚未满足整体连接条件时不触发完整配置的成功连接自动保存。
|
||||
|
||||
组件状态包括未配置、未启用、待授权、启动中、就绪、待发现节点、重连中、失败、断开中、已断开。引擎运行但没有节点显示“待发现节点”;有节点也不等于所有远端服务可达。聚合状态依据所选功能、引擎与当前接入方式是否就绪计算,不用一个布尔值覆盖两侧。
|
||||
|
||||
授权未完成不能显示就绪;取消返回未连接并保留配置。权限撤销或 VPN 被其他应用替换时停止声称路由有效,显示原因与重新连接入口。等待状态不得伪造系统授权框。
|
||||
|
||||
概览主按钮为“连接所选功能”或“断开所选功能”;组合模式运行时显示“断开全部”。失败重试仅影响失败组件的前提是共用网络入口无需重建,否则先提示整个会话可能中断。功能切换也先评估重建要求。
|
||||
|
||||
组合方案只允许一个系统 TUN 的所有者;代理和组网通过统一入口分流。应用内 SDK 模式只影响接入该库的应用连接,不声称接管其他应用流量。
|
||||
|
||||
## 2. 草稿、保存与生效
|
||||
|
||||
编辑状态分为草稿、已保存待生效、应用中、已生效、应用失败。草稿、持久化配置和当前运行快照分开维护;返回未保存页面提供保存、放弃、继续编辑。
|
||||
|
||||
- 保存前校验当前协议、能力和字段依赖;错误定位到字段,不能把未支持参数悄悄写入有效配置。
|
||||
- 保存只写入持久化配置,不自动启动连接。运行中需重建的修改显示待生效以及旧的有效值,提供稍后或重新连接。
|
||||
- 运行功能、虚拟 IP、TUN 接入方式及无法热更新的内核参数视为需要重连。规则、DNS、出口等是否能热更新由实际能力决定,不能统一承诺不中断。
|
||||
- 重连确认列出影响及“现有游戏/远程连接可能中断”。先验证新配置再变更,失败尽量恢复旧运行配置;恢复失败明确显示未连接及重试,不保证旧连接仍存在。
|
||||
- 删除、恢复默认、订阅更新和应用配置均有进行中与失败反馈,重复点击不得创建重复任务。
|
||||
|
||||
## 3. 代理来源、出口与规则
|
||||
|
||||
订阅和手动节点是配置来源,不是独立代理引擎。来源开关表示参与可选节点列表;不隐式切换运行出口。节点按稳定标识关联,不只按显示名称匹配。
|
||||
|
||||
普通导入流程:输入/扫码 → 下载或解析 → 支持项及不支持原因预览 → 导入节点。首版只开放实际解析器支持的格式和协议;识别 sing-box JSON 也只提取可支持节点,不接管其中的 TUN、DNS、路由、管理端口或组网规则。超时、空结果、非法格式保留输入并禁用完成操作。
|
||||
|
||||
订阅节点显示来源且只读,可复制为手动节点编辑。更新订阅保留手动节点;Wi-Fi 限制关闭后允许移动网络更新。保存地址与“保存并更新”是不同操作,后者先校验保存,再下载到暂存结果。
|
||||
|
||||
更新、停用或删除来源若影响当前出口,先展示差异并要求选择替代节点或明确停止代理;取消保留旧来源、旧节点和运行出口。自动更新遇到当前节点消失不得擅自删除,标记待处理并保留旧可用快照。替代节点失败按失败/回退状态报告,不谎称切换成功。
|
||||
|
||||
代理页分别展示选中出口、运行出口、最近检测结果。选中不等于启动,检测可用也不等于每个目标可达。自动模式点选节点时明确切回手动并反馈;检测使用一致的目标、超时与方法,显示“HTTP 检测耗时”,不称为组网链路 RTT。
|
||||
|
||||
规则顺序:受管理的组网目标优先 → 用户普通规则按顺序匹配 → 一个固定默认出口。用户不能拖动、关闭受管理的组网规则,也不能重复创建可拖动的兜底规则。
|
||||
|
||||
规则模式执行普通规则;全局模式普通互联网流量使用所选代理;直连模式普通互联网流量直连。后两者显示普通规则暂停(包含用户的拒绝规则),组网优先规则仍有效。仅组网时普通代理规则整体暂停,保留编辑结果供以后启用。
|
||||
|
||||
匹配类型明确为精确域名、域名后缀、CIDR、规则集;后缀 example.cn 匹配自身及子域,精确匹配不扩展到子域。不把含糊的星号语法自动转换成未知语义。规则集必须是支持的类型;编辑页显示优先级与生效/暂停状态。
|
||||
|
||||
节点编辑字段随支持协议变化,安全方式只保留一个适用选择(例如无、TLS、Reality)。测试草稿不保存、不启动正式代理、不更改全局路由;只有一个“保存节点”主操作。
|
||||
|
||||
## 4. 公告子网与访问路径
|
||||
|
||||
默认自动学习并接入符合规则的远端公告,无远端子网手动列表。学习远端公告与发布本机局域网是不同能力;后者未实现时禁用,不能将远端 CIDR 写成本机发布项。
|
||||
|
||||
公告需符合现有 SDK 接受规则及权限约束,并校验 CIDR、来源和本地冲突;不接受所有 RFC1918 地址、不自动接管默认路由。显示拒绝的具体原因。已知本地同网段冲突不能仅靠最长前缀自动解决,应阻止接入并提示冲突。
|
||||
|
||||
| 状态 | 含义与显示 |
|
||||
| --- | --- |
|
||||
| 已学习 / 待接入 | 已收到公告,尚未执行或等待接入条件 |
|
||||
| 接入中 | 正在更新当前接入方式的路由/规则 |
|
||||
| 已生效 | 系统模式:系统路由已安装;应用内模式:应用内可用;统一 TUN:分流已生效 |
|
||||
| 接入失败 | 保留已学习信息,显示操作错误与重试;不显示已安装 |
|
||||
| 已拒绝 | 不符合规则或与本地网段冲突,说明原因 |
|
||||
| 已撤销 / 已失效 | 不再作为有效组网路线;保留事件和更新时间 |
|
||||
|
||||
列表顶部为状态统计,不是筛选控件。同 CIDR 多个公告合并为一个条目,显示所有发布者、实际下一跳和当前选用路径;发布者不必等于下一跳。重叠且允许的子网按最长前缀匹配,具体下一跳由有效组网路由决定。
|
||||
|
||||
路由与流量规则更新应作为一致的变更处理,避免一侧已撤销、一侧仍显示生效;更新失败标记该子网不可用并记录原因。关闭自动接入先提示将撤销自动接入的子网,保留组网虚拟地址;成功后同步移除相关有效状态。
|
||||
|
||||
组网暂时失联时,已知组网目的地不可静默转入互联网代理。公告撤销后移除失效的组网转发路径,但保留目的地址的保护记录,提示不可用;不会生成泛化私网阻断。用户显式解除该目标保护并通过本地冲突检查后,可恢复本地普通访问。显式关闭组网功能时提示移除组网路由与保护,之后由所选功能及本地网络处理,不能仍称组网可达。
|
||||
|
||||
应用内接入只供库内连接 API 使用;系统模式才为系统应用安装路由;统一入口模式由同一 TUN 的分流规则接入。子网详情按实际方式标状态,不能一律写“系统路由已安装”。
|
||||
|
||||
## 5. 组网配置与线路策略
|
||||
|
||||
组网方式切换联动字段:手动需要有效引导节点 URI;公共方式使用明确来源的引导列表;独立方式允许无引导但解释无法凭空发现其他设备。引导节点不是互联网代理出口。当前系统模式静态 IP;DHCP 未支持时不可启用。验证地址、前缀与已知虚拟 IP 冲突,未知冲突不能保证已排除。
|
||||
|
||||
关闭 P2P 后禁用 UDP/TCP/对称 NAT 打洞控件并保留原值;重新开启恢复可用。IPv4/IPv6 STUN 分别选择默认或自定义,IPv6 能力不足时说明。监听校验协议与完整 URI。TCP 打洞按编译能力启用,UPnP 未暴露能力时禁用。
|
||||
|
||||
高级配置由 SDK 能力白名单驱动。加密固定开启;多线程、仅物理网卡、KCP/QUIC、出口节点、系统转发、本地子网发布等未支持项不得伪装可用。延迟优先不另设与线路策略冲突的开关,只显示当前策略对应的值。
|
||||
|
||||
线路策略支持 adaptive、direct、latency、hop;界面分别表达自适应、直连优先、延迟优先、跳数优先。自适应“明显更好”使用 SDK 的绝对和相对改善阈值及持续确认时间,示例值为 15ms、15%、10 秒、30 秒冷却;不是切换确认次数。实际执行条件以 SDK 算法为准。
|
||||
|
||||
对应字段为 min_improvement_ms、min_improvement_ratio、hold_seconds、cooldown_seconds、prefer_udp、relay_peer_ids。候选中继筛选不是强制始终走某节点。每个目标显示自己的当前路径;不能用一个全局路径替代全部目的节点。
|
||||
|
||||
## 6. 数据和诊断
|
||||
|
||||
节点的在线、当前转发路径、有直连可用和打洞建立分别表示,存在 TCP 引导直连不等于目标正在走该直连。无测量值显示未测得,过期显示时间/过期,不能补零或固定 7ms。
|
||||
|
||||
区分链路 RTT、路由估算、HTTP 代理测试耗时、TCP 建连耗时、UDP 回显耗时。检测失败次数/失败率不称为数据包丢包率;UDP 需可用的回显服务,没有响应不能直接认定所有 UDP 或设备不可达。路径图只展示组网下一跳,非公网 traceroute。
|
||||
|
||||
上传下载速率与累计分别显示单位、方向、采样时间、统计范围。当前隧道统计含控制流量时明确标注;接口与隧道统计不可直接相加造成重复计数。首页总量按明确口径汇总;节点更换连接或计数器重置时重置基准,不产生负速度。无采样、暂停与零流量是不同状态。
|
||||
|
||||
## 7. DNS、默认配置与后台
|
||||
|
||||
DNS 区分普通、代理出口、启动解析和组网域名规则;每条组网 DNS 规则包括域名范围、服务器、请求出口及失败策略。组网域名解析失败不得自动送公共 DNS;启用 FakeIP 必须排除这些域名。代理服务器启动解析不得依赖尚未建立的同一个代理。
|
||||
|
||||
仅组网时普通系统 DNS 保持原平台处理,组网 DNS 只作用于所接入的应用内/系统目标范围;仅代理不启用组网 DNS;组合模式普通解析按代理配置执行,组网范围优先。清缓存与启用 FakeIP 不是同一操作,修改是否重连按实际能力提示。
|
||||
|
||||
配置加载优先级:已保存配置 → 安装包默认配置 → 空配置。显示当前来源。记住配置开启且完整连接成功后自动保存,另提供显式保存;不依赖退出回调。恢复安装包默认只加载草稿,保存和应用另行确认。删除已保存配置提示下次可能重新加载安装包默认,不会删除内置默认值。
|
||||
|
||||
用户保存的敏感配置使用平台安全存储;自用 APK 内嵌默认密钥仍可提取,不能声称所有秘密仅存在 Keystore/钥匙串。展示和日志默认隐藏,编辑时显式查看不等于允许日志记录。
|
||||
|
||||
启动应用、恢复上次功能选择、自动连接分别设置;恢复功能不等于恢复连接。自动连接默认关闭,等待权限时不得标已连接。登录/开机启动、电池策略、前台服务由平台能力决定;未实现项禁用并说明。Android VPN 被其他 VPN 替换时显示已停止,不循环争抢权限。
|
||||
|
||||
日志始终脱敏密钥、密码、令牌、认证头与敏感 URL 参数;导出也脱敏。明确容量/保留时间和导出时间范围,错误重复限流。清空显示与删除历史分开,当前页面仅提供清空显示时不得声称文件已删除。
|
||||
|
||||
## 8. 24 页修正对应关系
|
||||
|
||||
| 页码 | 页面 | 修正 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 概览 | 两侧状态、部分可用、明确断开范围和流量口径 |
|
||||
| 2 | 代理 | 手动/自动联动、选中/运行/检测区分 |
|
||||
| 3 | 组网 | 在线台数、路径与延迟来源、速率和累计 |
|
||||
| 4 | 设置 | 精确入口、自动接入关闭后的撤销说明 |
|
||||
| 5 | 导入 | 节点提取、解析预览、支持性和失败状态 |
|
||||
| 6 | 订阅管理 | 来源语义、暂存更新、当前出口失效确认 |
|
||||
| 7 | 代理节点详情 | 来源只读、复制编辑、选择与启动分开 |
|
||||
| 8 | 分流规则 | 锁定组网优先、单一兜底、模式暂停状态 |
|
||||
| 9 | 基础配置 | 方式依赖、引导解释、地址校验、保存待生效 |
|
||||
| 10 | 连接与打洞 | P2P 联动、独立 STUN、监听与能力校验 |
|
||||
| 11 | 高级配置 | 固定加密、不支持项禁用、统一线路策略来源 |
|
||||
| 12 | 线路策略 | 四种实际模式、阈值/确认时长/冷却、候选中继 |
|
||||
| 13 | 节点详情 | 当前路径和可用直连分开、测量时间与统计范围 |
|
||||
| 14 | 自动接入子网 | 状态阶段、同 CIDR 合并、顶部统计语义 |
|
||||
| 15 | 子网详情 | 根据接入方式显示生效、失败和撤销处理 |
|
||||
| 16 | 网络诊断 | 正确检测名称、失败统计、UDP 服务前提 |
|
||||
| 17 | DNS 设置 | 域名范围、出口、启动解析、失败策略与 FakeIP 排除 |
|
||||
| 18 | 默认配置 | 来源优先级、保存时机、恢复草稿与内嵌秘密说明 |
|
||||
| 19 | 启动与后台 | 启动/恢复/自动连接独立、平台权限与能力 |
|
||||
| 20 | 运行日志 | 强制脱敏、容量、导出范围、清空语义 |
|
||||
| 21 | 首次使用 | 按功能补配置、进入首页不隐式连接 |
|
||||
| 22 | 添加代理节点 | 协议动态字段、唯一安全方式与保存、草稿测试 |
|
||||
| 23 | 编辑订阅 | 保存/保存并更新区分、手动节点保留、失效出口处理 |
|
||||
| 24 | 编辑分流规则 | 确定匹配语义、能力暂停、顺序和校验 |
|
||||
|
||||
## 9. 实现验收场景
|
||||
|
||||
1. 组合模式缺代理配置、单侧失败、两侧就绪及 VPN 授权取消时,总状态和按钮与实际一致。
|
||||
2. 保存虚拟 IP 不立即重建;重连确认、失败及恢复失败均有明确状态;离开草稿不静默丢弃。
|
||||
3. 导入完整 JSON 不覆盖系统分流;解析失败保留输入;订阅更新删除当前出口时取消能保留原配置。
|
||||
4. 同 CIDR 多发布者不重复安装;应用内与系统模式均自动接入合规公告;本地冲突、撤销、故障和关闭自动接入均不显示虚假生效或泄漏到互联网代理。
|
||||
5. 全局与直连模式正确暂停普通规则,生效组网优先规则保留;仅组网时代理相关动作禁用。
|
||||
6. P2P 关闭联动、SDK 不支持项、检测过期、无 UDP 回显、DNS 失败和嵌入配置提示均与实际能力一致。
|
||||
|
||||
这组验收用于后续客户端实现;本次只完成设计修正,没有执行客户端功能验收。
|
||||
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.6 MiB |
|
After Width: | Height: | Size: 1.5 MiB |
@@ -0,0 +1,99 @@
|
||||
# MeshPort V4 生成提示词
|
||||
|
||||
工具:内置 image_gen.imagegen。以 V3 图为参考进行编辑,保留原图;修正补充图采用后续定向编辑。交互定义以 V4 交互说明为准。
|
||||
|
||||
## main
|
||||
|
||||
```text
|
||||
Edit the supplied MeshPort four-screen mobile UI board. Preserve warm ivory, white rounded cards, pale cyan, teal controls, MeshPort logo, four straight-on complete phones and Simplified Chinese typography. This is revised V4 design preview with fictional metrics. Make Chinese text readable and all bottom navigation visible. Recompose content as needed. Four main pages 概览 / 代理 / 组网 / 设置.
|
||||
Required corrected behavior:
|
||||
Overview selected 代理+组网. Global summary amber 部分可用; proxy card state 未配置 with 导入配置 button, mode 规则/全局/直连 disabled until configured, not green started. Mesh card green 已连接 with192.168.20.6 and在线3台 (not3/3), independently operating. Notice 代理未配置,组网仍可用. Traffic card title 当前组网流量 subtitle 隧道统计,含控制流量; down82KB/s up35KB/s and subtle sparkline; no totals mixing proxy with mesh or duplicate summing. Rows Redmi_AX6 直连 7ms 链路RTT; DIG-US 直连167ms 链路RTT; ORA-JP 中继267ms 路由估算, each small down/up numbers. Primary bottom 断开全部; small outline 补齐代理配置. Capability selector仅组网/仅代理/代理+组网 must include hint 切换运行功能可能需要重新连接.
|
||||
Proxy main page is a separate illustrative configured state, not same simultaneous snapshot: header small 示例:代理运行中. Mode规则 selected; current node JapanTokyo85ms label 测试耗时; badge 手动选择. Candidate list show selected versus availability as separate markers, selected JapanTokyo, HK42ms tested available, SG 未检测, US 超时. Node selection row 手动 / 自动. Footer 自动模式下点选节点将切回手动. Settings rows 节点来源与订阅 / 导入节点 / 分流规则. Group priority notice only 组网有效地址优先,普通模式规则不覆盖.
|
||||
Mesh main header green 运行中; localaddress192.168.20.6; 在线3台. list node details distinctions直连可用 versus 当前路径, include7ms链路RTT and267ms路由估算. accepted subnet192.168.21.0/24 status统一分流已生效 (not OSrouteinstalled, this is planned combined mode). Settings entry组网配置 and线路策略.
|
||||
Settings main grouped items 默认配置与保存 / 组网配置 / 节点来源与订阅 / 分流与DNS / 启动与后台 / 网络诊断 / 运行日志. 自动接入公告子网 toggle ON helper关闭将撤销已自动接入子网. Bottom version0.2.0设计预览.
|
||||
Avoid any claim all switches already implemented. All four pages illustration states independent, no credentials.
|
||||
```
|
||||
|
||||
## proxy
|
||||
|
||||
```text
|
||||
Edit supplied MeshPort board A, preserving four full straight-on phones, ivory white cyan teal cards, restrained styling and readable Simplified Chinese. Keep all content and buttons inside safe margins.
|
||||
Four pages: 导入节点 / 节点来源与订阅 / 代理节点详情 / 分流规则.
|
||||
1 导入节点: tabs订阅链接/配置文件/扫码. show name自用代理, addresshttps://example.com/sub, button解析预览. Preview成功解析8个节点; unsupported2条 small amber note可查看原因. Include a concise notice普通导入仅提取节点,不替换组网、路由或DNS. selector导入方式新增来源 / 更新同一来源. Auto-update toggleON interval24小时. Footer导入8个节点 teal. Scan helper supportsrecognizednodeURLs, do not promise arbitrary subscriptionformats.
|
||||
2 节点来源与订阅: hero explanatory来源启用后加入节点列表,不自动切换当前出口. cards自用代理 启用 8个节点, 当前选中节点来自此来源, update/editactions;备用代理toggleOFF 3个节点;手动节点 1个 chevron separate source notsubscription. lastupdateerroramber tiny保留上次可用节点. one inline confirm state 删除正在使用的来源? 将移除8个节点;需要先选择其他出口 with取消 and选择替代节点 buttons, not automatic silentlydelete. This confirmation can be bottom sheet, dim underlyingverylight.
|
||||
3 代理节点详情: 日本·东京, badges来源自用代理 / 已选中 / 检测可用;85ms labelHTTP测试耗时 not RTT; protocolVLESS read-only fieldsjp.example.com443 TCP TLS enabled credentials masked. Note订阅节点只读,更新由订阅管理. buttons测试连接 / 复制为手动节点. primary选择此节点 separated from startingtheVPN, helper选择节点不会启动代理. No editable originalsubscriptioncredentialseye.
|
||||
4 分流规则: top small current mode全局; locked fixed systemgroup组网有效地址→MeshPort with lockicon; text始终生效. ordinaryrulelist国内网站→直连 and广告过滤→拦截 visuallygrey pausedlabel 全局模式暂停. Editable roworderdraghandles onlyordinaryruleitems; no “其他网站” movablecatchall. bottomfixedcard普通流量默认出口→当前代理 withlock; under规则模式由规则决定,全局模式固定代理. Button添加规则; hint规则编辑不会覆盖系统组网规则. All cardsfictional.
|
||||
```
|
||||
|
||||
## network_config
|
||||
|
||||
```text
|
||||
Edit supplied MeshPort four-screen network configuration board. Preserve four complete mobile phones, Chinese labels, warmwhite cards, cyan andteal, safearea. Titles 基础配置 / 连接与打洞 / 高级配置 / 线路策略. Correct existing semantic problems, don't just change title.
|
||||
Screen1基础配置: small amberbanner 草稿·尚未保存. NetworkGameNet secretmasked nodeMeshPort-Android IPv4192.168.20.6 /24; DHCP switchdisabled note当前系统模式需静态地址. 组网方式 radio 手动 / 公共引导节点 / 独立. Show manual initialnodes tcp://relay-us.example.com:52015 tcp://relay-jp.example.com:52015. Helper初始节点用于发现组网节点,不是上网代理. compact addressvalid check虚拟IP格式有效,连接时检查已知地址冲突. footer 保存配置 filled, 重新连接 disabled untilsaved; info修改地址或组网身份需重连.
|
||||
Screen2连接与打洞: principal首选协议UDP dropdown and监听UDP0.0.0.0:11010 add address action. P2P toggleOFF in this illustrative screen. UDP打洞、TCP打洞、对称NAT打洞 allgrey disabled retainingtheirlast-on values and note启用P2P后可调整打洞设置. UPnP grey OFF capabilitylabel当前SDK未开放. Separate IPv4 STUN row默认服务器 / 自定义chevron; independent IPv6 STUN row默认服务器 / 自定义chevron, notthree mutuallyexclusiveoptions. Footer保存配置, helper修改连接参数可能需要重连.
|
||||
Screen3高级配置: group已支持 private networkmodeON, IPv6ON, 延迟优先ON. 加密传输固定row 始终开启 with lock noeditabletoggle. section暂未支持 grey rows KCP/QUIC代理, 发布本地子网, 出口节点, 系统转发, 多线程/仅物理网卡 each small 当前SDK未开放, don't present enabledswitches. info学习远端子网不等于发布本地子网. bottom查看完整TOML outlined; warning修改后先校验,需重连的配置不会立即生效.
|
||||
Screen4线路策略: radio modes自适应selected / 直连优先 / 延迟优先 / 跳数优先, NOT指定中继asmode. explanatory质量接近优先直连,持续明显改善才切换. form真实支持字段 绝对改善门槛15ms; 相对改善门槛15%; 持续确认时长10秒; 切换冷却时长30秒. UDP优先toggleON. 候选中继 自动发现 / 手动筛选, helper候选列表不强制中继,直连仍可使用. bottomsmall group目标节点DIG-US, 当前路径直连167ms, notglobalpath. footer保存策略, status待应用. All quantitativevaluesdesignexamples.
|
||||
```
|
||||
|
||||
## network_config_fix
|
||||
|
||||
```text
|
||||
Precise final correction of the supplied four-phone MeshPort V4 configurationboard. Keep every phone, spacing, palette and all unrelated content unchanged. On phone3 高级配置, REPLACE the editable 延迟优先 toggle and its erroneous performance explanation with a READ-ONLY row named 线路选择, value 使用线路策略设置, with small helper 由线路策略统一决定,避免重复开关 and chevron link to线路策略. Do not provide a second latency-firstswitch. On phone2连接与打洞 fix监听地址 to show complete URI udp://0.0.0.0:11010 rather thanbare0.0.0.0. On phone4线路策略 keep all existing15ms,15%,10秒,30秒 parameters andfourmodes andcandidatefiltersemantics. Do not alter any other controls. Clear readableChinese exactwording and all phonesfullyvisible.
|
||||
```
|
||||
|
||||
## network_details
|
||||
|
||||
```text
|
||||
Edit supplied MeshPort four-screen node/routes/diagnostic board, preservecomplete straightonphones andwarmivory whitecyan teal visualtheme. Readable Chinese, no cropped buttons. Pages 节点详情 / 自动接入子网 / 子网详情 / 网络诊断.
|
||||
1节点详情Redmi_AX6: onlinegreen, address192.168.20.3. clear 当前转发路径 本机→Redmi_AX6 直连UDP and separate 可用连接 UDP直连1条, notsamefact. RTT7ms label链路RTT, updated18:17:06. small sparkline最近60秒. traffic↓82KB/s ↑35KB/s, totals4.9MB5.5MB label隧道统计·包含控制流量. NATPortRestricted coreversion2.6.4. 公告子网192.168.21.0/24green已生效. button测试连通性. tinyhint未测得或过期的RTT显示—.
|
||||
2自动接入子网: segmented已生效1 / 待接入1 / 未接入1. showcards192.168.21.0/24green已生效; 发布者Redmi_AX6、备用NAS; 当前下一跳Redmi_AX6; 同网段多个发布节点合并展示. second10.80.0.0/24blue待接入 正在更新分流. third192.168.20.0/24amber未接入 与虚拟网段重叠. intro仅接入通过校验的公告,不接管全部私有地址. policyrows /16至/32 最大32条 私有IPv4. Footer刷新公告; secondarylastupdate18:17.
|
||||
3子网详情192.168.21.0/24: row 发布节点Redmi_AX6; 当前下一跳Redmi_AX6; 接入方式统一分流; 接入状态已生效; 更新时间18:17. NOT系统路由installed onthiscombined-modeexample. Small hint应用内模式显示应用内可用,独立系统模式显示系统路由. path本机192.168.20.6→Redmi_AX6→目标192.168.21.201. testaddress192.168.21.201 port5900; button测试连接; resultTCP连接成功12ms label连接耗时. information组网不可用时不自动转到互联网代理; 公告撤销后同步更新接入状态. Connectionlost canillustrate smallinlinegreybadge暂无异常 notcontradictions.
|
||||
4网络诊断: targets192.168.21.201 port5900. tabsTCP连接 / UDP回显 / 组网路径, TCPselected. count10 timeout3秒. button开始检测. green10/10成功; 最小连接耗时7ms 平均12ms 最大18ms; 检测失败率0% NOT丢包率. path heading组网下一跳, notpublictraceroute. threechecklist 组网引擎运行 / 子网分流已生效 / TCP5900端口可达. noteUDP检测需目标支持回显,未响应不等于设备离线. Bottom导出诊断报告. Corrected metrics, realistic design-only samples.
|
||||
```
|
||||
|
||||
## settings
|
||||
|
||||
```text
|
||||
Edit MeshPort supplied four-screen settings board to revised logical V4 design. Preservecomplete phones, warmivory white roundedcards cyan-teal and Chinese typography. Four pages DNS设置 / 默认配置与保存 / 启动与后台 / 运行日志. Important: create coherent realistic mobile content, concise, no overflowing bottomcontrols.
|
||||
1DNS设置 topbadge已保存·待应用. group普通解析: 直连DNS系统解析; 代理DNShttps://dns.example.com/dns-query, 请求出口当前代理; 启动解析系统解析 helper用于解析代理服务器初始地址. group组网解析: 匹配域名home.arpa; DNS服务器192.168.20.3; 请求出口MeshPort; 不可达行为返回失败,不使用公网DNS. DNS缓存toggleON; FakeIPtoggleOFF, note组网域名始终排除FakeIP. Bottom保存配置; action应用更改; inlinehint应用失败保留原配置. Do not show technical “JNI” etc.
|
||||
2默认配置与保存: hero当前来源 已保存配置; group 当前网络GameNet IP192.168.20.6/24. toggle连接成功后自动保存ON; 启动恢复已保存配置ON; 自动连接OFF. Info优先保存配置,无保存时加载安装包默认值. privacyambernote已保存配置加密存储;自用安装包默认配置含密钥,请勿分发. primary保存当前草稿. showbottomconfirmation sheet 恢复安装包默认配置? subtitle仅加载到草稿,不立即保存或重连. buttons取消 / 载入草稿. Smallunderlyingdelete row删除保存配置 helper下次启动将重新载入安装包默认值. No claim exit-auto-save.
|
||||
3启动与后台: 安卓page group启动 开机启动disabled当前版本未开放; 打开应用自动连接OFF; 恢复上次功能选择ON helper只恢复选择,不恢复连接状态. group后台 前台通知 enabledlocked; 电池优化 未放行 with前往系统设置 action; 后台运行权限待检查. group恢复 自动重连ON designplanned; 网络变化重试ON; compact note以当前平台实现能力开放. Smallstatebanner等待系统VPN授权 and helper授权完成前不标记已连接. bottom检查运行环境. ShowOSpolicy actual constraintsnotpermanentguarantee.
|
||||
4运行日志: filters全部/组网/代理/路由/错误; search. rows with timestampshort events 已应用子网规则192.168.21.0/24; 组网UDP直连建立; 代理节点测试完成85ms; 读取保存配置; 订阅更新失败保留旧节点 (amber). group设置日志级别信息; 敏感信息脱敏locked始终启用; 容量上限1000条; 导出范围最近1小时. note密钥、订阅令牌不会导出. bottom导出脱敏日志 / 清空当前显示; tinyhint清空显示不会删除已导出文件. These are plannedUIstates, no secret strings or real subscriptionURLs.
|
||||
```
|
||||
|
||||
## editors
|
||||
|
||||
```text
|
||||
Edit supplied MeshPort four-phone first-use/editorboard, preserve fully visible phones, ivory white cyan teal style, crispChinese.
|
||||
Titles 首次使用 / 添加手动节点 / 编辑订阅 / 编辑分流规则.
|
||||
1首次使用: logoMeshPort subtitle代理与组网,一个客户端. selected仅组网 card, otherchoices仅代理、代理+组网. configstatus仅show默认组网配置已载入 green, group选择或导入其他组网配置 outlinedrow. Proxyconfigurationrow notrequired note仅组网无需代理配置. VPNpermission未申请 withhelper点击连接时由系统请求授权. rememberfunctionchoiceON. bottom开始使用 button thenhelper进入首页,不自动连接. For otherchoices conditionalrequiredconfigs describedconcise inonehint配置要求随使用方式变化.
|
||||
2添加手动节点: small sourcebadge手动节点. protocolVLESS dropdown; fields名称日本·东京; serverjp.example.com; port443; UUIDmasked. 传输TCPselected / WebSocket / gRPC. Single dropdown安全方式TLS (choices无/TLS/Reality) NOT independentTLSswitch. TLSfieldsserverNamejp.example.com, 验证证书ON. collapsed高级参数 andnote字段随协议与传输方式变化. optionalerrorstate inputport443validgreen; bottomonlytwoactions 测试草稿 outlined and 保存节点 teal, no topduplicate保存or创建. helper测试不会保存或启动代理.
|
||||
3编辑订阅: amberbadge草稿·地址已修改. fields名称自用代理 URLhttps://example.com/new-sub. autoupdateON interval24小时 WiFionlyOFF. 保留手动节点ON (nodesstayindependent manualsource); 保留当前节点选择ON helper原节点消失时要求选择替代节点. lastupdate8nodes successfulold timestamp. buttons 保存订阅 and 保存并更新; small inlinehelper立即更新使用已保存地址,修改需先保存. discrete删除订阅 redlink withfootnote删除前检查当前出口是否引用此来源. Failureupdate note更新失败保留原节点.
|
||||
4编辑分流规则: 名称国内网站; matchingtype dropdown域名后缀 instead ofambiguousglobtabs; textareaexample.cn only(no*.); explanation匹配example.cn及其子域名. note其他类型:精确域名、IP网段、规则集. 当前运行功能仅组网 smallgreylabel. actionradios直连selected / 当前代理disabled helper仅组网时不可用 / 拦截. ruleenabledON. lockednotice系统组网规则先于普通规则. orderrow位于普通规则第2条 chevron. previewexample.cn→直连 / a.example.cn→直连. bottom保存规则onlyone, no redundanttopSave. smallhint规则仅作用于普通流量. All changesdraft andtestedseparately; no promiseshotreloadalwayssafe.
|
||||
```
|
||||
|
||||
## editors_fix
|
||||
|
||||
```text
|
||||
Precise final corrections to supplied four-phone MeshPort V4 editor board; preserve every unrelated item and warmivory cyan-teal styling. On phone3编辑订阅, switch仅Wi-Fi更新 is OFF. Replace its helper exactly with 关闭时允许移动网络更新. Replace the editable 保留手动节点 toggle with a LOCKED read-only row 手动节点独立保存, value 始终保留, helper 手动节点不属于订阅,不随订阅更新删除. Keep 保留当前节点选择 control and original-node-disappeared replacement explanation. Keep Save andSaveandupdate actions.
|
||||
On phone1首次使用, order choices仅组网(selected),仅代理,代理+组网 consistently. Row选择或导入其他组网配置 should be neutral secondaryaction withgreyplus, NOTamberwarning, because默认组网配置已载入. Atbottom记住我的选择 use ONE switch only; remove duplicate checkbox.
|
||||
On phone2 and4 leave protocolform anddomain-suffix semantics exactly as they are. Keepallphonesfullyvisible, legibleChinese andno newlabels.
|
||||
```
|
||||
|
||||
## states
|
||||
|
||||
```text
|
||||
Use case ui-mockup. Additional STATE board for revised MeshPort V4, four complete mobilephoneviewports sidebyside, Simplified Chinese clear text, same warmivory white roundedcards palecyan teal style, no purple, no actualsystemdialogimpersonation, fictitiousdemo only. These are states of existingpages, NOTnew navigationpages. Abovephoneslabels 等待授权 / 导入失败 / 保存后需重连 / 当前节点被移除.
|
||||
Phone1overviewMeshPort: selected代理+组网, totalstate等待授权 cyan; proxy待启动 andmesh待启动 separatelygrey, no greenconnected. centeredcard 需要系统VPN授权 subtitle系统将显示连接请求,请在系统弹窗确认; button继续授权; link取消连接. smallprogress步骤配置校验完成✓ → 等待授权 → 启动服务, lasttwoinactive. No simulatedOS permission grant button. bottomtabs概览代理组网设置.
|
||||
Phone2导入节点: inputexample.com/sub, mode订阅链接; resultdownloadfailedamber 获取订阅失败 subtitle连接超时,现有节点不受影响; buttons重试 and修改地址. secondarymuted解析预览未完成,导入buttondisabled. smallinlineunsupportedformatmessage(notsecond simultaneousfatalstate)帮助支持的格式与错误详情 chevron. User's inputretained.
|
||||
Phone3基础配置 withnewdraftIPv4192.168.20.7 andbadge已保存·待生效. Bottomsheet 需要重新连接才能生效 subtitle虚拟IP已变更;当前游戏和远程连接可能中断. clearbuttons 稍后应用 / 重新连接. helper稍后应用保留当前运行配置. Uppercardshows当前运行192.168.20.6→保存配置192.168.20.7 explicitdifferent. No autoreconnect.
|
||||
Phone4订阅更新: underlyingcard新订阅8个节点已解析 withnoappliedbadge; oldselectednode日本·东京 now removed. Bottomsheet当前节点已不在新订阅中; subtitle更新尚未应用,当前配置保留. List replacement香港42msradioselected / 新加坡108ms. buttons取消更新 / 选择并应用. helptext应用仅在确认后进行;必要时提示重连. Do not promiseallconnectionsuninterrupted. All fourphonecontentfits safearea.
|
||||
```
|
||||
|
||||
## states_fix
|
||||
|
||||
```text
|
||||
Precise small corrections to supplied MeshPort four-phone stateboard. Preserve all other composition andtext. Phone1 currentmodecontrol MUST have THREE options 仅组网 / 仅代理 / 代理+组网, with 代理+组网 selected. Bothservices therefore remain待启动 while waitingauthorization. Replace the existing two-option 代理/组网 control completely; threeoptiontextmustallfit. Phone2subscriptionURLfield shouldread https://example.com/sub withscheme, notbareexample.com/sub. Phone4 headingabovechange-list shouldread 订阅变更预览 instead of节点列表(8), because the removedJapanrowisadiffentrynotanewnode. All remainingcontentanddialogsidentical. ClearChinese, fullyvisible, no extra explanations orlogochanges.
|
||||
```
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 1.6 MiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.6 MiB |