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:
shenlei
2026-10-15 18:17:42 +09:00
co-authored by Claude Opus 5.5
parent 29d236f3fe
commit dc1bfc99d2
34 changed files with 1724 additions and 715 deletions
@@ -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) } })
}
}
}
@@ -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()