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
@@ -17,6 +17,7 @@ class MeshProxySession {
String? _bridge;
List<String> _prefixes = [];
bool _ownsNetwork = false, _closed = false;
int _epoch = 0;
Future<void> _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<void> _watchRoutes(int epoch, int? generation) async {
bool current() => epoch == _epoch && _ownsNetwork && !_closed;
while (current()) {
final Map<String, dynamic> 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<Map<String, dynamic>> 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 : <String, dynamic>{});
@@ -92,7 +110,7 @@ class MeshProxySession {
}
});
Future<void> _sync(Map<String, dynamic> snapshot) async {
final prefixes = usesMesh ? effectiveMeshPrefixes(snapshot) : <String>[];
final prefixes = usesMesh ? meshPrefixes(snapshot) : <String>[];
_protected.addAll(prefixes);
if (prefixes.join(',') == _prefixes.join(',') &&
(state == 'Running' || state == 'Partial')) {
@@ -131,6 +149,7 @@ class MeshProxySession {
Future<void> stop() => _queue(_stop);
Future<void> _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<String> effectiveMeshPrefixes(Map<String, dynamic> snapshot) {
/// Routable mesh prefixes as projected by the SDK: the overlay network plus
/// accepted advertised subnets, canonical and sorted.
List<String> meshPrefixes(Map<String, dynamic> snapshot) {
final platform = snapshot['platform_network'] as Map?;
final values = <dynamic>[
snapshot['ipv4'],
if (platform?['subnet_routes_scope'] == 'accepted_projection')
...?platform?['subnet_routes'] as List?,
];
final result = <String>{};
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<int>();
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<String>().toList();
}
@@ -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<String, dynamic> 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<String, dynamic>.from(
v['optimization'] as Map? ?? {'mode': 'adaptive'},
);
final flags = <String, dynamic>{
...?v['flags'] as Map<String, dynamic>?,
'no_tun': !system,
'use_smoltcp': !system,
'enable_encryption': true,
'enable_ipv6': v['enable_ipv6'] ?? true,
'latency_first': ['adaptive', 'latency'].contains(optimization['mode']),
};
final lines = <String>[
'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<String> toToml(MeshPortClient client) => client.buildConfig(values);
}