Fix Android VPN startup and verify automatic subnet routing
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<application
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
project(meshport_android)
|
||||
add_library(meshport_ffi SHARED IMPORTED)
|
||||
set_target_properties(meshport_ffi PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmeshport_ffi.so")
|
||||
set_target_properties(meshport_ffi PROPERTIES
|
||||
IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmeshport_ffi.so"
|
||||
IMPORTED_NO_SONAME TRUE)
|
||||
add_library(meshport_android SHARED bridge.cpp)
|
||||
target_link_libraries(meshport_android meshport_ffi)
|
||||
target_link_options(meshport_android PRIVATE "-Wl,-z,max-page-size=16384")
|
||||
|
||||
+26
-1
@@ -8,6 +8,7 @@ import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
@@ -21,6 +22,7 @@ class MainActivity : FlutterActivity() {
|
||||
if (call.method == "prepare_android_vpn") {
|
||||
if (permissionResult != null) { result.error("VPN_BUSY", "VPN authorization pending", null); return@setMethodCallHandler }
|
||||
val intent = VpnService.prepare(this)
|
||||
Log.i("MeshPortVPN", "VPN permission request: ${if (intent == null) "already granted" else "dialog required"}")
|
||||
if (intent == null) result.success(null)
|
||||
else { permissionResult = result; startActivityForResult(intent, 1001) }
|
||||
return@setMethodCallHandler
|
||||
@@ -29,6 +31,27 @@ class MainActivity : FlutterActivity() {
|
||||
try {
|
||||
val profiles = ProfileStore(this)
|
||||
when (call.method) {
|
||||
"debug_os_echo" -> {
|
||||
check(BuildConfig.DEBUG)
|
||||
val host = "10.253.79.1"
|
||||
val payload = "Android system socket".toByteArray()
|
||||
java.net.Socket().use { socket ->
|
||||
socket.soTimeout = 5000
|
||||
socket.connect(java.net.InetSocketAddress(host, 17007), 5000)
|
||||
socket.getOutputStream().write(payload)
|
||||
val reply = ByteArray(payload.size)
|
||||
java.io.DataInputStream(socket.getInputStream()).readFully(reply)
|
||||
check(reply.contentEquals(payload))
|
||||
}
|
||||
java.net.DatagramSocket().use { socket ->
|
||||
socket.soTimeout = 5000
|
||||
socket.send(java.net.DatagramPacket(payload, payload.size, java.net.InetAddress.getByName(host), 17007))
|
||||
val reply = java.net.DatagramPacket(ByteArray(256), 256)
|
||||
socket.receive(reply)
|
||||
check(reply.data.copyOf(reply.length).contentEquals(payload))
|
||||
}
|
||||
main.post { result.success(true) }
|
||||
}
|
||||
"load_profile" -> { val value = profiles.load(); main.post { result.success(value) } }
|
||||
"save_profile" -> { profiles.save(call.arguments as String); main.post { result.success(null) } }
|
||||
"delete_profile" -> { profiles.delete(); main.post { result.success(null) } }
|
||||
@@ -44,6 +67,7 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
"android_vpn_request" -> {
|
||||
val request = JSONObject(call.arguments as String)
|
||||
if (request.optString("op") != "status") Log.i("MeshPortVPN", "Control operation: ${request.optString("op")}")
|
||||
require(request.toString().toByteArray(Charsets.UTF_8).size <= 131072)
|
||||
if (request.getString("op") == "start" && MeshVpnService.current == null) {
|
||||
check(VpnService.prepare(this) == null) { "Android VPN authorization required" }
|
||||
@@ -64,7 +88,7 @@ class MainActivity : FlutterActivity() {
|
||||
try {
|
||||
val reply = service.request(request).toString()
|
||||
main.post { result.success(reply) }
|
||||
} catch (error: Exception) { main.post { result.error("VPN_REQUEST", error.message, null) } }
|
||||
} catch (error: Throwable) { main.post { result.error("VPN_REQUEST", error.message, null) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,6 +102,7 @@ class MainActivity : FlutterActivity() {
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode == 1001) {
|
||||
Log.i("MeshPortVPN", "VPN permission result: $resultCode")
|
||||
val pending = permissionResult; permissionResult = null
|
||||
if (resultCode == Activity.RESULT_OK) pending?.success(null)
|
||||
else pending?.error("VPN_DENIED", "Android VPN authorization cancelled", null)
|
||||
|
||||
+29
-2
@@ -6,6 +6,9 @@ import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.IpPrefix
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.system.OsConstants
|
||||
import android.util.Log
|
||||
@@ -53,8 +56,8 @@ class MeshVpnService : VpnService() {
|
||||
check(!running) { "VPN already started" }
|
||||
failure = null
|
||||
Log.i("MeshPortVPN", "Creating native VPN context")
|
||||
handle = NativeBridge.newContext()
|
||||
try {
|
||||
handle = NativeBridge.newContext()
|
||||
val config = request.getString("toml")
|
||||
val validation = native(JSONObject().put("op", "validate").put("toml", config).put("include_profile", true)).getJSONObject("data")
|
||||
check(validation.getString("runtime_mode") == "system_vpn")
|
||||
@@ -65,7 +68,7 @@ class MeshVpnService : VpnService() {
|
||||
running = true
|
||||
rebuild(emptyList())
|
||||
result
|
||||
} catch (error: Exception) { shutdown(); stopSelf(); throw error }
|
||||
} catch (error: Throwable) { shutdown(); stopSelf(); throw error }
|
||||
}
|
||||
"stop" -> { shutdown(); stopSelf(); JSONObject().put("ok", true).put("data", JSONObject()) }
|
||||
"status" -> {
|
||||
@@ -109,6 +112,30 @@ class MeshVpnService : VpnService() {
|
||||
Thread.sleep(100)
|
||||
}
|
||||
check(ready) { "Native TUN attachment timed out" }
|
||||
// establish() returns before ConnectivityService publishes the
|
||||
// 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 cidr = it.split('/')
|
||||
IpPrefix(InetAddress.getByName(cidr[0]), cidr[1].toInt())
|
||||
}.toSet()
|
||||
var registered = false
|
||||
for (attempt in 0 until 50) {
|
||||
registered = connectivity.allNetworks.any { candidate ->
|
||||
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.routes.filter { it.destination.address is java.net.Inet4Address && it.type == android.net.RouteInfo.RTN_UNICAST }
|
||||
.map { it.destination }.toSet() == expected
|
||||
}
|
||||
if (registered) break
|
||||
Thread.sleep(100)
|
||||
}
|
||||
check(registered) { "Android VPN network registration timed out" }
|
||||
// Let newly published network state reach socket clients as well.
|
||||
Thread.sleep(300)
|
||||
Log.i("MeshPortVPN", "TUN ready")
|
||||
tun = next
|
||||
installed = routes
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -11,7 +12,7 @@ const target = '10.253.79.1:17007';
|
||||
String config(String mode) =>
|
||||
'''
|
||||
hostname = "Android-validation"
|
||||
ipv4 = "10.253.83.11/24"
|
||||
ipv4 = "10.253.83.${mode == 'application' ? '11' : '12'}/24"
|
||||
listeners = []
|
||||
stun_servers = []
|
||||
stun_servers_v6 = []
|
||||
@@ -30,8 +31,10 @@ Future<void> waitForRoutes(
|
||||
bool installed = false,
|
||||
}) async {
|
||||
final deadline = DateTime.now().add(const Duration(seconds: 40));
|
||||
Map<String, dynamic>? lastState;
|
||||
while (DateTime.now().isBefore(deadline)) {
|
||||
final state = await client.status();
|
||||
lastState = state;
|
||||
final platform = state['platform_network'] as Map? ?? {};
|
||||
final routes =
|
||||
platform[installed ? 'installed_subnet_routes' : 'subnet_routes']
|
||||
@@ -40,6 +43,7 @@ Future<void> waitForRoutes(
|
||||
if (withdrawn ? routes.isEmpty : routes.contains('10.253.79.0/24')) return;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
}
|
||||
debugPrint('ANDROID_ROUTE_TIMEOUT_STATE ${jsonEncode(lastState)}');
|
||||
throw StateError('Automatic subnet route transition timed out');
|
||||
}
|
||||
|
||||
@@ -91,13 +95,24 @@ void main() {
|
||||
try {
|
||||
await vpn.start(config('system_vpn'));
|
||||
await waitForRoutes(vpn, installed: true);
|
||||
expect(await channel.invokeMethod<bool>('debug_os_echo'), true);
|
||||
debugPrint('ANDROID_JAVA_OS_TCP_UDP_PASS');
|
||||
// Plain OS sockets prove that traffic from other applications can use
|
||||
// the VPN. No SDK stream is used for these transfers.
|
||||
final socket = await Socket.connect(
|
||||
'10.253.79.1',
|
||||
17007,
|
||||
timeout: const Duration(seconds: 10),
|
||||
);
|
||||
late Socket socket;
|
||||
debugPrint('ANDROID_SYSTEM_SOCKET_START');
|
||||
try {
|
||||
socket = await Socket.connect(
|
||||
'10.253.79.1',
|
||||
17007,
|
||||
timeout: const Duration(seconds: 30),
|
||||
);
|
||||
} catch (_) {
|
||||
debugPrint(
|
||||
'ANDROID_OS_TCP_FAILURE_STATE ${jsonEncode(await vpn.status())}',
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
try {
|
||||
socket.add(utf8.encode('OS TCP Android'));
|
||||
await socket.flush();
|
||||
@@ -111,16 +126,27 @@ void main() {
|
||||
socket.destroy();
|
||||
}
|
||||
final udp = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
|
||||
final received = Completer<Datagram>();
|
||||
final subscription = udp.listen((event) {
|
||||
if (event == RawSocketEvent.read) {
|
||||
final packet = udp.receive();
|
||||
if (packet != null && !received.isCompleted) {
|
||||
received.complete(packet);
|
||||
}
|
||||
}
|
||||
}, onError: received.completeError);
|
||||
try {
|
||||
final reply = udp.firstWhere((event) => event == RawSocketEvent.read);
|
||||
udp.send(
|
||||
utf8.encode('OS UDP Android'),
|
||||
InternetAddress('10.253.79.1'),
|
||||
17007,
|
||||
);
|
||||
await reply.timeout(const Duration(seconds: 10));
|
||||
expect(utf8.decode(udp.receive()!.data), 'OS UDP Android');
|
||||
final reply = await received.future.timeout(
|
||||
const Duration(seconds: 10),
|
||||
);
|
||||
expect(utf8.decode(reply.data), 'OS UDP Android');
|
||||
} finally {
|
||||
await subscription.cancel();
|
||||
udp.close();
|
||||
}
|
||||
debugPrint('ANDROID_SYSTEM_VPN_TCP_UDP_PASS');
|
||||
|
||||
Reference in New Issue
Block a user