From e1fe6f99cf303121a100c7bc1f936ed50e3921a9 Mon Sep 17 00:00:00 2001 From: uubooster-team Date: Sat, 31 Oct 2026 21:11:59 +0800 Subject: [PATCH] fix(network): handle gatewayless IPv4 VPN links Provide compatible gateway metadata for IPv4 VPN links without changing VPN routing, and keep text and JSON network snapshots consistent. Add regression tests for gateway selection and network snapshots. --- .../runtime/LinuxNetworkLinkComponent.kt | 38 +++-- .../runtime/LinuxNetworkLinkComponentTest.kt | 158 ++++++++++++++++++ tools/tests/test_netmanager.py | 12 ++ 3 files changed, 197 insertions(+), 11 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt index 06a0348253..7081d88114 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt @@ -9,6 +9,7 @@ import android.net.ConnectivityManager import android.net.LinkProperties import android.net.Network import android.net.NetworkCapabilities +import android.net.RouteInfo import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.os.Build @@ -23,6 +24,7 @@ import java.io.File import java.io.IOException import java.net.Inet4Address import java.net.Inet6Address +import java.net.InetAddress import org.json.JSONArray import org.json.JSONObject @@ -156,7 +158,7 @@ class LinuxNetworkLinkComponent( try { file.parentFile?.mkdirs() val staged = File(file.path + ".staged") - staged.writeText(describe(properties)) + staged.writeText(describe(properties, capabilities)) if (!staged.renameTo(file)) throw IOException("Could not replace $file") } catch (e: IOException) { Log.w(TAG, "Could not publish the network link", e) @@ -210,11 +212,7 @@ class LinuxNetworkLinkComponent( } }) put("gateways", JSONArray().apply { - properties?.routes.orEmpty().filter { it.isDefaultRoute }.forEach { - it.gateway?.takeUnless { address -> address.isAnyLocalAddress }?.let { address -> - put(address.hostAddress?.substringBefore('%')) - } - } + gateways(properties, capabilities).forEach { put(it.hostAddress?.substringBefore('%')) } }) put("dns", JSONArray().apply { properties?.dnsServers.orEmpty().filter { !it.isLinkLocalAddress }.forEach { @@ -301,7 +299,7 @@ class LinuxNetworkLinkComponent( } } - private fun describe(properties: LinkProperties?): String { + internal fun describe(properties: LinkProperties?, capabilities: NetworkCapabilities?): String { val addresses = properties?.linkAddresses.orEmpty() .filter { it.address is Inet4Address || it.address is Inet6Address } val name = properties?.interfaceName?.takeIf { addresses.isNotEmpty() } ?: OFFLINE_NAME @@ -316,10 +314,7 @@ class LinuxNetworkLinkComponent( for (address in addresses) { append("addr ${address.address.hostAddress?.substringBefore('%')} ${address.prefixLength}\n") } - for (family in listOf(Inet4Address::class.java, Inet6Address::class.java)) { - val gateway = properties?.routes.orEmpty() - .firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress } - ?.gateway ?: continue + for (gateway in gateways(properties, capabilities)) { append("gw ${gateway.hostAddress?.substringBefore('%')}\n") } } @@ -329,6 +324,27 @@ class LinuxNetworkLinkComponent( seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) } companion object { + internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List = + listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family -> + properties?.routes.orEmpty() + .firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress } + ?.gateway + ?: if (family == Inet4Address::class.java && + capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true && + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && + properties?.interfaceName != null && + properties.routes.any { + it.destination.address is Inet4Address && + (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || it.type == RouteInfo.RTN_UNICAST) + } + ) { + properties.linkAddresses.firstOrNull { + it.address is Inet4Address && !it.address.isAnyLocalAddress && + !it.address.isLoopbackAddress && !it.address.isLinkLocalAddress + }?.address + } else null + } + internal fun seededMac(readId: () -> String?): String { val id = runCatching(readId).getOrNull() ?: "bannerlator" val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray()) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt new file mode 100644 index 0000000000..ee745b7d14 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt @@ -0,0 +1,158 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.net.IpPrefix +import android.net.LinkAddress +import android.net.LinkProperties +import android.net.NetworkCapabilities +import android.net.RouteInfo +import androidx.test.core.app.ApplicationProvider +import java.net.InetAddress +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers +import org.robolectric.util.ReflectionHelpers.ClassParameter.from + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28, 34], manifest = Config.NONE) +class LinuxNetworkLinkComponentTest { + @get:Rule val temporary = TemporaryFolder() + + private fun capabilities(vpn: Boolean = true, internet: Boolean = true) = NetworkCapabilities().apply { + ReflectionHelpers.callInstanceMethod(this, "addTransportType", + from(Int::class.javaPrimitiveType, if (vpn) NetworkCapabilities.TRANSPORT_VPN else NetworkCapabilities.TRANSPORT_WIFI)) + if (internet) ReflectionHelpers.callInstanceMethod(this, "addCapability", + from(Int::class.javaPrimitiveType, NetworkCapabilities.NET_CAPABILITY_INTERNET)) + } + + private fun properties(vararg addresses: String) = LinkProperties().apply { + interfaceName = "tun0" + addresses.forEach { + val address = ReflectionHelpers.callConstructor(LinkAddress::class.java, + from(InetAddress::class.java, InetAddress.getByName(it.substringBefore('/'))), + from(Int::class.javaPrimitiveType, it.substringAfter('/').toInt())) + ReflectionHelpers.callInstanceMethod(this, "addLinkAddress", from(LinkAddress::class.java, address)) + } + } + + private fun LinkProperties.route(destination: String, prefix: Int, gateway: String = "0.0.0.0", + type: Int = RouteInfo.RTN_UNICAST) = apply { + addRoute(ReflectionHelpers.callConstructor(RouteInfo::class.java, + from(IpPrefix::class.java, IpPrefix(InetAddress.getByName(destination), prefix)), + from(InetAddress::class.java, InetAddress.getByName(gateway)), + from(String::class.java, interfaceName), + from(Int::class.javaPrimitiveType, type))) + } + + private fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?) = + LinuxNetworkLinkComponent.gateways(properties, capabilities).map { it.hostAddress } + + @Test fun vpnWithOnLinkDefaultRouteHasNonzeroCompatibilityGateway() { + val link = properties("10.0.0.1/24").route("0.0.0.0", 0) + assertEquals(listOf("10.0.0.1"), gateways(link, capabilities())) + } + + @Test fun vpnWithSplitRoutesHasCompatibilityGatewayWithoutDefaultRoute() { + val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1) + assertEquals(listOf("10.0.0.1"), gateways(link, capabilities())) + assertTrue(link.routes.none { it.isDefaultRoute }) + assertTrue(link.routes.all { it.gateway!!.isAnyLocalAddress }) + } + + @Test fun realDefaultGatewayIsPreservedEvenForVpn() { + val link = properties("10.0.0.2/24").route("0.0.0.0", 0, "10.0.0.1") + assertEquals(listOf("10.0.0.1"), gateways(link, capabilities())) + } + + @Test fun wifiDefaultGatewayIsUnchanged() { + val link = properties("192.168.1.2/24").route("0.0.0.0", 0, "192.168.1.1") + assertEquals(listOf("192.168.1.1"), gateways(link, capabilities(vpn = false))) + } + + @Test fun nonVpnLinkWithoutGatewayDoesNotBecomeInternetConnected() { + val link = properties("192.168.1.2/24").route("0.0.0.0", 0) + assertTrue(gateways(link, capabilities(vpn = false)).isEmpty()) + } + + @Test fun vpnWithoutInternetCapabilityDoesNotGetGateway() { + val link = properties("10.0.0.1/24").route("0.0.0.0", 0) + assertTrue(gateways(link, capabilities(internet = false)).isEmpty()) + } + + @Test fun missingNetworkOrCapabilitiesDoesNotGetGateway() { + val link = properties("10.0.0.1/24").route("0.0.0.0", 0) + assertTrue(gateways(null, capabilities()).isEmpty()) + assertTrue(gateways(link, null).isEmpty()) + } + + @Test fun vpnWithoutRoutesDoesNotGetGateway() { + assertTrue(gateways(properties("10.0.0.1/24"), capabilities()).isEmpty()) + } + + @Test fun vpnWithoutIpv4AddressDoesNotGetIpv4Gateway() { + val link = properties("fd00::2/64").route("0.0.0.0", 0) + assertTrue(gateways(link, capabilities()).isEmpty()) + } + + @Test fun vpnWithoutIpv4RoutesDoesNotGetIpv4Gateway() { + val link = properties("10.0.0.1/24").route("::", 0, "::") + assertTrue(gateways(link, capabilities()).isEmpty()) + } + + @Test fun reconnectingVpnWithRetainedAddressDoesNotGetGateway() { + val link = properties("10.0.0.1/24").apply { interfaceName = null } + .route("0.0.0.0", 0, type = RouteInfo.RTN_UNREACHABLE) + .route("128.0.0.0", 1, type = RouteInfo.RTN_UNREACHABLE) + assertTrue(gateways(link, capabilities()).isEmpty()) + val description = LinuxNetworkLinkComponent(ApplicationProvider.getApplicationContext(), temporary.root) + .describe(link, capabilities()) + assertTrue(description.contains("addr 10.0.0.1 24\n")) + assertFalse(description.contains("gw ")) + } + + @Config(sdk = [34]) + @Test fun vpnWithoutUnicastIpv4RouteDoesNotGetGateway() { + val link = properties("10.0.0.1/24") + .route("0.0.0.0", 0, type = RouteInfo.RTN_UNREACHABLE) + .route("10.0.0.0", 8, type = RouteInfo.RTN_THROW) + assertTrue(gateways(link, capabilities()).isEmpty()) + } + + @Test fun unspecifiedLoopbackAndLinkLocalAddressesAreNotGateways() { + val link = properties("0.0.0.0/32", "127.0.0.1/8", "169.254.1.2/16").route("0.0.0.0", 0) + assertTrue(gateways(link, capabilities()).isEmpty()) + } + + @Test fun ipv6DefaultGatewayIsPreservedAlongsideVpnIpv4Gateway() { + val link = properties("10.0.0.1/24", "fd00::2/64") + .route("0.0.0.0", 0).route("::", 0, "fe80::1") + assertEquals(listOf(InetAddress.getByName("10.0.0.1"), InetAddress.getByName("fe80::1")), + LinuxNetworkLinkComponent.gateways(link, capabilities())) + } + + @Test fun publishedLinkContainsGatewayAndKeepsVpnInterfaceAndAddress() { + val context = ApplicationProvider.getApplicationContext() + val component = LinuxNetworkLinkComponent(context, temporary.root) + val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1) + val before = ReflectionHelpers.callConstructor(LinkProperties::class.java, from(LinkProperties::class.java, link)) + val description = component.describe(link, capabilities()) + assertTrue(description.contains("if tun0 2 1500\n")) + assertTrue(description.contains("addr 10.0.0.1 24\n")) + assertTrue(description.contains("gw 10.0.0.1\n")) + ReflectionHelpers.callInstanceMethod(component, "write", + from(LinkProperties::class.java, link), from(NetworkCapabilities::class.java, capabilities())) + assertEquals(description, temporary.root.resolve("etc/droiddeck-net").readText()) + val state = org.json.JSONObject(temporary.root.resolve("etc/droiddeck-network.json").readText()) + assertEquals("tun0", state.getString("interface")) + assertEquals("vpn", state.getString("transport")) + assertEquals(listOf("10.0.0.1"), (0 until state.getJSONArray("gateways").length()).map { + state.getJSONArray("gateways").getString(it) + }) + assertEquals(before, link) + } +} diff --git a/tools/tests/test_netmanager.py b/tools/tests/test_netmanager.py index 5f65d97d41..1346f54d2b 100644 --- a/tools/tests/test_netmanager.py +++ b/tools/tests/test_netmanager.py @@ -97,6 +97,18 @@ class NetworkObjectsTest(unittest.TestCase): self.assertEqual(found[nm.device_path(state)][nm.NAME + ".Device"]["DeviceType"].unpack(), device_type) self.assertNotIn(nm.AP, found) + def test_vpn_compatibility_gateway_is_exposed_without_changing_address(self): + state = dict(WIFI, transport="vpn", interface="tun0", + addresses=[{"address": "10.0.0.1", "prefix": 24}], + gateways=["10.0.0.1"]) + found = nm.objects(state) + ipv4 = found[nm.IP4][nm.NAME + ".IP4Config"] + self.assertEqual(ipv4["Gateway"].unpack(), "10.0.0.1") + self.assertEqual(ipv4["AddressData"].unpack(), [{"address": "10.0.0.1", "prefix": 24}]) + self.assertEqual(found[nm.device_path(state)][nm.NAME + ".Device"]["DeviceType"].unpack(), 16) + self.assertTrue(found[nm.ACTIVE][nm.NAME + ".Connection.Active"]["Default"].unpack()) + self.assertEqual(found[nm.ROOT][nm.NAME]["Connectivity"].unpack(), 4) + def test_named_current_and_nearby_access_points(self): current = {"ssid": "Current Wi-Fi", "bssid": "00:11:22:33:44:55", "strength": 75, "capabilities": "[WPA2-PSK-CCMP][RSN-PSK+SAE-CCMP][ESS]"}