Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

**中文**
Expand Down
1 change: 1 addition & 0 deletions app/proguard-rules.pro
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 49 additions & 0 deletions app/src/main/java/com/multiroute/cellular/DualSimController.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
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<Pair<Int, Int>> =
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
val apk = context.applicationInfo.sourceDir.replace("'", "'\\''")
for ((pid, _) in running) {
// 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()) {
delay(100)
}
if (processes().isNotEmpty()) return@withLock false
if (selected == 0) return@withLock true
val command = "setsid /system/bin/env CLASSPATH='$apk' /system/bin/app_process /system/bin $ENTRY $selected </dev/null >/dev/null 2>&1 &"
if (!SuHelper.executeCommand(command, timeoutSeconds = 5)) return@withLock false
delay(1200)
processes().singleOrNull()?.second == selected
}
}
}
257 changes: 257 additions & 0 deletions app/src/main/java/com/multiroute/cellular/DualSimDaemon.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
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<ConnectivityManager.NetworkCallback> 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<SubscriptionInfo> subs = subscriptions.getActiveSubscriptionInfoList();
java.util.ArrayList<Integer> 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 == 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");
}
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";
// 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, ""))) set.invoke(null, key, "1");
} catch (Exception e) { throw new IllegalStateException("Cannot enable dual data", e); }
}
});
Runnable cleanup = () -> {
session.close();
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 {
cleanup.run();
}
}
}
Original file line number Diff line number Diff line change
@@ -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>): Int =
if (defaultId >= 0 && defaultId in activeIds) activeIds.distinct().filter { it != defaultId }.singleOrNull() ?: -1 else -1

}
Original file line number Diff line number Diff line change
@@ -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<Int>, routes: Map<Int, String>): Map<String, Set<Int>> =
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() }
}
Loading
Loading