Snapshot uncommitted work: proxy UI, sing-box integration, socks bridge
- Lab app: proxy panel, node editor, configuration and detail pages, responsive layout, and related tests - Add meshport-socks crate and sing-box bridge scripts/docs - Add singbox_flutter binding and meshport_client_core package - FFI, VPN helper (unified mac path), and Android/macOS runner updates - Docs for architecture, client runtime, UI design, and validation - UI design output artifacts under outputs/ui Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Haiku 5.5
parent
10b10e5bdf
commit
2f185f914d
@@ -4,6 +4,8 @@ add_library(meshport_ffi SHARED IMPORTED)
|
||||
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_proxy SHARED IMPORTED)
|
||||
set_target_properties(meshport_proxy PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libmeshport_proxy.so" IMPORTED_NO_SONAME TRUE)
|
||||
add_library(meshport_android SHARED bridge.cpp)
|
||||
target_link_libraries(meshport_android meshport_ffi)
|
||||
target_link_libraries(meshport_android meshport_ffi meshport_proxy)
|
||||
target_link_options(meshport_android PRIVATE "-Wl,-z,max-page-size=16384")
|
||||
|
||||
@@ -2,7 +2,15 @@
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <sys/ioctl.h>
|
||||
#include <linux/if_tun.h>
|
||||
#include <net/if.h>
|
||||
extern "C" {
|
||||
uint64_t meshport_proxy_context_new();
|
||||
void meshport_proxy_context_free(uint64_t);
|
||||
char* meshport_proxy_call(uint64_t, const char*);
|
||||
void meshport_proxy_string_free(char*);
|
||||
void meshport_proxy_set_socket_protector(uintptr_t);
|
||||
uint64_t meshport_context_new();
|
||||
void meshport_context_free(uint64_t);
|
||||
char* meshport_call(uint64_t, const char*);
|
||||
@@ -21,6 +29,7 @@ static bool protectSocket(int fd) {
|
||||
if (attached) vm->DetachCurrentThread();
|
||||
return ok;
|
||||
}
|
||||
static int proxyProtectSocket(int fd) { return protectSocket(fd) ? 1 : 0; }
|
||||
extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* value, void*) {
|
||||
vm = value;
|
||||
JNIEnv* env = nullptr;
|
||||
@@ -31,6 +40,7 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* value, void*) {
|
||||
protectMethod = env->GetStaticMethodID(bridge, "protectFd", "(I)Z");
|
||||
if (!protectMethod) return JNI_ERR;
|
||||
meshport_set_android_socket_protector(protectSocket);
|
||||
meshport_proxy_set_socket_protector(reinterpret_cast<uintptr_t>(proxyProtectSocket));
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_newContext(JNIEnv*, jobject) {
|
||||
@@ -39,7 +49,7 @@ extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_n
|
||||
extern "C" JNIEXPORT void JNICALL Java_com_example_meshport_1lab_NativeBridge_freeContext(JNIEnv*, jobject, jlong handle) {
|
||||
meshport_context_free(static_cast<uint64_t>(handle));
|
||||
}
|
||||
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_call(JNIEnv* env, jobject, jlong handle, jstring text) {
|
||||
static jstring controlCall(JNIEnv* env, jlong handle, jstring text, bool proxy) {
|
||||
auto stringClass = env->FindClass("java/lang/String");
|
||||
auto charset = env->NewStringUTF("UTF-8");
|
||||
auto getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
|
||||
@@ -49,11 +59,25 @@ extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge
|
||||
if (size > 131072) return env->NewStringUTF("{\"ok\":false,\"error\":\"Request too large\"}");
|
||||
std::string input(size, '\0');
|
||||
env->GetByteArrayRegion(bytes, 0, size, reinterpret_cast<jbyte*>(input.data()));
|
||||
char* response = meshport_call(static_cast<uint64_t>(handle), input.c_str());
|
||||
char* response = (proxy ? meshport_proxy_call : meshport_call)(static_cast<uint64_t>(handle), input.c_str());
|
||||
if (!response) return nullptr;
|
||||
auto output = env->NewByteArray(static_cast<jsize>(strlen(response)));
|
||||
env->SetByteArrayRegion(output, 0, env->GetArrayLength(output), reinterpret_cast<jbyte*>(response));
|
||||
meshport_string_free(response);
|
||||
(proxy ? meshport_proxy_string_free : meshport_string_free)(response);
|
||||
auto constructor = env->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V");
|
||||
return static_cast<jstring>(env->NewObject(stringClass, constructor, output, charset));
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_call(JNIEnv* env, jobject, jlong handle, jstring text) { return controlCall(env,handle,text,false); }
|
||||
extern "C" JNIEXPORT jlong JNICALL Java_com_example_meshport_1lab_NativeBridge_newProxyContext(JNIEnv*, jobject) {
|
||||
return static_cast<jlong>(meshport_proxy_context_new());
|
||||
}
|
||||
extern "C" JNIEXPORT void JNICALL Java_com_example_meshport_1lab_NativeBridge_freeProxyContext(JNIEnv*, jobject, jlong handle) {
|
||||
meshport_proxy_context_free(static_cast<uint64_t>(handle));
|
||||
}
|
||||
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_proxyCall(JNIEnv* env, jobject, jlong handle, jstring text) { return controlCall(env,handle,text,true); }
|
||||
extern "C" JNIEXPORT jstring JNICALL Java_com_example_meshport_1lab_NativeBridge_tunName(JNIEnv* env, jobject, jint fd) {
|
||||
struct ifreq request{};
|
||||
if (ioctl(fd,TUNGETIFF,&request)<0) return nullptr;
|
||||
return env->NewStringUTF(request.ifr_name);
|
||||
}
|
||||
|
||||
+82
@@ -4,6 +4,19 @@ import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import android.app.Activity
|
||||
import android.graphics.BitmapFactory
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
import com.google.zxing.BarcodeFormat
|
||||
import com.google.zxing.BinaryBitmap
|
||||
import com.google.zxing.DecodeHintType
|
||||
import com.google.zxing.MultiFormatReader
|
||||
import com.google.zxing.RGBLuminanceSource
|
||||
import com.google.zxing.common.HybridBinarizer
|
||||
import com.google.zxing.multi.GenericMultipleBarcodeReader
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.CodingErrorAction
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.Handler
|
||||
@@ -16,9 +29,34 @@ class MainActivity : FlutterActivity() {
|
||||
private val background = Executors.newSingleThreadExecutor()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var permissionResult: MethodChannel.Result? = null
|
||||
private var importResult: MethodChannel.Result? = null
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "meshport/system_vpn").setMethodCallHandler { call, result ->
|
||||
if (call.method in listOf("import_file", "import_qr_image", "scan_qr")) {
|
||||
if (importResult != null) { result.error("IMPORT_BUSY", "Import already open", null); return@setMethodCallHandler }
|
||||
importResult = result
|
||||
try {
|
||||
if (call.method == "scan_qr") {
|
||||
val options = ScanOptions().setDesiredBarcodeFormats(ScanOptions.QR_CODE).setBeepEnabled(false).setPrompt("扫描配置二维码").setOrientationLocked(false)
|
||||
startActivityForResult(ScanContract().createIntent(this, options), 2003)
|
||||
} else {
|
||||
val image = call.method == "import_qr_image"
|
||||
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType(if (image) "image/*" else "*/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
startActivityForResult(intent, if (image) 2002 else 2001)
|
||||
}
|
||||
} catch (_: Exception) { importResult=null;result.error("IMPORT_UNAVAILABLE", "No file picker or camera available", null) }
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
if (call.method == "startup_status" || call.method == "set_startup") {
|
||||
val prefs = getSharedPreferences("startup",MODE_PRIVATE)
|
||||
if (call.method == "set_startup") {
|
||||
val args = call.arguments as? Map<*, *>
|
||||
if (args?.containsKey("login") == true) {result.error("UNSUPPORTED", "Android does not use macOS login items", null); return@setMethodCallHandler}
|
||||
(args?.get("auto_connect") as? Boolean)?.let { prefs.edit().putBoolean("auto_connect",it).apply() }
|
||||
}
|
||||
result.success(mapOf("auto_connect" to prefs.getBoolean("auto_connect",false),"login_status" to "unsupported"));return@setMethodCallHandler
|
||||
}
|
||||
if (call.method == "prepare_android_vpn") {
|
||||
if (permissionResult != null) { result.error("VPN_BUSY", "VPN authorization pending", null); return@setMethodCallHandler }
|
||||
val intent = VpnService.prepare(this)
|
||||
@@ -52,6 +90,9 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
main.post { result.success(true) }
|
||||
}
|
||||
"load_proxy_profile" -> { val value = ProfileStore(this,"proxy").load(); main.post { result.success(value) } }
|
||||
"save_proxy_profile" -> { ProfileStore(this,"proxy").save(call.arguments as String); main.post { result.success(null) } }
|
||||
"delete_proxy_profile" -> { ProfileStore(this,"proxy").delete(); main.post { result.success(null) } }
|
||||
"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) } }
|
||||
@@ -101,6 +142,46 @@ class MainActivity : FlutterActivity() {
|
||||
@Deprecated("Legacy VPN permission result")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode in 2001..2003) {
|
||||
val pending = importResult; importResult=null
|
||||
if (pending == null) return
|
||||
if (resultCode != Activity.RESULT_OK) { pending.success(null);return }
|
||||
if (requestCode == 2003) {
|
||||
val contents = ScanContract().parseResult(resultCode,data).contents
|
||||
if (contents != null && contents.toByteArray(Charsets.UTF_8).size > 1024*1024) pending.error("IMPORT_LIMIT","QR payload too large",null) else pending.success(contents)
|
||||
return
|
||||
}
|
||||
val uri=data?.data
|
||||
if(uri==null) {pending.error("IMPORT_FAILED","No file selected",null);return}
|
||||
background.execute {
|
||||
try {
|
||||
val max = if(requestCode==2002) 20*1024*1024 else 1024*1024
|
||||
val bytes = contentResolver.openInputStream(uri)?.use { input ->
|
||||
val output=ByteArrayOutputStream();val buffer=ByteArray(8192)
|
||||
while(true) {val n=input.read(buffer);if(n<0) break;require(output.size()+n <= max);output.write(buffer,0,n)}
|
||||
output.toByteArray()
|
||||
} ?: error("Unreadable file")
|
||||
val text = if(requestCode==2001) {
|
||||
Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString()
|
||||
} else {
|
||||
val bounds=BitmapFactory.Options().apply {inJustDecodeBounds=true}
|
||||
BitmapFactory.decodeByteArray(bytes,0,bytes.size,bounds)
|
||||
require(bounds.outWidth>0 && bounds.outHeight>0 && bounds.outWidth.toLong()*bounds.outHeight<=20000000)
|
||||
val bitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.size) ?: error("Invalid image")
|
||||
try {
|
||||
val pixels=IntArray(bitmap.width*bitmap.height);bitmap.getPixels(pixels,0,bitmap.width,0,0,bitmap.width,bitmap.height)
|
||||
val binary=BinaryBitmap(HybridBinarizer(RGBLuminanceSource(bitmap.width,bitmap.height,pixels)))
|
||||
val hints=mapOf(DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE))
|
||||
val codes=GenericMultipleBarcodeReader(MultiFormatReader()).decodeMultiple(binary,hints).map {it.text}.toSet()
|
||||
require(codes.size==1);codes.single()
|
||||
} finally {bitmap.recycle()}
|
||||
}
|
||||
require(text.toByteArray(Charsets.UTF_8).size<=1024*1024)
|
||||
main.post {pending.success(text)}
|
||||
} catch (_:Exception) {main.post {pending.error("IMPORT_FAILED","Invalid, oversized file or no unique QR code",null)}}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (requestCode == 1001) {
|
||||
Log.i("MeshPortVPN", "VPN permission result: $resultCode")
|
||||
val pending = permissionResult; permissionResult = null
|
||||
@@ -111,6 +192,7 @@ class MainActivity : FlutterActivity() {
|
||||
override fun onDestroy() {
|
||||
permissionResult?.error("VPN_CANCELLED", "Activity closed during VPN authorization", null)
|
||||
permissionResult = null
|
||||
importResult?.error("IMPORT_CANCELLED", "Activity closed", null); importResult=null
|
||||
background.shutdown()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
+125
-2
@@ -22,6 +22,13 @@ class MeshVpnService : VpnService() {
|
||||
val worker = ScheduledThreadPoolExecutor(1)
|
||||
private var handle = 0L
|
||||
private var tun: ParcelFileDescriptor? = null
|
||||
private var proxyHandle = 0L
|
||||
private var unified = false
|
||||
private var meshEnabled = true
|
||||
private var proxyProfile = JSONObject()
|
||||
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>()
|
||||
private var running = false
|
||||
@@ -37,10 +44,14 @@ class MeshVpnService : VpnService() {
|
||||
.setSmallIcon(R.drawable.ic_stat_meshport).setContentIntent(open).setOngoing(true).build())
|
||||
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) rebuild(next)
|
||||
if (next != installed) { if (unified) restartProxy(next) else rebuild(next) }
|
||||
} catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
|
||||
}, 2, 2, TimeUnit.SECONDS)
|
||||
}
|
||||
@@ -59,6 +70,13 @@ class MeshVpnService : VpnService() {
|
||||
try {
|
||||
handle = NativeBridge.newContext()
|
||||
val config = request.getString("toml")
|
||||
unified = request.has("unified_profile")
|
||||
if (unified) {
|
||||
proxyProfile = JSONObject(request.getJSONObject("unified_profile").toString())
|
||||
meshEnabled = proxyProfile.optString("feature", "combined") != "proxy"
|
||||
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")
|
||||
check(validation.getString("runtime_mode") == "system_vpn")
|
||||
ipv4 = validation.getJSONObject("profile").getString("ipv4")
|
||||
@@ -73,7 +91,7 @@ class MeshVpnService : VpnService() {
|
||||
"stop" -> { shutdown(); stopSelf(); JSONObject().put("ok", true).put("data", JSONObject()) }
|
||||
"status" -> {
|
||||
if (!running) JSONObject().put("ok", true).put("data", JSONObject().put("state", if (failure == null) "Stopped" else "Failed").put("peer_count", 0))
|
||||
else native(request).also { reply ->
|
||||
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")
|
||||
}
|
||||
@@ -142,8 +160,113 @@ class MeshVpnService : VpnService() {
|
||||
previous?.close()
|
||||
} catch (error: Exception) { next.close(); throw error }
|
||||
}
|
||||
|
||||
private fun proxyCall(value: JSONObject): JSONObject {
|
||||
val result = JSONObject(NativeBridge.proxyCall(proxyHandle, value.toString()))
|
||||
check(result.optBoolean("ok")) { result.optString("error", "Proxy engine failed") }
|
||||
return result
|
||||
}
|
||||
private fun physicalNetwork(): android.net.Network {
|
||||
val manager = getSystemService(ConnectivityManager::class.java)
|
||||
return manager.allNetworks.firstOrNull {
|
||||
val caps = manager.getNetworkCapabilities(it)
|
||||
caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true &&
|
||||
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
|
||||
} ?: error("No physical network available")
|
||||
}
|
||||
private fun startUnified(config: String) {
|
||||
val manager = getSystemService(ConnectivityManager::class.java)
|
||||
physical = physicalNetwork(); setUnderlyingNetworks(arrayOf(physical!!))
|
||||
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)
|
||||
}
|
||||
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()) }
|
||||
builder.allowFamily(OsConstants.AF_INET6)
|
||||
}
|
||||
tun = builder.establish() ?: error("VPN authorization revoked")
|
||||
proxyHandle = NativeBridge.newProxyContext()
|
||||
check(proxyHandle != 0L)
|
||||
proxyCall(JSONObject().put("op","configure_cache").put("directory",cacheDir.absolutePath))
|
||||
restartProxy(routes)
|
||||
running = true
|
||||
networkCallback = object: ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: android.net.Network) { worker.execute { updatePhysical() } }
|
||||
override fun onLost(network: android.net.Network) { worker.execute { updatePhysical() } }
|
||||
}
|
||||
manager.registerNetworkCallback(android.net.NetworkRequest.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(),networkCallback!!)
|
||||
}
|
||||
private fun updatePhysical() {
|
||||
if (!running || !unified) return
|
||||
try {
|
||||
val next = physicalNetwork()
|
||||
if (next != physical) { physical=next;setUnderlyingNetworks(arrayOf(next));restartProxy(installed) }
|
||||
} 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)
|
||||
}
|
||||
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) {
|
||||
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()))
|
||||
.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))
|
||||
installed = 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)
|
||||
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))
|
||||
data.put("platform_network",platform)
|
||||
return JSONObject().put("ok",true).put("data",data)
|
||||
}
|
||||
private fun shutdown() {
|
||||
running = false
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@ package com.example.meshport_lab
|
||||
|
||||
object NativeBridge {
|
||||
init { System.loadLibrary("meshport_android") }
|
||||
external fun tunName(fd: Int): String?
|
||||
external fun newProxyContext(): Long
|
||||
external fun freeProxyContext(handle: Long)
|
||||
external fun proxyCall(handle: Long, request: String): String
|
||||
external fun newContext(): Long
|
||||
external fun freeContext(handle: Long)
|
||||
external fun call(handle: Long, request: String): String
|
||||
|
||||
Reference in New Issue
Block a user