Move mesh networking logic into the SDK and fix lifecycle bugs
SDK: - Add build_config/migrate_config, mesh_cidrs, route_generation, health and start_bridged; expose abi_info (capability revision 2). - Add wait_routes long-poll; stop wakes waiters, and context_free now stops the network immediately instead of waiting for waiters to time out. Hosts: - Dart: waitRoutes(), MeshProxySession route watcher, ABI capability check. - Android: fix a deadlock where every VPN request waited on its own single-thread worker; requests are now async, status is served from a snapshot, and combined mode reports Partial when the mesh stops. - macOS helper: mesh-only unified mode stops when the mesh is lost; installed_subnet_routes excludes the overlay. - Lab: restore Partial sessions, write migrated profiles back, remove the unreachable TOML import dialog; native test now connects via the form. Docs updated accordingly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
29d236f3fe
commit
dc1bfc99d2
+4
-5
@@ -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) } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+163
-67
@@ -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<String>()
|
||||
private var physical: android.net.Network? = null
|
||||
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||
private var ipv4 = ""
|
||||
private var installed = emptyList<String>()
|
||||
// Overlay and routed destinations come from the SDK projection; the
|
||||
// service only installs them and never derives prefixes itself.
|
||||
private var overlayAddress = ""
|
||||
private var overlayPrefix = 0
|
||||
private var overlayNetwork = ""
|
||||
private var meshCidrs = emptyList<String>()
|
||||
private var routeGeneration = -1L
|
||||
private var running = false
|
||||
private var failure: String? = null
|
||||
override fun onCreate() {
|
||||
@@ -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<String>) {
|
||||
if (!running || context != handle || generation == routeGeneration) return
|
||||
if (cidrs != meshCidrs) { if (unified) restartProxy(cidrs) else rebuild(cidrs) }
|
||||
routeGeneration = generation
|
||||
}
|
||||
/** Long-polls the SDK route watch off `worker` so a slow wait never delays requests. */
|
||||
private fun watchRoutes(context: Long, from: Long) {
|
||||
val session = ++watchSession
|
||||
Thread({
|
||||
var generation = from
|
||||
while (session == watchSession) {
|
||||
val reply = try {
|
||||
JSONObject(NativeBridge.call(context, JSONObject().put("op", "wait_routes")
|
||||
.put("after_generation", generation).put("timeout_ms", 10000).toString()))
|
||||
} catch (_: Exception) { return@Thread }
|
||||
// An error means the context is gone; a stopped network is
|
||||
// left to the health tick, which knows the session's mode.
|
||||
if (!reply.optBoolean("ok")) return@Thread
|
||||
val data = reply.getJSONObject("data")
|
||||
if (!data.optBoolean("running")) return@Thread
|
||||
if (!data.optBoolean("changed")) continue
|
||||
generation = data.getLong("route_generation")
|
||||
val cidrs = strings(data.getJSONArray("mesh_cidrs"))
|
||||
val next = generation
|
||||
try {
|
||||
onWorker {
|
||||
if (session == watchSession) try { applyRoutes(context, next, cidrs) }
|
||||
catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
|
||||
}
|
||||
} catch (_: java.util.concurrent.RejectedExecutionException) { return@Thread }
|
||||
}
|
||||
}, "meshport-route-watch").apply { isDaemon = true }.start()
|
||||
}
|
||||
private fun strings(list: org.json.JSONArray) = (0 until list.length()).map { list.getString(it) }
|
||||
private fun useOverlay(overlay: JSONObject?, mode: String) {
|
||||
checkNotNull(overlay) { "Static mesh address required for $mode" }
|
||||
overlayAddress = overlay.getString("address")
|
||||
overlayPrefix = overlay.getInt("prefix")
|
||||
overlayNetwork = overlay.getString("network")
|
||||
}
|
||||
private fun native(request: JSONObject): JSONObject {
|
||||
check(handle != 0L) { "VPN context not started" }
|
||||
val response = JSONObject(NativeBridge.call(handle, request.toString()))
|
||||
check(response.optBoolean("ok")) { response.optString("error", "Native request failed") }
|
||||
return response
|
||||
}
|
||||
fun request(request: JSONObject): JSONObject {
|
||||
/**
|
||||
* Callable from any thread; [reply] runs on `worker`, or immediately for a
|
||||
* status answered from the snapshot. Never blocks the caller.
|
||||
*/
|
||||
fun request(request: JSONObject, reply: (Result<JSONObject>) -> Unit) {
|
||||
val snapshot = statusSnapshot
|
||||
if (request.optString("op") == "status" && snapshot != null) {
|
||||
reply(Result.success(JSONObject(snapshot))); return
|
||||
}
|
||||
try {
|
||||
// Republish the snapshot before replying, so the caller's next
|
||||
// status already reflects this operation.
|
||||
worker.execute {
|
||||
val result = runCatching { dispatch(request) }
|
||||
refreshStatus()
|
||||
reply(result)
|
||||
}
|
||||
} catch (error: java.util.concurrent.RejectedExecutionException) {
|
||||
reply(Result.failure(IllegalStateException("VPN service is stopping")))
|
||||
}
|
||||
}
|
||||
private fun dispatch(request: JSONObject): JSONObject {
|
||||
return when (request.getString("op")) {
|
||||
"start" -> {
|
||||
check(!running) { "VPN already started" }
|
||||
@@ -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<String>) {
|
||||
val parts = ipv4.split('/')
|
||||
val address = parts[0]
|
||||
val prefix = if (parts.size == 2) parts[1].toInt() else 24
|
||||
val raw = InetAddress.getByName(address).address
|
||||
val network = raw.mapIndexed { index, byte ->
|
||||
val bits = (prefix - index * 8).coerceIn(0, 8)
|
||||
(byte.toInt() and (0xff shl (8 - bits))).and(0xff)
|
||||
}.joinToString(".")
|
||||
private fun rebuild(cidrs: List<String>) {
|
||||
// The overlay network is always on the TUN, even when the SDK does not
|
||||
// project it as routable for bridged hosts.
|
||||
val routes = (cidrs + overlayNetwork).toSortedSet()
|
||||
val builder = Builder().setSession("MeshPort").setMtu(1280)
|
||||
.addAddress(address, prefix).addRoute(network, prefix).allowFamily(OsConstants.AF_INET6)
|
||||
.addAddress(overlayAddress, overlayPrefix).allowFamily(OsConstants.AF_INET6)
|
||||
for (route in routes) {
|
||||
val cidr = route.split('/')
|
||||
builder.addRoute(cidr[0], cidr[1].toInt())
|
||||
}
|
||||
Log.i("MeshPortVPN", "Establishing TUN with ${routes.size} learned routes")
|
||||
Log.i("MeshPortVPN", "Establishing TUN with ${routes.size} mesh routes")
|
||||
val next = builder.establish() ?: error("Android VPN authorization revoked")
|
||||
val previous = tun
|
||||
try {
|
||||
@@ -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<String>()
|
||||
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<String>) {
|
||||
proxyCall(JSONObject().put("op","stop"))
|
||||
val config = JSONObject(proxyProfile.toString())
|
||||
val active = routes.toMutableSet()
|
||||
if (meshEnabled) {
|
||||
val state = native(JSONObject().put("op","status")).getJSONObject("data")
|
||||
val value = state.getString("ipv4").split('/')
|
||||
val prefix = IpPrefix(InetAddress.getByName(value[0]),value[1].toInt())
|
||||
active.add("${prefix.address.hostAddress}/${prefix.prefixLength}")
|
||||
protected.addAll(active)
|
||||
}
|
||||
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()
|
||||
|
||||
@@ -36,11 +36,12 @@ Future<void> waitForRoutes(
|
||||
final state = await client.status();
|
||||
lastState = state;
|
||||
final platform = state['platform_network'] as Map? ?? {};
|
||||
// mesh_cidrs is the SDK's routable set (overlay + accepted subnets).
|
||||
final routes =
|
||||
platform[installed ? 'installed_subnet_routes' : 'subnet_routes']
|
||||
platform[installed ? 'installed_subnet_routes' : 'mesh_cidrs']
|
||||
as List? ??
|
||||
[];
|
||||
if (withdrawn ? routes.isEmpty : routes.contains('10.253.79.0/24')) return;
|
||||
if (routes.contains('10.253.79.0/24') != withdrawn) return;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
}
|
||||
debugPrint('ANDROID_ROUTE_TIMEOUT_STATE ${jsonEncode(lastState)}');
|
||||
|
||||
@@ -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<ConfigImportDialog> createState() => _ConfigImportDialogState();
|
||||
}
|
||||
|
||||
class _ConfigImportDialogState extends State<ConfigImportDialog> {
|
||||
final editor = TextEditingController();
|
||||
@override
|
||||
void dispose() {
|
||||
editor.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String error = '';
|
||||
Future<void> read(String method) async {
|
||||
try {
|
||||
final value = await const MethodChannel(
|
||||
'meshport/system_vpn',
|
||||
).invokeMethod<String>(method);
|
||||
if (value != null && mounted) {
|
||||
setState(() {
|
||||
editor.text = value;
|
||||
error = '';
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) setState(() => error = '导入失败,请检查权限或文件格式');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AlertDialog(
|
||||
title: const Text('导入 TOML'),
|
||||
content: SizedBox(
|
||||
width: 560,
|
||||
child: 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('校验并连接'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -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'),
|
||||
|
||||
@@ -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<LabScreen> {
|
||||
Future<void> 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<LabScreen> {
|
||||
bool restored = false;
|
||||
if (profileSupported) {
|
||||
try {
|
||||
final stored = (await vpnChannel.invokeMethod<String>(
|
||||
'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<LabScreen> {
|
||||
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<LabScreen> {
|
||||
(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<LabScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
String buildConfig() {
|
||||
final form = buildFormConfig();
|
||||
Future<String> buildConfig() async {
|
||||
final form = await buildFormConfig();
|
||||
return loadedForm == form && loadedConfig != null ? loadedConfig! : form;
|
||||
}
|
||||
|
||||
@@ -421,9 +424,13 @@ class _LabScreenState extends State<LabScreen> {
|
||||
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<String, dynamic> networkValues() => {
|
||||
@@ -455,7 +462,39 @@ class _LabScreenState extends State<LabScreen> {
|
||||
.toList(),
|
||||
},
|
||||
};
|
||||
String buildFormConfig() => NetworkProfile(networkValues()).toToml();
|
||||
Future<String> buildFormConfig() =>
|
||||
NetworkProfile(networkValues()).toToml(applicationClient!);
|
||||
|
||||
/// Application-mode internet-only proxying never starts the mesh, so an
|
||||
/// incomplete network form must not block it.
|
||||
Future<String> startableFormConfig() async =>
|
||||
runtimeMode == 'application' &&
|
||||
singBoxEnabled &&
|
||||
proxyProfile.feature == 'proxy'
|
||||
? ''
|
||||
: await buildFormConfig();
|
||||
|
||||
/// Drops options earlier releases saved; the SDK owns the migration rules.
|
||||
Future<String?> 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<String?> loadMigratedProfile() async {
|
||||
final stored = await vpnChannel.invokeMethod<String>('load_profile');
|
||||
final migrated = await migratedProfile(stored);
|
||||
if (migrated != null && migrated != stored) {
|
||||
try {
|
||||
await applicationClient!.validate(migrated);
|
||||
await vpnChannel.invokeMethod<void>('save_profile', migrated);
|
||||
log('已移除旧版配置项并保存迁移后的网络配置');
|
||||
} catch (_) {
|
||||
log('旧版配置已在内存中迁移,但未能写回 $profileStorage');
|
||||
}
|
||||
}
|
||||
return migrated;
|
||||
}
|
||||
|
||||
Future<void> saveNetworkValues(Map<String, dynamic> values) async {
|
||||
final incoming = NetworkProfile(values).values;
|
||||
final policy = incoming['optimization'] as Map;
|
||||
@@ -463,7 +502,7 @@ class _LabScreenState extends State<LabScreen> {
|
||||
.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<LabScreen> {
|
||||
}
|
||||
|
||||
Future<void> 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<LabScreen> {
|
||||
Future<void> migrateLegacyProfiles() async {
|
||||
await vpnChannel.invokeMethod<void>('migrate_profiles');
|
||||
final proxy = await vpnChannel.invokeMethod<String>('load_proxy_profile');
|
||||
final network = (await vpnChannel.invokeMethod<String>(
|
||||
'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<LabScreen> {
|
||||
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<String, dynamic>.from(routes.first),
|
||||
peer: peers.isEmpty
|
||||
? null
|
||||
: Map<String, dynamic>.from(peers.first),
|
||||
status: status,
|
||||
);
|
||||
return NodeDetailBody(node: node, peer: peer, status: status);
|
||||
}),
|
||||
),
|
||||
]),
|
||||
@@ -1356,8 +1378,9 @@ class _LabScreenState extends State<LabScreen> {
|
||||
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<LabScreen> {
|
||||
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<LabScreen> {
|
||||
LogsPageBody(logs: logs, onClear: () => setState(() => logs.clear())),
|
||||
),
|
||||
);
|
||||
Future<void> importConfig() async {
|
||||
final text = await showDialog<String>(
|
||||
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];
|
||||
|
||||
@@ -23,15 +23,12 @@ class NodeTelemetry extends StatelessWidget {
|
||||
for (final peer in status['peers'] as List? ?? [])
|
||||
peer['peer_id']: Map<String, dynamic>.from(peer),
|
||||
};
|
||||
final nodes = <dynamic, Map<String, dynamic>>{
|
||||
for (final route in status['routes'] as List? ?? [])
|
||||
route['peer_id']: Map<String, dynamic>.from(route),
|
||||
};
|
||||
for (final id in peers.keys) {
|
||||
nodes.putIfAbsent(id, () => {'peer_id': id});
|
||||
}
|
||||
// The SDK merges routes and links and classifies path and latency source.
|
||||
final nodes = [
|
||||
for (final node in status['nodes'] as List? ?? [])
|
||||
Map<String, dynamic>.from(node as Map),
|
||||
];
|
||||
final local = status['local_peer'] as Map?;
|
||||
if (local != null) nodes.remove(local['peer_id']);
|
||||
if (nodes.isEmpty && local == null) {
|
||||
return const Text('尚未发现节点,连接后显示链路延迟与流量。');
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
],
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<String> logs() => (lab.logs as List).cast<String>();
|
||||
Finder field(String label) => find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget is TextField && widget.decoration?.labelText == label,
|
||||
);
|
||||
Future<void> waitForLog(String text) async {
|
||||
for (var i = 0; i < 60 && !logs().any((l) => l.contains(text)); i++) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 50)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
expect(logs(), contains(contains(text)));
|
||||
}
|
||||
|
||||
await waitForLog('原生库已加载');
|
||||
// Startup restores profiles first; let it finish before overriding them.
|
||||
await waitForLog('穿透');
|
||||
// Mesh-only, in-app engine: no helper, VPN permission or proxy node.
|
||||
lab.runtimeMode = 'application';
|
||||
lab.proxyProfile.feature = 'mesh';
|
||||
lab.proxyProfile.entry = 'application';
|
||||
await tester.tap(find.text('组网').last);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('基础配置'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(field('网络名称'), 'ui-local-test');
|
||||
await tester.enterText(field('网络密钥'), 'test-only');
|
||||
await tester.enterText(field('虚拟 IPv4 / 前缀'), '10.79.0.11/24');
|
||||
await tester.tap(find.text('保存草稿'));
|
||||
await waitForLog('网络配置已保存到');
|
||||
for (var i = 0; i < 40 && find.text('保存中…').evaluate().isNotEmpty; i++) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 50)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
await tester.pageBack();
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('概览').last);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('连接').last);
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
for (
|
||||
var i = 0;
|
||||
i < 40 && !logs().any((l) => l.contains('[启动组网引擎] 成功'));
|
||||
i++
|
||||
) {
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
});
|
||||
await tester.pump();
|
||||
}
|
||||
expect(logs(), contains(contains('[启动组网引擎] 成功')));
|
||||
for (
|
||||
var i = 0;
|
||||
i < 40 && find.text('引擎运行中 · 0 个节点').evaluate().isEmpty;
|
||||
i++
|
||||
) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 100)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
expect(find.text('引擎运行中 · 0 个节点'), findsOneWidget);
|
||||
expect(find.textContaining('当前设备'), findsOneWidget);
|
||||
expect(find.textContaining('节点 ID'), findsOneWidget);
|
||||
await tester.tap(find.text('断开连接'));
|
||||
for (var i = 0; i < 40 && find.text('尚未连接').evaluate().isEmpty; i++) {
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
});
|
||||
await tester.pump();
|
||||
}
|
||||
expect(find.text('尚未连接'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
});
|
||||
},
|
||||
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
|
||||
);
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshport_lab/features/lab_screen.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'TOML import starts real native engine and can stop it',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LabScreen()));
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
});
|
||||
await tester.pump();
|
||||
expect(find.textContaining('原生库已加载'), findsOneWidget);
|
||||
await tester.tap(find.text('设置').last);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('导入'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('粘贴 TOML 并连接'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(find.byType(TextField).last, '''
|
||||
ipv4 = "10.79.0.11"
|
||||
listeners = []
|
||||
stun_servers = []
|
||||
stun_servers_v6 = []
|
||||
[network_identity]
|
||||
network_name = "ui-local-test"
|
||||
network_secret = "test-only"
|
||||
[flags]
|
||||
default_protocol = "udp"
|
||||
''');
|
||||
await tester.tap(find.text('校验并连接').last);
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
await tester.pumpAndSettle();
|
||||
for (
|
||||
var i = 0;
|
||||
i < 40 && find.textContaining('导入配置并启动引擎').evaluate().isEmpty;
|
||||
i++
|
||||
) {
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
});
|
||||
await tester.pump();
|
||||
}
|
||||
expect(find.textContaining('导入配置并启动引擎'), findsOneWidget);
|
||||
await tester.tap(find.text('概览').last);
|
||||
await tester.pumpAndSettle();
|
||||
for (
|
||||
var i = 0;
|
||||
i < 40 && find.text('引擎运行中 · 0 个节点').evaluate().isEmpty;
|
||||
i++
|
||||
) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 100)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
expect(find.text('引擎运行中 · 0 个节点'), findsOneWidget);
|
||||
expect(find.textContaining('当前设备'), findsOneWidget);
|
||||
expect(find.textContaining('节点 ID'), findsOneWidget);
|
||||
await tester.tap(find.text('断开连接'));
|
||||
for (var i = 0; i < 40 && find.text('尚未连接').evaluate().isEmpty; i++) {
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
});
|
||||
await tester.pump();
|
||||
}
|
||||
expect(find.text('尚未连接'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.runAsync(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
});
|
||||
},
|
||||
skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'),
|
||||
);
|
||||
}
|
||||
@@ -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<String, dynamic>.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();
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -21,6 +22,8 @@ void main() {
|
||||
case 'delete_profile':
|
||||
stored = null;
|
||||
return null;
|
||||
case 'save_proxy_profile':
|
||||
return null;
|
||||
default:
|
||||
throw StateError('Unexpected call: ${call.method}');
|
||||
}
|
||||
@@ -31,30 +34,42 @@ void main() {
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null),
|
||||
);
|
||||
|
||||
Future<void> waitFor(WidgetTester tester, Finder finder) async {
|
||||
for (var i = 0; i < 60 && finder.evaluate().isEmpty; i++) {
|
||||
// The overview shows only the newest log lines; read the full log list.
|
||||
List<String> logs(WidgetTester tester) =>
|
||||
((tester.state(find.byType(LabScreen, skipOffstage: false)) as dynamic)
|
||||
.logs
|
||||
as List)
|
||||
.cast<String>();
|
||||
|
||||
Future<void> waitForLog(WidgetTester tester, String text) async {
|
||||
for (
|
||||
var i = 0;
|
||||
i < 100 && !logs(tester).any((line) => line.contains(text));
|
||||
i++
|
||||
) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 50)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
expect(finder, findsWidgets);
|
||||
expect(logs(tester), contains(contains(text)));
|
||||
}
|
||||
|
||||
Future<void> openSettings(WidgetTester tester) async {
|
||||
Future<void> openApp(WidgetTester tester) async {
|
||||
await tester.pumpWidget(const MaterialApp(home: LabScreen()));
|
||||
await waitFor(tester, find.textContaining('原生库已加载'));
|
||||
await waitFor(
|
||||
tester,
|
||||
find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget is Text &&
|
||||
(widget.data?.contains('已载入默认配置') == true ||
|
||||
widget.data?.contains('已载入默认网络配置') == true ||
|
||||
widget.data?.contains('已自动载入保存的网络配置') == true),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('设置').last);
|
||||
await waitForLog(tester, '原生库已加载');
|
||||
await waitForLog(tester, '载入');
|
||||
}
|
||||
|
||||
Future<void> openPage(WidgetTester tester, String tab, String entry) async {
|
||||
await tester.tap(find.text(tab).last);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(entry));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> back(WidgetTester tester) async {
|
||||
await tester.pageBack();
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
@@ -69,45 +84,36 @@ void main() {
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await openSettings(tester);
|
||||
await openApp(tester);
|
||||
await openPage(tester, '组网', '基础配置');
|
||||
await tester.enterText(field('网络名称'), '我的网络');
|
||||
await tester.enterText(field('网络密钥'), 'test-only-secret');
|
||||
await tester.enterText(field('节点名称'), 'saved-node');
|
||||
await tester.enterText(field('虚拟 IPv4'), '10.79.0.11/24');
|
||||
await tester.tap(find.text('保存配置'));
|
||||
await waitFor(tester, find.textContaining('网络配置已保存到 macOS 钥匙串'));
|
||||
await tester.enterText(field('虚拟 IPv4 / 前缀'), '10.79.0.11/24');
|
||||
await tester.tap(find.text('保存草稿'));
|
||||
await waitForLog(tester, '网络配置已保存到');
|
||||
expect(stored, contains('我的网络'));
|
||||
expect(find.text('尚未连接'), findsNothing); // The settings page is selected.
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 100)),
|
||||
);
|
||||
await openSettings(tester);
|
||||
await waitFor(tester, find.textContaining('已自动载入保存的网络配置'));
|
||||
expect(tester.widget<TextField>(field('网络名称')).controller!.text, '我的网络');
|
||||
expect(
|
||||
tester.widget<TextField>(field('网络密钥')).controller!.text,
|
||||
'test-only-secret',
|
||||
);
|
||||
expect(
|
||||
tester.widget<TextField>(field('节点名称')).controller!.text,
|
||||
'saved-node',
|
||||
);
|
||||
expect(
|
||||
tester.widget<TextField>(field('虚拟 IPv4')).controller!.text,
|
||||
'10.79.0.11/24',
|
||||
);
|
||||
await tester.tap(find.text('概览').last);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('尚未连接'), findsOneWidget);
|
||||
await tester.tap(find.text('设置').last);
|
||||
await tester.pumpAndSettle();
|
||||
await openApp(tester);
|
||||
await waitForLog(tester, '已自动载入保存的网络配置');
|
||||
await openPage(tester, '组网', '基础配置');
|
||||
String text(String label) =>
|
||||
tester.widget<TextField>(field(label)).controller!.text;
|
||||
expect(text('网络名称'), '我的网络');
|
||||
expect(text('网络密钥'), 'test-only-secret');
|
||||
expect(text('节点名称'), 'saved-node');
|
||||
expect(text('虚拟 IPv4 / 前缀'), '10.79.0.11/24');
|
||||
await back(tester);
|
||||
await openPage(tester, '设置', '默认配置');
|
||||
await tester.tap(find.text('删除已保存配置'));
|
||||
await waitFor(tester, find.textContaining('已删除保存的配置'));
|
||||
await waitForLog(tester, '已删除保存的配置');
|
||||
expect(stored, isNull);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
},
|
||||
skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'),
|
||||
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
@@ -126,14 +132,34 @@ network_secret = "test-only"
|
||||
disable_udp_hole_punching = true
|
||||
''';
|
||||
final original = stored;
|
||||
await openSettings(tester);
|
||||
await waitFor(tester, find.textContaining('已自动载入保存的网络配置'));
|
||||
await tester.ensureVisible(find.text('保存配置'));
|
||||
await openApp(tester);
|
||||
await waitForLog(tester, '已自动载入保存的网络配置');
|
||||
await openPage(tester, '设置', '默认配置');
|
||||
await tester.tap(find.text('保存配置'));
|
||||
await waitFor(tester, find.textContaining('网络配置已保存到 macOS 钥匙串'));
|
||||
await waitForLog(tester, '网络配置已保存到');
|
||||
expect(stored, original);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
},
|
||||
skip: !const bool.hasEnvironment('MESHPORT_LIBRARY'),
|
||||
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'legacy profile is migrated and written back on restore',
|
||||
(tester) async {
|
||||
stored = '''
|
||||
hostname = "legacy-node"
|
||||
ipv4 = "10.79.0.11/24"
|
||||
subnet_routes = ["192.168.21.0/24"]
|
||||
[network_identity]
|
||||
network_name = "legacy"
|
||||
network_secret = "test-only"
|
||||
''';
|
||||
await openApp(tester);
|
||||
await waitForLog(tester, '已自动载入保存的网络配置');
|
||||
expect(stored, isNot(contains('subnet_routes')));
|
||||
expect(stored, contains('legacy-node'));
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
},
|
||||
skip: Platform.environment['MESHPORT_LIBRARY'] == null,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<String> routes = ['192.168.21.0/24'];
|
||||
List<String> get cidrs => {?overlay, ...routes}.toList()..sort();
|
||||
int generation = 1;
|
||||
var _routesChanged = Completer<void>();
|
||||
void _wake() {
|
||||
_routesChanged.complete();
|
||||
_routesChanged = Completer<void>();
|
||||
}
|
||||
|
||||
/// Publishes a route change the way the SDK watch does.
|
||||
void announceRoutes(List<String> next) {
|
||||
routes = next;
|
||||
generation++;
|
||||
_wake();
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> request(Map<String, dynamic> input) async {
|
||||
final op = input['op'] as String;
|
||||
if (op == 'wait_routes') {
|
||||
// Long poll: not logged so lifecycle event assertions stay exact.
|
||||
if (state == 'Running' && input['after_generation'] == generation) {
|
||||
await _routesChanged.future;
|
||||
}
|
||||
final running = state == 'Running';
|
||||
return {
|
||||
'ok': true,
|
||||
'data': {
|
||||
'running': running,
|
||||
'changed': !running || input['after_generation'] != generation,
|
||||
'route_generation': running ? generation : null,
|
||||
'mesh_cidrs': running ? cidrs : [],
|
||||
},
|
||||
};
|
||||
}
|
||||
events.add('mesh.$op');
|
||||
if (op == 'start_bridged') {
|
||||
if (mode != 'application') {
|
||||
return {'ok': false, 'error': 'bridged routing requires application'};
|
||||
}
|
||||
if (state != 'Stopped') return {'ok': false, 'error': 'already started'};
|
||||
}
|
||||
final data = switch (op) {
|
||||
'validate' => {'runtime_mode': mode},
|
||||
'start' => (() {
|
||||
'start_bridged' => (() {
|
||||
state = 'Running';
|
||||
return <String, dynamic>{};
|
||||
bridge = true;
|
||||
return <String, dynamic>{
|
||||
'listen': '127.0.0.1:50001',
|
||||
'route_generation': generation,
|
||||
};
|
||||
})(),
|
||||
'stop' => (() {
|
||||
state = 'Stopped';
|
||||
_wake();
|
||||
return <String, dynamic>{};
|
||||
})(),
|
||||
'socks_stop' => (() {
|
||||
bridge = false;
|
||||
return <String, dynamic>{};
|
||||
})(),
|
||||
'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,
|
||||
},
|
||||
},
|
||||
_ => <String, dynamic>{},
|
||||
@@ -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<void>.delayed(const Duration(milliseconds: 10));
|
||||
}
|
||||
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.23.0/24');
|
||||
expect(f.session.state, 'Running');
|
||||
f.events.clear();
|
||||
await f.session.stop();
|
||||
expect(f.events, ['proxy.stop', 'mesh.socks_stop', 'mesh.stop']);
|
||||
await f.session.close();
|
||||
});
|
||||
test('failed engine startup rolls back and permits retry', () async {
|
||||
final f = Fixture();
|
||||
f.proxy.failStart = true;
|
||||
@@ -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<StateError>().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');
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user