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..d203e59 --- /dev/null +++ b/app/src/main/java/com/multiroute/cellular/DualSimDaemon.java @@ -0,0 +1,214 @@ +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; +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()); + } + } + + // 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"); + } + 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); + 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); + 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 { 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"); + 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); + } + } +} 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/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/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))) + } +} 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