Files
MeshPort/bindings/flutter/meshport_flutter/lib/src/client.dart
T
shenleiandClaude Opus 5.5 dc1bfc99d2 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>
2026-10-15 18:17:42 +09:00

281 lines
9.1 KiB
Dart

import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
String _defaultLibrary() {
if (Platform.isMacOS) {
final bundled =
'${File(Platform.resolvedExecutable).parent.parent.path}/Frameworks/libmeshport_ffi.dylib';
if (File(bundled).existsSync()) return bundled;
}
return Platform.isWindows
? 'meshport_ffi.dll'
: Platform.isMacOS
? 'libmeshport_ffi.dylib'
: 'libmeshport_ffi.so';
}
DynamicLibrary _open(String path) =>
Platform.isIOS ? DynamicLibrary.process() : DynamicLibrary.open(path);
Map<String, dynamic> _call(String path, int handle, String request) {
final library = _open(path);
final call = library
.lookupFunction<
Pointer<Utf8> Function(Uint64, Pointer<Utf8>),
Pointer<Utf8> Function(int, Pointer<Utf8>)
>('meshport_call');
final free = library
.lookupFunction<
Void Function(Pointer<Utf8>),
void Function(Pointer<Utf8>)
>('meshport_string_free');
final input = request.toNativeUtf8();
try {
final result = call(handle, input);
if (result == nullptr) throw StateError('Native response is null');
try {
return jsonDecode(result.toDartString()) as Map<String, dynamic>;
} finally {
free(result);
}
} finally {
calloc.free(input);
}
}
/// Lowest native capability revision this binding drives (`abi_info`).
const int minimumCapabilityRevision = 2;
class MeshPortClient {
final String libraryPath;
final int _handle;
final Future<Map<String, dynamic>> Function(Map<String, dynamic>)? _transport;
final Future<void> Function()? _closeTransport;
bool _closed = false;
MeshPortClient._(this.libraryPath, this._handle)
: _transport = null,
_closeTransport = null;
/// A platform-owned control transport. Responses use the same ABI JSON envelope.
MeshPortClient.fromTransport({
required Future<Map<String, dynamic>> Function(Map<String, dynamic>)
request,
required Future<void> Function() close,
}) : libraryPath = '',
_handle = 0,
_transport = request,
_closeTransport = close;
static Future<MeshPortClient> open({String? libraryPath}) async {
final path = libraryPath ?? _defaultLibrary();
final handle = await Isolate.run(() {
final lib = _open(path);
final version = lib.lookupFunction<Uint32 Function(), int Function()>(
'meshport_abi_version',
)();
if (version != 1) throw StateError('Unsupported MeshPort ABI: $version');
return lib.lookupFunction<Uint64 Function(), int Function()>(
'meshport_context_new',
)();
});
if (handle == 0) throw StateError('Could not create MeshPort context');
final client = MeshPortClient._(path, handle);
int? revision;
try {
revision = (await client.abiInfo())['revision'] as int?;
} catch (_) {}
if (revision == null || revision < minimumCapabilityRevision) {
await client.close();
throw StateError(
'MeshPort native library at $path is too old '
'(capability revision ${revision ?? 'unknown'}, '
'need $minimumCapabilityRevision); rebuild meshport-ffi',
);
}
return client;
}
/// `{abi, revision, operations}` of the loaded native library.
Future<Map<String, dynamic>> abiInfo() => request({'op': 'abi_info'});
Future<Map<String, dynamic>> request(Map<String, dynamic> request) async {
if (_closed) throw StateError('MeshPort context is closed');
final path = libraryPath, handle = _handle, text = jsonEncode(request);
final response = _transport != null
? await _transport(request)
: await Isolate.run(() => _call(path, handle, text));
if (response['ok'] != true)
throw StateError(
response['error'] as String? ?? 'Native operation failed',
);
return response['data'] as Map<String, dynamic>;
}
/// Returns the overlay projection. [checkLocalOverlap] also rejects an
/// overlay that collides with an existing interface on this device.
Future<Map<String, dynamic>> validate(
String toml, {
bool checkLocalOverlap = false,
}) => request({
'op': 'validate',
'toml': toml,
if (checkLocalOverlap) 'check_local_overlap': true,
});
/// Builds the SDK-accepted TOML from a structured profile draft. Mode,
/// transport and encryption invariants are applied by the SDK.
Future<String> buildConfig(Map<String, dynamic> profile) async =>
(await request({'op': 'build_config', 'profile': profile}))['toml']
as String;
/// Removes options earlier releases saved; returns [toml] unchanged when
/// nothing needed migrating.
Future<String> migrateConfig(String toml) async =>
(await request({'op': 'migrate_config', 'toml': toml}))['toml'] as String;
Future<void> start(String toml, {bool checkLocalOverlap = false}) async {
await request({
'op': 'start',
'toml': toml,
if (checkLocalOverlap) 'check_local_overlap': true,
});
}
/// Starts an application-mode network and its local TCP/UDP bridge as one
/// operation; a failure leaves neither running. Returns `listen`, `overlay`,
/// `mesh_cidrs` and `route_generation`.
Future<Map<String, dynamic>> startBridged(
String toml, {
int port = 0,
int maxSessions = 128,
bool checkLocalOverlap = false,
bool requireStaticOverlay = false,
}) => request({
'op': 'start_bridged',
'toml': toml,
'port': port,
'max_sessions': maxSessions,
if (checkLocalOverlap) 'check_local_overlap': true,
if (requireStaticOverlay) 'require_static_overlay': true,
});
Future<void> stop() async {
await request({'op': 'stop'});
}
/// Long-polls mesh routes: returns as soon as `route_generation` differs
/// from [afterGeneration] or the network stops, otherwise after [timeout]
/// with `changed: false`. Runs outside the context's serial lock, so other
/// requests proceed meanwhile. Returns `running`, `changed`,
/// `route_generation`, `mesh_cidrs` and `subnet_routes`.
Future<Map<String, dynamic>> waitRoutes({
int? afterGeneration,
Duration timeout = const Duration(seconds: 25),
}) => request({
'op': 'wait_routes',
if (afterGeneration != null) 'after_generation': afterGeneration,
'timeout_ms': timeout.inMilliseconds,
});
/// Local IPv4 TCP/UDP bridge for a host proxy engine. Application mode only.
/// Data travels on native sockets, outside the serial JSON I/O interface.
Future<Map<String, dynamic>> startSocksBridge({
int port = 0,
int maxSessions = 128,
}) =>
request({'op': 'socks_start', 'port': port, 'max_sessions': maxSessions});
Future<void> stopSocksBridge() async {
await request({'op': 'socks_stop'});
}
Future<Map<String, dynamic>> socksBridgeStatus() =>
request({'op': 'socks_status'});
/// Opt in to bounded process-wide punch tracing. Does not replace host logging.
Future<Map<String, dynamic>> enableDiagnostics() =>
request({'op': 'diagnostics_enable'});
Future<Map<String, dynamic>> status() => request({'op': 'status'});
Future<Map<String, dynamic>> probe(
String target, {
bool udp = false,
bool echo = false,
int timeoutMs = 5000,
}) => request({
'op': 'probe',
'target': target,
'protocol': udp ? 'UDP' : 'TCP',
'echo': echo,
'timeout_ms': timeoutMs,
});
Future<int> connectTcp(String target) async =>
(await request({'op': 'tcp_connect', 'target': target}))['resource']
as int;
Future<void> writeTcp(int stream, Uint8List data) async {
await request({
'op': 'tcp_write',
'resource': stream,
'bytes': data.toList(),
});
}
Future<Uint8List> readTcp(int stream, {int maxBytes = 16384}) async =>
Uint8List.fromList(
List<int>.from(
(await request({
'op': 'tcp_read',
'resource': stream,
'max_bytes': maxBytes,
}))['bytes'],
),
);
Future<int> bindUdp({int port = 0}) async =>
(await request({'op': 'udp_bind', 'port': port}))['resource'] as int;
Future<void> sendUdp(int socket, String target, Uint8List data) async {
await request({
'op': 'udp_send',
'resource': socket,
'target': target,
'bytes': data.toList(),
});
}
Future<Map<String, dynamic>> sampleUdpQuality(
int socket,
String target,
int sequence, {
int timeoutMs = 1000,
}) => request({
'op': 'quality_sample',
'resource': socket,
'target': target,
'sequence': sequence,
'timeout_ms': timeoutMs,
});
Future<Map<String, dynamic>> receiveUdp(int socket) =>
request({'op': 'udp_receive', 'resource': socket});
Future<void> closeResource(int resource) async {
await request({'op': 'resource_close', 'resource': resource});
}
Future<void> close() async {
if (_closed) return;
_closed = true;
if (_closeTransport != null) {
await _closeTransport();
return;
}
final path = libraryPath, handle = _handle;
await Isolate.run(
() =>
_open(path).lookupFunction<Void Function(Uint64), void Function(int)>(
'meshport_context_free',
)(handle),
);
}
}