Initial MeshPort SDK and cross-platform client

This commit is contained in:
shenlei
2026-10-10 15:16:32 +09:00
commit e73e599165
664 changed files with 209894 additions and 0 deletions
@@ -0,0 +1,8 @@
/// MeshPort native SDK. All native calls execute outside the UI isolate.
library;
export 'src/client.dart';
export 'src/quality.dart';
export 'src/system_vpn.dart';
@@ -0,0 +1,192 @@
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);
}
}
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');
return MeshPortClient._(path, handle);
}
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>;
}
Future<void> validate(String toml) async {
await request({'op': 'validate', 'toml': toml});
}
Future<void> start(String toml) async {
await request({'op': 'start', 'toml': toml});
}
Future<void> stop() async {
await request({'op': 'stop'});
}
/// 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),
);
}
}
@@ -0,0 +1,28 @@
/// Summaries of real echo samples. Loss means no valid reply before the deadline.
class QualitySummary {
QualitySummary(Iterable<Map<String, dynamic>> samples) {
final rows = samples.toList();
sent = rows.length;
final values = rows
.where((r) => r['success'] == true && r['elapsed_ms'] is num)
.map((r) => (r['elapsed_ms'] as num).toDouble())
.where((v) => v.isFinite && v >= 0)
.toList();
received = values.length;
if (values.isEmpty) return;
var differences = 0.0;
for (var i = 1; i < values.length; i++) {
differences += (values[i] - values[i - 1]).abs();
}
jitterMs = values.length < 2 ? null : differences / (values.length - 1);
values.sort();
medianMs = values.length.isOdd
? values[values.length ~/ 2]
: (values[values.length ~/ 2 - 1] + values[values.length ~/ 2]) / 2;
p95Ms = values[(values.length * .95).ceil() - 1];
}
late int sent, received;
double? medianMs, p95Ms, jitterMs;
double? get lossPercent =>
sent == 0 ? null : 100.0 * (sent - received) / sent;
}
@@ -0,0 +1,118 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'client.dart';
/// Android's host supplies VpnService authorization and a serialized control
/// channel. Keeping Flutter APIs out of this library permits non-Flutter hosts.
Future<MeshPortClient> openAndroidSystemVpn({
required Future<void> Function() prepare,
required Future<Map<String, dynamic>> Function(Map<String, dynamic>) request,
}) async {
if (!Platform.isAndroid)
throw UnsupportedError('Android VPN requires Android');
await prepare();
return MeshPortClient.fromTransport(
request: request,
close: () async {
await request({'op': 'stop'});
},
);
}
/// The host app supplies administrator authorization, without elevating its UI.
Future<MeshPortClient> openMacSystemVpn({
required Future<void> Function(String socketPath, int uid) launch,
}) async {
if (!Platform.isMacOS)
throw UnsupportedError('System VPN currently supports macOS only');
final uid = DynamicLibrary.process()
.lookupFunction<Uint32 Function(), int Function()>('getuid')();
final directory = await Directory('/tmp').createTemp('meshport-vpn-');
ServerSocket? listener;
Socket? socket;
StreamIterator<String>? replies;
StreamSubscription<Socket>? subscription;
Future<void> cleanup() async {
socket?.destroy();
await replies?.cancel();
await subscription?.cancel();
await listener?.close();
if (await directory.exists()) await directory.delete(recursive: true);
}
try {
final permissions = await Process.run('/bin/chmod', [
'700',
directory.path,
]);
if (permissions.exitCode != 0)
throw StateError('Cannot protect VPN control directory');
final address = '${directory.path}/control.sock';
listener = await ServerSocket.bind(
InternetAddress(address, type: InternetAddressType.unix),
0,
);
final accepted = Completer<Socket>();
subscription = listener.listen(
(connection) {
if (accepted.isCompleted) {
connection.destroy();
} else {
accepted.complete(connection);
}
},
onError: (Object e) {
if (!accepted.isCompleted) accepted.completeError(e);
},
);
await launch(address, uid);
socket = await accepted.future.timeout(const Duration(seconds: 10));
replies = StreamIterator(
socket!
.cast<List<int>>()
.transform(utf8.decoder)
.transform(const LineSplitter()),
);
Future<void> queue = Future.value();
Future<Map<String, dynamic>> request(Map<String, dynamic> value) {
final job = queue.then((_) async {
final encoded = jsonEncode(value);
if (utf8.encode(encoded).length > 131072)
throw ArgumentError('Request exceeds control limit');
socket!.write('$encoded\n');
await socket!.flush();
final received = await replies!.moveNext().timeout(
const Duration(seconds: 30),
);
if (!received)
throw StateError(
'VPN helper disconnected; reconnect to authorize again',
);
return jsonDecode(replies!.current) as Map<String, dynamic>;
});
queue = job.then<void>(
(_) {},
onError: (Object e, StackTrace s) {
socket?.destroy();
},
);
return job;
}
return MeshPortClient.fromTransport(
request: request,
close: () async {
try {
await request({'op': 'stop'});
} finally {
await cleanup();
}
},
);
} catch (_) {
await cleanup();
rethrow;
}
}
@@ -0,0 +1,8 @@
name: meshport_flutter
description: Application-only EasyTier networking SDK bindings for MeshPort.
version: 0.1.0
publish_to: none
environment:
sdk: ^3.11.0
dependencies:
ffi: ^2.1.4