From 05236b2bb549c0aa433966a02e54b4e4154054b7 Mon Sep 17 00:00:00 2001 From: RunawayBoat <62377122+RunawayBoat@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:37:24 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20HyperOS=203=20?= =?UTF-8?q?=E5=89=AF=E5=8D=A1=E6=95=B0=E6=8D=AE=E9=80=9A=E9=81=93=E6=BF=80?= =?UTF-8?q?=E6=B4=BB=E6=A0=B8=E5=BF=83=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/proguard-rules.pro | 1 + .../multiroute/cellular/DualSimController.kt | 46 ++++++++++ .../multiroute/cellular/DualSimDaemon.java | 87 +++++++++++++++++++ 3 files changed, 134 insertions(+) create mode 100644 app/src/main/java/com/multiroute/cellular/DualSimController.kt create mode 100644 app/src/main/java/com/multiroute/cellular/DualSimDaemon.java diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index b8caa85..e7993b4 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -47,6 +47,7 @@ -keep class com.multiroute.MainActivity { *; } -keep class com.multiroute.ui.main.MainScreenViewModel { *; } -keep class com.multiroute.wifi.SlaveWifiBridge { *; } +-keep class com.multiroute.cellular.DualSimDaemon { public static void main(java.lang.String[]); } # ------------------------------------------------------------- # 6. Jetpack Compose diff --git a/app/src/main/java/com/multiroute/cellular/DualSimController.kt b/app/src/main/java/com/multiroute/cellular/DualSimController.kt new file mode 100644 index 0000000..5e96a03 --- /dev/null +++ b/app/src/main/java/com/multiroute/cellular/DualSimController.kt @@ -0,0 +1,46 @@ +package com.multiroute.cellular + +import android.content.Context +import com.multiroute.util.SuHelper +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** Manages only our own root process; it does not persist or auto-start at boot. */ +object DualSimController { + private const val ENTRY = "com.multiroute.cellular.DualSimDaemon" + private val mutex = Mutex() + private val linePattern = Regex("^\\s*(\\d+)\\s+\\S*app_process(?:32|64)?\\s+/system/bin\\s+$ENTRY\\s+([12])\\s*$") + + private fun processes(): List> = + SuHelper.executeShellWithOutput("ps -A -o PID,ARGS", timeoutSeconds = 5).mapNotNull { line -> + linePattern.matchEntire(line)?.let { it.groupValues[1].toInt() to it.groupValues[2].toInt() } + } + + suspend fun status(): Int = withContext(Dispatchers.IO) { processes().singleOrNull()?.second ?: 0 } + + suspend fun select(context: Context, selected: Int): Boolean = withContext(Dispatchers.IO) { + mutex.withLock { + require(selected in 0..2) + if (!SuHelper.isRootAvailable()) return@withLock false + val running = processes() + if (running.size == 1 && running[0].second == selected) return@withLock true + for ((pid, _) in running) { + if (!SuHelper.executeCommand("kill -TERM $pid")) return@withLock false + } + var attempts = 0 + while (attempts++ < 30 && processes().isNotEmpty()) { + delay(100) + } + if (processes().isNotEmpty()) return@withLock false + if (selected == 0) return@withLock true + val apk = context.applicationInfo.sourceDir.replace("'", "'\\''") + val command = "setsid /system/bin/env CLASSPATH='$apk' /system/bin/app_process /system/bin $ENTRY $selected /dev/null 2>&1 &" + if (!SuHelper.executeCommand(command, timeoutSeconds = 5)) return@withLock false + delay(1200) + processes().singleOrNull()?.second == selected + } + } +} diff --git a/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java b/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java new file mode 100644 index 0000000..d045099 --- /dev/null +++ b/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java @@ -0,0 +1,87 @@ +package com.multiroute.cellular; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.net.Network; +import android.net.NetworkCapabilities; +import android.net.NetworkRequest; +import android.net.TelephonyNetworkSpecifier; +import android.os.Looper; +import android.telephony.SubscriptionInfo; +import android.telephony.SubscriptionManager; +import java.lang.reflect.Method; +import java.util.List; + +/** Root app_process entry point. A live callback holds the requested secondary network. */ +public final class DualSimDaemon { + /** app_process does not inherit the telephony initialization performed in Zygote. */ + private static void initializeTelephony() throws Exception { + Class initializer = Class.forName("android.telephony.TelephonyFrameworkInitializer"); + if (initializer.getMethod("getTelephonyServiceManager").invoke(null) == null) { + Class manager = Class.forName("android.os.TelephonyServiceManager"); + initializer.getMethod("setTelephonyServiceManager", manager) + .invoke(null, manager.getConstructor().newInstance()); + } + } + + public static void main(String[] args) throws Exception { + if (args.length != 1 || !(args[0].equals("1") || args[0].equals("2"))) { + throw new IllegalArgumentException("Expected mode 1 or 2"); + } + Looper.prepareMainLooper(); + initializeTelephony(); + Class activityThread = Class.forName("android.app.ActivityThread"); + Object thread = activityThread.getMethod("systemMain").invoke(null); + Context context = (Context) activityThread.getMethod("getSystemContext").invoke(thread); + SubscriptionManager sm = context.getSystemService(SubscriptionManager.class); + int primary = SubscriptionManager.getDefaultDataSubscriptionId(); + List subscriptions = sm.getActiveSubscriptionInfoList(); + int secondary = SubscriptionManager.INVALID_SUBSCRIPTION_ID; + if (subscriptions != null) for (SubscriptionInfo info : subscriptions) { + if (info.getSubscriptionId() != primary) { + if (secondary != SubscriptionManager.INVALID_SUBSCRIPTION_ID) { + throw new IllegalStateException("More than one secondary subscription"); + } + secondary = info.getSubscriptionId(); + } + } + if (!SubscriptionManager.isValidSubscriptionId(primary) || !SubscriptionManager.isValidSubscriptionId(secondary)) { + throw new IllegalStateException("Two active subscriptions are required"); + } + Class properties = Class.forName("android.os.SystemProperties"); + Method get = properties.getMethod("get", String.class, String.class); + Method set = properties.getMethod("set", String.class, String.class); + String key = "ril.multisim.dualdata_status"; + String original = (String) get.invoke(null, key, "2"); + boolean changed = args[0].equals("1") && !original.equals("1"); + ConnectivityManager cm = context.getSystemService(ConnectivityManager.class); + NetworkRequest.Builder builder = new NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) + .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .addCapability(NetworkCapabilities.NET_CAPABILITY_MMS) + .setNetworkSpecifier(new TelephonyNetworkSpecifier.Builder().setSubscriptionId(secondary).build()); + if (args[0].equals("2")) builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); + ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() { + @Override public void onAvailable(Network n) { android.util.Log.i("MultiRouteDualSim", "available " + n); } + @Override public void onLost(Network n) { android.util.Log.i("MultiRouteDualSim", "lost " + n); } + @Override public void onUnavailable() { + android.util.Log.w("MultiRouteDualSim", "unavailable"); + Looper.getMainLooper().quitSafely(); + } + }; + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { cm.unregisterNetworkCallback(callback); } catch (Exception ignored) { } + try { + if (changed && "1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, original); + } catch (Exception ignored) { } + })); + try { + if (changed) set.invoke(null, key, "1"); + cm.requestNetwork(builder.build(), callback); + Looper.loop(); + } finally { + try { cm.unregisterNetworkCallback(callback); } catch (Exception ignored) { } + if (changed && "1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, original); + } + } +} From 21361db82431733175cc7d5025a4946d471681ec Mon Sep 17 00:00:00 2001 From: RunawayBoat <62377122+RunawayBoat@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:37:45 +0800 Subject: [PATCH 2/7] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=9C=82=E7=AA=9D?= =?UTF-8?q?=E5=88=86=E6=B5=81=E7=9A=84=E6=AF=8F=E5=BA=94=E7=94=A8=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E7=BD=91=E7=BB=9C=E3=80=81DNS=20=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E5=8F=8A=20IPv6=20=E5=9B=9E=E9=80=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hook/CellularDefaultNetworkPolicy.kt | 15 +++ .../com/multiroute/hook/MultiRouteModule.kt | 116 ++++++++++++++++++ .../java/com/multiroute/util/ModuleState.kt | 1 + .../com/multiroute/util/RouteRuleBuilder.kt | 6 + .../main/java/com/multiroute/util/SuHelper.kt | 11 ++ .../hook/CellularDefaultNetworkPolicyTest.kt | 25 ++++ .../multiroute/util/RouteRuleBuilderTest.kt | 12 ++ 7 files changed, 186 insertions(+) create mode 100644 app/src/main/java/com/multiroute/hook/CellularDefaultNetworkPolicy.kt create mode 100644 app/src/test/java/com/multiroute/hook/CellularDefaultNetworkPolicyTest.kt diff --git a/app/src/main/java/com/multiroute/hook/CellularDefaultNetworkPolicy.kt b/app/src/main/java/com/multiroute/hook/CellularDefaultNetworkPolicy.kt new file mode 100644 index 0000000..4d2fb66 --- /dev/null +++ b/app/src/main/java/com/multiroute/hook/CellularDefaultNetworkPolicy.kt @@ -0,0 +1,15 @@ +package com.multiroute.hook + +import com.multiroute.util.RouteRuleBuilder + +/** Only explicitly assigned cellular UIDs participate; unrelated system preferences stay intact. */ +internal object CellularDefaultNetworkPolicy { + fun isCellular(iface: String): Boolean = + iface.startsWith("rmnet") || iface.startsWith("ccmni") || iface == "cellular" + + fun groups(platformUids: Set, routes: Map): Map> = + routes.entries.filter { (uid, iface) -> + uid in platformUids && RouteRuleBuilder.isValidUid(uid) && + RouteRuleBuilder.isValidInterfaceName(iface) && isCellular(iface) + }.groupBy({ it.value }, { it.key }).mapValues { it.value.toSet() } +} diff --git a/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt b/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt index e1a1123..42763cc 100644 --- a/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt +++ b/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt @@ -63,6 +63,8 @@ class MultiRouteModule : XposedModule() { } private var isConnectivityHooked = false + @Volatile private var connectivityService: Any? = null + private var cellularPreferenceFingerprint: String? = null private val isSlaveWifiHooked = AtomicBoolean(false) private val isDualStaHooked = AtomicBoolean(false) @Volatile private var isTetheringHooked = false @@ -315,6 +317,7 @@ class MultiRouteModule : XposedModule() { var hookedCount = 0 if (hookGetMobileDataPreferredUids(csClass)) hookedCount++ + if (hookCellularDefaultRequests(csClass)) hookedCount++ if (hookGetDefaultNetworkForUid(csClass)) hookedCount++ if (hookGetActiveNetworkForUidInternal(csClass)) hookedCount++ @@ -355,6 +358,116 @@ class MultiRouteModule : XposedModule() { } } + /** + * A route override alone does not change netd's per-UID DNS network or socket mark. + * Split the platform's mobile preference into subscription-specific multilayer requests; + * ConnectivityService then updates netd and default-network callbacks itself. + */ + private fun hookCellularDefaultRequests(csClass: Class<*>): Boolean { + val factory = csClass.declaredMethods.firstOrNull { + it.name == "createNrisFromMobileDataPreferredUids" && it.parameterTypes.size == 1 && + Set::class.java.isAssignableFrom(it.parameterTypes[0]) + } ?: return false + val createRequest = csClass.declaredMethods.firstOrNull { + it.name == "createDefaultInternetRequestForTransport" && it.parameterTypes.size == 2 + } ?: return false + val createNris = csClass.declaredMethods.firstOrNull { + it.name == "createNrisForPreferenceOrder" && it.parameterTypes.size == 3 + } ?: return false + val typeClass = createRequest.parameterTypes[1] + val types = typeClass.enumConstants ?: return false + val requestType = types.firstOrNull { (it as Enum<*>).name == "REQUEST" } ?: return false + val fallbackType = types.firstOrNull { (it as Enum<*>).name == "TRACK_DEFAULT" } ?: return false + val preference = runCatching { + csClass.getDeclaredField("PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED") + .apply { isAccessible = true }.getInt(null) + }.getOrNull() ?: return false + listOf(factory, createRequest, createNris).forEach { it.isAccessible = true } + return try { + deoptimize(factory) + hook(factory).intercept { chain -> + connectivityService = chain.thisObject + reloadPreferencesCacheIfNeeded() + @Suppress("UNCHECKED_CAST") + val allUids = chain.getArg(0) as Set + val pinned = mutableSetOf() + val result = android.util.ArraySet() + try { + val groups = CellularDefaultNetworkPolicy.groups(allUids, HashMap(cachedUidRoutes)) + for ((iface, uids) in groups) { + val agent = findNetworkAgentForChannel(chain.thisObject, iface) ?: continue + val nc = findNetworkCapabilitiesField(agent.javaClass)?.apply { isAccessible = true } + ?.get(agent) as? NetworkCapabilities ?: continue + if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || + !nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) continue + val specifier = NetworkCapabilities::class.java.getMethod("getNetworkSpecifier") + .invoke(nc) as? android.net.TelephonyNetworkSpecifier ?: continue + val selected = createRequest.invoke(chain.thisObject, + NetworkCapabilities.TRANSPORT_CELLULAR, requestType) + val capabilities = selected.javaClass.getField("networkCapabilities") + .get(selected) as NetworkCapabilities + NetworkCapabilities::class.java.getMethod("setNetworkSpecifier", + android.net.NetworkSpecifier::class.java).invoke(capabilities, specifier) + // Mode 2 may expose a restricted Internet bearer. This is a system-owned + // per-UID request, not an unprivileged app request for restricted access. + if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)) { + NetworkCapabilities::class.java.getMethod("removeCapability", Int::class.javaPrimitiveType) + .invoke(capabilities, NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) + } + val fallback = createRequest.invoke(chain.thisObject, -1, fallbackType) + @Suppress("UNCHECKED_CAST") + val nris = createNris.invoke(chain.thisObject, uids, listOf(selected, fallback), preference) as Set + result.addAll(nris) + pinned.addAll(uids) + log(Log.INFO, TAG, "[CellularDefault] $uids -> $iface ($specifier)") + } + } catch (t: Throwable) { + log(Log.ERROR, TAG, "[CellularDefault] Could not pin subscription; using platform preference", t) + result.clear() + pinned.clear() + } + // Call the original exactly once, including on unsupported ROMs. + @Suppress("UNCHECKED_CAST") + val unchanged = chain.proceed(arrayOf(allUids - pinned)) as Set + result.addAll(unchanged) + result + } + log(Log.INFO, TAG, "Successfully hooked subscription-specific mobile defaults") + true + } catch (t: Throwable) { + log(Log.ERROR, TAG, "Failed to hook subscription-specific mobile defaults", t) + false + } + } + + private fun refreshCellularDefaults() { + val service = connectivityService ?: return + val handler = getAllFields(service.javaClass).firstOrNull { it.name == "mHandler" } + ?.apply { isAccessible = true }?.get(service) as? android.os.Handler ?: return + handler.post { + try { + lastPrefCacheTime = 0L + reloadPreferencesCacheIfNeeded() + val routes = cachedUidRoutes.filterValues { CellularDefaultNetworkPolicy.isCellular(it) } + val fingerprint = routes.toSortedMap().map { (uid, iface) -> + val agent = findNetworkAgentForChannel(service, iface) + val nc = agent?.let { findNetworkCapabilitiesField(it.javaClass) + ?.apply { isAccessible = true }?.get(it) } as? NetworkCapabilities + val specifier = nc?.let { NetworkCapabilities::class.java + .getMethod("getNetworkSpecifier").invoke(it) } + "$uid:$iface:$specifier:${nc?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)}" + }.joinToString(";") + if (fingerprint != cellularPreferenceFingerprint) { + service.javaClass.getDeclaredMethod("updateMobileDataPreferredUids") + .apply { isAccessible = true }.invoke(service) + cellularPreferenceFingerprint = fingerprint + } + } catch (t: Throwable) { + log(Log.WARN, TAG, "[CellularDefault] Refresh failed", t) + } + } + } + private fun hookGetDefaultNetworkForUid(csClass: Class<*>): Boolean { val method = csClass.declaredMethods.firstOrNull { it.name == "getDefaultNetworkForUid" && @@ -367,6 +480,7 @@ class MultiRouteModule : XposedModule() { deoptimize(method) hook(method).intercept { chain -> val uid = chain.getArg(0) as Int + connectivityService = chain.thisObject val targetChannel = getTargetChannelForUid(uid) if (targetChannel != null && targetChannel != CHANNEL_DEFAULT) { @@ -731,6 +845,7 @@ class MultiRouteModule : XposedModule() { } when (intent?.action) { + ModuleStateParser.ACTION_ROUTES_CHANGED -> refreshCellularDefaults() ModuleStateParser.ACTION_KEEPALIVE_CHANGED -> { if (!isKeepSlaveWifiScreenOff()) { log(Log.INFO, TAG, "[KeepAlive] Switch is off; no hooks installed.") @@ -786,6 +901,7 @@ class MultiRouteModule : XposedModule() { } val filter = android.content.IntentFilter().apply { addAction(ModuleStateParser.ACTION_KEEPALIVE_CHANGED) + addAction(ModuleStateParser.ACTION_ROUTES_CHANGED) addAction(ModuleStateParser.ACTION_CONNECT_SLAVE_WIFI) addAction(ModuleStateParser.ACTION_DISCONNECT_SLAVE_WIFI) } diff --git a/app/src/main/java/com/multiroute/util/ModuleState.kt b/app/src/main/java/com/multiroute/util/ModuleState.kt index 68de552..d4b4740 100644 --- a/app/src/main/java/com/multiroute/util/ModuleState.kt +++ b/app/src/main/java/com/multiroute/util/ModuleState.kt @@ -43,6 +43,7 @@ object ModuleStateParser { * re-checks the persistent flag when it arrives, so a stray broadcast cannot enable anything by itself. */ const val ACTION_KEEPALIVE_CHANGED = "com.multiroute.ACTION_KEEPALIVE_CHANGED" + const val ACTION_ROUTES_CHANGED = "com.multiroute.ACTION_ROUTES_CHANGED" /** Broadcast dispatched to system_server to initiate secondary Wi-Fi connection via SlaveWifiService. */ const val ACTION_CONNECT_SLAVE_WIFI = "com.multiroute.ACTION_CONNECT_SLAVE_WIFI" diff --git a/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt b/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt index 284d5d1..8c9c87b 100644 --- a/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt +++ b/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt @@ -142,6 +142,12 @@ object RouteRuleBuilder { for (uid in uids) { commands.add("$IP_BIN rule add uidrange $uid-$uid lookup $iface pref $pref;") commands.add("$IP_BIN -6 rule add uidrange $uid-$uid lookup $iface pref $pref;") + if (iface.startsWith("rmnet") || iface.startsWith("ccmni") || iface == "cellular") { + // Fail fast instead of silently falling through to the other SIM's IPv6. + // Re-evaluated on every sync/boot, so acquiring IPv6 restores normal routing. + commands.add("if ! $IP_BIN -6 route show table $iface 2>/dev/null | /system/bin/grep -q '^default'; then " + + "$IP_BIN -6 rule add unreachable uidrange $uid-$uid pref $pref; fi;") + } } } return commands diff --git a/app/src/main/java/com/multiroute/util/SuHelper.kt b/app/src/main/java/com/multiroute/util/SuHelper.kt index f219a60..fe73b8c 100644 --- a/app/src/main/java/com/multiroute/util/SuHelper.kt +++ b/app/src/main/java/com/multiroute/util/SuHelper.kt @@ -588,6 +588,7 @@ object SuHelper { executeCommand(cleanupScript, timeoutSeconds = RULE_SCRIPT_TIMEOUT_SECONDS) executeCommand("rm -f /data/adb/service.d/00-multiroute-restore.sh") executeCommand("rm -f ${RouteRuleBuilder.RULE_CACHE_PATH}") + notifyRouteRulesChanged(context) return true } @@ -670,6 +671,9 @@ object SuHelper { // instead, and the app re-applies the redirect with fresh resolvers once it runs. updateRuleCache(activeChannelMap) } + // UID membership can stay unchanged while the selected SIM changes. A setting write + // alone then emits no observer event, so refresh after publishing the new route cache. + notifyRouteRulesChanged(context) return bootSaved } @@ -696,6 +700,13 @@ object SuHelper { } } + private fun notifyRouteRulesChanged(context: Context) { + runCatching { + context.sendBroadcast(android.content.Intent(ModuleStateParser.ACTION_ROUTES_CHANGED) + .setPackage("android")) + }.onFailure { Log.w(TAG, "Could not notify system_server of route changes", it) } + } + /** * Publishes the uid→interface map to [RouteRuleBuilder.RULE_CACHE_PATH]. * diff --git a/app/src/test/java/com/multiroute/hook/CellularDefaultNetworkPolicyTest.kt b/app/src/test/java/com/multiroute/hook/CellularDefaultNetworkPolicyTest.kt new file mode 100644 index 0000000..e99743c --- /dev/null +++ b/app/src/test/java/com/multiroute/hook/CellularDefaultNetworkPolicyTest.kt @@ -0,0 +1,25 @@ +package com.multiroute.hook + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CellularDefaultNetworkPolicyTest { + @Test fun keepsTwoSimAssignmentsSeparateAndLeavesUnassignedUidsAlone() { + val groups = CellularDefaultNetworkPolicy.groups(setOf(10596, 10698, 10700, 10701), mapOf( + 10596 to "rmnet_data2", 10698 to "rmnet_data4", 10700 to "wlan0", + 10702 to "rmnet_data2", 10701 to "default")) + assertEquals(mapOf("rmnet_data2" to setOf(10596), "rmnet_data4" to setOf(10698)), groups) + } + + @Test fun switchingInterfaceMovesTheSameUidAndClearingRemovesIt() { + val uids = setOf(10596) + assertEquals(mapOf("rmnet_data4" to uids), + CellularDefaultNetworkPolicy.groups(uids, mapOf(10596 to "rmnet_data4"))) + assertEquals(emptyMap>(), CellularDefaultNetworkPolicy.groups(uids, emptyMap())) + } + + @Test fun rejectsSystemUidsAndInvalidInterfaceNames() { + assertEquals(emptyMap>(), CellularDefaultNetworkPolicy.groups( + setOf(1000, 10596), mapOf(1000 to "rmnet_data2", 10596 to "rmnet_data2;reboot"))) + } +} diff --git a/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt b/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt index ff822c5..dd7491b 100644 --- a/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt +++ b/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt @@ -7,6 +7,18 @@ import org.junit.Test class RouteRuleBuilderTest { + @Test fun cellularIpv6FallbackIsScopedToAssignedUidAndRemovedByNormalCleanup() { + val commands = RouteRuleBuilder.buildUidRoutingCommands(mapOf("rmnet_data2" to listOf(10596))) + assertEquals(3, commands.size) + assertTrue(commands.last().contains("-6 route show table rmnet_data2")) + assertTrue(commands.last().contains("rule add unreachable uidrange 10596-10596 pref 14500")) + assertFalse(RouteRuleBuilder.buildUidRoutingCommands(mapOf("wlan0" to listOf(10698))) + .any { it.contains("unreachable") }) + assertTrue(RouteRuleBuilder.buildCleanupCommands().any { + it.contains("-6 rule del pref 14500") + }) + } + @Test fun testInterfaceNameSanitization() { // Valid interface names From bf0fb5c937f3dd838ebb1eb06a6e2e8fab1ab205 Mon Sep 17 00:00:00 2001 From: RunawayBoat <62377122+RunawayBoat@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:38:56 +0800 Subject: [PATCH 3/7] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E5=89=AF=E5=8D=A1?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=94=B3=E8=AF=B7=E4=B8=8E=E4=B8=BB=E5=89=AF?= =?UTF-8?q?=E5=8D=A1=E5=88=87=E6=8D=A2=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../multiroute/cellular/DualSimDaemon.java | 189 +++++++++++++++--- .../cellular/SubscriptionSelection.kt | 8 + .../cellular/SubscriptionSelectionTest.kt | 15 ++ 3 files changed, 181 insertions(+), 31 deletions(-) create mode 100644 app/src/main/java/com/multiroute/cellular/SubscriptionSelection.kt create mode 100644 app/src/test/java/com/multiroute/cellular/SubscriptionSelectionTest.kt diff --git a/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java b/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java index d045099..d203e59 100644 --- a/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java +++ b/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java @@ -1,12 +1,17 @@ package com.multiroute.cellular; import android.content.Context; +import android.content.BroadcastReceiver; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Build; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkRequest; import android.net.TelephonyNetworkSpecifier; import android.os.Looper; +import android.os.Handler; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import java.lang.reflect.Method; @@ -24,6 +29,150 @@ private static void initializeTelephony() throws Exception { } } + // TelephonyIntents hidden framework broadcast; verified against this device's framework DEX. + private static final String DEFAULT_DATA_CHANGED = + "android.intent.action.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED"; + + private static final class Session { + final Context context; + final ConnectivityManager cm; + final boolean restricted; + final Runnable prepareRequest; + final Handler handler = new Handler(Looper.getMainLooper()); + final java.util.ArrayList callbacks = new java.util.ArrayList<>(); + int primary = -1, secondary = -1; + volatile boolean closed; + final SubscriptionManager subscriptions; + boolean subscriptionListenerRegistered, receiverRegistered; + final Runnable refreshTask = this::refreshSubscriptions; + final SubscriptionManager.OnSubscriptionsChangedListener subscriptionListener = + new SubscriptionManager.OnSubscriptionsChangedListener() { + @Override public void onSubscriptionsChanged() { scheduleRefresh(); } + }; + final BroadcastReceiver defaultDataReceiver = new BroadcastReceiver() { + @Override public void onReceive(Context ignored, Intent intent) { + if (DEFAULT_DATA_CHANGED.equals(intent.getAction())) { + scheduleRefresh(); + } + } + }; + Session(Context context, ConnectivityManager cm, boolean restricted, Runnable prepareRequest) { + this.context = context; this.cm = cm; this.restricted = restricted; + this.prepareRequest = prepareRequest; + this.subscriptions = context.getSystemService(SubscriptionManager.class); + } + void close() { + // Block delayed refreshes and network callbacks before releasing any resources. + synchronized (callbacks) { + closed = true; + handler.removeCallbacksAndMessages(null); + } + if (subscriptionListenerRegistered) { + try { subscriptions.removeOnSubscriptionsChangedListener(subscriptionListener); } + catch (Exception e) { android.util.Log.w("MultiRouteDualSim", "Listener cleanup failed", e); } + subscriptionListenerRegistered = false; + } + if (receiverRegistered) { + try { context.unregisterReceiver(defaultDataReceiver); } + catch (Exception e) { android.util.Log.w("MultiRouteDualSim", "Receiver cleanup failed", e); } + receiverRegistered = false; + } + releaseRequests(); + } + void releaseRequests() { + synchronized (callbacks) { + for (ConnectivityManager.NetworkCallback callback : callbacks) { + try { cm.unregisterNetworkCallback(callback); } catch (Exception ignored) { } + } + callbacks.clear(); + } + } + void request(boolean mms) { + final int targetSub = secondary; + final String kind = mms ? "INTERNET+MMS" : "INTERNET"; + NetworkRequest.Builder builder = new NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) + .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .setNetworkSpecifier(new TelephonyNetworkSpecifier.Builder().setSubscriptionId(targetSub).build()); + if (mms) builder.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS); + if (restricted) builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); + ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() { + @Override public void onAvailable(Network n) { + android.util.Log.i("MultiRouteDualSim", kind + " sub=" + targetSub + " available " + n); + } + @Override public void onLost(Network n) { + android.util.Log.i("MultiRouteDualSim", kind + " sub=" + targetSub + " lost " + n); + } + @Override public void onUnavailable() { + android.util.Log.w("MultiRouteDualSim", kind + " unavailable sub=" + targetSub); + } + }; + synchronized (callbacks) { + if (closed) return; + android.util.Log.i("MultiRouteDualSim", "request " + kind + " sub=" + targetSub); + cm.requestNetwork(builder.build(), callback); + callbacks.add(callback); + } + } + void scheduleRefresh() { + // Both event sources run on our handler; coalesce bursts during a SIM transition. + synchronized (callbacks) { + if (closed) return; + handler.removeCallbacks(refreshTask); + handler.postDelayed(refreshTask, 300); + } + } + void start() { + // Register before the initial read so a concurrent default-data change cannot be missed. + subscriptions.addOnSubscriptionsChangedListener(command -> handler.post(command), subscriptionListener); + subscriptionListenerRegistered = true; + IntentFilter filter = new IntentFilter(DEFAULT_DATA_CHANGED); + if (Build.VERSION.SDK_INT >= 33) { + context.registerReceiver(defaultDataReceiver, filter, null, handler, Context.RECEIVER_EXPORTED); + } else { + context.registerReceiver(defaultDataReceiver, filter, null, handler); + } + receiverRegistered = true; + scheduleRefresh(); + } + void refreshSubscriptions() { + if (closed) return; + try { + int nextPrimary = SubscriptionManager.getDefaultDataSubscriptionId(); + List subs = subscriptions.getActiveSubscriptionInfoList(); + java.util.ArrayList ids = new java.util.ArrayList<>(); + if (subs != null) for (SubscriptionInfo sub : subs) ids.add(sub.getSubscriptionId()); + int nextSecondary = SubscriptionSelection.INSTANCE.secondary(nextPrimary, ids); + if (primary == nextPrimary && secondary == nextSecondary) return; + releaseRequests(); + primary = nextPrimary; secondary = nextSecondary; + android.util.Log.i("MultiRouteDualSim", "retarget primary=" + primary + " secondary=" + secondary); + if (secondary >= 0) { + prepareRequest.run(); + // Submit independent requests immediately. A carrier may satisfy one or both + // with the same bearer; one rejected variant must not cancel the other. + boolean registered = false; + Exception failure = null; + for (boolean mms : new boolean[]{false, true}) { + try { + request(mms); + registered = true; + } catch (Exception e) { + failure = e; + android.util.Log.w("MultiRouteDualSim", + "Request variant failed mms=" + mms + " sub=" + secondary, e); + } + } + if (!registered) throw new IllegalStateException("Both network requests failed", failure); + } + } catch (Exception e) { + android.util.Log.e("MultiRouteDualSim", "Subscription refresh failed", e); + releaseRequests(); primary = -1; secondary = -1; + } + } + + } + public static void main(String[] args) throws Exception { if (args.length != 1 || !(args[0].equals("1") || args[0].equals("2"))) { throw new IllegalArgumentException("Expected mode 1 or 2"); @@ -33,21 +182,6 @@ public static void main(String[] args) throws Exception { Class activityThread = Class.forName("android.app.ActivityThread"); Object thread = activityThread.getMethod("systemMain").invoke(null); Context context = (Context) activityThread.getMethod("getSystemContext").invoke(thread); - SubscriptionManager sm = context.getSystemService(SubscriptionManager.class); - int primary = SubscriptionManager.getDefaultDataSubscriptionId(); - List subscriptions = sm.getActiveSubscriptionInfoList(); - int secondary = SubscriptionManager.INVALID_SUBSCRIPTION_ID; - if (subscriptions != null) for (SubscriptionInfo info : subscriptions) { - if (info.getSubscriptionId() != primary) { - if (secondary != SubscriptionManager.INVALID_SUBSCRIPTION_ID) { - throw new IllegalStateException("More than one secondary subscription"); - } - secondary = info.getSubscriptionId(); - } - } - if (!SubscriptionManager.isValidSubscriptionId(primary) || !SubscriptionManager.isValidSubscriptionId(secondary)) { - throw new IllegalStateException("Two active subscriptions are required"); - } Class properties = Class.forName("android.os.SystemProperties"); Method get = properties.getMethod("get", String.class, String.class); Method set = properties.getMethod("set", String.class, String.class); @@ -55,32 +189,25 @@ public static void main(String[] args) throws Exception { String original = (String) get.invoke(null, key, "2"); boolean changed = args[0].equals("1") && !original.equals("1"); ConnectivityManager cm = context.getSystemService(ConnectivityManager.class); - NetworkRequest.Builder builder = new NetworkRequest.Builder() - .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) - .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - .addCapability(NetworkCapabilities.NET_CAPABILITY_MMS) - .setNetworkSpecifier(new TelephonyNetworkSpecifier.Builder().setSubscriptionId(secondary).build()); - if (args[0].equals("2")) builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); - ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() { - @Override public void onAvailable(Network n) { android.util.Log.i("MultiRouteDualSim", "available " + n); } - @Override public void onLost(Network n) { android.util.Log.i("MultiRouteDualSim", "lost " + n); } - @Override public void onUnavailable() { - android.util.Log.w("MultiRouteDualSim", "unavailable"); - Looper.getMainLooper().quitSafely(); + Session session = new Session(context, cm, args[0].equals("2"), () -> { + if (args[0].equals("1")) { + try { + if (!"1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, "1"); + } catch (Exception e) { throw new IllegalStateException("Cannot enable dual data", e); } } - }; + }); Runtime.getRuntime().addShutdownHook(new Thread(() -> { - try { cm.unregisterNetworkCallback(callback); } catch (Exception ignored) { } + try { session.close(); } catch (Exception ignored) { } try { if (changed && "1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, original); } catch (Exception ignored) { } })); try { if (changed) set.invoke(null, key, "1"); - cm.requestNetwork(builder.build(), callback); + session.start(); Looper.loop(); } finally { - try { cm.unregisterNetworkCallback(callback); } catch (Exception ignored) { } + try { session.close(); } catch (Exception ignored) { } if (changed && "1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, original); } } diff --git a/app/src/main/java/com/multiroute/cellular/SubscriptionSelection.kt b/app/src/main/java/com/multiroute/cellular/SubscriptionSelection.kt new file mode 100644 index 0000000..2ddd1ac --- /dev/null +++ b/app/src/main/java/com/multiroute/cellular/SubscriptionSelection.kt @@ -0,0 +1,8 @@ +package com.multiroute.cellular + +/** Selects the unique active subscription other than the current default data subscription. */ +object SubscriptionSelection { + fun secondary(defaultId: Int, activeIds: List): Int = + if (defaultId >= 0 && defaultId in activeIds) activeIds.distinct().filter { it != defaultId }.singleOrNull() ?: -1 else -1 + +} diff --git a/app/src/test/java/com/multiroute/cellular/SubscriptionSelectionTest.kt b/app/src/test/java/com/multiroute/cellular/SubscriptionSelectionTest.kt new file mode 100644 index 0000000..c30e4b0 --- /dev/null +++ b/app/src/test/java/com/multiroute/cellular/SubscriptionSelectionTest.kt @@ -0,0 +1,15 @@ +package com.multiroute.cellular + +import org.junit.Assert.assertEquals +import org.junit.Test + +class SubscriptionSelectionTest { + @Test fun changingDefaultReversesSecondaryWithoutSlotAssumptions() { + assertEquals(15, SubscriptionSelection.secondary(2, listOf(2, 15))) + assertEquals(2, SubscriptionSelection.secondary(15, listOf(2, 15))) + assertEquals(-1, SubscriptionSelection.secondary(-1, listOf(2, 15))) + assertEquals(-1, SubscriptionSelection.secondary(9, listOf(2, 15))) + assertEquals(-1, SubscriptionSelection.secondary(2, listOf(2))) + assertEquals(-1, SubscriptionSelection.secondary(2, listOf(2, 15, 18))) + } +} From 78686e69ae63421e25fe0f314c96a2b66b394e8a Mon Sep 17 00:00:00 2001 From: Linoleic Date: Fri, 30 Oct 2026 21:08:27 +0800 Subject: [PATCH 4/7] fix(cellular): align effective routes with per-app network defaults --- .../hook/CellularFrameworkCompat.kt | 42 +++++ .../hook/CellularNetworkSelection.kt | 7 + .../multiroute/hook/EffectiveRouteSnapshot.kt | 12 ++ .../com/multiroute/hook/MultiRouteModule.kt | 169 ++++++++---------- .../main/java/com/multiroute/util/SuHelper.kt | 100 ++++------- .../hook/CellularFrameworkCompatTest.kt | 61 +++++++ .../hook/CellularNetworkSelectionTest.kt | 19 ++ .../hook/EffectiveRouteSnapshotTest.kt | 26 +++ 8 files changed, 273 insertions(+), 163 deletions(-) create mode 100644 app/src/main/java/com/multiroute/hook/CellularFrameworkCompat.kt create mode 100644 app/src/main/java/com/multiroute/hook/CellularNetworkSelection.kt create mode 100644 app/src/main/java/com/multiroute/hook/EffectiveRouteSnapshot.kt create mode 100644 app/src/test/java/com/multiroute/hook/CellularFrameworkCompatTest.kt create mode 100644 app/src/test/java/com/multiroute/hook/CellularNetworkSelectionTest.kt create mode 100644 app/src/test/java/com/multiroute/hook/EffectiveRouteSnapshotTest.kt diff --git a/app/src/main/java/com/multiroute/hook/CellularFrameworkCompat.kt b/app/src/main/java/com/multiroute/hook/CellularFrameworkCompat.kt new file mode 100644 index 0000000..1276a2e --- /dev/null +++ b/app/src/main/java/com/multiroute/hook/CellularFrameworkCompat.kt @@ -0,0 +1,42 @@ +package com.multiroute.hook + +import java.lang.reflect.Method + +internal object CellularFrameworkCompat { + /** The handler implementation remains available on ROMs which removed the old entry point. */ + fun refreshMethod(type: Class<*>): Method? { + for (name in listOf("handleMobileDataPreferredUidsChanged", "updateMobileDataPreferredUids")) { + var current: Class<*>? = type + while (current != null) { + current.declaredMethods.firstOrNull { + it.name == name && it.parameterTypes.isEmpty() && it.returnType == Void.TYPE + }?.let { return it.apply { isAccessible = true } } + current = current.superclass + } + } + return null + } + + /** Call on the service Handler. Newer ROMs skip rebuilding when only the SIM changed. */ + fun refresh(service: Any) { + val method = refreshMethod(service.javaClass) ?: error("No cellular refresh entry point") + if (method.name != "handleMobileDataPreferredUidsChanged") { + method.invoke(service) + return + } + val field = generateSequence(service.javaClass) { it.superclass } + .flatMap { it.declaredFields.asSequence() }.firstOrNull { + it.name == "mMobileDataPreferredUids" && Set::class.java.isAssignableFrom(it.type) + }?.apply { isAccessible = true } ?: error("No cellular preference comparison cache") + val previous = field.get(service) + // Never returned by the getter or passed to the request factory. Native code replaces it + // with the real set before constructing requests. Revert if it fails before replacing it. + val invalidated = java.util.HashSet().apply { add(Int.MIN_VALUE) } + try { + field.set(service, invalidated) + method.invoke(service) + } finally { + if (field.get(service) === invalidated) field.set(service, previous) + } + } +} diff --git a/app/src/main/java/com/multiroute/hook/CellularNetworkSelection.kt b/app/src/main/java/com/multiroute/hook/CellularNetworkSelection.kt new file mode 100644 index 0000000..a87a557 --- /dev/null +++ b/app/src/main/java/com/multiroute/hook/CellularNetworkSelection.kt @@ -0,0 +1,7 @@ +package com.multiroute.hook + +/** Restricts only module-owned requests. The platform still checks capabilities and network scores. */ +internal object CellularNetworkSelection { + fun candidates(target: K, networks: Collection, identity: (T) -> K?): List = + networks.filter { identity(it) == target } +} diff --git a/app/src/main/java/com/multiroute/hook/EffectiveRouteSnapshot.kt b/app/src/main/java/com/multiroute/hook/EffectiveRouteSnapshot.kt new file mode 100644 index 0000000..f7c3473 --- /dev/null +++ b/app/src/main/java/com/multiroute/hook/EffectiveRouteSnapshot.kt @@ -0,0 +1,12 @@ +package com.multiroute.hook + +import com.multiroute.util.RouteRuleBuilder + +/** A published empty snapshot means no effective routes; only absence permits legacy preferences. */ +internal object EffectiveRouteSnapshot { + fun resolve(published: String?, preferences: Map): Map = + if (published != null) RouteRuleBuilder.parseRuleCache(published) + else preferences.filter { (uid, iface) -> + RouteRuleBuilder.isValidUid(uid) && RouteRuleBuilder.isValidInterfaceName(iface) + } +} diff --git a/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt b/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt index 42763cc..df3c4c0 100644 --- a/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt +++ b/app/src/main/java/com/multiroute/hook/MultiRouteModule.kt @@ -65,6 +65,8 @@ class MultiRouteModule : XposedModule() { private var isConnectivityHooked = false @Volatile private var connectivityService: Any? = null private var cellularPreferenceFingerprint: String? = null + private val cellularRequestNetworks = java.util.Collections.synchronizedMap( + java.util.WeakHashMap()) private val isSlaveWifiHooked = AtomicBoolean(false) private val isDualStaHooked = AtomicBoolean(false) @Volatile private var isTetheringHooked = false @@ -364,6 +366,13 @@ class MultiRouteModule : XposedModule() { * ConnectivityService then updates netd and default-network callbacks itself. */ private fun hookCellularDefaultRequests(csClass: Class<*>): Boolean { + if (CellularFrameworkCompat.refreshMethod(csClass) == null) { + log(Log.WARN, TAG, "Cellular preference refresh unsupported; retaining platform defaults") + return false + } + // Subscription selectors alone cannot distinguish two Internet bearers on the same SIM. + // Refuse to install partial pinning if the platform's ranking entry point is unsupported. + if (!hookCellularNetworkRanking(csClass)) return false val factory = csClass.declaredMethods.firstOrNull { it.name == "createNrisFromMobileDataPreferredUids" && it.parameterTypes.size == 1 && Set::class.java.isAssignableFrom(it.parameterTypes[0]) @@ -384,6 +393,8 @@ class MultiRouteModule : XposedModule() { }.getOrNull() ?: return false listOf(factory, createRequest, createNris).forEach { it.isAccessible = true } return try { + csClass.declaredMethods.filter { it.name == "handleMobileDataPreferredUidsChanged" } + .forEach { deoptimize(it) } deoptimize(factory) hook(factory).intercept { chain -> connectivityService = chain.thisObject @@ -396,6 +407,8 @@ class MultiRouteModule : XposedModule() { val groups = CellularDefaultNetworkPolicy.groups(allUids, HashMap(cachedUidRoutes)) for ((iface, uids) in groups) { val agent = findNetworkAgentForChannel(chain.thisObject, iface) ?: continue + val targetNetwork = findNetworkField(agent.javaClass)?.apply { isAccessible = true } + ?.get(agent) as? Network ?: continue val nc = findNetworkCapabilitiesField(agent.javaClass)?.apply { isAccessible = true } ?.get(agent) as? NetworkCapabilities ?: continue if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || @@ -417,6 +430,8 @@ class MultiRouteModule : XposedModule() { val fallback = createRequest.invoke(chain.thisObject, -1, fallbackType) @Suppress("UNCHECKED_CAST") val nris = createNris.invoke(chain.thisObject, uids, listOf(selected, fallback), preference) as Set + // The factory mutates request UID ranges, which also changes its hash code. + cellularRequestNetworks[selected as android.net.NetworkRequest] = targetNetwork result.addAll(nris) pinned.addAll(uids) log(Log.INFO, TAG, "[CellularDefault] $uids -> $iface ($specifier)") @@ -455,11 +470,12 @@ class MultiRouteModule : XposedModule() { ?.apply { isAccessible = true }?.get(it) } as? NetworkCapabilities val specifier = nc?.let { NetworkCapabilities::class.java .getMethod("getNetworkSpecifier").invoke(it) } - "$uid:$iface:$specifier:${nc?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)}" + val network = agent?.let { findNetworkField(it.javaClass)?.apply { isAccessible = true }?.get(it) } + "$uid:$iface:$network:$specifier:${nc?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)}" }.joinToString(";") if (fingerprint != cellularPreferenceFingerprint) { - service.javaClass.getDeclaredMethod("updateMobileDataPreferredUids") - .apply { isAccessible = true }.invoke(service) + // Already on ConnectivityService's Handler, including for the private handler path. + CellularFrameworkCompat.refresh(service) cellularPreferenceFingerprint = fingerprint } } catch (t: Throwable) { @@ -468,6 +484,34 @@ class MultiRouteModule : XposedModule() { } } + /** Filter candidates for our selected request only; fallback and unrelated requests stay native. */ + private fun hookCellularNetworkRanking(csClass: Class<*>): Boolean = try { + val rankerClass = getAllFields(csClass).first { it.name == "mNetworkRanker" }.type + val rank = rankerClass.declaredMethods.first { + it.name == "getBestNetwork" && it.parameterTypes.size == 3 && + it.parameterTypes[0] == android.net.NetworkRequest::class.java && + Collection::class.java.isAssignableFrom(it.parameterTypes[1]) + }.apply { isAccessible = true } + csClass.declaredMethods.filter { it.name == "computeNetworkReassignment" }.forEach { deoptimize(it) } + deoptimize(rank) + hook(rank).intercept { chain -> + val target = cellularRequestNetworks[chain.getArg(0) as android.net.NetworkRequest] + ?: return@intercept chain.proceed() + @Suppress("UNCHECKED_CAST") + val networks = chain.getArg(1) as Collection + fun identity(agent: Any): Network? = findNetworkField(agent.javaClass) + ?.apply { isAccessible = true }?.get(agent) as? Network + val candidates = CellularNetworkSelection.candidates(target, networks, ::identity) + val incumbent = chain.getArg(2)?.takeIf { identity(it) == target } + chain.proceed(arrayOf(chain.getArg(0), candidates, incumbent)) + } + log(Log.INFO, TAG, "Successfully hooked exact cellular network ranking") + true + } catch (t: Throwable) { + log(Log.WARN, TAG, "Exact cellular ranking unsupported; retaining platform defaults", t) + false + } + private fun hookGetDefaultNetworkForUid(csClass: Class<*>): Boolean { val method = csClass.declaredMethods.firstOrNull { it.name == "getDefaultNetworkForUid" && @@ -614,112 +658,39 @@ class MultiRouteModule : XposedModule() { // High-frequency in-memory preference caching in system_server (1.5s TTL) private val prefCacheLock = Any() @Volatile private var lastPrefCacheTime: Long = 0L - private val cachedUidRoutes = ConcurrentHashMap() + @Volatile private var cachedUidRoutes: Map = emptyMap() @Volatile private var cachedCellularUids: Set = emptySet() private val PREF_CACHE_TTL_MS = 1500L - /** While the app has not started yet, poll less often and stay quiet unless the cache changes. */ - private val FALLBACK_CACHE_TTL_MS = 10_000L - @Volatile private var cacheFallbackActive = false - private var lastCacheFileStamp = -1L - private var lastWrittenCacheText: String? = null - private fun reloadPreferencesCacheIfNeeded() { - val now = System.currentTimeMillis() - val ttl = if (cacheFallbackActive) FALLBACK_CACHE_TTL_MS else PREF_CACHE_TTL_MS - if (now - lastPrefCacheTime < ttl) return - + val now = android.os.SystemClock.elapsedRealtime() + if (now - lastPrefCacheTime < PREF_CACHE_TTL_MS) return synchronized(prefCacheLock) { - if (now - lastPrefCacheTime < ttl) return + if (now - lastPrefCacheTime < PREF_CACHE_TTL_MS) return try { - val prefs = getRemotePreferences(PREF_NAME) - val newUidRoutes = mutableMapOf() - - for ((key, value) in prefs.all) { - val channelStr = value as? String ?: continue - val uid = if (key.startsWith("uid_")) { - key.removePrefix("uid_").toIntOrNull() - } else { - key.toIntOrNull() - } - if (uid != null && RouteRuleBuilder.isValidInterfaceName(channelStr)) { - newUidRoutes[uid] = channelStr - } - } - - // Routes actually handed to the hooks: the preferences, or the cached copy while the - // app has not been started in this boot. - var effectiveRoutes: Map = newUidRoutes - - if (newUidRoutes.isEmpty()) { - // Start of a boot: the module app has not been started yet, and LSPosed then returns - // an empty map rather than failing. Fall back to the cache the app publishes on - // every sync, otherwise the hooks would not know any rule for the first ~90s. - // - // This runs on a hot path (every getDefaultNetworkForUid call), so the file is only - // re-read when it actually changed and the transition is logged exactly once - - // otherwise the fallback produced ~50 identical log lines per boot. - val file = java.io.File(RouteRuleBuilder.RULE_CACHE_PATH) - val stamp = if (file.canRead()) file.lastModified() else -1L - effectiveRoutes = if (cacheFallbackActive && stamp == lastCacheFileStamp) { - HashMap(cachedUidRoutes) - } else { - lastCacheFileStamp = stamp - val cached = readRuleCache() - if (cached.isNotEmpty()) { - log(Log.INFO, TAG, "Preferences empty (app not started yet); using cached rule map (${cached.size} entries)") - } else { - log(Log.INFO, TAG, "Preferences empty and no rule cache available yet") - } - cached - } - cacheFallbackActive = true - } else { - if (cacheFallbackActive) { - log(Log.INFO, TAG, "Preferences readable again; dropping the cached-rule fallback") - } - cacheFallbackActive = false - lastCacheFileStamp = -1L - writeRuleCacheIfChanged(newUidRoutes) - } - - cachedUidRoutes.clear() - cachedUidRoutes.putAll(effectiveRoutes) - cachedCellularUids = effectiveRoutes.filterValues { isCellularChannel(it) }.keys.toSet() + val file = java.io.File(RouteRuleBuilder.RULE_CACHE_PATH) + // Never replace an effective scenario/online snapshot with base assignments. A + // present but unreadable file is an error, not permission to resurrect base rules. + val published = if (file.exists()) file.readText() else null + val preferences = if (published == null) { + getRemotePreferences(PREF_NAME).all.mapNotNull { (key, value) -> + val uid = key.removePrefix("uid_").toIntOrNull() + val iface = value as? String + if (uid != null && iface != null) uid to iface else null + }.toMap() + } else emptyMap() + val routes = EffectiveRouteSnapshot.resolve(published, preferences) + cachedUidRoutes = routes + cachedCellularUids = routes.filterValues { isCellularChannel(it) }.keys.toSet() lastPrefCacheTime = now } catch (t: Throwable) { - log(Log.WARN, TAG, "Failed to reload remote preferences in system_server: ${t.message}") + lastPrefCacheTime = now + log(Log.WARN, TAG, "Could not reload effective route snapshot: ${t.message}") } } } - /** Cellular channels are the ones the platform tracks in `mobile_data_preferred_uids`. */ - private fun isCellularChannel(iface: String): Boolean = - iface.startsWith("rmnet") || iface.startsWith("ccmni") || iface == "cellular" - - /** Reads the app-published uid→interface cache; see [RouteRuleBuilder.RULE_CACHE_PATH]. */ - private fun readRuleCache(): Map = try { - val file = java.io.File(RouteRuleBuilder.RULE_CACHE_PATH) - if (file.canRead()) RouteRuleBuilder.parseRuleCache(file.readText()) else emptyMap() - } catch (t: Throwable) { - log(Log.WARN, TAG, "Could not read rule cache: ${t.message}") - emptyMap() - } - - /** Self-heals the cache whenever the preferences were readable and non-empty (only on change). */ - private fun writeRuleCacheIfChanged(uidToIface: Map) { - val text = RouteRuleBuilder.buildRuleCacheText(uidToIface) - if (text == lastWrittenCacheText) return - try { - val file = java.io.File(RouteRuleBuilder.RULE_CACHE_PATH) - file.writeText(text) - file.setReadable(true, false) - lastWrittenCacheText = text - lastCacheFileStamp = file.lastModified() - } catch (t: Throwable) { - log(Log.WARN, TAG, "Could not write rule cache: ${t.message}") - } - } + private fun isCellularChannel(iface: String): Boolean = CellularDefaultNetworkPolicy.isCellular(iface) private fun getTargetChannelForUid(uid: Int): String? { reloadPreferencesCacheIfNeeded() @@ -1293,6 +1264,8 @@ class MultiRouteModule : XposedModule() { val callback = object : android.net.ConnectivityManager.NetworkCallback() { override fun onAvailable(network: android.net.Network) = onLinkChanged() override fun onLost(network: android.net.Network) = onLinkChanged() + override fun onCapabilitiesChanged(network: android.net.Network, capabilities: NetworkCapabilities) = + onLinkChanged() override fun onLinkPropertiesChanged( network: android.net.Network, linkProperties: android.net.LinkProperties @@ -1320,6 +1293,8 @@ class MultiRouteModule : XposedModule() { * debounce is needed because one transition produces several callbacks. */ private fun onLinkChanged() { + // Network identities can change without a UID or subscription change, including without plans. + refreshCellularDefaults() val now = System.currentTimeMillis() if (now - lastScenarioWakeAt < 3000L) return lastScenarioWakeAt = now diff --git a/app/src/main/java/com/multiroute/util/SuHelper.kt b/app/src/main/java/com/multiroute/util/SuHelper.kt index fe73b8c..14c241a 100644 --- a/app/src/main/java/com/multiroute/util/SuHelper.kt +++ b/app/src/main/java/com/multiroute/util/SuHelper.kt @@ -523,7 +523,6 @@ object SuHelper { ) val channelToUidsMap = mutableMapOf>() - val cellularUids = mutableSetOf() val hotspotIface = runCatching { com.multiroute.wifi.DualWifiManager.checkHotspotState(context).iface }.getOrNull() for ((uid, channelId) in uidRules) { @@ -550,46 +549,18 @@ object SuHelper { } channelToUidsMap.getOrPut(channelId) { mutableListOf() }.add(uid) - if (channelId.startsWith("rmnet") || channelId.startsWith("ccmni") || channelId.contains("mobile")) { - cellularUids.add(uid) - } } - // 1. Keep the platform's own "mobile data preferred" list in step with the assignments: add the - // UIDs that are missing and take back the ones this app added earlier, so unassigning an app no - // longer leaves a permanent entry behind. Only UIDs recorded as ours are ever removed; entries - // owned by the system or another tool stay untouched. - val oursMerged = RouteConfigProvider.getMergedCellularUids(context) - val platformUids = RouteRuleBuilder.parseUidList( - runCatching { - Settings.Secure.getString(context.contentResolver, "mobile_data_preferred_uids") - }.getOrDefault("") - ) - val (desiredPlatformUids, ourContribution) = - RouteRuleBuilder.mergeCellularUids(platformUids, cellularUids, oursMerged) - syncMobileDataPreferredUids(context, desiredPlatformUids) - RouteConfigProvider.setMergedCellularUids(context, ourContribution) - // 2. Validate interface route tables val candidateChannels = channelToUidsMap.keys if (candidateChannels.isEmpty()) { - // User explicitly cleared all routing rules: clean up kernel rules, boot script and cache, - // and take this app's UIDs back out of the platform's preferred-mobile-data list. - val ours = RouteConfigProvider.getMergedCellularUids(context) - if (ours.isNotEmpty()) { - val current = runCatching { - Settings.Secure.getString(context.contentResolver, "mobile_data_preferred_uids") - }.getOrDefault("") - syncMobileDataPreferredUids(context, RouteRuleBuilder.parseUidList(current) - ours) - RouteConfigProvider.setMergedCellularUids(context, emptySet()) - Log.i(TAG, "Removed ${ours.size} UID(s) this app had added to mobile_data_preferred_uids") - } - val cleanupScript = RouteRuleBuilder.buildFullSyncScript(emptyMap()) - executeCommand(cleanupScript, timeoutSeconds = RULE_SCRIPT_TIMEOUT_SECONDS) - executeCommand("rm -f /data/adb/service.d/00-multiroute-restore.sh") - executeCommand("rm -f ${RouteRuleBuilder.RULE_CACHE_PATH}") + val success = executeCommand(RouteRuleBuilder.buildFullSyncScript(emptyMap()), + timeoutSeconds = RULE_SCRIPT_TIMEOUT_SECONDS) + if (!success || !updateRuleCache(emptyMap())) return false + syncCellularPreferredUids(context, emptySet()) + val removed = executeCommand("rm -f /data/adb/service.d/00-multiroute-restore.sh") notifyRouteRulesChanged(context) - return true + return removed } // A rule whose table has no default route does not blackhole traffic - the kernel falls through @@ -663,14 +634,18 @@ object SuHelper { val bootScript = RouteRuleBuilder.buildFullSyncScript(bootChannels, connectedPrefixes) val bootSaved = updateBootRestoreScript(bootScript, bootChannels.keys) if (activeChannelMap.isEmpty()) { - updateRuleCache(emptyMap()) + if (!updateRuleCache(emptyMap())) return false Log.w(TAG, "All configured channels are offline; kernel rules cleared, boot script updated with current targets") } else { // The boot script deliberately carries no DNS resolvers: they can change between boots // (different network), and a stale one would break resolution. It flushes the NAT chain // instead, and the app re-applies the redirect with fresh resolvers once it runs. - updateRuleCache(activeChannelMap) + if (!updateRuleCache(activeChannelMap)) return false } + val cellularUids = activeChannelMap.filterKeys { + com.multiroute.hook.CellularDefaultNetworkPolicy.isCellular(it) + }.values.flatten().toSet() + syncCellularPreferredUids(context, cellularUids) // UID membership can stay unchanged while the selected SIM changes. A setting write // alone then emits no observer event, so refresh after publishing the new route cache. notifyRouteRulesChanged(context) @@ -707,35 +682,28 @@ object SuHelper { }.onFailure { Log.w(TAG, "Could not notify system_server of route changes", it) } } - /** - * Publishes the uid→interface map to [RouteRuleBuilder.RULE_CACHE_PATH]. - * - * At the start of every boot, and until this app has been started, LSPosed's RemotePreferences - * return an empty map, so the ConnectivityService hooks cannot see any rule. This cache gives them - * a known-good fallback, and it is refreshed on every successful sync. - */ - private fun updateRuleCache(channelToUidsMap: Map>) { - val uidToIface = mutableMapOf() - for ((iface, uids) in channelToUidsMap) { - if (!RouteRuleBuilder.isValidInterfaceName(iface)) continue - for (uid in uids) uidToIface[uid] = iface - } - val cacheText = RouteRuleBuilder.buildRuleCacheText(uidToIface) - if (cacheText.isEmpty()) { - executeCommand("rm -f ${RouteRuleBuilder.RULE_CACHE_PATH}") - return - } - try { - val cmd = "cat << 'MCROUTE_CACHE_EOF' > ${RouteRuleBuilder.RULE_CACHE_PATH}\n" + - "$cacheText\n" + - "MCROUTE_CACHE_EOF\n" + - "chmod 644 ${RouteRuleBuilder.RULE_CACHE_PATH}" - if (!executeCommand(cmd)) { - Log.w(TAG, "Rule cache update returned a non-zero exit code") - } - } catch (t: Throwable) { - Log.w(TAG, "Failed to update rule cache: ${t.message}") - } + /** Publish only successfully applied, online assignments; an empty file is authoritative. */ + private fun updateRuleCache(channelToUidsMap: Map>): Boolean { + val routes = channelToUidsMap.flatMap { (iface, uids) -> uids.map { it to iface } }.toMap() + val text = RouteRuleBuilder.buildRuleCacheText(routes) + val path = RouteRuleBuilder.RULE_CACHE_PATH + // Root writes a sibling and renames it, so system_server cannot observe a partial snapshot. + val command = "(cat > $path.tmp << 'MCROUTE_CACHE_EOF'\n" + text + + "\nMCROUTE_CACHE_EOF\n) && chmod 644 $path.tmp && mv -f $path.tmp $path" + return executeCommand(command) + } + + private fun syncCellularPreferredUids(context: Context, cellularUids: Set) { + val oursMerged = RouteConfigProvider.getMergedCellularUids(context) + val platformUids = RouteRuleBuilder.parseUidList( + runCatching { + Settings.Secure.getString(context.contentResolver, "mobile_data_preferred_uids") + }.getOrDefault("") + ) + val (desiredPlatformUids, ourContribution) = + RouteRuleBuilder.mergeCellularUids(platformUids, cellularUids, oursMerged) + syncMobileDataPreferredUids(context, desiredPlatformUids) + RouteConfigProvider.setMergedCellularUids(context, ourContribution) } @androidx.annotation.Keep diff --git a/app/src/test/java/com/multiroute/hook/CellularFrameworkCompatTest.kt b/app/src/test/java/com/multiroute/hook/CellularFrameworkCompatTest.kt new file mode 100644 index 0000000..fba203d --- /dev/null +++ b/app/src/test/java/com/multiroute/hook/CellularFrameworkCompatTest.kt @@ -0,0 +1,61 @@ +package com.multiroute.hook + +import org.junit.Assert.* +import org.junit.Test + +class CellularFrameworkCompatTest { + private open class HandlerOnly { + private var mMobileDataPreferredUids: Set = setOf(10596) + var refreshed = false + @Suppress("unused") private fun handleMobileDataPreferredUidsChanged() { + val desired = setOf(10596) + if (desired == mMobileDataPreferredUids) return + mMobileDataPreferredUids = desired + refreshed = true + } + } + private class NewRom : HandlerOnly() + private class OldRom : HandlerOnly() { + @Suppress("unused") fun updateMobileDataPreferredUids() { error("Should prefer handler") } + } + private class ThrowingRom { + private var mMobileDataPreferredUids: Set = emptySet() + @Suppress("unused") private fun handleMobileDataPreferredUidsChanged() { error("Native refresh failed") } + fun cached() = mMobileDataPreferredUids + } + private class LegacyOnly { + var refreshed = false + @Suppress("unused") fun updateMobileDataPreferredUids() { refreshed = true } + } + private class WrongSignature { + @Suppress("unused") fun updateMobileDataPreferredUids(uid: Int) = uid + } + + @Test fun prefersHandlerEvenWhenOldEntryPointExists() { + val rom = OldRom() + CellularFrameworkCompat.refresh(rom) + assertTrue(rom.refreshed) + } + + @Test fun sameUidSetStillRebuildsRequestsWhenTargetChanges() { + val rom = NewRom() + CellularFrameworkCompat.refresh(rom) + assertTrue(rom.refreshed) + } + + @Test fun restoresComparisonCacheWhenNativeRefreshFailsBeforeUpdatingIt() { + val rom = ThrowingRom() + assertThrows(java.lang.reflect.InvocationTargetException::class.java) { CellularFrameworkCompat.refresh(rom) } + assertTrue(rom.cached().isEmpty()) + } + + @Test fun fallsBackToOldEntryWhenHandlerIsAbsent() { + val rom = LegacyOnly() + CellularFrameworkCompat.refresh(rom) + assertTrue(rom.refreshed) + } + + @Test fun unsupportedSignatureIsNotInvoked() { + assertNull(CellularFrameworkCompat.refreshMethod(WrongSignature::class.java)) + } +} diff --git a/app/src/test/java/com/multiroute/hook/CellularNetworkSelectionTest.kt b/app/src/test/java/com/multiroute/hook/CellularNetworkSelectionTest.kt new file mode 100644 index 0000000..d199a79 --- /dev/null +++ b/app/src/test/java/com/multiroute/hook/CellularNetworkSelectionTest.kt @@ -0,0 +1,19 @@ +package com.multiroute.hook + +import org.junit.Assert.assertEquals +import org.junit.Test + +class CellularNetworkSelectionTest { + private data class Agent(val netId: Int, val subId: Int, val iface: String) + + @Test fun identicalSubscriptionSelectorsStillKeepDifferentBearersSeparate() { + val networks = listOf(Agent(101, 2, "rmnet_data2"), Agent(102, 2, "rmnet_data4")) + assertEquals(listOf(networks[1]), CellularNetworkSelection.candidates(102, networks) { it.netId }) + } + + @Test fun reusedInterfaceAndSubscriptionDoNotResurrectADeadNetwork() { + val networks = listOf(Agent(103, 2, "rmnet_data4")) + assertEquals(emptyList(), CellularNetworkSelection.candidates(102, networks) { it.netId }) + assertEquals(networks, CellularNetworkSelection.candidates(103, networks) { it.netId }) + } +} diff --git a/app/src/test/java/com/multiroute/hook/EffectiveRouteSnapshotTest.kt b/app/src/test/java/com/multiroute/hook/EffectiveRouteSnapshotTest.kt new file mode 100644 index 0000000..f2a5df9 --- /dev/null +++ b/app/src/test/java/com/multiroute/hook/EffectiveRouteSnapshotTest.kt @@ -0,0 +1,26 @@ +package com.multiroute.hook + +import org.junit.Assert.assertEquals +import org.junit.Test + +class EffectiveRouteSnapshotTest { + @Test fun scenarioAndOnlineSnapshotWinsOverNonEmptyBaseAssignments() { + val base = mapOf(10596 to "rmnet_data2", 10698 to "rmnet_data2") + assertEquals(mapOf(10596 to "rmnet_data4"), + EffectiveRouteSnapshot.resolve("10596 rmnet_data4\n", base)) + assertEquals(emptyMap(), EffectiveRouteSnapshot.resolve("\n", base)) + } + + @Test fun baseIsOnlyUsedBeforeTheFirstSnapshotExists() { + assertEquals(mapOf(10596 to "rmnet_data2"), EffectiveRouteSnapshot.resolve(null, + mapOf(10596 to "rmnet_data2", 1000 to "rmnet_data2", 10698 to "bad;cmd"))) + } + + @Test fun scenarioCanIntroduceCellularSelectionWithoutChangingTheBase() { + val base = mapOf(10596 to "wlan0") + val effective = EffectiveRouteSnapshot.resolve("10596 rmnet_data4", base) + assertEquals(mapOf("rmnet_data4" to setOf(10596)), + CellularDefaultNetworkPolicy.groups(setOf(10596), effective)) + assertEquals(mapOf(10596 to "wlan0"), base) + } +} From ce35568206dbb05f54fd6eaf8f7fe8794d6dd689 Mon Sep 17 00:00:00 2001 From: Linoleic Date: Fri, 30 Oct 2026 21:08:28 +0800 Subject: [PATCH 5/7] fix(routing): guard cellular IPv6 after route withdrawal --- .../java/com/multiroute/util/RouteRuleBuilder.kt | 16 +++++----------- .../com/multiroute/util/RouteRuleBuilderTest.kt | 4 +++- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt b/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt index 8c9c87b..b651c1f 100644 --- a/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt +++ b/app/src/main/java/com/multiroute/util/RouteRuleBuilder.kt @@ -14,13 +14,8 @@ object RouteRuleBuilder { const val BOOT_LOG_PATH = "/data/adb/multiroute/last_boot_sync.log" /** - * uid→interface cache read by the hook when LSPosed's RemotePreferences cannot be read yet. - * - * Observed on device: while the module app has not been started in the current boot, - * `getRemotePreferences()` returns an *empty* (not failing) map, so the ConnectivityService hooks - * had no idea about the configured rules for the first ~90 seconds of every boot. The app writes - * this file on every sync (via root) and the module also refreshes it whenever it manages to read - * the preferences, so the hook can always fall back to a known-good rule map. + * Effective uid→interface snapshot, published atomically by the app after kernel synchronization. + * Hooks prefer it over base preferences, including an empty snapshot. Only the app writes it. */ const val RULE_CACHE_PATH = "/data/system/multiroute_rules_cache" @@ -143,10 +138,9 @@ object RouteRuleBuilder { commands.add("$IP_BIN rule add uidrange $uid-$uid lookup $iface pref $pref;") commands.add("$IP_BIN -6 rule add uidrange $uid-$uid lookup $iface pref $pref;") if (iface.startsWith("rmnet") || iface.startsWith("ccmni") || iface == "cellular") { - // Fail fast instead of silently falling through to the other SIM's IPv6. - // Re-evaluated on every sync/boot, so acquiring IPv6 restores normal routing. - commands.add("if ! $IP_BIN -6 route show table $iface 2>/dev/null | /system/bin/grep -q '^default'; then " + - "$IP_BIN -6 rule add unreachable uidrange $uid-$uid pref $pref; fi;") + // Keep the guard even while IPv6 works: a later route withdrawal must not let + // this UID fall through to another SIM. A successful lookup above wins first. + commands.add("$IP_BIN -6 rule add unreachable uidrange $uid-$uid pref $pref;") } } } diff --git a/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt b/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt index dd7491b..ee750e8 100644 --- a/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt +++ b/app/src/test/java/com/multiroute/util/RouteRuleBuilderTest.kt @@ -10,7 +10,9 @@ class RouteRuleBuilderTest { @Test fun cellularIpv6FallbackIsScopedToAssignedUidAndRemovedByNormalCleanup() { val commands = RouteRuleBuilder.buildUidRoutingCommands(mapOf("rmnet_data2" to listOf(10596))) assertEquals(3, commands.size) - assertTrue(commands.last().contains("-6 route show table rmnet_data2")) + // Unconditional: a default may exist during sync and disappear before the next sync. + assertFalse(commands.last().contains("route show")) + assertTrue(commands[1].contains("lookup rmnet_data2")) assertTrue(commands.last().contains("rule add unreachable uidrange 10596-10596 pref 14500")) assertFalse(RouteRuleBuilder.buildUidRoutingCommands(mapOf("wlan0" to listOf(10698))) .any { it.contains("unreachable") }) From 9b6fa92dba1a580855034367783f06b32375c700 Mon Sep 17 00:00:00 2001 From: Linoleic Date: Fri, 30 Oct 2026 21:08:28 +0800 Subject: [PATCH 6/7] fix(cellular): acknowledge daemon cleanup before stopping --- .../multiroute/cellular/DualSimController.kt | 7 ++- .../multiroute/cellular/DualSimDaemon.java | 63 ++++++++++++++++--- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/multiroute/cellular/DualSimController.kt b/app/src/main/java/com/multiroute/cellular/DualSimController.kt index 5e96a03..f7ebf7b 100644 --- a/app/src/main/java/com/multiroute/cellular/DualSimController.kt +++ b/app/src/main/java/com/multiroute/cellular/DualSimController.kt @@ -27,8 +27,12 @@ object DualSimController { if (!SuHelper.isRootAvailable()) return@withLock false val running = processes() if (running.size == 1 && running[0].second == selected) return@withLock true + val apk = context.applicationInfo.sourceDir.replace("'", "'\\''") for ((pid, _) in running) { - if (!SuHelper.executeCommand("kill -TERM $pid")) return@withLock false + // Android app_process may exit on SIGTERM without running Java shutdown hooks. + // Ask the daemon to release requests and restore properties before acknowledging. + if (!SuHelper.executeCommand("/system/bin/env CLASSPATH='$apk' /system/bin/app_process /system/bin $ENTRY stop $pid", + timeoutSeconds = 8)) return@withLock false } var attempts = 0 while (attempts++ < 30 && processes().isNotEmpty()) { @@ -36,7 +40,6 @@ object DualSimController { } if (processes().isNotEmpty()) return@withLock false if (selected == 0) return@withLock true - val apk = context.applicationInfo.sourceDir.replace("'", "'\\''") val command = "setsid /system/bin/env CLASSPATH='$apk' /system/bin/app_process /system/bin $ENTRY $selected /dev/null 2>&1 &" if (!SuHelper.executeCommand(command, timeoutSeconds = 5)) return@withLock false delay(1200) diff --git a/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java b/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java index d203e59..7e09bce 100644 --- a/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java +++ b/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java @@ -174,6 +174,18 @@ void refreshSubscriptions() { } public static void main(String[] args) throws Exception { + if (args.length == 2 && args[0].equals("stop")) { + int pid = Integer.parseInt(args[1]); + if (pid <= 0) throw new IllegalArgumentException("Invalid daemon PID"); + try (android.net.LocalSocket client = new android.net.LocalSocket()) { + client.connect(new android.net.LocalSocketAddress("multiroute.dualsim." + pid)); + client.setSoTimeout(5000); + if (client.getPeerCredentials().getUid() != 0) throw new SecurityException("Not our root daemon"); + client.getOutputStream().write(1); + if (client.getInputStream().read() != 1) throw new IllegalStateException("Cleanup not acknowledged"); + } + return; + } if (args.length != 1 || !(args[0].equals("1") || args[0].equals("2"))) { throw new IllegalArgumentException("Expected mode 1 or 2"); } @@ -186,29 +198,60 @@ public static void main(String[] args) throws Exception { Method get = properties.getMethod("get", String.class, String.class); Method set = properties.getMethod("set", String.class, String.class); String key = "ril.multisim.dualdata_status"; - String original = (String) get.invoke(null, key, "2"); + // Preserve an unset/empty value too; inventing "2" changes devices without this property. + String original = (String) get.invoke(null, key, ""); boolean changed = args[0].equals("1") && !original.equals("1"); ConnectivityManager cm = context.getSystemService(ConnectivityManager.class); Session session = new Session(context, cm, args[0].equals("2"), () -> { if (args[0].equals("1")) { try { - if (!"1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, "1"); + if (!"1".equals(get.invoke(null, key, ""))) set.invoke(null, key, "1"); } catch (Exception e) { throw new IllegalStateException("Cannot enable dual data", e); } } }); - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - try { session.close(); } catch (Exception ignored) { } + Runnable cleanup = () -> { + session.close(); try { - if (changed && "1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, original); - } catch (Exception ignored) { } - })); - try { + if (changed && "1".equals(get.invoke(null, key, ""))) set.invoke(null, key, original); + } catch (Exception e) { throw new IllegalStateException("Cannot restore dual data property", e); } + }; + Runtime.getRuntime().addShutdownHook(new Thread(cleanup)); + try (android.net.LocalServerSocket control = new android.net.LocalServerSocket( + "multiroute.dualsim." + android.os.Process.myPid())) { + Thread listener = new Thread(() -> { + while (!session.closed) { + try (android.net.LocalSocket client = control.accept()) { + // The controller invokes the stop command as root. Reject other apps before reading. + if (client.getPeerCredentials().getUid() != 0) continue; + client.setSoTimeout(2000); + if (client.getInputStream().read() != 1) continue; + java.util.concurrent.CountDownLatch done = new java.util.concurrent.CountDownLatch(1); + session.handler.post(() -> { + try { + // Serialize cleanup with subscription retargeting to prevent property re-enablement. + cleanup.run(); + client.getOutputStream().write(1); + } catch (Exception e) { + android.util.Log.e("MultiRouteDualSim", "Controlled cleanup failed", e); + } finally { + done.countDown(); + session.handler.getLooper().quitSafely(); + } + }); + done.await(5, java.util.concurrent.TimeUnit.SECONDS); + return; + } catch (Exception e) { + if (!session.closed) android.util.Log.w("MultiRouteDualSim", "Control request failed", e); + } + } + }, "MultiRouteDualSim-control"); + listener.setDaemon(true); + listener.start(); if (changed) set.invoke(null, key, "1"); session.start(); Looper.loop(); } finally { - try { session.close(); } catch (Exception ignored) { } - if (changed && "1".equals(get.invoke(null, key, "2"))) set.invoke(null, key, original); + cleanup.run(); } } } From b4bbbf2e0e7f1171520e2b032b5b9f3e4b2a2ab8 Mon Sep 17 00:00:00 2001 From: Linoleic Date: Fri, 30 Oct 2026 21:08:28 +0800 Subject: [PATCH 7/7] docs: describe pending cellular routing fixes --- CHANGELOG.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa1ee87..6a3124a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ Release notes are generated from the matching `## vX.Y.Z` section, verbatim. Kee bilingual, Chinese first: the release page is what most users read. --> +## Unreleased + +**中文** + +### 修复 + +- **多蜂窝网络分流**:系统默认网络与 DNS 使用当前生效的场景及在线通道配置;切换目标通道或同一接口的网络重建后刷新对应应用的网络选择。 +- **蜂窝 IPv6 回退**:目标通道丢失 IPv6 路由时阻止流量静默转入另一张 SIM,恢复路由后可继续使用原通道。 +- **副卡通道停用**:正常停用时先释放网络请求并恢复修改前的双卡状态,再退出后台进程。 + +**English** + +### Fixed + +- **Multiple cellular networks:** Use effective scenario and online-channel assignments for per-app default networks and DNS. Refresh selection when the target changes or its Network instance is replaced on the same interface. +- **Cellular IPv6 fallback:** Prevent traffic from silently using another SIM when the selected channel loses its IPv6 route. Resume using the selected channel when its route returns. +- **Secondary cellular shutdown:** Release network requests and restore the previous dual-SIM state before the background process exits during normal shutdown. + ## v1.5.0 - 2026-10-27 **中文**