From dc1bfc99d221dea964ba5c640453e5d1965425d8 Mon Sep 17 00:00:00 2001 From: shenlei Date: Thu, 15 Oct 2026 18:17:42 +0900 Subject: [PATCH] Move mesh networking logic into the SDK and fix lifecycle bugs SDK: - Add build_config/migrate_config, mesh_cidrs, route_generation, health and start_bridged; expose abi_info (capability revision 2). - Add wait_routes long-poll; stop wakes waiters, and context_free now stops the network immediately instead of waiting for waiters to time out. Hosts: - Dart: waitRoutes(), MeshProxySession route watcher, ABI capability check. - Android: fix a deadlock where every VPN request waited on its own single-thread worker; requests are now async, status is served from a snapshot, and combined mode reports Partial when the mesh stops. - macOS helper: mesh-only unified mode stops when the mesh is lost; installed_subnet_routes excludes the overlay. - Lab: restore Partial sessions, write migrated profiles back, remove the unreachable TOML import dialog; native test now connects via the form. Docs updated accordingly. Co-Authored-By: Claude Opus 5.5 --- .../com/example/meshport_lab/MainActivity.kt | 9 +- .../example/meshport_lab/MeshVpnService.kt | 230 ++++++++--- .../android_network_test.dart | 5 +- .../lib/features/config_import_dialog.dart | 86 ---- .../lib/features/detail_pages.dart | 16 +- .../meshport_lab/lib/features/lab_screen.dart | 129 +++--- .../lib/features/network_telemetry.dart | 41 +- .../test/configuration_pages_test.dart | 20 +- .../test/native_connect_test.dart | 112 +++++ .../meshport_lab/test/native_import_test.dart | 76 ---- .../meshport_lab/test/network_limit_test.dart | 10 +- apps/meshport_lab/test/profile_test.dart | 122 +++--- .../meshport_lab/test/proxy_session_test.dart | 159 +++++-- apps/meshport_lab/test/telemetry_test.dart | 42 +- .../meshport_flutter/lib/src/client.dart | 85 +++- .../meshport-easytier/src/config_builder.rs | 197 +++++++++ crates/meshport-easytier/src/lib.rs | 308 ++++++++++++-- crates/meshport-easytier/src/system_routes.rs | 65 +++ crates/meshport-ffi/src/lib.rs | 388 ++++++++++++++++-- crates/meshport/src/lib.rs | 8 + docs/advanced-client-features.md | 2 +- docs/architecture.md | 2 + docs/client-runtime.md | 8 +- docs/compatibility.md | 2 + docs/ffi-contract.md | 15 +- docs/singbox-integration.md | 2 +- docs/system-vpn.md | 6 +- docs/testing.md | 8 +- .../lib/src/mesh_proxy_session.dart | 102 +++-- .../lib/src/network_profile.dart | 44 +- .../meshport-vpn-helper/src/mac/self_test.rs | 11 +- tools/meshport-vpn-helper/src/mac/unified.rs | 76 ++-- .../src/mac/unified_test.rs | 2 +- tools/meshport-vpn-helper/src/main.rs | 51 +-- 34 files changed, 1724 insertions(+), 715 deletions(-) delete mode 100644 apps/meshport_lab/lib/features/config_import_dialog.dart create mode 100644 apps/meshport_lab/test/native_connect_test.dart delete mode 100644 apps/meshport_lab/test/native_import_test.dart create mode 100644 crates/meshport-easytier/src/config_builder.rs diff --git a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt index 32d79db..1c4b671 100644 --- a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt +++ b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MainActivity.kt @@ -141,11 +141,10 @@ class MainActivity : FlutterActivity() { val reply = JSONObject().put("ok", true).put("data", data).toString() main.post { result.success(reply) } } else { - service.worker.execute { - try { - val reply = service.request(request).toString() - main.post { result.success(reply) } - } catch (error: Throwable) { main.post { result.error("VPN_REQUEST", error.message, null) } } + service.request(request) { reply -> + reply.fold( + { main.post { result.success(it.toString()) } }, + { error -> main.post { result.error("VPN_REQUEST", error.message, null) } }) } } } diff --git a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt index 4b4eb61..63889b3 100644 --- a/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt +++ b/apps/meshport_lab/android/app/src/main/kotlin/com/example/meshport_lab/MeshVpnService.kt @@ -17,9 +17,16 @@ import java.net.InetAddress import java.util.concurrent.ScheduledThreadPoolExecutor import java.util.concurrent.TimeUnit +// All service state is confined to `worker`: requests from the activity, the +// health tick, network callbacks and route updates run there one at a time. +// Status reads a snapshot refreshed after every worker task, so a slow TUN +// rebuild never stalls the UI poll. class MeshVpnService : VpnService() { companion object { @Volatile var current: MeshVpnService? = null; private set } - val worker = ScheduledThreadPoolExecutor(1) + private val worker = ScheduledThreadPoolExecutor(1) + @Volatile private var statusSnapshot: String? = null + // Invalidates the route watcher thread of a previous session. + @Volatile private var watchSession = 0 private var handle = 0L private var tun: ParcelFileDescriptor? = null private var proxyHandle = 0L @@ -29,8 +36,13 @@ class MeshVpnService : VpnService() { private val protected = sortedSetOf() private var physical: android.net.Network? = null private var networkCallback: ConnectivityManager.NetworkCallback? = null - private var ipv4 = "" - private var installed = emptyList() + // Overlay and routed destinations come from the SDK projection; the + // service only installs them and never derives prefixes itself. + private var overlayAddress = "" + private var overlayPrefix = 0 + private var overlayNetwork = "" + private var meshCidrs = emptyList() + private var routeGeneration = -1L private var running = false private var failure: String? = null override fun onCreate() { @@ -42,26 +54,109 @@ class MeshVpnService : VpnService() { startForeground(77, Notification.Builder(this, "meshport_vpn") .setContentTitle("MeshPort").setContentText("VPN 服务正在运行") .setSmallIcon(R.drawable.ic_stat_meshport).setContentIntent(open).setOngoing(true).build()) + // Health tick. Route changes normally arrive from the watcher thread; + // the generation check here only covers a watcher that has exited. worker.scheduleWithFixedDelay({ - if (running) try { - 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) { if (unified) restartProxy(next) else rebuild(next) } - } catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() } + try { tick() } finally { refreshStatus() } }, 2, 2, TimeUnit.SECONDS) } + private fun tick() { + if (running) try { + if (unified) { + check(proxyCall(JSONObject().put("op","status")).getJSONObject("data").getString("state") == "Running") + if (!meshEnabled) return + } + val data = native(JSONObject().put("op", "status")).getJSONObject("data") + val health = data.optJSONObject("health") ?: JSONObject() + val routable = health.optBoolean(if (unified) "mesh_routable" else "engine_running") + if (!routable) { + // Combined mode keeps the proxy and drops mesh routes; + // mesh-only unified and system VPN have nothing left to serve. + check(unified && proxyProfile.optString("feature", "combined") == "combined") { "Mesh network stopped" } + if (meshCidrs.isNotEmpty()) { + Log.w("MeshPortVPN", "Mesh unavailable; proxy continues without mesh routes") + restartProxy(emptyList()) + } + return + } + val platform = data.getJSONObject("platform_network") + applyRoutes(handle, platform.getLong("route_generation"), strings(platform.getJSONArray("mesh_cidrs"))) + } catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() } + } + /** Runs [block] on `worker`, then republishes the status snapshot. */ + private fun onWorker(block: () -> Unit) = worker.execute { try { block() } finally { refreshStatus() } } + private fun refreshStatus() { + statusSnapshot = try { dispatch(JSONObject().put("op", "status")).toString() } catch (_: Exception) { null } + } + /** Runs on `worker`. Ignores stale updates from a previous context. */ + private fun applyRoutes(context: Long, generation: Long, cidrs: List) { + if (!running || context != handle || generation == routeGeneration) return + if (cidrs != meshCidrs) { if (unified) restartProxy(cidrs) else rebuild(cidrs) } + routeGeneration = generation + } + /** Long-polls the SDK route watch off `worker` so a slow wait never delays requests. */ + private fun watchRoutes(context: Long, from: Long) { + val session = ++watchSession + Thread({ + var generation = from + while (session == watchSession) { + val reply = try { + JSONObject(NativeBridge.call(context, JSONObject().put("op", "wait_routes") + .put("after_generation", generation).put("timeout_ms", 10000).toString())) + } catch (_: Exception) { return@Thread } + // An error means the context is gone; a stopped network is + // left to the health tick, which knows the session's mode. + if (!reply.optBoolean("ok")) return@Thread + val data = reply.getJSONObject("data") + if (!data.optBoolean("running")) return@Thread + if (!data.optBoolean("changed")) continue + generation = data.getLong("route_generation") + val cidrs = strings(data.getJSONArray("mesh_cidrs")) + val next = generation + try { + onWorker { + if (session == watchSession) try { applyRoutes(context, next, cidrs) } + catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() } + } + } catch (_: java.util.concurrent.RejectedExecutionException) { return@Thread } + } + }, "meshport-route-watch").apply { isDaemon = true }.start() + } + private fun strings(list: org.json.JSONArray) = (0 until list.length()).map { list.getString(it) } + private fun useOverlay(overlay: JSONObject?, mode: String) { + checkNotNull(overlay) { "Static mesh address required for $mode" } + overlayAddress = overlay.getString("address") + overlayPrefix = overlay.getInt("prefix") + overlayNetwork = overlay.getString("network") + } private fun native(request: JSONObject): JSONObject { check(handle != 0L) { "VPN context not started" } val response = JSONObject(NativeBridge.call(handle, request.toString())) check(response.optBoolean("ok")) { response.optString("error", "Native request failed") } return response } - fun request(request: JSONObject): JSONObject { + /** + * Callable from any thread; [reply] runs on `worker`, or immediately for a + * status answered from the snapshot. Never blocks the caller. + */ + fun request(request: JSONObject, reply: (Result) -> Unit) { + val snapshot = statusSnapshot + if (request.optString("op") == "status" && snapshot != null) { + reply(Result.success(JSONObject(snapshot))); return + } + try { + // Republish the snapshot before replying, so the caller's next + // status already reflects this operation. + worker.execute { + val result = runCatching { dispatch(request) } + refreshStatus() + reply(result) + } + } catch (error: java.util.concurrent.RejectedExecutionException) { + reply(Result.failure(IllegalStateException("VPN service is stopping"))) + } + } + private fun dispatch(request: JSONObject): JSONObject { return when (request.getString("op")) { "start" -> { check(!running) { "VPN already started" } @@ -77,14 +172,18 @@ class MeshVpnService : VpnService() { 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") + val validation = native(JSONObject().put("op", "validate").put("toml", config)).getJSONObject("data") check(validation.getString("runtime_mode") == "system_vpn") - ipv4 = validation.getJSONObject("profile").getString("ipv4") + useOverlay(validation.optJSONObject("overlay"), "system VPN") Log.i("MeshPortVPN", "Starting native engine") + // The SDK rejects an overlay that overlaps an existing interface. val result = native(request) Log.i("MeshPortVPN", "Native engine started") running = true - rebuild(emptyList()) + val platform = native(JSONObject().put("op", "status")).getJSONObject("data").getJSONObject("platform_network") + rebuild(strings(platform.getJSONArray("mesh_cidrs"))) + routeGeneration = platform.getLong("route_generation") + watchRoutes(handle, routeGeneration) result } catch (error: Throwable) { shutdown(); stopSelf(); throw error } } @@ -92,8 +191,9 @@ class MeshVpnService : VpnService() { "status" -> { if (!running) JSONObject().put("ok", true).put("data", JSONObject().put("state", if (failure == null) "Stopped" else "Failed").put("peer_count", 0)) 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") + // A stopped mesh reports no platform_network. + reply.getJSONObject("data").optJSONObject("platform_network") + ?.put("installed_subnet_routes", org.json.JSONArray(meshCidrs - overlayNetwork))?.put("route_installation", "android_vpn") } } "diagnostics_enable" -> { @@ -102,22 +202,17 @@ class MeshVpnService : VpnService() { else -> native(request) } } - private fun rebuild(routes: List) { - val parts = ipv4.split('/') - val address = parts[0] - val prefix = if (parts.size == 2) parts[1].toInt() else 24 - val raw = InetAddress.getByName(address).address - val network = raw.mapIndexed { index, byte -> - val bits = (prefix - index * 8).coerceIn(0, 8) - (byte.toInt() and (0xff shl (8 - bits))).and(0xff) - }.joinToString(".") + private fun rebuild(cidrs: List) { + // The overlay network is always on the TUN, even when the SDK does not + // project it as routable for bridged hosts. + val routes = (cidrs + overlayNetwork).toSortedSet() val builder = Builder().setSession("MeshPort").setMtu(1280) - .addAddress(address, prefix).addRoute(network, prefix).allowFamily(OsConstants.AF_INET6) + .addAddress(overlayAddress, overlayPrefix).allowFamily(OsConstants.AF_INET6) for (route in routes) { val cidr = route.split('/') builder.addRoute(cidr[0], cidr[1].toInt()) } - Log.i("MeshPortVPN", "Establishing TUN with ${routes.size} learned routes") + Log.i("MeshPortVPN", "Establishing TUN with ${routes.size} mesh routes") val next = builder.establish() ?: error("Android VPN authorization revoked") val previous = tun try { @@ -134,7 +229,7 @@ class MeshVpnService : VpnService() { // network. Wait for the exact address and route set on this TUN, // including removals, before exposing it as usable to callers. val connectivity = getSystemService(ConnectivityManager::class.java) - val expected = (routes + "$network/$prefix").map { + val expected = routes.map { val cidr = it.split('/') IpPrefix(InetAddress.getByName(cidr[0]), cidr[1].toInt()) }.toSet() @@ -144,7 +239,7 @@ class MeshVpnService : VpnService() { val capabilities = connectivity.getNetworkCapabilities(candidate) val properties = connectivity.getLinkProperties(candidate) capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true && - properties?.linkAddresses?.any { it.address.hostAddress == address } == true && + properties?.linkAddresses?.any { it.address.hostAddress == overlayAddress } == true && properties.routes.filter { it.destination.address is java.net.Inet4Address && it.type == android.net.RouteInfo.RTN_UNICAST } .map { it.destination }.toSet() == expected } @@ -156,7 +251,7 @@ class MeshVpnService : VpnService() { Thread.sleep(300) Log.i("MeshPortVPN", "TUN ready") tun = next - installed = routes + meshCidrs = cidrs previous?.close() } catch (error: Exception) { next.close(); throw error } } @@ -178,30 +273,25 @@ class MeshVpnService : VpnService() { val manager = getSystemService(ConnectivityManager::class.java) physical = physicalNetwork(); setUnderlyingNetworks(arrayOf(physical!!)) Log.i("MeshPortVPN", "Unified VPN: physical network selected; mesh enabled=$meshEnabled") + var routes = emptyList() 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) + // One SDK step: application mode, static routable overlay, no local + // overlap, then network + bridge, rolled back together on failure. + val started = native(JSONObject().put("op","start_bridged").put("toml",config) + .put("check_local_overlap",true).put("require_static_overlay",true)).getJSONObject("data") + useOverlay(started.optJSONObject("overlay"), "unified VPN") + proxyProfile.put("mesh_socks", started.getString("listen")) + routes = strings(started.getJSONArray("mesh_cidrs")) + routeGeneration = started.getLong("route_generation") + protected.add(overlayNetwork) } val builder = Builder().setSession("MeshPort · 代理与组网").setMtu(1280) .addAddress("172.19.0.1",30).addAddress("fdfe:dcba:9876::1",126) val internet = proxyProfile.optString("feature","combined") != "mesh" - 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()) } + for (route in (protected + routes).toSortedSet()) { val cidr=route.split('/');builder.addRoute(cidr[0],cidr[1].toInt()) } builder.allowFamily(OsConstants.AF_INET6) } tun = builder.establish() ?: error("VPN authorization revoked") @@ -209,12 +299,15 @@ class MeshVpnService : VpnService() { proxyHandle = NativeBridge.newProxyContext() check(proxyHandle != 0L) proxyCall(JSONObject().put("op","configure_cache").put("directory",cacheDir.absolutePath)) + // The TUN above already carries these routes; no re-establish needed. + meshCidrs = routes restartProxy(routes) running = true + if (meshEnabled) watchRoutes(handle, routeGeneration) Log.i("MeshPortVPN", "Unified VPN: proxy engine ready") networkCallback = object: ConnectivityManager.NetworkCallback() { - override fun onAvailable(network: android.net.Network) { worker.execute { updatePhysical() } } - override fun onLost(network: android.net.Network) { worker.execute { updatePhysical() } } + override fun onAvailable(network: android.net.Network) { onWorker { updatePhysical() } } + override fun onLost(network: android.net.Network) { onWorker { updatePhysical() } } } manager.registerNetworkCallback(android.net.NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) @@ -224,41 +317,37 @@ class MeshVpnService : VpnService() { if (!running || !unified) return try { val next = physicalNetwork() - if (next != physical) { physical=next;setUnderlyingNetworks(arrayOf(next));restartProxy(installed) } + if (next != physical) { physical=next;setUnderlyingNetworks(arrayOf(next));restartProxy(meshCidrs) } } catch (_: Exception) { failure="物理网络已断开,请重新连接";shutdown();stopSelf() } } private fun restartProxy(routes: List) { 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) - } + if (meshEnabled) protected.addAll(routes) val manager = getSystemService(ConnectivityManager::class.java) val iface = manager.getLinkProperties(physical!!)?.interfaceName ?: error("Physical interface unavailable") val index = java.net.NetworkInterface.getByName(iface)?.index ?: error("Physical index unavailable") - if (proxyProfile.optString("feature") == "mesh" && routes != installed) { + if (proxyProfile.optString("feature") == "mesh" && routes != meshCidrs) { val builder = Builder().setSession("MeshPort · 组网").setMtu(1280) .addAddress("172.19.0.1",30).addAddress("fdfe:dcba:9876::1",126).allowFamily(OsConstants.AF_INET6) for (route in protected) { val cidr=route.split('/');builder.addRoute(cidr[0],cidr[1].toInt()) } val previous=tun try { tun=builder.establish() ?: error("VPN authorization revoked") } finally { previous?.close() } } - config.put("listen_port",10818).put("mesh_cidrs",org.json.JSONArray(active.sorted())) + config.put("listen_port",10818).put("mesh_cidrs",org.json.JSONArray(routes)) .put("protected_cidrs",org.json.JSONArray(protected)) .put("tun",JSONObject().put("fd",tun!!.fd).put("name",NativeBridge.tunName(tun!!.fd) ?: error("TUN name unavailable")) .put("physical_interface",iface).put("physical_index",index)) proxyCall(JSONObject().put("op","start").put("config",config)) - Log.i("MeshPortVPN", "Unified VPN: protected physical sockets; learned routes=${routes.size}") - installed = routes + Log.i("MeshPortVPN", "Unified VPN: protected physical sockets; mesh routes=${routes.size}") + meshCidrs = routes } private fun unifiedStatus(): JSONObject { val data = if (meshEnabled) native(JSONObject().put("op","status")).getJSONObject("data") else JSONObject().put("state","Running").put("peer_count",0) + // The VPN and proxy are up even when the mesh is not: report Partial + // (as the macOS helper does) so hosts still treat it as connected. + if (meshEnabled && data.optJSONObject("health")?.optBoolean("mesh_routable") != true) data.put("state","Partial") data.put("runtime_mode","unified_vpn").put("proxy",proxyCall(JSONObject().put("op","status")).getJSONObject("data")) val platform = data.optJSONObject("platform_network") ?: JSONObject() platform.put("ready",tun!=null).put("route_installation","singbox_tun").put("protected_subnets",org.json.JSONArray(protected)) @@ -268,15 +357,22 @@ class MeshVpnService : VpnService() { private fun shutdown() { if (running || handle != 0L || proxyHandle != 0L || tun != null) Log.i("MeshPortVPN", "Stopping VPN and releasing TUN") running = false + watchSession++ if (proxyHandle != 0L) { NativeBridge.freeProxyContext(proxyHandle); proxyHandle = 0L } val connectivity = getSystemService(ConnectivityManager::class.java) networkCallback?.let { try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {} } networkCallback = null; physical = null; protected.clear(); unified = false - if (handle != 0L) { NativeBridge.freeContext(handle); handle = 0L } - tun?.close(); tun = null; installed = emptyList() + if (handle != 0L) { + // Stop first: it wakes an in-flight wait_routes, which otherwise + // keeps the network alive until its timeout after the free. + try { native(JSONObject().put("op", "stop")) } catch (_: Exception) {} + NativeBridge.freeContext(handle); handle = 0L + } + tun?.close(); tun = null; meshCidrs = emptyList(); routeGeneration = -1L + overlayAddress = ""; overlayPrefix = 0; overlayNetwork = "" } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int = START_NOT_STICKY - override fun onRevoke() { worker.execute { shutdown(); stopSelf() } } + override fun onRevoke() { onWorker { shutdown(); stopSelf() } } override fun onDestroy() { worker.execute { shutdown(); if (current === this) current = null; worker.shutdown() } super.onDestroy() diff --git a/apps/meshport_lab/integration_test/android_network_test.dart b/apps/meshport_lab/integration_test/android_network_test.dart index 96ace31..d5cf9cf 100644 --- a/apps/meshport_lab/integration_test/android_network_test.dart +++ b/apps/meshport_lab/integration_test/android_network_test.dart @@ -36,11 +36,12 @@ Future waitForRoutes( final state = await client.status(); lastState = state; final platform = state['platform_network'] as Map? ?? {}; + // mesh_cidrs is the SDK's routable set (overlay + accepted subnets). final routes = - platform[installed ? 'installed_subnet_routes' : 'subnet_routes'] + platform[installed ? 'installed_subnet_routes' : 'mesh_cidrs'] as List? ?? []; - if (withdrawn ? routes.isEmpty : routes.contains('10.253.79.0/24')) return; + if (routes.contains('10.253.79.0/24') != withdrawn) return; await Future.delayed(const Duration(milliseconds: 200)); } debugPrint('ANDROID_ROUTE_TIMEOUT_STATE ${jsonEncode(lastState)}'); diff --git a/apps/meshport_lab/lib/features/config_import_dialog.dart b/apps/meshport_lab/lib/features/config_import_dialog.dart deleted file mode 100644 index 0b096a1..0000000 --- a/apps/meshport_lab/lib/features/config_import_dialog.dart +++ /dev/null @@ -1,86 +0,0 @@ -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 { - const ConfigImportDialog({super.key}); - @override - State createState() => _ConfigImportDialogState(); -} - -class _ConfigImportDialogState extends State { - final editor = TextEditingController(); - @override - void dispose() { - editor.dispose(); - super.dispose(); - } - - String error = ''; - Future read(String method) async { - try { - final value = await const MethodChannel( - 'meshport/system_vpn', - ).invokeMethod(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: 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: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('取消'), - ), - FilledButton( - onPressed: () => Navigator.pop(context, editor.text), - child: const Text('校验并连接'), - ), - ], - ); -} diff --git a/apps/meshport_lab/lib/features/detail_pages.dart b/apps/meshport_lab/lib/features/detail_pages.dart index f951a61..5597e39 100644 --- a/apps/meshport_lab/lib/features/detail_pages.dart +++ b/apps/meshport_lab/lib/features/detail_pages.dart @@ -54,11 +54,9 @@ class NodeDetailBody extends StatelessWidget { }); @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; + // Path and latency source come classified from the SDK `nodes` projection. + final direct = node['path'] == 'direct'; + final latency = node['latency_ms']; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -75,14 +73,12 @@ class NodeDetailBody extends StatelessWidget { ListTile( title: const Text('直连能力'), subtitle: Text( - '${peer?['direct'] == true ? '有直连可用' : '未发现直连'} · ${peer?['hole_punched'] == true ? '打洞建立' : '未确认打洞'}', + '${node['direct_available'] == 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' : ''}', - ), + title: Text(node['latency_source'] == 'link_rtt' ? '链路 RTT' : '路由估算'), + subtitle: Text(latency == null ? '未测得' : '$latency ms'), ), ListTile( title: const Text('虚拟地址 / NAT'), diff --git a/apps/meshport_lab/lib/features/lab_screen.dart b/apps/meshport_lab/lib/features/lab_screen.dart index 521cb19..ab1b0c4 100644 --- a/apps/meshport_lab/lib/features/lab_screen.dart +++ b/apps/meshport_lab/lib/features/lab_screen.dart @@ -6,7 +6,6 @@ import 'package:flutter/services.dart'; import 'package:meshport_flutter/meshport_flutter.dart'; import 'package:meshport_client_core/meshport_client_core.dart'; import 'package:singbox_flutter/singbox_flutter.dart'; -import 'config_import_dialog.dart'; import 'network_telemetry.dart'; import 'proxy_panel.dart'; import 'configuration_pages.dart'; @@ -107,10 +106,15 @@ class _LabScreenState extends State { Future initialize() async { try { log('客户端启动 · ${Platform.operatingSystem} · 代理诊断日志已开启'); - const path = String.fromEnvironment('MESHPORT_LIBRARY'); + // A --dart-define wins; the process environment serves `flutter test` + // and development runs. Release builds use the bundled library. + const defined = String.fromEnvironment('MESHPORT_LIBRARY'); + final path = defined.isNotEmpty + ? defined + : Platform.environment['MESHPORT_LIBRARY']; final opened = await diagnosticStage( '加载 MeshPort 动态库', - () => MeshPortClient.open(libraryPath: path.isEmpty ? null : path), + () => MeshPortClient.open(libraryPath: path), ); if (!mounted) { await opened.close(); @@ -139,9 +143,7 @@ class _LabScreenState extends State { bool restored = false; if (profileSupported) { try { - final stored = (await vpnChannel.invokeMethod( - 'load_profile', - ))?.replaceAll(RegExp(r'^subnet_routes\s*=.*$', multiLine: true), ''); + final stored = await loadMigratedProfile(); if (stored != null) { await loadForm(stored); restored = true; @@ -197,7 +199,8 @@ class _LabScreenState extends State { if (Platform.isAndroid) { final snapshot = await androidVpnRequest({'op': 'status'}); final data = snapshot['data'] as Map?; - if (data?['state'] == 'Running') { + // Partial: a combined VPN whose mesh stopped still carries the proxy. + if (data?['state'] == 'Running' || data?['state'] == 'Partial') { systemClient = client = MeshPortClient.fromTransport( request: androidVpnRequest, close: () async { @@ -227,7 +230,7 @@ class _LabScreenState extends State { (singBoxEnabled && proxyProfile.feature == 'proxy'))) { log('按已保存配置自动连接'); await perform((_) async { - await startConfig(buildFormConfig()); + await startConfig(await startableFormConfig()); runningProxyMode = proxyProfile.modeLabel; runningProxyLabel = proxyProfile.nodes @@ -393,8 +396,8 @@ class _LabScreenState extends State { } } - String buildConfig() { - final form = buildFormConfig(); + Future buildConfig() async { + final form = await buildFormConfig(); return loadedForm == form && loadedConfig != null ? loadedConfig! : form; } @@ -421,9 +424,13 @@ class _LabScreenState extends State { routeMode = optimization['mode'] as String; preferUdp = optimization['prefer_udp'] == true; relayIds.text = (optimization['relay_peer_ids'] as List).join(','); - loadedConfig = config; - loadedForm = buildFormConfig(); }); + // Rendered from the fields just loaded, so an untouched form maps back + // to the original text (and keeps options the form cannot show). + final form = await buildFormConfig(); + if (!mounted) return; + loadedConfig = config; + loadedForm = form; } Map networkValues() => { @@ -455,7 +462,39 @@ class _LabScreenState extends State { .toList(), }, }; - String buildFormConfig() => NetworkProfile(networkValues()).toToml(); + Future buildFormConfig() => + NetworkProfile(networkValues()).toToml(applicationClient!); + + /// Application-mode internet-only proxying never starts the mesh, so an + /// incomplete network form must not block it. + Future startableFormConfig() async => + runtimeMode == 'application' && + singBoxEnabled && + proxyProfile.feature == 'proxy' + ? '' + : await buildFormConfig(); + + /// Drops options earlier releases saved; the SDK owns the migration rules. + Future migratedProfile(String? stored) async => + stored == null ? null : await applicationClient!.migrateConfig(stored); + + /// Loads the saved network profile and, when the SDK migrates it, writes + /// the migrated text back so the legacy form is not reloaded next launch. + Future loadMigratedProfile() async { + final stored = await vpnChannel.invokeMethod('load_profile'); + final migrated = await migratedProfile(stored); + if (migrated != null && migrated != stored) { + try { + await applicationClient!.validate(migrated); + await vpnChannel.invokeMethod('save_profile', migrated); + log('已移除旧版配置项并保存迁移后的网络配置'); + } catch (_) { + log('旧版配置已在内存中迁移,但未能写回 $profileStorage'); + } + } + return migrated; + } + Future saveNetworkValues(Map values) async { final incoming = NetworkProfile(values).values; final policy = incoming['optimization'] as Map; @@ -463,7 +502,7 @@ class _LabScreenState extends State { .map((v) => v is int ? v : int.parse('$v')) .toList(); if (incoming['runtime_mode'] != 'application') incoming['dhcp'] = false; - final toml = NetworkProfile(incoming).toToml(); + final toml = await NetworkProfile(incoming).toToml(applicationClient!); await applicationClient!.request({'op': 'validate', 'toml': toml}); await saveProfile(toml, explicit: true); await loadForm(toml); @@ -497,7 +536,7 @@ class _LabScreenState extends State { } Future connect(MeshPortClient c) async { - final config = buildConfig(); + final config = await buildConfig(); await startConfig(config); proxyProfile.entry = runtimeMode; proxyProfile.proxyEnabled = singBoxEnabled; @@ -633,9 +672,7 @@ class _LabScreenState extends State { Future migrateLegacyProfiles() async { await vpnChannel.invokeMethod('migrate_profiles'); final proxy = await vpnChannel.invokeMethod('load_proxy_profile'); - final network = (await vpnChannel.invokeMethod( - 'load_profile', - ))?.replaceAll(RegExp(r'^subnet_routes\s*=.*$', multiLine: true), ''); + final network = await loadMigratedProfile(); if (network != null) await loadForm(network); if (proxy != null) { final imported = ProxyProfile.fromJson( @@ -1227,22 +1264,7 @@ class _LabScreenState extends State { NodeTelemetry( status: status, onNode: (node, peer) => openDetail('节点详情', () { - final id = node['peer_id']; - final routes = (status['routes'] as List? ?? []).where( - (v) => v['peer_id'] == id, - ); - final peers = (status['peers'] as List? ?? []).where( - (v) => v['peer_id'] == id, - ); - return NodeDetailBody( - node: routes.isEmpty - ? {'peer_id': id, 'hostname': node['hostname']} - : Map.from(routes.first), - peer: peers.isEmpty - ? null - : Map.from(peers.first), - status: status, - ); + return NodeDetailBody(node: node, peer: peer, status: status); }), ), ]), @@ -1356,8 +1378,9 @@ class _LabScreenState extends State { FilledButton.icon( onPressed: busy || client == null ? null - : () => - perform((_) => saveProfile(buildConfig(), explicit: true)), + : () => perform( + (_) async => saveProfile(await buildConfig(), explicit: true), + ), icon: const Icon(Icons.save_outlined), label: const Text('保存配置'), ), @@ -1606,18 +1629,13 @@ class _LabScreenState extends State { await proxySaveTail; proxyProfile.entry = runtimeMode; if (profileSupported) await saveProxyProfile(); - final nextConfig = buildFormConfig(); - if (proxyProfile.feature != 'proxy') { - await applicationClient!.request({ - 'op': 'validate', - 'toml': nextConfig, - }); - } + // build_config validates, so a bad form fails before stopping anything. + if (proxyProfile.feature != 'proxy') await buildFormConfig(); if (running) await stopActive(c); singBoxEnabled = runtimeMode == 'unified_vpn' || (runtimeMode == 'application' && proxyProfile.feature != 'mesh'); - await startConfig(buildFormConfig()); + await startConfig(await startableFormConfig()); runningProxyLabel = proxyProfile.nodes .where((n) => n.id == proxyProfile.selectedId) @@ -1655,29 +1673,6 @@ class _LabScreenState extends State { LogsPageBody(logs: logs, onClear: () => setState(() => logs.clear())), ), ); - Future importConfig() async { - final text = await showDialog( - context: context, - builder: (_) => const ConfigImportDialog(), - ); - if (text != null && mounted) { - await perform((c) async { - await loadForm(text); - proxyProfile.feature = 'mesh'; - proxyProfile.entry = runtimeMode; - proxyProfile.proxyEnabled = false; - singBoxEnabled = false; - await startConfig(text); - try { - await saveProxyProfile(); - } catch (_) { - log('组网已连接,但连接方式未能保存,请重试保存'); - } - log('导入配置并启动引擎'); - }); - } - } - @override Widget build(BuildContext context) { final pages = [overview, proxyPage, nodes, settings]; diff --git a/apps/meshport_lab/lib/features/network_telemetry.dart b/apps/meshport_lab/lib/features/network_telemetry.dart index d219887..d8252a9 100644 --- a/apps/meshport_lab/lib/features/network_telemetry.dart +++ b/apps/meshport_lab/lib/features/network_telemetry.dart @@ -23,15 +23,12 @@ class NodeTelemetry extends StatelessWidget { for (final peer in status['peers'] as List? ?? []) peer['peer_id']: Map.from(peer), }; - final nodes = >{ - for (final route in status['routes'] as List? ?? []) - route['peer_id']: Map.from(route), - }; - for (final id in peers.keys) { - nodes.putIfAbsent(id, () => {'peer_id': id}); - } + // The SDK merges routes and links and classifies path and latency source. + final nodes = [ + for (final node in status['nodes'] as List? ?? []) + Map.from(node as Map), + ]; final local = status['local_peer'] as Map?; - if (local != null) nodes.remove(local['peer_id']); if (nodes.isEmpty && local == null) { return const Text('尚未发现节点,连接后显示链路延迟与流量。'); } @@ -77,17 +74,15 @@ class NodeTelemetry extends StatelessWidget { ), if (local != null && nodes.isNotEmpty) const Divider(), if (local != null && nodes.isEmpty) const Text('尚未发现其他节点。'), - ...nodes.values.map((node) { + ...nodes.map((node) { final peer = peers[node['peer_id']]; - final directAvailable = peer?['direct'] == true; - final direct = - directAvailable && - (node['next_hop_peer_id'] == null || - node['next_hop_peer_id'] == node['peer_id']); - final measured = direct ? (peer?['latency_ms'] as num?) : null; - final estimated = node['estimated_latency_ms'] as num?; - final latency = measured ?? estimated; - final latencyLabel = measured != null ? '链路 RTT' : '路由估算'; + final directAvailable = node['direct_available'] == true; + final direct = node['path'] == 'direct'; + final metered = node['metered'] == true; + final latency = node['latency_ms'] as num?; + final latencyLabel = node['latency_source'] == 'link_rtt' + ? '链路 RTT' + : '路由估算'; return InkWell( onTap: onNode == null ? null : () => onNode!(node, peer), child: Padding( @@ -122,7 +117,7 @@ class NodeTelemetry extends StatelessWidget { ), const SizedBox(height: 6), Text( - '${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${direct && peer?['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}', + '${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${node['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}', ), if (node['udp_nat_type'] != null) Text( @@ -134,13 +129,13 @@ class NodeTelemetry extends StatelessWidget { ), const SizedBox(height: 6), Text( - peer == null + !metered ? '流量经下一跳 ${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)}', + : '↓ ${formatBytes(node['rx_bytes_per_second'] as num?, rate: true)} ↑ ${formatBytes(node['tx_bytes_per_second'] as num?, rate: true)}', ), - if (peer != null) + if (metered) Text( - '当前链路累计 ↓ ${formatBytes(peer['rx_bytes'] as num?)} ↑ ${formatBytes(peer['tx_bytes'] as num?)}', + '当前链路累计 ↓ ${formatBytes(node['rx_bytes'] as num?)} ↑ ${formatBytes(node['tx_bytes'] as num?)}', style: Theme.of(context).textTheme.bodySmall, ), ], diff --git a/apps/meshport_lab/test/configuration_pages_test.dart b/apps/meshport_lab/test/configuration_pages_test.dart index 43ea1da..e7943ef 100644 --- a/apps/meshport_lab/test/configuration_pages_test.dart +++ b/apps/meshport_lab/test/configuration_pages_test.dart @@ -1,6 +1,8 @@ +import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshport_client_core/meshport_client_core.dart'; +import 'package:meshport_flutter/meshport_flutter.dart'; import 'package:meshport_lab/features/configuration_pages.dart'; void main() { @@ -62,9 +64,10 @@ void main() { await tester.pumpAndSettle(); expect(find.text('请输入有效域名或 CIDR,不接受星号语法'), findsOneWidget); }); + final library = Platform.environment['MESHPORT_LIBRARY']; test( 'network draft preserves supported options and forces encrypted single-stack host', - () { + () async { final draft = NetworkProfile({ 'runtime_mode': 'unified_vpn', 'ipv4': '10.77.0.11/24', @@ -75,10 +78,17 @@ void main() { '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 = []')); + final client = await MeshPortClient.open(libraryPath: library); + try { + final toml = await draft.toToml(client); + expect(toml, contains('no_tun = true')); + expect(toml, contains('disable_p2p = true')); + expect(toml, contains('enable_encryption = true')); + expect(toml, contains('stun_servers = []')); + } finally { + await client.close(); + } }, + skip: library == null ? 'Requires native Rust library' : false, ); } diff --git a/apps/meshport_lab/test/native_connect_test.dart b/apps/meshport_lab/test/native_connect_test.dart new file mode 100644 index 0000000..1f8bbac --- /dev/null +++ b/apps/meshport_lab/test/native_connect_test.dart @@ -0,0 +1,112 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshport_lab/features/lab_screen.dart'; + +void main() { + const channel = MethodChannel('meshport/system_vpn'); + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + // Profile storage: nothing stored, saves accepted. + setUp( + () => binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (_) async => null, + ), + ); + tearDown( + () => + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null), + ); + testWidgets( + 'form connect starts real native engine and can stop it', + (tester) async { + tester.view.physicalSize = const Size(1400, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget(const MaterialApp(home: LabScreen())); + final lab = tester.state(find.byType(LabScreen)) as dynamic; + List logs() => (lab.logs as List).cast(); + Finder field(String label) => find.byWidgetPredicate( + (widget) => + widget is TextField && widget.decoration?.labelText == label, + ); + Future waitForLog(String text) async { + for (var i = 0; i < 60 && !logs().any((l) => l.contains(text)); i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await tester.pump(); + } + expect(logs(), contains(contains(text))); + } + + await waitForLog('原生库已加载'); + // Startup restores profiles first; let it finish before overriding them. + await waitForLog('穿透'); + // Mesh-only, in-app engine: no helper, VPN permission or proxy node. + lab.runtimeMode = 'application'; + lab.proxyProfile.feature = 'mesh'; + lab.proxyProfile.entry = 'application'; + await tester.tap(find.text('组网').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('基础配置')); + await tester.pumpAndSettle(); + await tester.enterText(field('网络名称'), 'ui-local-test'); + await tester.enterText(field('网络密钥'), 'test-only'); + await tester.enterText(field('虚拟 IPv4 / 前缀'), '10.79.0.11/24'); + await tester.tap(find.text('保存草稿')); + await waitForLog('网络配置已保存到'); + for (var i = 0; i < 40 && find.text('保存中…').evaluate().isNotEmpty; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await tester.pump(); + } + await tester.pageBack(); + await tester.pumpAndSettle(); + await tester.tap(find.text('概览').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('连接').last); + await tester.pump(const Duration(milliseconds: 500)); + for ( + var i = 0; + i < 40 && !logs().any((l) => l.contains('[启动组网引擎] 成功')); + i++ + ) { + await tester.runAsync(() async { + await Future.delayed(const Duration(milliseconds: 100)); + }); + await tester.pump(); + } + expect(logs(), contains(contains('[启动组网引擎] 成功'))); + for ( + var i = 0; + i < 40 && find.text('引擎运行中 · 0 个节点').evaluate().isEmpty; + i++ + ) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 100)), + ); + await tester.pump(); + } + expect(find.text('引擎运行中 · 0 个节点'), findsOneWidget); + expect(find.textContaining('当前设备'), findsOneWidget); + expect(find.textContaining('节点 ID'), findsOneWidget); + await tester.tap(find.text('断开连接')); + for (var i = 0; i < 40 && find.text('尚未连接').evaluate().isEmpty; i++) { + await tester.runAsync(() async { + await Future.delayed(const Duration(milliseconds: 100)); + }); + await tester.pump(); + } + expect(find.text('尚未连接'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await Future.delayed(const Duration(milliseconds: 100)); + }); + }, + skip: Platform.environment['MESHPORT_LIBRARY'] == null, + ); +} diff --git a/apps/meshport_lab/test/native_import_test.dart b/apps/meshport_lab/test/native_import_test.dart deleted file mode 100644 index 41ac621..0000000 --- a/apps/meshport_lab/test/native_import_test.dart +++ /dev/null @@ -1,76 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:meshport_lab/features/lab_screen.dart'; - -void main() { - testWidgets( - 'TOML import starts real native engine and can stop it', - (tester) async { - await tester.pumpWidget(const MaterialApp(home: LabScreen())); - await tester.runAsync(() async { - await Future.delayed(const Duration(milliseconds: 500)); - }); - await tester.pump(); - expect(find.textContaining('原生库已加载'), findsOneWidget); - await tester.tap(find.text('设置').last); - await tester.pumpAndSettle(); - await tester.tap(find.text('导入')); - await tester.pumpAndSettle(); - await tester.tap(find.text('粘贴 TOML 并连接')); - await tester.pumpAndSettle(); - await tester.enterText(find.byType(TextField).last, ''' -ipv4 = "10.79.0.11" -listeners = [] -stun_servers = [] -stun_servers_v6 = [] -[network_identity] -network_name = "ui-local-test" -network_secret = "test-only" -[flags] -default_protocol = "udp" -'''); - await tester.tap(find.text('校验并连接').last); - await tester.pump(const Duration(milliseconds: 500)); - await tester.pumpAndSettle(); - for ( - var i = 0; - i < 40 && find.textContaining('导入配置并启动引擎').evaluate().isEmpty; - i++ - ) { - await tester.runAsync(() async { - await Future.delayed(const Duration(milliseconds: 100)); - }); - await tester.pump(); - } - expect(find.textContaining('导入配置并启动引擎'), findsOneWidget); - await tester.tap(find.text('概览').last); - await tester.pumpAndSettle(); - for ( - var i = 0; - i < 40 && find.text('引擎运行中 · 0 个节点').evaluate().isEmpty; - i++ - ) { - await tester.runAsync( - () => Future.delayed(const Duration(milliseconds: 100)), - ); - await tester.pump(); - } - expect(find.text('引擎运行中 · 0 个节点'), findsOneWidget); - expect(find.textContaining('当前设备'), findsOneWidget); - expect(find.textContaining('节点 ID'), findsOneWidget); - await tester.tap(find.text('断开连接')); - for (var i = 0; i < 40 && find.text('尚未连接').evaluate().isEmpty; i++) { - await tester.runAsync(() async { - await Future.delayed(const Duration(milliseconds: 100)); - }); - await tester.pump(); - } - expect(find.text('尚未连接'), findsOneWidget); - await tester.pumpWidget(const SizedBox.shrink()); - await tester.runAsync(() async { - await Future.delayed(const Duration(milliseconds: 100)); - }); - }, - skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'), - ); -} diff --git a/apps/meshport_lab/test/network_limit_test.dart b/apps/meshport_lab/test/network_limit_test.dart index 168eba9..e4765fa 100644 --- a/apps/meshport_lab/test/network_limit_test.dart +++ b/apps/meshport_lab/test/network_limit_test.dart @@ -9,8 +9,8 @@ void main() { 'flags': {'foreign_relay_bps_limit': 18446744073709552000.0}, }); expect( - p.toToml(), - contains('foreign_relay_bps_limit = "18446744073709551615"'), + (p.values['flags'] as Map)['foreign_relay_bps_limit'], + '18446744073709551615', ); expect( NetworkProfile.unsignedLimit('18446744073709551614'), @@ -39,11 +39,13 @@ void main() { Map.from(projected['profile']), ); p.values['runtime_mode'] = 'unified_vpn'; - await client.validate(p.toToml()); + final toml = await p.toToml(client); + await client.validate(toml); expect( - p.toToml(), + toml, contains('foreign_relay_bps_limit = "18446744073709551615"'), ); + expect(toml, contains('mode = "application"')); } finally { await client.close(); } diff --git a/apps/meshport_lab/test/profile_test.dart b/apps/meshport_lab/test/profile_test.dart index e3acf99..e1303e4 100644 --- a/apps/meshport_lab/test/profile_test.dart +++ b/apps/meshport_lab/test/profile_test.dart @@ -1,3 +1,4 @@ +import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -21,6 +22,8 @@ void main() { case 'delete_profile': stored = null; return null; + case 'save_proxy_profile': + return null; default: throw StateError('Unexpected call: ${call.method}'); } @@ -31,30 +34,42 @@ void main() { binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null), ); - Future waitFor(WidgetTester tester, Finder finder) async { - for (var i = 0; i < 60 && finder.evaluate().isEmpty; i++) { + // The overview shows only the newest log lines; read the full log list. + List logs(WidgetTester tester) => + ((tester.state(find.byType(LabScreen, skipOffstage: false)) as dynamic) + .logs + as List) + .cast(); + + Future waitForLog(WidgetTester tester, String text) async { + for ( + var i = 0; + i < 100 && !logs(tester).any((line) => line.contains(text)); + i++ + ) { await tester.runAsync( () => Future.delayed(const Duration(milliseconds: 50)), ); await tester.pump(); } - expect(finder, findsWidgets); + expect(logs(tester), contains(contains(text))); } - Future openSettings(WidgetTester tester) async { + Future openApp(WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: LabScreen())); - await waitFor(tester, find.textContaining('原生库已加载')); - await waitFor( - tester, - find.byWidgetPredicate( - (widget) => - widget is Text && - (widget.data?.contains('已载入默认配置') == true || - widget.data?.contains('已载入默认网络配置') == true || - widget.data?.contains('已自动载入保存的网络配置') == true), - ), - ); - await tester.tap(find.text('设置').last); + await waitForLog(tester, '原生库已加载'); + await waitForLog(tester, '载入'); + } + + Future openPage(WidgetTester tester, String tab, String entry) async { + await tester.tap(find.text(tab).last); + await tester.pumpAndSettle(); + await tester.tap(find.text(entry)); + await tester.pumpAndSettle(); + } + + Future back(WidgetTester tester) async { + await tester.pageBack(); await tester.pumpAndSettle(); } @@ -69,45 +84,36 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); - await openSettings(tester); + await openApp(tester); + await openPage(tester, '组网', '基础配置'); await tester.enterText(field('网络名称'), '我的网络'); await tester.enterText(field('网络密钥'), 'test-only-secret'); await tester.enterText(field('节点名称'), 'saved-node'); - await tester.enterText(field('虚拟 IPv4'), '10.79.0.11/24'); - await tester.tap(find.text('保存配置')); - await waitFor(tester, find.textContaining('网络配置已保存到 macOS 钥匙串')); + await tester.enterText(field('虚拟 IPv4 / 前缀'), '10.79.0.11/24'); + await tester.tap(find.text('保存草稿')); + await waitForLog(tester, '网络配置已保存到'); expect(stored, contains('我的网络')); - expect(find.text('尚未连接'), findsNothing); // The settings page is selected. await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync( () => Future.delayed(const Duration(milliseconds: 100)), ); - await openSettings(tester); - await waitFor(tester, find.textContaining('已自动载入保存的网络配置')); - expect(tester.widget(field('网络名称')).controller!.text, '我的网络'); - expect( - tester.widget(field('网络密钥')).controller!.text, - 'test-only-secret', - ); - expect( - tester.widget(field('节点名称')).controller!.text, - 'saved-node', - ); - expect( - tester.widget(field('虚拟 IPv4')).controller!.text, - '10.79.0.11/24', - ); - await tester.tap(find.text('概览').last); - await tester.pumpAndSettle(); - expect(find.text('尚未连接'), findsOneWidget); - await tester.tap(find.text('设置').last); - await tester.pumpAndSettle(); + await openApp(tester); + await waitForLog(tester, '已自动载入保存的网络配置'); + await openPage(tester, '组网', '基础配置'); + String text(String label) => + tester.widget(field(label)).controller!.text; + expect(text('网络名称'), '我的网络'); + expect(text('网络密钥'), 'test-only-secret'); + expect(text('节点名称'), 'saved-node'); + expect(text('虚拟 IPv4 / 前缀'), '10.79.0.11/24'); + await back(tester); + await openPage(tester, '设置', '默认配置'); await tester.tap(find.text('删除已保存配置')); - await waitFor(tester, find.textContaining('已删除保存的配置')); + await waitForLog(tester, '已删除保存的配置'); expect(stored, isNull); await tester.pumpWidget(const SizedBox.shrink()); }, - skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'), + skip: Platform.environment['MESHPORT_LIBRARY'] == null, ); testWidgets( @@ -126,14 +132,34 @@ network_secret = "test-only" disable_udp_hole_punching = true '''; final original = stored; - await openSettings(tester); - await waitFor(tester, find.textContaining('已自动载入保存的网络配置')); - await tester.ensureVisible(find.text('保存配置')); + await openApp(tester); + await waitForLog(tester, '已自动载入保存的网络配置'); + await openPage(tester, '设置', '默认配置'); await tester.tap(find.text('保存配置')); - await waitFor(tester, find.textContaining('网络配置已保存到 macOS 钥匙串')); + await waitForLog(tester, '网络配置已保存到'); expect(stored, original); await tester.pumpWidget(const SizedBox.shrink()); }, - skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'), + skip: Platform.environment['MESHPORT_LIBRARY'] == null, + ); + + testWidgets( + 'legacy profile is migrated and written back on restore', + (tester) async { + stored = ''' +hostname = "legacy-node" +ipv4 = "10.79.0.11/24" +subnet_routes = ["192.168.21.0/24"] +[network_identity] +network_name = "legacy" +network_secret = "test-only" +'''; + await openApp(tester); + await waitForLog(tester, '已自动载入保存的网络配置'); + expect(stored, isNot(contains('subnet_routes'))); + expect(stored, contains('legacy-node')); + await tester.pumpWidget(const SizedBox.shrink()); + }, + skip: Platform.environment['MESHPORT_LIBRARY'] == null, ); } diff --git a/apps/meshport_lab/test/proxy_session_test.dart b/apps/meshport_lab/test/proxy_session_test.dart index d5fe575..680a70e 100644 --- a/apps/meshport_lab/test/proxy_session_test.dart +++ b/apps/meshport_lab/test/proxy_session_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshport_flutter/meshport_flutter.dart'; @@ -47,29 +48,75 @@ class Fixture { ); late final session = MeshProxySession(mesh: mesh, proxy: proxy); String state = 'Stopped', mode = 'application'; - String? ip = '10.77.0.11/24'; + bool bridge = false; + // SDK projection: canonical overlay network plus accepted subnets. + String? overlay = '10.77.0.0/24'; List routes = ['192.168.21.0/24']; + List get cidrs => {?overlay, ...routes}.toList()..sort(); + int generation = 1; + var _routesChanged = Completer(); + void _wake() { + _routesChanged.complete(); + _routesChanged = Completer(); + } + + /// Publishes a route change the way the SDK watch does. + void announceRoutes(List next) { + routes = next; + generation++; + _wake(); + } + Future> request(Map input) async { final op = input['op'] as String; + if (op == 'wait_routes') { + // Long poll: not logged so lifecycle event assertions stay exact. + if (state == 'Running' && input['after_generation'] == generation) { + await _routesChanged.future; + } + final running = state == 'Running'; + return { + 'ok': true, + 'data': { + 'running': running, + 'changed': !running || input['after_generation'] != generation, + 'route_generation': running ? generation : null, + 'mesh_cidrs': running ? cidrs : [], + }, + }; + } events.add('mesh.$op'); + if (op == 'start_bridged') { + if (mode != 'application') { + return {'ok': false, 'error': 'bridged routing requires application'}; + } + if (state != 'Stopped') return {'ok': false, 'error': 'already started'}; + } final data = switch (op) { - 'validate' => {'runtime_mode': mode}, - 'start' => (() { + 'start_bridged' => (() { state = 'Running'; - return {}; + bridge = true; + return { + 'listen': '127.0.0.1:50001', + 'route_generation': generation, + }; })(), 'stop' => (() { state = 'Stopped'; + _wake(); + return {}; + })(), + 'socks_stop' => (() { + bridge = false; return {}; })(), - '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, + 'platform_network': {'mesh_cidrs': state == 'Running' ? cidrs : []}, + 'health': { + 'engine_running': state == 'Running', + 'bridge_running': state == 'Running' && bridge, + 'mesh_routable': state == 'Running' && bridge, }, }, _ => {}, @@ -87,7 +134,6 @@ void main() { 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']; @@ -107,6 +153,21 @@ void main() { await expectLater(f.session.start('test'), throwsStateError); }, ); + test('route changes are applied from the SDK watch without a poll', () async { + final f = Fixture(); + await f.session.start('test'); + expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.21.0/24'); + f.announceRoutes(['192.168.23.0/24']); + for (var i = 0; i < 50 && !f.events.last.contains('192.168.23.0'); i++) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.23.0/24'); + expect(f.session.state, 'Running'); + f.events.clear(); + await f.session.stop(); + expect(f.events, ['proxy.stop', 'mesh.socks_stop', 'mesh.stop']); + await f.session.close(); + }); test('failed engine startup rolls back and permits retry', () async { final f = Fixture(); f.proxy.failStart = true; @@ -130,10 +191,10 @@ void main() { final duplicate = f.session.start('test'); await expectLater(duplicate, throwsStateError); await first; - expect(f.events.where((e) => e == 'mesh.start').length, 1); + expect(f.events.where((e) => e == 'mesh.start_bridged').length, 1); await f.session.stop(); f.mode = 'system_vpn'; - await expectLater(f.session.start('test'), throwsUnsupportedError); + await expectLater(f.session.start('test'), throwsStateError); await f.session.close(); }, ); @@ -141,11 +202,11 @@ void main() { 'wait for DHCP then start; unexpected engine failure cleans mesh', () async { final f = Fixture(); - f.ip = null; + f.overlay = null; f.routes = []; await f.session.start('test'); expect(f.session.state, 'AwaitingAddress'); - f.ip = '10.77.0.11/24'; + f.overlay = '10.77.0.0/24'; await f.session.refresh(); expect(f.session.state, 'Running'); f.proxy.state = 'Failed'; @@ -155,26 +216,54 @@ void main() { await f.session.close(); }, ); + test('mesh prefixes are read from the SDK projection only', () { + expect( + meshPrefixes({ + 'ipv4': '10.77.0.11/24', + 'platform_network': { + 'subnet_routes': ['0.0.0.0/0'], + 'mesh_cidrs': ['10.77.0.0/24', '192.168.21.0/24'], + }, + }), + ['10.77.0.0/24', '192.168.21.0/24'], + ); + expect(meshPrefixes({'ipv4': '10.77.0.11/24'}), isEmpty); + expect( + () => meshPrefixes({ + 'platform_network': { + 'mesh_cidrs': [7], + }, + }), + throwsStateError, + ); + }); + test('a busy context is refused without stopping its network', () async { + final f = Fixture(); + f.state = 'Running'; + await expectLater(f.session.start('test'), throwsStateError); + expect(f.events.where((e) => e == 'mesh.stop'), isEmpty); + expect(f.state, 'Running'); + await f.session.close(); + }); test( - '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'], + 'mesh-only session fails when the SDK reports the bridge down', + () async { + final f = Fixture(); + await f.session.start('test'); + f.bridge = false; + await expectLater( + f.session.refresh(), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Mesh bridge stopped unexpectedly', + ), + ), ); + expect(f.session.state, 'Failed'); + expect(f.state, 'Stopped'); + await f.session.close(); }, ); test( @@ -189,7 +278,9 @@ void main() { await session.start('invalid mesh config'); expect(session.state, 'Running'); expect( - f.events.where((e) => e == 'mesh.start' || e == 'mesh.validate'), + f.events.where( + (e) => e.startsWith('mesh.start') || e == 'mesh.validate', + ), isEmpty, ); expect(f.proxy.lastProfile?['feature'], 'proxy'); diff --git a/apps/meshport_lab/test/telemetry_test.dart b/apps/meshport_lab/test/telemetry_test.dart index 5dd2566..13077ad 100644 --- a/apps/meshport_lab/test/telemetry_test.dart +++ b/apps/meshport_lab/test/telemetry_test.dart @@ -20,7 +20,7 @@ void main() { 'version': 'test-core', }, 'peers': [], - 'routes': [], + 'nodes': [], }, ), ), @@ -53,13 +53,30 @@ void main() { 'tx_bytes_per_second': 512.0, }, ], - 'routes': [ - {'peer_id': 1, 'hostname': 'game-server', 'ipv4': '10.77.0.2'}, + 'nodes': [ + { + 'peer_id': 1, + 'hostname': 'game-server', + 'ipv4': '10.77.0.2', + 'path': 'direct', + 'direct_available': true, + 'latency_ms': 23.4, + 'latency_source': 'link_rtt', + 'metered': true, + 'rx_bytes': 2048, + 'tx_bytes': 1024, + 'rx_bytes_per_second': 1024.0, + 'tx_bytes_per_second': 512.0, + }, { 'peer_id': 2, 'hostname': 'relay-target', - 'estimated_latency_ms': 89, 'next_hop_peer_id': 1, + 'path': 'relay', + 'direct_available': false, + 'latency_ms': 89, + 'latency_source': 'route_estimate', + 'metered': false, }, ], }, @@ -85,14 +102,18 @@ void main() { 'peers': [ {'peer_id': 1, 'direct': true, 'latency_ms': 166.5}, ], - 'routes': [ + 'nodes': [ { 'peer_id': 1, 'hostname': 'DIG-US', 'next_hop_peer_id': 2, - 'estimated_latency_ms': 108, 'udp_nat_type': 'FullCone', 'version': '2.4.5', + 'path': 'relay', + 'direct_available': true, + 'latency_ms': 108, + 'latency_source': 'route_estimate', + 'metered': true, }, ], }, @@ -121,12 +142,17 @@ void main() { 'latency_ms': 7.497, }, ], - 'routes': [ + 'nodes': [ { 'peer_id': 3157594741, 'hostname': 'Redmi_AX6', 'next_hop_peer_id': 3157594741, - 'estimated_latency_ms': 7, + 'path': 'direct', + 'direct_available': true, + 'hole_punched': true, + 'latency_ms': 7.497, + 'latency_source': 'link_rtt', + 'metered': true, }, ], }, diff --git a/bindings/flutter/meshport_flutter/lib/src/client.dart b/bindings/flutter/meshport_flutter/lib/src/client.dart index 21ee2f1..c5a6c45 100644 --- a/bindings/flutter/meshport_flutter/lib/src/client.dart +++ b/bindings/flutter/meshport_flutter/lib/src/client.dart @@ -47,6 +47,9 @@ Map _call(String path, int handle, String request) { } } +/// Lowest native capability revision this binding drives (`abi_info`). +const int minimumCapabilityRevision = 2; + class MeshPortClient { final String libraryPath; final int _handle; @@ -79,9 +82,25 @@ class MeshPortClient { )(); }); if (handle == 0) throw StateError('Could not create MeshPort context'); - return MeshPortClient._(path, handle); + final client = MeshPortClient._(path, handle); + int? revision; + try { + revision = (await client.abiInfo())['revision'] as int?; + } catch (_) {} + if (revision == null || revision < minimumCapabilityRevision) { + await client.close(); + throw StateError( + 'MeshPort native library at $path is too old ' + '(capability revision ${revision ?? 'unknown'}, ' + 'need $minimumCapabilityRevision); rebuild meshport-ffi', + ); + } + return client; } + /// `{abi, revision, operations}` of the loaded native library. + Future> abiInfo() => request({'op': 'abi_info'}); + Future> request(Map request) async { if (_closed) throw StateError('MeshPort context is closed'); final path = libraryPath, handle = _handle, text = jsonEncode(request); @@ -95,18 +114,72 @@ class MeshPortClient { return response['data'] as Map; } - Future validate(String toml) async { - await request({'op': 'validate', 'toml': toml}); + /// Returns the overlay projection. [checkLocalOverlap] also rejects an + /// overlay that collides with an existing interface on this device. + Future> validate( + String toml, { + bool checkLocalOverlap = false, + }) => request({ + 'op': 'validate', + 'toml': toml, + if (checkLocalOverlap) 'check_local_overlap': true, + }); + + /// Builds the SDK-accepted TOML from a structured profile draft. Mode, + /// transport and encryption invariants are applied by the SDK. + Future buildConfig(Map profile) async => + (await request({'op': 'build_config', 'profile': profile}))['toml'] + as String; + + /// Removes options earlier releases saved; returns [toml] unchanged when + /// nothing needed migrating. + Future migrateConfig(String toml) async => + (await request({'op': 'migrate_config', 'toml': toml}))['toml'] as String; + + Future start(String toml, {bool checkLocalOverlap = false}) async { + await request({ + 'op': 'start', + 'toml': toml, + if (checkLocalOverlap) 'check_local_overlap': true, + }); } - Future start(String toml) async { - await request({'op': 'start', 'toml': toml}); - } + /// Starts an application-mode network and its local TCP/UDP bridge as one + /// operation; a failure leaves neither running. Returns `listen`, `overlay`, + /// `mesh_cidrs` and `route_generation`. + Future> startBridged( + String toml, { + int port = 0, + int maxSessions = 128, + bool checkLocalOverlap = false, + bool requireStaticOverlay = false, + }) => request({ + 'op': 'start_bridged', + 'toml': toml, + 'port': port, + 'max_sessions': maxSessions, + if (checkLocalOverlap) 'check_local_overlap': true, + if (requireStaticOverlay) 'require_static_overlay': true, + }); Future stop() async { await request({'op': 'stop'}); } + /// Long-polls mesh routes: returns as soon as `route_generation` differs + /// from [afterGeneration] or the network stops, otherwise after [timeout] + /// with `changed: false`. Runs outside the context's serial lock, so other + /// requests proceed meanwhile. Returns `running`, `changed`, + /// `route_generation`, `mesh_cidrs` and `subnet_routes`. + Future> waitRoutes({ + int? afterGeneration, + Duration timeout = const Duration(seconds: 25), + }) => request({ + 'op': 'wait_routes', + if (afterGeneration != null) 'after_generation': afterGeneration, + 'timeout_ms': timeout.inMilliseconds, + }); + /// Local IPv4 TCP/UDP bridge for a host proxy engine. Application mode only. /// Data travels on native sockets, outside the serial JSON I/O interface. Future> startSocksBridge({ diff --git a/crates/meshport-easytier/src/config_builder.rs b/crates/meshport-easytier/src/config_builder.rs new file mode 100644 index 0000000..1f4b6ef --- /dev/null +++ b/crates/meshport-easytier/src/config_builder.rs @@ -0,0 +1,197 @@ +//! Structured profile <-> TOML. Hosts edit a JSON draft; the SDK owns the +//! mode invariants and the exact configuration text it will accept. +use anyhow::{Context, Result, bail}; +use serde_json::Value; + +/// Keys removed from saved configurations by earlier releases. +const LEGACY_KEYS: [&str; 1] = ["subnet_routes"]; + +/// Builds a validated configuration from a form draft. Any `runtime_mode` other +/// than `system_vpn` (including a host's unified VPN) runs the mesh in +/// application mode; transport and encryption invariants are not host choices. +pub fn build_config(profile: &Value) -> Result { + let profile = profile.as_object().context("profile must be an object")?; + let text = |key: &str, default: &str| -> Result { + match profile.get(key) { + None | Some(Value::Null) => Ok(Value::from(default)), + Some(value @ Value::String(_)) => Ok(value.clone()), + Some(_) => bail!("{key} must be a string"), + } + }; + let system = profile.get("runtime_mode").and_then(Value::as_str) == Some("system_vpn"); + let mut optimization = match profile.get("optimization") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(map)) => map.clone(), + Some(_) => bail!("optimization must be an object"), + }; + optimization + .entry("mode") + .or_insert_with(|| Value::from("adaptive")); + let latency_first = matches!( + optimization.get("mode").and_then(Value::as_str), + Some("adaptive" | "latency") + ); + let mut flags = match profile.get("flags") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(map)) => map.clone(), + Some(_) => bail!("flags must be an object"), + }; + flags.insert("no_tun".into(), Value::from(!system)); + flags.insert("use_smoltcp".into(), Value::from(!system)); + flags.insert("enable_encryption".into(), Value::from(true)); + flags.insert( + "enable_ipv6".into(), + profile + .get("enable_ipv6") + .filter(|v| !v.is_null()) + .cloned() + .unwrap_or(Value::from(true)), + ); + flags.insert("latency_first".into(), Value::from(latency_first)); + + let mut root = serde_json::Map::new(); + root.insert("hostname".into(), text("hostname", "MeshPort")?); + if profile.get("dhcp").and_then(Value::as_bool) == Some(true) { + root.insert("dhcp".into(), Value::from(true)); + } else { + root.insert("ipv4".into(), text("ipv4", "")?); + } + root.insert( + "listeners".into(), + profile + .get("listeners") + .filter(|v| !v.is_null()) + .cloned() + .unwrap_or(Value::Array(vec![])), + ); + for key in ["stun_servers", "stun_servers_v6"] { + if let Some(value) = profile.get(key).filter(|v| !v.is_null()) { + root.insert(key.into(), value.clone()); + } + } + let peers = match profile.get("peers") { + None | Some(Value::Null) => vec![], + Some(Value::Array(peers)) => peers + .iter() + .map(|uri| serde_json::json!({"uri": uri})) + .collect(), + Some(_) => bail!("peers must be an array"), + }; + if !peers.is_empty() { + root.insert("peer".into(), Value::Array(peers)); + } + root.insert( + "network_identity".into(), + serde_json::json!({ + "network_name": text("network_name", "")?, + "network_secret": text("network_secret", "")?, + }), + ); + root.insert("flags".into(), Value::Object(drop_nulls(flags))); + root.insert( + "runtime".into(), + serde_json::json!({"mode": if system { "system_vpn" } else { "application" }}), + ); + root.insert( + "optimization".into(), + Value::Object(drop_nulls(optimization)), + ); + let value = toml::Value::try_from(Value::Object(root)) + .map_err(|_| anyhow::anyhow!("profile contains values TOML cannot represent"))?; + let output = + toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?; + super::parse_config(&output)?; + Ok(output) +} + +fn drop_nulls(map: serde_json::Map) -> serde_json::Map { + map.into_iter().filter(|(_, v)| !v.is_null()).collect() +} + +/// Removes options earlier releases saved but this SDK no longer accepts. +/// Returns the input unchanged (formatting preserved) when nothing is removed. +pub fn migrate_config(input: &str) -> Result<(String, bool)> { + let mut value: toml::Value = + toml::from_str(input).map_err(|_| anyhow::anyhow!("invalid TOML configuration"))?; + let table = value + .as_table_mut() + .context("configuration must be a TOML table")?; + let mut changed = false; + for key in LEGACY_KEYS { + changed |= table.remove(key).is_some(); + if let Some(runtime) = table.get_mut("runtime").and_then(|v| v.as_table_mut()) { + changed |= runtime.remove(key).is_some(); + } + } + if !changed { + return Ok((input.to_owned(), false)); + } + let output = + toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?; + Ok((output, true)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ConfigLoader; + use serde_json::json; + + fn draft() -> Value { + json!({ + "runtime_mode": "unified_vpn", + "ipv4": "10.77.0.11/24", + "network_name": "test", + "network_secret": "test-only", + "flags": {"disable_p2p": true, "foreign_relay_bps_limit": "18446744073709551615", "no_tun": false}, + "listeners": ["udp://0.0.0.0:11010"], + "stun_servers": [], + "peers": ["tcp://192.0.2.1:11010"], + "optimization": {"mode": "direct"}, + "unknown_projection_field": true, + }) + } + + #[test] + fn host_modes_force_invariants_and_round_trip() { + let toml = build_config(&draft()).unwrap(); + let config = crate::parse_config(&toml).unwrap(); + let flags = config.get_flags(); + assert!(flags.no_tun && flags.use_smoltcp && flags.enable_encryption); + assert!(flags.disable_p2p && !flags.latency_first && flags.enable_ipv6); + assert_eq!(flags.foreign_relay_bps_limit, u64::MAX); + assert_eq!(config.get_peers().len(), 1); + assert!(toml.contains("stun_servers = []")); + assert!(toml.contains("mode = \"application\"")); + + let mut system = draft(); + system["runtime_mode"] = json!("system_vpn"); + let config = crate::parse_config(&build_config(&system).unwrap()).unwrap(); + assert!(!config.get_flags().no_tun && !config.get_flags().use_smoltcp); + } + + #[test] + fn dhcp_and_defaults() { + let toml = build_config(&json!({"dhcp": true, "ipv4": "", "network_name": "n"})).unwrap(); + let config = crate::parse_config(&toml).unwrap(); + assert!(config.get_dhcp() && config.get_flags().latency_first); + assert_eq!(config.get_hostname(), "MeshPort"); + assert!(build_config(&json!({"network_name": "n", "ipv4": 7})).is_err()); + assert!(build_config(&json!({"network_name": ""})).is_err()); + } + + #[test] + fn legacy_subnet_routes_are_removed_only_when_present() { + let base = "ipv4 = '10.77.0.11'\n[network_identity]\nnetwork_name = 'test'\n"; + assert_eq!(migrate_config(base).unwrap(), (base.to_owned(), false)); + for legacy in [ + format!("subnet_routes = ['192.168.21.0/24']\n{base}"), + format!("{base}[runtime]\nmode = 'system_vpn'\nsubnet_routes = ['192.168.21.0/24']\n"), + ] { + assert!(crate::parse_config(&legacy).is_err()); + let (migrated, changed) = migrate_config(&legacy).unwrap(); + assert!(changed && !migrated.contains("subnet_routes")); + crate::parse_config(&migrated).unwrap(); + } + } +} diff --git a/crates/meshport-easytier/src/lib.rs b/crates/meshport-easytier/src/lib.rs index 88c3a5c..a6d28e1 100644 --- a/crates/meshport-easytier/src/lib.rs +++ b/crates/meshport-easytier/src/lib.rs @@ -16,8 +16,50 @@ pub use easytier_core::peers::meshport_optimization::{Mode, OptimizationPolicy}; #[cfg(target_os = "android")] pub mod android; +mod config_builder; mod system_routes; +pub use config_builder::{build_config, migrate_config}; +pub use system_routes::mesh_cidrs; + +/// Rejects a static overlay that overlaps an address already on this host. +/// DHCP configurations have no overlay yet and pass. +pub fn check_local_overlap(config: &TomlConfig) -> Result<()> { + match config.get_ipv4() { + Some(ip) => system_routes::check_local_overlap(ip.address(), ip.network_length()), + None => Ok(()), + } +} + +/// Address plan for the host's virtual interface, derived from a static overlay. +pub fn overlay_projection(config: &TomlConfig) -> serde_json::Value { + config.get_ipv4().map_or(serde_json::Value::Null, |ip| { + overlay_json(ip.address(), ip.network_length()) + }) +} + +fn overlay_json(address: std::net::Ipv4Addr, prefix: u8) -> serde_json::Value { + let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0); + let network = std::net::Ipv4Addr::from(u32::from(address) & mask); + serde_json::json!({ + "address": address.to_string(), + "prefix": prefix, + "network": format!("{network}/{prefix}"), + "routable": system_routes::routable_overlay(address, prefix).is_some(), + }) +} + +/// Destinations to route through the mesh. `generation` increases on every +/// change of `cidrs` so hosts compare one number instead of the sets. +/// `stopped` is set once, with empty routes, when the network stops. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +pub struct MeshRoutes { + pub generation: u64, + pub cidrs: Vec, + pub subnet_routes: Vec, + pub stopped: bool, +} + pub const REVISION: &str = "7af7bdc16a41d64d58743d15023a63b3eed2102c"; /// Strict mode-aware allowlist. Unknown options fail rather than disappear. @@ -252,6 +294,117 @@ pub struct Engine { events: Mutex>, journal: Mutex>, event_sequence: Mutex, + routes: tokio::sync::watch::Sender, + route_task: Mutex>>, +} + +impl Drop for Engine { + fn drop(&mut self) { + if let Some(task) = self.route_task.get_mut().ok().and_then(Option::take) { + task.abort(); + } + } +} + +async fn current_routes(instance: &NativeCoreInstance) -> (Vec, Vec) { + let accepted = instance + .packet_plane() + .proxy_cidr_diff(&Default::default()) + .await + .map(|d| d.current.into_iter().collect::>()) + .unwrap_or_default(); + let overlay = instance + .node_snapshot() + .await + .ipv4_addr + .map(|ip| (ip.address(), ip.network_length())); + ( + system_routes::mesh_cidrs(overlay, &accepted), + accepted.iter().map(|r| r.to_string()).collect(), + ) +} + +fn publish_routes( + sender: &tokio::sync::watch::Sender, + cidrs: Vec, + subnet_routes: Vec, +) { + sender.send_if_modified(|current| { + if current.cidrs == cidrs && current.subnet_routes == subnet_routes { + return false; + } + current.generation += 1; + current.cidrs = cidrs; + current.subnet_routes = subnet_routes; + true + }); +} + +/// Joins link and route views into one row per remote node. A node counts as +/// direct only when it has a direct transport and is its own next hop; the +/// measured link RTT applies only then, otherwise the route estimate does. +fn merge_nodes( + local_peer_id: Option, + peers: &[serde_json::Value], + routes: &[serde_json::Value], +) -> Vec { + let mut order = Vec::new(); + let mut rows: HashMap = HashMap::new(); + for route in routes { + if let Some(id) = route["peer_id"].as_u64() + && rows.insert(id, route.clone()).is_none() + { + order.push(id); + } + } + for peer in peers { + if let Some(id) = peer["peer_id"].as_u64() { + rows.entry(id).or_insert_with(|| { + order.push(id); + serde_json::json!({"peer_id": id}) + }); + } + } + order + .into_iter() + .filter(|id| Some(*id) != local_peer_id) + .map(|id| { + let route = &rows[&id]; + let peer = peers.iter().find(|p| p["peer_id"].as_u64() == Some(id)); + let direct_available = peer.is_some_and(|p| p["direct"] == true); + let next_hop = route["next_hop_peer_id"].as_u64(); + let direct = direct_available && next_hop.is_none_or(|hop| hop == id); + let measured = peer + .filter(|_| direct) + .and_then(|p| p["latency_ms"].as_f64()); + let estimated = route["estimated_latency_ms"].as_f64(); + let mut node = route.clone(); + node["path"] = serde_json::json!(if direct { "direct" } else { "relay" }); + node["direct_available"] = serde_json::json!(direct_available); + node["hole_punched"] = + serde_json::json!(direct && peer.is_some_and(|p| p["hole_punched"] == true)); + node["latency_ms"] = serde_json::json!(measured.or(estimated)); + node["latency_source"] = serde_json::json!(if measured.is_some() { + Some("link_rtt") + } else if estimated.is_some() { + Some("route_estimate") + } else { + None + }); + node["metered"] = serde_json::json!(peer.is_some()); + if let Some(peer) = peer { + for key in [ + "rx_bytes", + "tx_bytes", + "rx_bytes_per_second", + "tx_bytes_per_second", + ] { + node[key] = peer[key].clone(); + } + } + node + }) + .collect() } #[derive(Default)] @@ -275,6 +428,9 @@ impl Engine { { bail!("system_vpn requires a platform VPN build and platform authorization"); } + if mode == RuntimeMode::SystemVpn { + check_local_overlap(&config)?; + } let optimization = optimization_config(input)?; let instance = create_native_instance(config.clone())?; instance @@ -293,6 +449,21 @@ impl Engine { instance.stop().await; return Err(error); } + let (routes, _) = tokio::sync::watch::channel(MeshRoutes::default()); + let (cidrs, subnet_routes) = current_routes(&instance).await; + publish_routes(&routes, cidrs, subnet_routes); + let route_task = tokio::spawn({ + let instance = instance.clone(); + let routes = routes.clone(); + async move { + let mut tick = tokio::time::interval(std::time::Duration::from_secs(1)); + loop { + tick.tick().await; + let (cidrs, subnet_routes) = current_routes(&instance).await; + publish_routes(&routes, cidrs, subnet_routes); + } + } + }); Ok(Self { instance, config, @@ -303,8 +474,14 @@ impl Engine { events: Mutex::new(events), journal: Mutex::new(Vec::new()), event_sequence: Mutex::new(0), + routes, + route_task: Mutex::new(Some(route_task)), }) } + /// Notifies on every change of the destinations to route through the mesh. + pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver { + self.routes.subscribe() + } pub fn redact_diagnostic(&self, text: &str) -> String { let secret = self .config @@ -326,6 +503,20 @@ impl Engine { self.instance.attach_tun_fd(fd) } pub async fn stop(&self) { + if let Some(task) = self.route_task.lock().unwrap().take() { + task.abort(); + } + // Wake route watchers: a stopped network routes nothing. + self.routes.send_if_modified(|routes| { + if routes.stopped { + return false; + } + routes.generation += 1; + routes.cidrs.clear(); + routes.subnet_routes.clear(); + routes.stopped = true; + true + }); self.instance.stop().await; *self.interface_name.lock().unwrap() = None; } @@ -412,18 +603,10 @@ impl Engine { .await, ); } - let subnet_routes = self - .instance - .packet_plane() - .proxy_cidr_diff(&Default::default()) - .await - .map(|d| { - d.current - .into_iter() - .map(|r| r.to_string()) - .collect::>() - }) - .unwrap_or_default(); + let (cidrs, subnet_routes) = current_routes(&self.instance).await; + publish_routes(&self.routes, cidrs, subnet_routes); + let mesh_routes = self.routes.borrow().clone(); + let subnet_routes = mesh_routes.subnet_routes.clone(); let mut traffic = self.traffic.lock().unwrap(); let now = Instant::now(); let seconds = traffic @@ -471,6 +654,22 @@ impl Engine { traffic.sampled_at = Some(now); let flags = self.config.get_flags(); let latency_first = flags.latency_first; + let route_rows = routes.iter().map(|r| { + let path_latency = if latency_first {r.path_latency_latency_first.unwrap_or(r.path_latency)} else {r.path_latency}; + serde_json::json!({"peer_id": r.peer_id, "hostname": r.hostname, + "ipv4": r.ipv4_addr.as_ref().map(|v| v.to_string()), + "advertised_subnets": r.proxy_cidrs, + "cost": effective_hops.get(&r.peer_id).copied().flatten().map(|hop| if hop == r.peer_id {1} else if latency_first {r.cost_latency_first.unwrap_or(r.cost)} else {r.cost}), + "version": r.version, + "udp_nat_type": r.stun_info.as_ref().map(|s| format!("{:?}", easytier::proto::common::NatType::try_from(s.udp_nat_type).unwrap_or_default())), + "disable_p2p": r.feature_flag.as_ref().map(|f| f.disable_p2p), + "need_p2p": r.feature_flag.as_ref().map(|f| f.need_p2p), + "next_hop_peer_id": effective_hops.get(&r.peer_id).copied().flatten(), + "candidate_next_hop_peer_id": if latency_first { r.next_hop_peer_id_latency_first.unwrap_or(r.next_hop_peer_id) } else { r.next_hop_peer_id }, + "estimated_latency_ms": if path_latency > 0 {Some(path_latency)} else {None} + }) + }).collect::>(); + let nodes = merge_nodes(Some(u64::from(node.peer_id)), &peer_stats, &route_rows); let interface_name = self.interface_name.lock().unwrap().clone(); serde_json::json!({ "state": format!("{:?}", self.instance.state()), @@ -513,21 +712,8 @@ impl Engine { "tx_bytes_per_second": seconds.filter(|s| *s > 0.0).map(|s| total_tx_delta as f64 / s), "scope": "tunnel_including_control" }, - "routes": routes.iter().map(|r| { - let path_latency = if latency_first {r.path_latency_latency_first.unwrap_or(r.path_latency)} else {r.path_latency}; - serde_json::json!({"peer_id": r.peer_id, "hostname": r.hostname, - "ipv4": r.ipv4_addr.as_ref().map(|v| v.to_string()), - "advertised_subnets": r.proxy_cidrs, - "cost": effective_hops.get(&r.peer_id).copied().flatten().map(|hop| if hop == r.peer_id {1} else if latency_first {r.cost_latency_first.unwrap_or(r.cost)} else {r.cost}), - "version": r.version, - "udp_nat_type": r.stun_info.as_ref().map(|s| format!("{:?}", easytier::proto::common::NatType::try_from(s.udp_nat_type).unwrap_or_default())), - "disable_p2p": r.feature_flag.as_ref().map(|f| f.disable_p2p), - "need_p2p": r.feature_flag.as_ref().map(|f| f.need_p2p), - "next_hop_peer_id": effective_hops.get(&r.peer_id).copied().flatten(), - "candidate_next_hop_peer_id": if latency_first { r.next_hop_peer_id_latency_first.unwrap_or(r.next_hop_peer_id) } else { r.next_hop_peer_id }, - "estimated_latency_ms": if path_latency > 0 {Some(path_latency)} else {None} - }) - }).collect::>(), + "routes": route_rows, + "nodes": nodes, "application_only": self.mode == RuntimeMode::Application, "runtime_mode": self.mode, "platform_network": { @@ -536,7 +722,9 @@ impl Engine { "route_scope": if !subnet_routes.is_empty() { "overlay_and_remote_subnets" } else { "overlay_only" }, "subnet_route_mode": "automatic", "route_installation": if self.mode == RuntimeMode::SystemVpn { "system" } else { "sdk_only" }, - "subnet_routes": subnet_routes, "subnet_routes_scope": "accepted_projection", "dns_changed": false, "default_route_changed": false + "subnet_routes": subnet_routes, "subnet_routes_scope": "accepted_projection", "dns_changed": false, "default_route_changed": false, + "mesh_cidrs": mesh_routes.cidrs, "route_generation": mesh_routes.generation, + "overlay": node.ipv4_addr.map_or(serde_json::Value::Null, |ip| overlay_json(ip.address(), ip.network_length())) }, "upstream_revision": REVISION }) } @@ -635,6 +823,40 @@ mod tests { ); } #[test] + fn nodes_classify_path_and_latency_source() { + use serde_json::json; + let peers = vec![ + json!({"peer_id": 2, "direct": true, "hole_punched": true, "latency_ms": 12.5, "rx_bytes": 9}), + json!({"peer_id": 3, "direct": true, "latency_ms": 40.0}), + json!({"peer_id": 5, "direct": false}), + ]; + let routes = vec![ + json!({"peer_id": 1, "hostname": "self"}), + json!({"peer_id": 2, "next_hop_peer_id": 2, "estimated_latency_ms": 30}), + json!({"peer_id": 3, "next_hop_peer_id": 2, "estimated_latency_ms": 55}), + json!({"peer_id": 4, "next_hop_peer_id": 2}), + ]; + let nodes = merge_nodes(Some(1), &peers, &routes); + let ids: Vec<_> = nodes + .iter() + .map(|n| n["peer_id"].as_u64().unwrap()) + .collect(); + assert_eq!(ids, vec![2, 3, 4, 5]); + assert_eq!(nodes[0]["path"], "direct"); + assert_eq!(nodes[0]["latency_ms"], 12.5); + assert_eq!(nodes[0]["latency_source"], "link_rtt"); + assert_eq!(nodes[0]["hole_punched"], true); + assert_eq!(nodes[0]["rx_bytes"], 9); + // Direct link exists but traffic is routed through peer 2. + assert_eq!(nodes[1]["path"], "relay"); + assert_eq!(nodes[1]["direct_available"], true); + assert_eq!(nodes[1]["latency_ms"], 55.0); + assert_eq!(nodes[1]["latency_source"], "route_estimate"); + assert_eq!(nodes[2]["metered"], false); + assert!(nodes[2]["latency_source"].is_null()); + assert_eq!(nodes[3]["path"], "relay"); + } + #[test] fn optimization_configuration_is_strict_and_controls_effective_flags() { let input = format!( "{BASE}\n[optimization]\nmode = 'adaptive'\nmin_improvement_ms = 20\nrelay_peer_ids = [10,20]" @@ -708,7 +930,15 @@ mod tests { let server = create_native_instance(server_config.clone()).unwrap(); server.start().await.unwrap(); let client = Engine::start(&format!("ipv4 = '10.253.80.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{identity}")).await.unwrap(); + let mut watch = client.watch_mesh_routes(); + assert_eq!(watch.borrow_and_update().cidrs, vec!["10.253.80.0/24"]); let result = tokio::time::timeout(Duration::from_secs(20), async { + // The watch fires on acceptance without anyone polling snapshots. + watch + .wait_for(|r| r.cidrs == ["10.253.79.0/24", "10.253.80.0/24"]) + .await + .unwrap(); + let learned_generation = watch.borrow().generation; loop { let snapshot = client.snapshot().await; let routes = snapshot["platform_network"]["subnet_routes"] @@ -781,16 +1011,26 @@ mod tests { }) .await .unwrap(); - while !client.snapshot().await["platform_network"]["subnet_routes"] - .as_array() + let withdrawn = watch + .wait_for(|r| r.cidrs == ["10.253.80.0/24"]) + .await .unwrap() - .is_empty() - { - tokio::time::sleep(Duration::from_millis(100)).await; - } + .generation; + assert!(withdrawn > learned_generation); + assert!( + client.snapshot().await["platform_network"]["subnet_routes"] + .as_array() + .unwrap() + .is_empty() + ); }) .await; + let mut on_stop = client.watch_mesh_routes(); + let before_stop = on_stop.borrow_and_update().generation; client.stop().await; + assert!(on_stop.has_changed().unwrap()); + let stopped = on_stop.borrow().clone(); + assert!(stopped.stopped && stopped.cidrs.is_empty() && stopped.generation > before_stop); server.stop().await; assert!(result.is_ok(), "automatic subnet test timed out"); } diff --git a/crates/meshport-easytier/src/system_routes.rs b/crates/meshport-easytier/src/system_routes.rs index 2979743..aee4c66 100644 --- a/crates/meshport-easytier/src/system_routes.rs +++ b/crates/meshport-easytier/src/system_routes.rs @@ -24,6 +24,52 @@ pub fn allowed(route: &Ipv4Cidr, overlay: Ipv4Addr, prefix: u8) -> bool { local_interfaces_allow(route) } +/// Overlay network when it can carry routed host traffic: a private IPv4 /16-/32. +pub fn routable_overlay(address: Ipv4Addr, prefix: u8) -> Option { + if !(16..=32).contains(&prefix) || !address.is_private() { + return None; + } + let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0); + Ipv4Cidr::new(Ipv4Addr::from(u32::from(address) & mask), prefix).ok() +} + +/// The canonical, sorted set of destinations hosts must send through the mesh: +/// the routable overlay network plus accepted advertised subnets. +pub fn mesh_cidrs(overlay: Option<(Ipv4Addr, u8)>, accepted: &[Ipv4Cidr]) -> Vec { + let mut result = std::collections::BTreeSet::new(); + if let Some(cidr) = overlay.and_then(|(address, prefix)| routable_overlay(address, prefix)) { + result.insert(cidr); + } + result.extend(accepted.iter().copied()); + // Always spell the prefix length; host routes would otherwise print bare. + result + .into_iter() + .map(|cidr| format!("{}/{}", cidr.first_address(), cidr.network_length())) + .collect() +} + +/// Fails when the overlay overlaps an address already configured on this host, +/// such as the physical LAN or another VPN. Reads interfaces fresh, uncached. +pub fn check_local_overlap(address: Ipv4Addr, prefix: u8) -> anyhow::Result<()> { + use network_interface::{Addr, NetworkInterface, NetworkInterfaceConfig}; + let interfaces = NetworkInterface::show() + .map_err(|_| anyhow::anyhow!("cannot inspect existing interfaces"))?; + let conflict = interfaces + .into_iter() + .flat_map(|iface| iface.addr) + .any(|addr| match addr { + Addr::V4(v4) => v4 + .netmask + .is_some_and(|mask| overlaps(address, prefix, v4.ip, u32::from(mask))), + _ => false, + }); + anyhow::ensure!( + !conflict, + "overlay overlaps an existing interface; choose another subnet or stop the conflicting VPN" + ); + Ok(()) +} + type InterfaceNetworks = Vec<(Ipv4Addr, u32)>; type InterfaceCache = Option<(std::time::Instant, Option)>; fn local_interfaces_allow(route: &Ipv4Cidr) -> bool { @@ -76,6 +122,25 @@ mod tests { assert!(permitted(&"10.5.0.1/32".parse().unwrap(), overlay, 24)); } #[test] + fn mesh_cidrs_are_canonical_sorted_and_skip_unroutable_overlays() { + let accepted: Vec = vec!["192.168.21.0/24".parse().unwrap()]; + assert_eq!( + mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 24)), &accepted), + vec!["10.77.0.0/24", "192.168.21.0/24"] + ); + assert_eq!( + mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 32)), &[]), + vec!["10.77.0.11/32"] + ); + for (address, prefix) in [("8.8.8.8", 24), ("10.0.0.1", 8)] { + assert_eq!( + mesh_cidrs(Some((address.parse().unwrap(), prefix)), &accepted), + vec!["192.168.21.0/24"] + ); + } + assert!(mesh_cidrs(None, &[]).is_empty()); + } + #[test] fn detects_physical_subnet_overlap() { let local = "10.10.8.54".parse().unwrap(); assert!(overlaps( diff --git a/crates/meshport-ffi/src/lib.rs b/crates/meshport-ffi/src/lib.rs index 41446df..f8b35c4 100644 --- a/crates/meshport-ffi/src/lib.rs +++ b/crates/meshport-ffi/src/lib.rs @@ -15,6 +15,33 @@ use std::{ }; use tokio::runtime::Runtime; static NEXT: AtomicU64 = AtomicU64::new(1); +/// Additive JSON operation set within ABI v1. Bump when hosts must rely on a +/// newly added operation or field; hosts reject libraries below what they need. +const CAPABILITY_REVISION: u32 = 2; +const OPERATIONS: &[&str] = &[ + "abi_info", + "build_config", + "migrate_config", + "validate", + "start", + "start_bridged", + "stop", + "status", + "wait_routes", + "socks_start", + "socks_stop", + "socks_status", + "diagnostics_enable", + "probe", + "quality_sample", + "tcp_connect", + "tcp_write", + "tcp_read", + "udp_bind", + "udp_send", + "udp_receive", + "resource_close", +]; #[cfg(target_os = "android")] #[unsafe(no_mangle)] pub extern "C" fn meshport_set_android_socket_protector( @@ -78,26 +105,134 @@ pub extern "C" fn meshport_context_new() -> u64 { #[unsafe(no_mangle)] pub extern "C" fn meshport_context_free(id: u64) { // Drop outside registry lock; in-flight calls retain an Arc until completion. - let _ = catch_unwind(|| { - let context = CONTEXTS.lock().unwrap().remove(&id); + let _ = catch_unwind(AssertUnwindSafe(|| { + let Some(context) = CONTEXTS.lock().unwrap().remove(&id) else { + return; + }; + // Stop now rather than when the last Arc drops: a `wait_routes` call + // holds one without the serial lock, and stopping is what wakes it. + if let Ok(mut network) = context.network.lock() { + let _ = stop_all(&context, &mut network); + } drop(context); - }); + })); +} +fn start_socks(context: &Context, n: &Arc, request: &Value) -> anyhow::Result { + let mut slot = context.socks.lock().unwrap(); + anyhow::ensure!(slot.is_none(), "SOCKS bridge already started"); + let port = match request.get("port") { + Some(value) => u16::try_from( + value + .as_u64() + .ok_or_else(|| anyhow::anyhow!("invalid port"))?, + )?, + None => 0, + }; + let max_sessions = match request.get("max_sessions") { + Some(value) => usize::try_from( + value + .as_u64() + .ok_or_else(|| anyhow::anyhow!("invalid session limit"))?, + )?, + None => 128, + }; + let options = meshport_socks::Options { + listen: std::net::SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, port), + max_sessions, + ..Default::default() + }; + let bridge = context + .runtime + .block_on(meshport_socks::Bridge::start(n.clone(), options))?; + let address = bridge.local_addr().to_string(); + *slot = Some(bridge); + Ok(address) +} +fn stop_all(context: &Context, network: &mut Option>) -> anyhow::Result<()> { + let bridge = context.socks.lock().unwrap().take(); + let result = match bridge { + Some(mut bridge) => context.runtime.block_on(bridge.stop()), + None => Ok(()), + }; + context.tcp.blocking_lock().clear(); + context.udp.blocking_lock().clear(); + if let Some(n) = network.take() { + context.runtime.block_on(n.stop()); + } + result } fn dispatch(context: &Context, request: Value) -> anyhow::Result { let op = request["op"] .as_str() .ok_or_else(|| anyhow::anyhow!("missing op"))?; + if op == "abi_info" { + return Ok(json!({"abi": 1, "revision": CAPABILITY_REVISION, "operations": OPERATIONS})); + } + // Long poll for route changes. Runs outside the serial context lock so a + // host can wait on one thread while issuing other requests on another. + if op == "wait_routes" { + let timeout_ms = request["timeout_ms"].as_u64().unwrap_or(25000); + anyhow::ensure!( + (1..=30000).contains(&timeout_ms), + "timeout_ms must be 1 to 30000" + ); + let after = match request.get("after_generation") { + None | Some(Value::Null) => None, + Some(value) => Some( + value + .as_u64() + .ok_or_else(|| anyhow::anyhow!("invalid after_generation"))?, + ), + }; + let network = context + .network + .lock() + .map_err(|_| anyhow::anyhow!("context lock poisoned"))? + .clone(); + let Some(network) = network else { + return Ok(json!({"running": false, "changed": after.is_some(), + "route_generation": null, "mesh_cidrs": [], "subnet_routes": []})); + }; + let mut watch = network.watch_mesh_routes(); + let changed = context.runtime.block_on(async { + tokio::time::timeout( + Duration::from_millis(timeout_ms), + watch.wait_for(|r| r.stopped || after.is_none_or(|a| r.generation != a)), + ) + .await + .is_ok() + }); + let routes = watch.borrow().clone(); + return Ok(json!({"running": !routes.stopped, + "changed": changed && after.is_some_and(|a| a != routes.generation), + "route_generation": routes.generation, "mesh_cidrs": routes.cidrs, + "subnet_routes": routes.subnet_routes})); + } if op == "diagnostics_enable" { return Ok(json!({"enabled": diagnostics::enable(), "scope": "process"})); } + if op == "build_config" { + return Ok(json!({"toml": meshport::build_config(&request["profile"])?})); + } + if op == "migrate_config" { + let input = request["toml"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("missing toml"))?; + let (toml, changed) = meshport::migrate_config(input)?; + return Ok(json!({"toml": toml, "changed": changed})); + } if op == "validate" { use meshport_easytier::ConfigLoader; let input = request["toml"] .as_str() .ok_or_else(|| anyhow::anyhow!("missing toml"))?; let config = meshport::validate_config(input)?; + if request["check_local_overlap"].as_bool() == Some(true) { + meshport::check_local_overlap(&config)?; + } let flags = config.get_flags(); - let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"}}); + let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"}, + "overlay": meshport::overlay_projection(&config)}); // Only return credentials when the local caller explicitly requests a // form projection. Ordinary validation remains free of credentials. if request["include_profile"].as_bool() == Some(true) { @@ -158,52 +293,64 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result { let config = request["toml"] .as_str() .ok_or_else(|| anyhow::anyhow!("missing toml"))?; + if request["check_local_overlap"].as_bool() == Some(true) { + meshport::check_local_overlap(&meshport::validate_config(config)?)?; + } *network = Some(Arc::new(context.runtime.block_on(Network::start(config))?)); Ok(json!({"engine_started": true})) } + // Application-mode network plus SOCKS bridge as one step, for hosts that + // route traffic into the mesh. Either both run or neither does. + "start_bridged" => { + use meshport_easytier::ConfigLoader; + anyhow::ensure!( + network.is_none(), + "already started; stop before applying a new configuration" + ); + let input = request["toml"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("missing toml"))?; + let config = meshport::validate_config(input)?; + anyhow::ensure!( + config.get_flags().no_tun, + "bridged routing requires application-mode MeshPort" + ); + let overlay = meshport::overlay_projection(&config); + anyhow::ensure!( + !overlay.is_null() || request["require_static_overlay"].as_bool() != Some(true), + "static mesh IPv4 required for bridged routing" + ); + anyhow::ensure!( + overlay.is_null() || overlay["routable"] == true, + "bridged routing requires a private IPv4 overlay with prefix /16 through /32" + ); + if request["check_local_overlap"].as_bool() == Some(true) { + meshport::check_local_overlap(&config)?; + } + let n = Arc::new(context.runtime.block_on(Network::start(input))?); + *network = Some(n.clone()); + let listen = match start_socks(context, &n, &request) { + Ok(listen) => listen, + Err(error) => { + let _ = stop_all(context, &mut network); + return Err(error); + } + }; + let routes = n.watch_mesh_routes().borrow().clone(); + Ok( + json!({"engine_started": true, "listen": listen, "overlay": overlay, + "mesh_cidrs": routes.cidrs, "route_generation": routes.generation}), + ) + } "stop" => { - 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() { - context.runtime.block_on(n.stop()); - } + stop_all(context, &mut network)?; Ok(json!({"stopped": true})) } "socks_start" => { let n = network .as_ref() .ok_or_else(|| anyhow::anyhow!("network is stopped"))?; - let 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); + let address = start_socks(context, n, &request)?; Ok( json!({"running": true, "listen": address, "tcp": true, "udp": true, "ipv4_only": true, "dns_resolution": false}), ) @@ -240,9 +387,24 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result { }) .collect::>(); snapshot["diagnostic_traces"] = json!(traces); + let engine_running = snapshot["state"] == "Running"; + let bridge_running = context + .socks + .lock() + .unwrap() + .as_ref() + .is_some_and(|b| b.snapshot().running); + // mesh_routable: traffic a host routes to mesh_cidrs via the + // bridge can currently be delivered. + snapshot["health"] = json!({"engine_running": engine_running, + "bridge_running": bridge_running, + "mesh_routable": engine_running && bridge_running}); Ok(snapshot) } - None => Ok(json!({"state": "Stopped", "peer_count": 0, "application_only": true})), + None => Ok( + json!({"state": "Stopped", "peer_count": 0, "application_only": true, + "health": {"engine_running": false, "bridge_running": false, "mesh_routable": false}}), + ), }, "quality_sample" => { let network = network @@ -486,6 +648,150 @@ mod tests { meshport_context_free(id); } + #[test] + fn config_build_and_migration_are_sdk_operations() { + let id = meshport_context_new(); + let built = call( + id, + &json!({"op": "build_config", "profile": {"runtime_mode": "unified_vpn", + "ipv4": "10.79.0.11/24", "network_name": "n", "network_secret": "s"}}) + .to_string(), + ); + assert_eq!(built["ok"], true); + let toml = built["data"]["toml"].as_str().unwrap(); + let validated = call(id, &json!({"op": "validate", "toml": toml}).to_string()); + assert_eq!(validated["data"]["runtime_mode"], "application"); + assert_eq!(validated["data"]["overlay"]["network"], "10.79.0.0/24"); + let legacy = format!("{toml}\nsubnet_routes = ['192.168.21.0/24']\n"); + let migrated = call( + id, + &json!({"op": "migrate_config", "toml": legacy}).to_string(), + ); + assert_eq!(migrated["data"]["changed"], true); + let migrated = migrated["data"]["toml"].as_str().unwrap(); + assert_eq!( + call(id, &json!({"op": "validate", "toml": migrated}).to_string())["ok"], + true + ); + meshport_context_free(id); + } + + #[test] + fn bridged_start_is_atomic_and_reports_routes_and_health() { + let id = meshport_context_new(); + let base = "listeners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'bridged-ffi-test'\nnetwork_secret = 'test-only'\n"; + let system = format!("ipv4 = '10.253.84.11/24'\n{base}[runtime]\nmode = 'system_vpn'\n"); + let wide = format!("ipv4 = '10.253.84.11/8'\n{base}"); + let dhcp = format!("dhcp = true\n{base}"); + for (config, static_required) in [(system, false), (wide, false), (dhcp, true)] { + let refused = call( + id, + &json!({"op": "start_bridged", "toml": config, + "require_static_overlay": static_required}) + .to_string(), + ); + assert_eq!(refused["ok"], false, "{config}"); + assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped"); + } + // Bridge failure (invalid session limit) rolls the network back. + let config = format!("ipv4 = '10.253.84.11/24'\n{base}"); + let failed = call( + id, + &json!({"op": "start_bridged", "toml": config, "max_sessions": 0}).to_string(), + ); + assert_eq!(failed["ok"], false); + assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped"); + + let started = call( + id, + &json!({"op": "start_bridged", "toml": config}).to_string(), + ); + assert_eq!(started["ok"], true, "{started}"); + assert_eq!(started["data"]["mesh_cidrs"], json!(["10.253.84.0/24"])); + assert!(started["data"]["route_generation"].as_u64().unwrap() >= 1); + assert!(std::net::TcpStream::connect(started["data"]["listen"].as_str().unwrap()).is_ok()); + let status = call(id, r#"{"op":"status"}"#)["data"].clone(); + assert_eq!(status["health"]["mesh_routable"], true); + assert_eq!( + status["platform_network"]["mesh_cidrs"], + json!(["10.253.84.0/24"]) + ); + assert_eq!( + status["platform_network"]["overlay"]["address"], + "10.253.84.11" + ); + let generation = started["data"]["route_generation"].as_u64().unwrap(); + let idle = call( + id, + &json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 200}) + .to_string(), + ); + assert_eq!(idle["data"]["changed"], false, "{idle}"); + assert_eq!(idle["data"]["running"], true); + assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true); + let status = call(id, r#"{"op":"status"}"#)["data"].clone(); + assert_eq!(status["health"]["engine_running"], true); + assert_eq!(status["health"]["mesh_routable"], false); + // A waiter does not hold the context: status still answers, and stop + // wakes it with empty routes well before its timeout. + let waiter = std::thread::spawn(move || { + let at = std::time::Instant::now(); + let reply = call( + id, + &json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000}) + .to_string(), + ); + (reply, at.elapsed()) + }); + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running"); + assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true); + let (woken, waited) = waiter.join().unwrap(); + assert!(waited < Duration::from_secs(10), "{waited:?}"); + assert_eq!(woken["data"]["running"], false, "{woken}"); + assert_eq!(woken["data"]["changed"], true); + assert_eq!(woken["data"]["mesh_cidrs"], json!([])); + assert_eq!( + call(id, r#"{"op":"wait_routes","timeout_ms":0}"#)["ok"], + false + ); + let info = call(id, r#"{"op":"abi_info"}"#)["data"].clone(); + assert_eq!(info["abi"], 1); + assert!(info["revision"].as_u64().unwrap() >= 2); + assert!( + info["operations"] + .as_array() + .unwrap() + .iter() + .any(|o| o == "wait_routes") + ); + assert_eq!( + call(id, r#"{"op":"status"}"#)["data"]["health"]["mesh_routable"], + false + ); + // Freeing without stop also stops the network and wakes a waiter. + let started = call( + id, + &json!({"op": "start_bridged", "toml": config}).to_string(), + ); + assert_eq!(started["ok"], true, "{started}"); + let generation = started["data"]["route_generation"].as_u64().unwrap(); + let waiter = std::thread::spawn(move || { + let at = std::time::Instant::now(); + let reply = call( + id, + &json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000}) + .to_string(), + ); + (reply, at.elapsed()) + }); + std::thread::sleep(Duration::from_millis(200)); + meshport_context_free(id); + let (woken, waited) = waiter.join().unwrap(); + assert!(waited < Duration::from_secs(10), "{waited:?}"); + assert_eq!(woken["data"]["running"], false, "{woken}"); + } + #[test] fn socks_control_lifecycle_and_context_cleanup() { use std::io::{Read, Write}; diff --git a/crates/meshport/src/lib.rs b/crates/meshport/src/lib.rs index 7ae7c70..c279721 100644 --- a/crates/meshport/src/lib.rs +++ b/crates/meshport/src/lib.rs @@ -4,6 +4,9 @@ mod system_probe; use anyhow::{Result, ensure}; use meshport_easytier::Engine; pub use meshport_easytier::parse_config as validate_config; +pub use meshport_easytier::{ + MeshRoutes, build_config, check_local_overlap, migrate_config, overlay_projection, +}; pub use meshport_netstack::{TcpListener, TcpStream, UdpSocket}; use std::{ net::SocketAddr, @@ -27,6 +30,11 @@ impl Network { pub async fn stop(&self) { self.engine.stop().await; } + /// Destinations to route through this network; changes as advertisements + /// are accepted or withdrawn. Use instead of polling `snapshot`. + pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver { + self.engine.watch_mesh_routes() + } /// Removes this network's secret from diagnostic text before export. pub fn redact_diagnostic(&self, text: &str) -> String { self.engine.redact_diagnostic(text) diff --git a/docs/advanced-client-features.md b/docs/advanced-client-features.md index 8e4021d..e34bbb9 100644 --- a/docs/advanced-client-features.md +++ b/docs/advanced-client-features.md @@ -20,7 +20,7 @@ Android 本轮已编译,按用户安排暂不安装真机。macOS 图片二维 - **代理 → 编辑普通规则**:添加、排序、启停规则集。普通规则先匹配,随后规则集,再使用默认出口;组网有效子网和已撤销子网保护始终在前。全局 / 直连模式暂停普通规则和规则集。 - **代理 → 编辑 DNS**:启动解析器仍为 IP;直连和代理解析器可填写 IP、`https://主机/dns-query` 或 `tls://主机:853`。DoH 默认 443、DoT 默认 853;TLS 校验保持开启。代理 DNS 经手动所选节点;解析器主机名由独立启动 DNS 解析,避免循环依赖。仅组网模式不接管互联网 DNS。 - **代理 → 导入与预览**:选择文件、相机扫码或二维码图片。只填入草稿,点击“解析并预览”后确认导入。HTTPS 订阅链接可以选择“作为订阅地址添加”。导入普通 sing-box JSON 只提取节点,不能覆盖受管理 TUN、DNS 和组网路由。 -- **组网配置导入**:TOML 导入对话框同样支持文件、相机和二维码图片,校验后由用户点击连接。 +- **组网配置**:通过组网页表单填写;原 TOML 导入对话框已移除。保存过的完整 TOML 在未修改表单时原样保留。 - **设置 → 启动与后台**:分别选择自动连接与 macOS 登录启动。登录项需要系统批准时会显示实际状态和系统设置入口;Android 自动连接指打开 APP 后连接,不代表开机后台建立 VPN。 ## 更新与缓存行为 diff --git a/docs/architecture.md b/docs/architecture.md index 3e317a2..92a288f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,3 +19,5 @@ UI 仅显示实测状态与结果。连接耗时与 echo 往返耗时分开标 选路优化在 vendor/easytier/easytier-core 的连接及下一跳选择层执行,适配层负责严格配置和实际路由快照。质量测量通过公开 Rust/C ABI/Dart API 发起真实 UDP echo,不改系统网络,详见 [优化说明](optimization.md)。 系统模式:Flutter → Dart Unix 控制通道 → macOS 特权 helper → 同一 C ABI → EasyTier TUN;其他应用通过普通系统 socket 使用虚拟网段。详见 [系统组网](system-vpn.md)。 + +组网规则归 SDK:配置生成与模式约束(`build_config`)、旧配置迁移(`migrate_config`)、虚拟网段与本机接口冲突检查、应用模式网络加桥接的原子启动(`start_bridged`)、路由目标投影(`mesh_cidrs` 与 `route_generation`)、组网可用性(`health`)以及节点直连/中继与延迟来源判定(`nodes`)都在 Rust 中实现。Dart 客户端核心、Android VpnService 与 macOS helper 只安装和展示这些结果,负责平台授权、socket protect、物理网络选择、OS 路由/DNS 守护与 sing-box 配置。质量测量循环仍由 Dart 驱动:ABI v1 每 context 串行,在原生侧运行约 30 秒的采样循环会阻塞同一 context 的状态轮询。 diff --git a/docs/client-runtime.md b/docs/client-runtime.md index 27dd2dd..7c9df08 100644 --- a/docs/client-runtime.md +++ b/docs/client-runtime.md @@ -33,13 +33,15 @@ macOS 统一 VPN 的仅组网模式使用 IPv4 TUN,只安装合规公告及会 ## 生命周期与保护 -组网启动顺序为 MeshPort → Rust SOCKS 桥接 → Go 引擎。停止顺序相反。启动失败回滚已有资源,网络停止失败保留所有权以便重试。`close()` 等待队列并释放代理上下文;宿主最终关闭 MeshPort。 +组网启动由 SDK `start_bridged` 一步完成 MeshPort 与 Rust SOCKS 桥接(失败由 SDK 一并回滚),再启动 Go 引擎;停止顺序相反。会话只在 `start_bridged` 成功后取得 context 所有权,context 已被占用时不会误停对方网络。网络停止失败保留所有权以便重试。组网配置由 SDK `build_config` 生成,旧版保存的配置经 `migrate_config` 迁移。`close()` 等待队列并释放代理上下文;宿主最终关闭 MeshPort。 -每 2 秒读取当前虚拟 IPv4 和 `platform_network.subnet_routes`,只采用 `accepted_projection`。规范化后有变化才重建 Go 配置,无需手动远端子网列表。重建关闭已有代理连接,尚非无损热更新。 +宿主状态轮询直接读取 SDK 的 `platform_network.mesh_cidrs`(虚拟网段加已接受公告子网,已规范化),并用 `health.mesh_routable` 判断组网是否可用;客户端不再自行解析或掩码计算前缀。集合变化才重建 Go 配置,无需手动远端子网列表。`MeshProxySession` 启动后另开一个 `wait_routes` 长轮询循环,路由一变化就排队重建,不必等下一次宿主轮询;宿主轮询仍负责健康检查。Android 服务用独立线程长轮询 `wait_routes`,把路由应用投递到服务的 worker 线程。重建关闭已有代理连接,尚非无损热更新。 本次连接期间见过的合规组网前缀形成保护集合。有效前缀先走组网,撤销的已知前缀被拒绝,不能落入普通代理或直连;显式停止会话后清空集合。SDK 数据面也独立验证当前有效公告。 -应用内联合模式中,组网暂不可用时普通代理可继续运行,状态为 `Partial`,组网目标保持拒绝。仅组网出现故障则清理会话。Android 服务故障目前整体停止,恢复行为尚需真机验证。 +应用内联合模式中,组网暂不可用时普通代理可继续运行,状态为 `Partial`,组网目标保持拒绝。仅组网出现故障则清理会话。Android 单一 VPN 同样按 `health.mesh_routable` 处理:联合(combined)模式下组网停止只撤掉组网路由、代理继续,状态报告 `Partial`(Lab 仍视为已连接,可断开);仅组网模式与系统 VPN 整体停止。该行为尚需真机验证。 + +Android `MeshVpnService` 的所有状态只在其 worker 线程上修改:Activity 发来的请求、2 秒健康检查、底层网络回调与路由更新都在这一个线程串行执行。请求接口为异步回调,不在 worker 上阻塞等待;每次 worker 任务结束后刷新状态快照,`status` 请求直接返回快照,不会被耗时的重建阻塞。`installed_subnet_routes` 在 Android 与 macOS 辅助进程中含义一致:只含已安装的公告子网,不含虚拟网段。 ## DNS diff --git a/docs/compatibility.md b/docs/compatibility.md index 9b2c874..acb6624 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -4,6 +4,8 @@ EasyTier 仓库:https://github.com/EasyTier/EasyTier vendor/easytier 是固定提交的本地定制快照,来源和修改清单见该目录 MESHPORT.md。基础提交:7af7bdc16a41d64d58743d15023a63b3eed2102c。Cargo.lock 固定传递依赖;build 使用 --locked。 +原生库能力:C ABI 为 v1,Flutter 绑定要求能力修订号(`abi_info.revision`)≥ 2;`MeshPortClient.open` 在打开时检查,旧库(无 `abi_info` 或修订号更低)会以“native library is too old … rebuild meshport-ffi”的 StateError 拒绝。`fromTransport`(Android VpnService、macOS 辅助进程)由各自宿主保证同版本原生库,不做该检查。 + 当前本机验证:macOS aarch64、Rust1.99、Flutter3.41.4/Dart3.11.1。 目标平台:macOS/Linux/Windows/iOS/Android。macOS 原生库和客户端已验证。Android ARM64 原生库、JNI 和 APK 已构建,真机配置加密存储、应用内与系统 VPN TCP/UDP,以及公告子网自动接入和撤销已通过。其他 runner 是脚手架,仍需要目标编译、链接、库加载和真机测试。iOS 使用静态链接,并需要保留导出符号。Android 说明见 android.md。 diff --git a/docs/ffi-contract.md b/docs/ffi-contract.md index 696cb6c..a804114 100644 --- a/docs/ffi-contract.md +++ b/docs/ffi-contract.md @@ -12,6 +12,17 @@ 控制操作:validate/start(toml)、stop、status。 +- `validate` 返回 `runtime_mode` 与 `overlay`(静态地址时为 `{address, prefix, network, routable}`,DHCP 为 null;`routable` 表示私有 IPv4 /16~/32)。可选 `check_local_overlap=true` 额外检查虚拟网段是否与本机现有接口重叠。 +- `start` 同样接受 `check_local_overlap`。系统模式启动时 SDK 总是执行该检查,宿主不再自行预检。 +- `build_config`(profile)由结构化表单草稿生成 SDK 接受的 TOML,返回 `toml`。`runtime_mode` 不是 `system_vpn`(包括宿主的 `unified_vpn`)时生成应用模式;`no_tun`/`use_smoltcp`、`enable_encryption=true`、`latency_first` 由 SDK 决定,宿主不再拼接 TOML。结果已通过 validate 同等校验。 +- `migrate_config`(toml)移除旧版保存过、当前不接受的字段(顶层或 runtime 中的 `subnet_routes`),返回 `toml` 与 `changed`;无需迁移时原样返回。 +- `abi_info` 返回 `{abi, revision, operations}`。`abi` 仍为 1;`revision` 是同一 ABI 内的能力修订号(当前 2:带 `build_config`/`migrate_config`/`start_bridged`/`wait_routes`/`health` 等),`operations` 列出支持的操作。宿主打开库后先调用它,修订号不足时给出明确错误,而不是在某个操作上才失败。旧库没有该操作,同样视为不满足。 +- `start_bridged`(toml,可选 port、max_sessions、check_local_overlap、require_static_overlay)一步完成:校验应用模式、静态地址须可路由、可选要求静态地址与本机冲突检查,再启动网络与 SOCKS 桥接;任一步失败两者都不保留。返回 `engine_started`、`listen`、`overlay`、`mesh_cidrs`、`route_generation`。 + +`status` 的 `platform_network` 增加 `mesh_cidrs`(虚拟网段(可路由时)加已接受公告子网,规范化、排序,/32 也带后缀)、`route_generation`(`mesh_cidrs` 每次变化递增,宿主只需比较这个数)与 `overlay`。`subnet_routes` 保留,表示已接受公告子网本身。`health` 为 `{engine_running, bridge_running, mesh_routable}`,`mesh_routable` 表示宿主此刻可把 `mesh_cidrs` 流量交给桥接;停止时全部为 false。宿主不再自行计算前缀或判断组网是否可用。 + +`wait_routes`(可选 `after_generation`,`timeout_ms` 1–30000,默认 25000)长轮询路由变化:`route_generation` 与 `after_generation` 不同或网络停止时立即返回,否则超时返回 `changed:false`。返回 `running`、`changed`、`route_generation`、`mesh_cidrs`、`subnet_routes`。它不占用 context 的串行锁,等待期间 status、stop 等请求照常执行;需在独立线程/isolate 调用。网络停止时 SDK 会递增 generation、清空路由并标记停止,等待方被唤醒并得到 `running:false`。没有网络时立即返回 `running:false`(传了 `after_generation` 时 `changed:true`)。`meshport_context_free` 会立即停止网络并唤醒在途等待,不必等其超时。 + `validate` 的 `include_profile=true` 投影将 `flags.foreign_relay_bps_limit` 编码为十进制字符串,以精确保留 u64 范围;宿主重新生成 TOML 时也应使用十进制字符串。默认无限制值为 `"18446744073709551615"`,不能经过浮点数转换。Flutter 会迁移旧配置中被舍入的默认无限制值,其他不精确或越界值要求重新输入。 应用内组网桥接:`socks_start`(可选 port,默认 0;max_sessions,默认 128)、`socks_status`、`socks_stop`。数据转发直接走原生并发任务,不经 JSON 字节 I/O。仅支持 IPv4 回环 SOCKS5 TCP/UDP;域名、IPv6、不支持的命令不做外部回退。stop/context free 先清理桥接再停止网络;socks_stop 不停止组网。需要新版原生库,详见 [SOCKS 桥接](socks-bridge.md)。 @@ -28,12 +39,14 @@ probe:target、protocol(TCP/UDP)、echo、timeout_ms。TCP echo=false 只 单次 JSON 请求 ≤128 KiB,配置 ≤64 KiB;写数据建议按16 KiB分块。UDP bytes ≤65507;TCP read 最大65535。普通 I/O 超时 1–30000 ms,默认5000 ms。连接/绑定超时当前固定5000 ms。 -该 ABI 同步且每 context 串行,必须在后台线程执行。停止和释放会等待在途请求完成;当前不提供立即取消。TCP超时后可能已有部分字节发出,不应直接重发整个消息。后续生产版需异步资源接口和结构化错误码。 +该 ABI 同步且每 context 串行(`wait_routes` 除外),必须在后台线程执行。停止和释放会等待在途请求完成(`wait_routes` 会被唤醒而非等待);当前不提供立即取消。TCP超时后可能已有部分字节发出,不应直接重发整个消息。后续生产版需异步资源接口和结构化错误码。 ## 网络遥测 `status` 增加 `traffic`:`rx_bytes` / `tx_bytes` 为当前引擎运行期间采样到的累计隧道字节,`rx_bytes_per_second` / `tx_bytes_per_second` 是两次状态采样间的平均 B/s。首次采样速率为 null,重启引擎重新计数。包含组网控制、心跳和转发流量,不等于应用有效载荷。计数来自存活连接快照;若连接在两次采样之间消失,最后一次采样后的字节可能未计入。 +`nodes` 是 SDK 合并 routes 与 peers 后的节点视图(排除本机,routes 顺序在前):`path`(direct/relay)、`direct_available`、`hole_punched`、`latency_ms` 与 `latency_source`(link_rtt / route_estimate / null)、`metered` 及该节点链路的 rx/tx 字段。直连且有 RTT 时取链路 RTT,否则取路由估算;界面直接展示,不再自行判定。 + `peers` 增加默认连接的 `latency_ms`(EasyTier ping RTT;未测出为 null),当前存活连接合计字节及采样速率。`routes` 增加所选路由的 `estimated_latency_ms` 与 `next_hop_peer_id`;估算为路由各链路延迟之和,不是端到端实测 RTT。多连接节点的 RTT 来自默认连接,流量为全部存活连接之和。中继目标未单独归集流量,其流量计入下一跳隧道。 `diagnostics_enable` 显式开启进程级穿透 tracing 采集,返回 enabled 与 scope。SDK 默认不安装全局 subscriber;已有宿主 subscriber 时 enabled=false,宿主应自行开启 EasyTier 穿透日志。启用后不可在本进程中卸载,采集仅匹配 easytier_core::connectivity::hole_punch,最多 200 条、每条 4 KiB;status 增加 diagnostic_traces,含递增 sequence,可跨采样去重。多实例共享采集范围;诊断中含节点地址,导出时当前网络密钥脱敏。 diff --git a/docs/singbox-integration.md b/docs/singbox-integration.md index 7623011..5e44978 100644 --- a/docs/singbox-integration.md +++ b/docs/singbox-integration.md @@ -30,7 +30,7 @@ SOCKS 出口依据 [sing-box 官方接口](https://sing-box.sagernet.org/configu 只有配置前缀内的 IPv4 流量进入组网出口;其他目标和域名请求显式拒绝,没有普通互联网出口。当前前缀额外限制为私网 /16–/32,不接受所有私网、公共段、IPv6 或默认路由。地址属于允许范围不等于已公告,宿主仍需从 SDK 的合规有效投影生成配置。 -mesh_cidrs 是宿主从 SDK 状态生成的内部字段,不是新增的用户手动远端子网列表。联调测试直接读取 platform_network.subnet_routes 和当前虚拟地址。Go 使用启动时快照;公告撤销由底层 SDK 即时阻止转发。现有客户端核心按有效投影变化自动重建 Go 引擎,无需手动列表;变化会关闭已有代理连接。无损热更新仍待实现;当前客户端核心已保留本次会话中的已知前缀,撤销目标由显式拒绝规则保护。 +mesh_cidrs 直接取自 SDK 状态的 `platform_network.mesh_cidrs`(或 `start_bridged` 返回值),宿主原样传入,不是用户手动远端子网列表,也不再由各宿主重复计算。Go 使用启动时快照;公告撤销由底层 SDK 即时阻止转发。现有客户端核心按有效投影变化自动重建 Go 引擎,无需手动列表;变化会关闭已有代理连接。无损热更新仍待实现;当前客户端核心已保留本次会话中的已知前缀,撤销目标由显式拒绝规则保护。 组网目标没有路由时返回连接失败或关闭连接,UDP 不交给其他出口。域名在分流第一条即拒绝,不做系统 DNS;此处描述最初 mesh-only 配置;当前联合模式已实现组网 DNS 和普通代理解析,FakeIP 已实现,范围见客户端运行控制。 diff --git a/docs/system-vpn.md b/docs/system-vpn.md index f9a797d..203adfd 100644 --- a/docs/system-vpn.md +++ b/docs/system-vpn.md @@ -22,7 +22,7 @@ Rust 的 `system-vpn` feature 是显式编译开关;默认 SDK 构建保持应 ## 启动和生命周期 -运行 `scripts/run-lab-macos.sh`,它构建并启动包含动态库与 helper 的开发应用。系统模式启动时 macOS 请求管理员授权;Flutter UI 不提权,独立 helper 创建网络接口。控制通道是当前用户私有临时目录中的 Unix socket,helper 校验对端 UID,限制请求大小与允许的操作。断开连接停止引擎,但应用存活期间保留已授权 helper 和控制通道,使用每 30 秒一次的空闲心跳支持下次连接复用授权。退出应用关闭控制通道并清理 helper;控制通道异常关闭或空闲超时也会停止引擎,临时目录由 Dart 清理。虚拟网段在启动前检查冲突。自动公告子网只允许私有 IPv4 /16 至 /32,最多 32 项(CIDR 排序后截取);过滤默认路由、公网、过宽网段、虚拟网段及本机接口重叠。接口缓存每 2 秒更新,系统路由定期重新同步;安装失败重试,公告撤回删除路由。 +运行 `scripts/run-lab-macos.sh`,它构建并启动包含动态库与 helper 的开发应用。系统模式启动时 macOS 请求管理员授权;Flutter UI 不提权,独立 helper 创建网络接口。控制通道是当前用户私有临时目录中的 Unix socket,helper 校验对端 UID,限制请求大小与允许的操作。断开连接停止引擎,但应用存活期间保留已授权 helper 和控制通道,使用每 30 秒一次的空闲心跳支持下次连接复用授权。退出应用关闭控制通道并清理 helper;控制通道异常关闭或空闲超时也会停止引擎,临时目录由 Dart 清理。虚拟网段在启动前检查冲突。自动公告子网只允许私有 IPv4 /16 至 /32,最多 32 项(CIDR 排序后截取);过滤默认路由、公网、过宽网段、虚拟网段及本机接口重叠。接口缓存每 2 秒更新,系统路由定期重新同步;安装失败重试,公告撤回删除路由。helper 是串行的请求/响应进程,由 GUI 状态轮询驱动,因此仍用轮询读取 `mesh_cidrs`,不使用 `wait_routes`;统一模式 status 的 `installed_subnet_routes` 不含虚拟网段,与 Android 一致;仅组网的统一模式在 `health.mesh_routable` 失效时整体停止(与 Android 一致),联合模式则保持代理并报告 `Partial`。 原生调用超过 60 秒时 helper 退出,以关闭 utun 文件描述符;Dart 控制请求超时为 30 秒。 @@ -42,4 +42,6 @@ macOS 的节点连接使用物理网卡候选,IPv4/IPv6 都排除其他 VPN 保留 v2rayN TUN,先用 `route -n get 192.168.21.201` 检查更具体的 /24 路由是否指向 MeshPort 的 utun。只设置 v2rayN “直连”规则不能建立 EasyTier 子网路由。如路由仍被代理接管,再检查 TUN 路由排除配置;不要依赖变化的 utun 编号设置永久路由。 -旧版 runtime.subnet_routes 已移除;Lab 恢复旧版已保存单行配置时会删除该字段并改用自动学习。直接使用 SDK 的旧配置应移除此字段。自动子网是 IPv4;移动端、Windows 的打包与实际互通尚待验证。 +旧版 runtime.subnet_routes 已移除;Lab 恢复旧版保存的配置时调用 SDK `migrate_config` 删除该字段并改用自动学习。直接使用 SDK 的旧配置也可调用该操作或手动移除此字段。 + +虚拟网段与本机现有接口重叠时,系统模式启动由 SDK 拒绝(“overlay overlaps an existing interface”),macOS helper 与 Android 服务不再各自预检。Android 上另一应用仍活动的 VPN 接口若与虚拟网段重叠,同样会被拒绝。自动子网是 IPv4;移动端、Windows 的打包与实际互通尚待验证。 diff --git a/docs/testing.md b/docs/testing.md index 01e5a82..34485fd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -20,7 +20,7 @@ ARM64 Rust 原生库、JNI 桥接、Android debug/release APK 构建通过。OPP - 穿透详细日志 opt-in 采集、保留节点 ID、过滤其他应用模块日志。 - Dart后台isolate → C ABI → Rust → 两节点EasyTier UDP通信,校验字节与来源。 - Flutter widget 初始未连接状态、设置入口。 -- Flutter TOML 导入 → 实际原生引擎启动 → 状态显示 → 断开连接。 +- Flutter 组网表单填写并保存 → 概览连接 → 实际原生引擎启动 → 状态显示 → 断开连接(`native_connect_test.dart`)。 - C 示例编译并读取原生实例状态。 - Flutter Redmi_AX6 打洞直连显示 7.5 ms 实测 RTT,排除错误中继标签。 - Flutter 节点 RTT、路由估算、流量速率和中继统计范围显示测试;已有直连但实际路由经中继时正确区分。 @@ -36,8 +36,10 @@ scripts/cargo-local.sh clippy --workspace --all-targets --no-deps --locked -- -D cd apps/meshport_lab flutter analyze flutter test -# 包含真实原生引擎的界面测试(先构建 Rust 库) -flutter test --dart-define=MESHPORT_LIBRARY="$(cd ../.. && pwd)/target/debug/libmeshport_ffi.dylib" +# 包含真实原生引擎的测试(先构建 Rust 库)。未设置环境变量时这些测试显示为 skip。 +MESHPORT_LIBRARY="$(cd ../.. && pwd)/target/debug/libmeshport_ffi.dylib" \ +MESHPORT_PROXY_LIBRARY="$(cd ../.. && pwd)/target/debug/libmeshport_proxy.dylib" \ +flutter test dart run tool/native_smoke.dart ../../target/debug/libmeshport_ffi.dylib ``` diff --git a/packages/meshport_client_core/lib/src/mesh_proxy_session.dart b/packages/meshport_client_core/lib/src/mesh_proxy_session.dart index c95e2f7..3ca2fc8 100644 --- a/packages/meshport_client_core/lib/src/mesh_proxy_session.dart +++ b/packages/meshport_client_core/lib/src/mesh_proxy_session.dart @@ -17,6 +17,7 @@ class MeshProxySession { String? _bridge; List _prefixes = []; bool _ownsNetwork = false, _closed = false; + int _epoch = 0; Future _tail = Future.value(); MeshProxySession({ required this.mesh, @@ -46,41 +47,58 @@ class MeshProxySession { } return; } - final validated = await mesh.request({'op': 'validate', 'toml': toml}); - if (validated['runtime_mode'] != 'application') - throw UnsupportedError('Unified system VPN is not implemented yet'); - if ((await mesh.status())['state'] != 'Stopped') - throw StateError('MeshPort context must be stopped'); _state = 'Starting'; try { - // Claim ownership before start so partial native startup is cleaned up. - _ownsNetwork = true; _active = true; - await mesh.start(toml); - _bridge = (await mesh.startSocksBridge())['listen'] as String; + // The SDK rolls back a partial network/bridge start itself; claim the + // context only once it is ours, so a busy context is never stopped. + final started = await mesh.startBridged(toml); + _ownsNetwork = true; + _bridge = started['listen'] as String; await _sync(await mesh.status()); + _watchRoutes(++_epoch, started['route_generation'] as int?); } catch (_) { await _fail(); rethrow; } }); + /// Applies route changes as the SDK reports them instead of waiting for the + /// next host poll. Health failures are still detected by [refresh]. + Future _watchRoutes(int epoch, int? generation) async { + bool current() => epoch == _epoch && _ownsNetwork && !_closed; + while (current()) { + final Map routes; + try { + routes = await mesh.waitRoutes(afterGeneration: generation); + } catch (_) { + return; // Older transports or a closed context: fall back to polling. + } + if (!current() || routes['running'] != true) return; + if (routes['changed'] != true) continue; + generation = routes['route_generation'] as int?; + try { + await _queue(() async { + if (current() && _active) await _sync(await mesh.status()); + }); + } catch (_) { + if (current()) await _queue(_fail).catchError((Object _) {}); + return; + } + } + } + /// Called by the host's status poll. Rebuild only on effective prefix changes. /// Existing engine sessions close on rebuild; withdrawn routes also fail at SDK. Future> refresh() => _queue(() async { try { final snapshot = await mesh.status(); - bool meshAvailable = true; - if (_ownsNetwork) { - if (profile['feature'] == 'combined') { - meshAvailable = - snapshot['state'] == 'Running' && - (await mesh.socksBridgeStatus())['running'] == true; - } else if (snapshot['state'] != 'Running') + final health = snapshot['health'] as Map? ?? const {}; + final meshAvailable = !_ownsNetwork || health['mesh_routable'] == true; + if (!meshAvailable && profile['feature'] != 'combined') { + if (health['engine_running'] != true) throw StateError('Mesh network stopped unexpectedly'); - if (profile['feature'] != 'combined' && - (await mesh.socksBridgeStatus())['running'] != true) - throw StateError('Mesh bridge stopped unexpectedly'); + throw StateError('Mesh bridge stopped unexpectedly'); } if (_active) { await _sync(meshAvailable ? snapshot : {}); @@ -92,7 +110,7 @@ class MeshProxySession { } }); Future _sync(Map snapshot) async { - final prefixes = usesMesh ? effectiveMeshPrefixes(snapshot) : []; + final prefixes = usesMesh ? meshPrefixes(snapshot) : []; _protected.addAll(prefixes); if (prefixes.join(',') == _prefixes.join(',') && (state == 'Running' || state == 'Partial')) { @@ -131,6 +149,7 @@ class MeshProxySession { Future stop() => _queue(_stop); Future _stop() async { + _epoch++; _state = 'Stopping'; endpoint = null; Object? failure; @@ -175,40 +194,13 @@ class MeshProxySession { } } -/// Only accepted SDK projections and the current virtual subnet enter routing. -/// Canonicalization prevents needless restarts caused by ordering/host-bit changes. -List effectiveMeshPrefixes(Map snapshot) { +/// Routable mesh prefixes as projected by the SDK: the overlay network plus +/// accepted advertised subnets, canonical and sorted. +List meshPrefixes(Map snapshot) { final platform = snapshot['platform_network'] as Map?; - final values = [ - snapshot['ipv4'], - if (platform?['subnet_routes_scope'] == 'accepted_projection') - ...?platform?['subnet_routes'] as List?, - ]; - final result = {}; - for (final value in values) { - if (value == null || value == '') continue; - if (value is! String) throw StateError('Invalid mesh prefix projection'); - final parts = value.split('/'); - final octets = parts.first.split('.').map(int.tryParse).toList(); - final bits = parts.length == 2 ? int.tryParse(parts[1]) : null; - if (bits == null || - bits < 16 || - bits > 32 || - octets.length != 4 || - octets.any((v) => v == null || v < 0 || v > 255)) - throw StateError('Unsupported mesh prefix projection'); - final ip = octets.cast(); - final private = - ip[0] == 10 || - (ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31) || - (ip[0] == 192 && ip[1] == 168); - if (!private) throw StateError('Mesh prefix must be private IPv4'); - final address = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3]; - final network = address & (0xffffffff << (32 - bits)); - result.add( - '${(network >> 24) & 255}.${(network >> 16) & 255}.${(network >> 8) & 255}.${network & 255}/$bits', - ); - } - if (result.length > 128) throw StateError('Too many mesh prefixes'); - return result.toList()..sort(); + final values = platform?['mesh_cidrs'] as List? ?? const []; + if (values.any((v) => v is! String)) + throw StateError('Invalid mesh prefix projection'); + if (values.length > 128) throw StateError('Too many mesh prefixes'); + return values.cast().toList(); } diff --git a/packages/meshport_client_core/lib/src/network_profile.dart b/packages/meshport_client_core/lib/src/network_profile.dart index 36ec7c9..2629bf2 100644 --- a/packages/meshport_client_core/lib/src/network_profile.dart +++ b/packages/meshport_client_core/lib/src/network_profile.dart @@ -1,5 +1,7 @@ import 'dart:convert'; +import 'package:meshport_flutter/meshport_flutter.dart'; + /// Client draft only; the Rust SDK remains the authority for native validation. class NetworkProfile { final Map values; @@ -37,44 +39,6 @@ class NetworkProfile { return result.toString(); } - String toToml() { - final v = values; - final mode = v['runtime_mode'] ?? 'application'; - final system = mode == 'system_vpn'; - final optimization = Map.from( - v['optimization'] as Map? ?? {'mode': 'adaptive'}, - ); - final flags = { - ...?v['flags'] as Map?, - 'no_tun': !system, - 'use_smoltcp': !system, - 'enable_encryption': true, - 'enable_ipv6': v['enable_ipv6'] ?? true, - 'latency_first': ['adaptive', 'latency'].contains(optimization['mode']), - }; - final lines = [ - 'hostname = ${jsonEncode(v['hostname'] ?? 'MeshPort')}', - if (v['dhcp'] == true) - 'dhcp = true' - else - 'ipv4 = ${jsonEncode(v['ipv4'] ?? '')}', - 'listeners = ${jsonEncode(v['listeners'] ?? [])}', - for (final key in ['stun_servers', 'stun_servers_v6']) - if (v[key] != null) '$key = ${jsonEncode(v[key])}', - for (final uri in v['peers'] as List? ?? []) - '[[peer]]\nuri = ${jsonEncode(uri)}', - '[network_identity]', - 'network_name = ${jsonEncode(v['network_name'] ?? '')}', - 'network_secret = ${jsonEncode(v['network_secret'] ?? '')}', - '[flags]', - for (final entry in flags.entries) - '${entry.key} = ${jsonEncode(entry.value)}', - '[runtime]', - 'mode = ${jsonEncode(system ? 'system_vpn' : 'application')}', - '[optimization]', - for (final entry in optimization.entries) - '${entry.key} = ${jsonEncode(entry.value)}', - ]; - return '${lines.join('\n')}\n'; - } + /// The SDK owns mode invariants and TOML encoding; this stays a draft. + Future toToml(MeshPortClient client) => client.buildConfig(values); } diff --git a/tools/meshport-vpn-helper/src/mac/self_test.rs b/tools/meshport-vpn-helper/src/mac/self_test.rs index 472f7ac..858d0b7 100644 --- a/tools/meshport-vpn-helper/src/mac/self_test.rs +++ b/tools/meshport-vpn-helper/src/mac/self_test.rs @@ -38,7 +38,7 @@ pub fn run() -> Result<()> { let port = std::net::UdpSocket::bind("127.0.0.1:0")?.local_addr()?.port(); let identity = "[network_identity]\nnetwork_name = 'meshport-vpn-self-test'\nnetwork_secret = 'test-only'\n"; let system_config = format!("ipv4 = '10.253.77.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{identity}[runtime]\nmode = 'system_vpn'"); - super::overlap_preflight(&system_config, true)?; + meshport::check_local_overlap(&meshport_easytier::parse_config(&system_config)?)?; stage("starting application server"); let server_config = easytier::common::config::TomlConfigLoader::new_from_str(&format!( "ipv4 = '10.253.78.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '10.253.78.0/24'\n{identity}[flags]\nno_tun = true\nuse_smoltcp = true" @@ -68,11 +68,10 @@ pub fn run() -> Result<()> { ensure!(started.elapsed() < Duration::from_secs(10), "peer discovery timeout"); tokio::time::sleep(Duration::from_millis(100)).await; } - while !vpn.snapshot().await["platform_network"]["subnet_routes"].as_array() - .is_some_and(|routes| routes.iter().any(|r| r == "10.253.78.0/24")) { - ensure!(started.elapsed() < Duration::from_secs(10), "advertised subnet learning timeout"); - tokio::time::sleep(Duration::from_millis(100)).await; - } + let mut routes = vpn.watch_mesh_routes(); + tokio::time::timeout(Duration::from_secs(10).saturating_sub(started.elapsed()), + routes.wait_for(|r| r.cidrs.iter().any(|c| c == "10.253.78.0/24"))) + .await.context("advertised subnet learning timeout")??; tokio::time::sleep(Duration::from_secs(2)).await; // Ordinary OS TCP socket: no MeshPort data-plane API on the client. let route = Command::new("/sbin/route").args(["-n", "get", "10.253.78.2"]).output()?; diff --git a/tools/meshport-vpn-helper/src/mac/unified.rs b/tools/meshport-vpn-helper/src/mac/unified.rs index bc8ca3f..b54840e 100644 --- a/tools/meshport-vpn-helper/src/mac/unified.rs +++ b/tools/meshport-vpn-helper/src/mac/unified.rs @@ -241,6 +241,7 @@ pub(super) struct Unified { profile: Value, protected: BTreeSet, active: BTreeSet, + overlay_network: Option, physical: String, mesh: bool, running: bool, @@ -300,31 +301,14 @@ fn physical_interface(internet: bool) -> Result { } Ok(interface) } +/// The SDK's canonical mesh destinations: overlay network plus accepted subnets. pub(super) fn prefixes(snapshot: &Value) -> Result> { - let mut result = BTreeSet::new(); - let address = snapshot["ipv4"] - .as_str() - .context("static mesh IPv4 required for unified VPN")?; - let prefix: std::net::Ipv4Addr = address - .split('/') - .next() - .context("invalid mesh IPv4")? - .parse()?; - let bits: u32 = address.split('/').nth(1).unwrap_or("24").parse()?; - ensure!((16..=32).contains(&bits), "unsupported mesh prefix"); - result.insert(format!( - "{}/{}", - std::net::Ipv4Addr::from(u32::from(prefix) & (u32::MAX << (32 - bits))), - bits - )); - if snapshot["platform_network"]["subnet_routes_scope"] == "accepted_projection" { - if let Some(routes) = snapshot["platform_network"]["subnet_routes"].as_array() { - for value in routes { - result.insert(value.as_str().context("invalid accepted route")?.into()); - } - } - } - Ok(result) + snapshot["platform_network"]["mesh_cidrs"] + .as_array() + .context("mesh routes unavailable")? + .iter() + .map(|value| Ok(value.as_str().context("invalid mesh route")?.to_owned())) + .collect() } impl Unified { pub fn active(&self) -> bool { @@ -363,26 +347,25 @@ impl Unified { .unwrap() .request(json!({"op":"configure_cache","directory":"/var/run"}))?; let result = (|| -> Result { + let mut active = BTreeSet::new(); if self.mesh { let config = request["toml"].as_str().context("configuration missing")?; - let validation = super::call(id, &json!({"op":"validate","toml":config}))?; + let bridge = super::call( + id, + &json!({"op":"start_bridged","toml":config, + "check_local_overlap":true,"require_static_overlay":true}), + )?; ensure!( - validation["ok"] == true && validation["data"]["runtime_mode"] == "application", - "unified VPN requires application-mode MeshPort" + bridge["ok"] == true, + "mesh startup failed: {}", + bridge["error"].as_str().unwrap_or("unknown error") ); - super::overlap_preflight(config, false)?; - let start = super::call(id, &json!({"op":"start","toml":config}))?; - ensure!(start["ok"] == true, "mesh startup failed"); - let bridge = super::call(id, &json!({"op":"socks_start"}))?; - ensure!(bridge["ok"] == true, "mesh bridge startup failed"); self.profile["mesh_socks"] = bridge["data"]["listen"].clone(); + self.overlay_network = bridge["data"]["overlay"]["network"] + .as_str() + .map(str::to_owned); + active = prefixes(&json!({"platform_network": bridge["data"]}))?; } - let snapshot = super::call(id, &json!({"op":"status"}))?["data"].clone(); - let active = if self.mesh { - prefixes(&snapshot)? - } else { - BTreeSet::new() - }; self.restart(active)?; if self.profile["feature"] != "mesh" { self.dns = Some(DnsGuard::install()?); @@ -411,7 +394,13 @@ impl Unified { } pub fn status(&mut self, id: u64) -> Result { let mut snapshot = super::call(id, &json!({"op":"status"}))?["data"].clone(); - let active = if self.mesh && snapshot["state"] == "Running" { + // Like Android: mesh-only has nothing left to serve once the mesh is + // gone (the caller then stops the session); combined keeps the proxy. + ensure!( + self.profile["feature"] != "mesh" || snapshot["health"]["mesh_routable"] == true, + "mesh network stopped unexpectedly" + ); + let active = if self.mesh && snapshot["health"]["mesh_routable"] == true { prefixes(&snapshot)? } else { BTreeSet::new() @@ -434,7 +423,13 @@ impl Unified { snapshot["proxy"] = proxy; snapshot["platform_network"]["ready"] = json!(true); snapshot["platform_network"]["route_installation"] = json!("macos_unified_tun"); - snapshot["platform_network"]["installed_subnet_routes"] = json!(self.active); + // Same meaning on every platform: advertised subnets only, not the overlay. + let installed: Vec<_> = self + .active + .iter() + .filter(|cidr| Some(*cidr) != self.overlay_network.as_ref()) + .collect(); + snapshot["platform_network"]["installed_subnet_routes"] = json!(installed); snapshot["platform_network"]["protected_subnets"] = json!(self.protected); Ok(json!({"ok":true,"data":snapshot})) } @@ -449,6 +444,7 @@ impl Unified { self.physical_route.take(); self.protected.clear(); self.active.clear(); + self.overlay_network = None; if let Some(error) = proxy_error { return Err(error); } diff --git a/tools/meshport-vpn-helper/src/mac/unified_test.rs b/tools/meshport-vpn-helper/src/mac/unified_test.rs index d665121..5749953 100644 --- a/tools/meshport-vpn-helper/src/mac/unified_test.rs +++ b/tools/meshport-vpn-helper/src/mac/unified_test.rs @@ -41,7 +41,7 @@ pub fn run() -> Result<()> { loop { let snapshot = unified.status(id.0)?; if snapshot["data"]["peer_count"].as_u64().unwrap_or(0) > 0 - && snapshot["data"]["platform_network"]["subnet_routes"] + && snapshot["data"]["platform_network"]["mesh_cidrs"] .as_array() .is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25")) { diff --git a/tools/meshport-vpn-helper/src/main.rs b/tools/meshport-vpn-helper/src/main.rs index 343ba4e..9659345 100644 --- a/tools/meshport-vpn-helper/src/main.rs +++ b/tools/meshport-vpn-helper/src/main.rs @@ -37,55 +37,14 @@ mod mac { Ok(decoded?) } } - fn overlap_preflight(config: &str, require_system: bool) -> Result<()> { + // Overlap with existing interfaces is checked by the SDK when a system + // VPN starts; the helper only refuses configurations it must not run. + fn require_system_mode(config: &str) -> Result<()> { let config = meshport_easytier::parse_config(config)?; ensure!( - !require_system || !config.get_flags().no_tun, + !config.get_flags().no_tun, "helper accepts only system_vpn mode" ); - let overlay = config.get_ipv4().context("static overlay IPv4 required")?; - let mut head = std::ptr::null_mut(); - unsafe { - ensure!( - libc::getifaddrs(&mut head) == 0, - "cannot inspect existing interfaces" - ); - let mut p = head; - let mut conflict = false; - while !p.is_null() { - let row = &*p; - if !row.ifa_addr.is_null() - && !row.ifa_netmask.is_null() - && (*row.ifa_addr).sa_family as i32 == libc::AF_INET - { - let a = &*(row.ifa_addr as *const libc::sockaddr_in); - let m = &*(row.ifa_netmask as *const libc::sockaddr_in); - let ip = u32::from_be(a.sin_addr.s_addr); - let mask = u32::from_be(m.sin_addr.s_addr); - let networks = - std::iter::once((overlay.first_address(), overlay.network_length())).chain( - config - .get_routes() - .unwrap_or_default() - .into_iter() - .map(|r| (r.first_address(), r.network_length())), - ); - if networks.into_iter().any(|(base, prefix)| { - let overlay_mask = u32::MAX << (32 - prefix); - ip & mask & overlay_mask == u32::from(base) & mask & overlay_mask - }) { - conflict = true; - break; - } - } - p = row.ifa_next; - } - libc::freeifaddrs(head); - ensure!( - !conflict, - "overlay or selected subnet overlaps an existing interface; choose another subnet or stop the conflicting VPN" - ); - } Ok(()) } fn dispatch( @@ -116,7 +75,7 @@ mod mac { } match request["op"].as_str() { Some("start") => { - overlap_preflight(request["toml"].as_str().context("missing toml")?, true)? + require_system_mode(request["toml"].as_str().context("missing toml")?)? } Some("stop" | "status" | "probe" | "validate" | "diagnostics_enable") => {} _ => bail!("operation unavailable in system VPN helper"),