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
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,33 @@
# Changelog

## SimBridge 2.5.0

Update both apps. Pairing is kept.

### Main phone
- **No more doubled texts:** every text from the SIM phone carries an id, and a resend of one that
already arrived is dropped (ideas from SMS Gateway for Android's message ids).
- **Rules and spam filter** (Settings > Messages): per sender, keyword or SIM choose *always alert*,
*silent*, *archive* or *block*. Unknown promotions with links go to Archived.
- **Quiet hours with VIP contacts** (Settings > Calls): texts stay silent and calls don't ring at
night, except for the people you pick.
- **App notifications from the SIM phone** (Dashboard > Controls): pick apps such as your bank;
their notifications arrive as messages.
- **Suggested replies** in a chat (full build, made on the phone).
- **Fingerprint lock** for remote screen, USSD and switches, and a **history** of what was changed
on the SIM phone (Settings > App).
- **Encrypted backups:** set a password when exporting (AES-256-GCM); rules, quiet hours, VIP list
and swipe choices are included now.
- **Charge limit** (80–95 %) and **daily report** switches on the dashboard.

### SIM phone (gateway)
- Resends can't run twice when the main phone registers twice in a row.
- **Hotspot works while on Wi-Fi:** it leaves Wi-Fi and tries again.
- **Watchdog:** restarts itself after a crash or when the system stops it, and tells the main phone.
- **Daily report** at 9:00: battery, signal, data used, anything waiting.
- **Audit log** of remote changes, and **app notification forwarding** (notification access is
granted through Shizuku).

## SimBridge 2.4.0

Update both apps. Pairing is kept.
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ main phone only ever uses Wi-Fi. See the [disclaimer](DISCLAIMER.md).
| 🎧 **HD voice** | 16 kHz wideband audio between the phones (L16), falling back to normal phone quality (G.711) when needed. |
| 🔒 **Encrypted and paired** | Pair once by scanning a QR code. Signalling runs over **TLS** pinned to the SIM phone's key, audio over **SRTP**, and every call or text needs the paired password. Mobile-data and internet addresses are refused. |
| 💬 **Texts, pictures and group chats** | A Google Messages-style app: conversations, contact photos, bubbles, notifications with **Reply** and **Mark as read**, **Sent / Delivered** reports, picture messages (MMS) and **group texts**. |
| 🧹 **Rules, spam filter, quiet hours** | Choose who always alerts, stays silent, is archived or blocked; promotions go to Archived; quiet hours let only VIP contacts through. |
| 🔔 **App notifications from the SIM phone** | Your bank or carrier app on the SIM phone? Its notifications arrive as messages on the main phone. |
| 🛡️ **Watchdog, daily report, charge limit** | The gateway restarts itself after a crash, sends a morning health text, and can stop charging at 80–95 %. |
| 👆 **Swipe, select, pin, archive, search** | Swipe a conversation (you choose what each direction does), select several for one action, pin, archive, star, search inside messages, tap links and phone numbers, and **send later** by holding Send. |
| 📥 **System SMS integration (optional)** | Make SimBridge the **default SMS app**: "Message" buttons in Contacts and other apps open it, the Phone app's *Reply with message* sends through the SIM, and texts are saved to Android's SMS database. Or keep Google Messages as default and just copy relayed texts into it (read-only). |
| 📵 **Missed calls while offline** | Calls the SIM phone gets while the main phone is out of reach are added to the Phone app's history with a *Call back* notification. |
Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ android {
applicationId = "io.github.simbridge.gateway"
minSdk = 30
targetSdk = 36
versionCode = 450
versionName = "2.4.0"
versionCode = 460
versionName = "2.5.0"
// Filter all transitive JNI libraries as well as PJSIP's own module outputs.
ndk {
//abiFilters += listOf("arm64-v8a", "x86_64")
Expand Down
10 changes: 10 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,16 @@
</intent-filter>
</receiver>
<receiver android:name=".MmsResultReceiver" android:exported="false" />
<receiver android:name=".GatewayWatchdog" android:exported="false" />
<service
android:name=".AppNotifications"
android:exported="true"
android:label="SimBridge"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<service
android:name=".RespondViaMessageService"
android:exported="true"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package io.github.sparkcyf.voicesipagent.app

import android.app.Notification
import android.content.Context
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification

/**
* Forwards the notifications of apps you pick (a bank or carrier app that only runs on this
* phone) to the main phone, where each app gets its own conversation. Needs notification access,
* which the gateway grants itself through Shizuku.
*/
class AppNotifications : NotificationListenerService() {
private val recent = LinkedHashMap<String, Long>()

override fun onNotificationPosted(sbn: StatusBarNotification) {
val pkg = sbn.packageName
if (pkg !in chosen(this)) return
val n = sbn.notification
if (n.flags and (Notification.FLAG_ONGOING_EVENT or Notification.FLAG_GROUP_SUMMARY) != 0) return
val e = n.extras
val title = e.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
val text = (e.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: e.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty()
if (title.isBlank() && text.isBlank()) return
val body = listOf(title, text).filter { it.isNotBlank() }.joinToString("\n")
// Apps re-post the same notification when it updates; send each text once per 10 minutes.
val now = System.currentTimeMillis()
synchronized(recent) {
val k = "$pkg|$body"
if ((recent[k] ?: 0) > now - 600_000) return
recent[k] = now
while (recent.size > 100) recent.remove(recent.keys.first())
}
val label = runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(pkg, 0)).toString() }.getOrDefault(pkg)
GatewayRuntime.get(this).forwardAppNotification(label, body)
}

companion object {
private const val PREFS = "control"
fun chosen(c: Context): Set<String> = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet("notif_apps", emptySet()).orEmpty()
fun choose(c: Context, apps: Set<String>) = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet("notif_apps", apps).apply()
const val COMPONENT = "io.github.simbridge.gateway/io.github.sparkcyf.voicesipagent.app.AppNotifications"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,47 @@ import android.app.Application
class GatewayApp : Application() {
override fun onCreate() {
super.onCreate()
installWatchdog()
// Telecom may start our process just to bind the InCallService, so the runtime (and with
// it the CellularEndpoint) must exist before any activity or service runs.
GatewayRuntime.get(this).start()
GatewayService.start(this)
}

/**
* On a crash, ask the system to start us again in 5 s and note it, so the main phone is told.
* Samsung's battery manager can also kill the process; the foreground service and the boot
* receiver bring it back, and [GatewayWatchdog] checks every 15 minutes.
*/
private fun installWatchdog() {
val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { t, e ->
runCatching {
getSharedPreferences("control", MODE_PRIVATE).edit().putBoolean("crashed", true).commit()
val pi = android.app.PendingIntent.getService(this, 7, android.content.Intent(this, GatewayService::class.java),
android.app.PendingIntent.FLAG_IMMUTABLE or android.app.PendingIntent.FLAG_UPDATE_CURRENT)
getSystemService(android.app.AlarmManager::class.java)
.set(android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP, android.os.SystemClock.elapsedRealtime() + 5000, pi)
}
previous?.uncaughtException(t, e)
}
GatewayWatchdog.schedule(this)
}
}

/** Every 15 minutes (even in Doze, with an inexact alarm) makes sure the gateway service runs. */
class GatewayWatchdog : android.content.BroadcastReceiver() {
override fun onReceive(c: android.content.Context, i: android.content.Intent) {
GatewayService.start(c)
schedule(c)
}

companion object {
fun schedule(c: android.content.Context) {
val pi = android.app.PendingIntent.getBroadcast(c, 8, android.content.Intent(c, GatewayWatchdog::class.java),
android.app.PendingIntent.FLAG_IMMUTABLE or android.app.PendingIntent.FLAG_UPDATE_CURRENT)
c.getSystemService(android.app.AlarmManager::class.java).setAndAllowWhileIdle(
android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP, android.os.SystemClock.elapsedRealtime() + 15 * 60_000L, pi)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,24 @@ import org.json.JSONObject
* events this phone reports (missed and blocked calls, SMS delivery). Events wait in a small
* persistent queue while no phone is registered.
*/
/** Control operations that change something on this phone; each is written to the [Audit] log. */
private val AUDITED = setOf("control", "ussd", "ussd-reply", "screen-start", "network-mode", "apn-select", "apn-add", "sms-app",
"at-place", "charge-limit", "locate", "block-rules", "voicemail")

/** Who changed what on this phone, and when (the last 200 entries). */
object Audit {
private const val MAX = 200
@Synchronized fun note(ctx: android.content.Context, what: String, from: String?) {
val p = ctx.getSharedPreferences("audit", android.content.Context.MODE_PRIVATE)
val a = runCatching { JSONArray(p.getString("log", "[]")) }.getOrDefault(JSONArray())
a.put(JSONObject().put("t", System.currentTimeMillis()).put("what", what).put("from", from ?: ""))
while (a.length() > MAX) a.remove(0)
p.edit().putString("log", a.toString()).apply()
}
@Synchronized fun recent(ctx: android.content.Context): JSONArray =
runCatching { JSONArray(ctx.getSharedPreferences("audit", android.content.Context.MODE_PRIVATE).getString("log", "[]")) }.getOrDefault(JSONArray())
}

class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {
private val prefs = app.getSharedPreferences("control", Context.MODE_PRIVATE)
private val main = Handler(Looper.getMainLooper())
Expand All @@ -34,7 +52,24 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {

fun handle(json: String, from: java.net.InetSocketAddress? = null) {
val o = runCatching { JSONObject(json) }.getOrNull() ?: return
when (o.optString("op")) {
val op = o.optString("op")
if (op in AUDITED) Audit.note(app, op + (o.optString("action").ifBlank { "" }.let { if (it.isEmpty()) "" else " $it" }) +
(if (o.has("on")) (if (o.optBoolean("on")) " on" else " off") else ""), from?.address?.hostAddress)
when (op) {
"apps" -> rt.worker { send(JSONObject().put("op", "apps").put("list", launchableApps()).put("chosen", JSONArray(AppNotifications.chosen(app).toList())), from) }
"notif-apps" -> rt.worker {
val set = (o.optJSONArray("list") ?: JSONArray()).let { a -> (0 until a.length()).map { a.getString(it) }.toSet() }
AppNotifications.choose(app, set)
// Notification access, granted through Shizuku (same as a tap in Settings).
if (set.isNotEmpty()) privilegedRaw("notif-access", AppNotifications.COMPONENT)
send(JSONObject().put("op", "control-result").put("action", "notif-apps").put("ok", true), from)
}
"audit" -> send(JSONObject().put("op", "audit").put("list", Audit.recent(app)), from)
"charge-limit" -> rt.worker {
privileged("charge-limit", o.optString("value", "off"))
send(status(), from)
}
"report" -> prefs.edit().putBoolean("daily_report", o.optBoolean("on", true)).apply()
"status" -> send(status(), from)
"ussd" -> ussd(o.optString("code"), o.optInt("sim", 0).takeIf { it > 0 }, from)
"ussd-reply" -> rt.worker { ussdReply("", privilegedRaw("ussd-reply", o.optString("text").take(40)), from) }
Expand Down Expand Up @@ -88,8 +123,14 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {
}

/** A relayed text that no phone confirmed. */
fun keepSms(from: String?, text: String, sim: Int?) =
keep(JSONObject().put("op", "__sms").put("from", from ?: "").put("text", text).apply { sim?.let { put("sim", it) } }, false)
fun keepSms(from: String?, text: String, sim: Int?, id: String) =
keep(JSONObject().put("op", "__sms").put("from", from ?: "").put("text", text).put("id", id).apply { sim?.let { put("sim", it) } }, false)

fun keepApp(app: String, text: String, id: String) =
keep(JSONObject().put("op", "__sms").put("from", "app").put("name", app).put("text", text).put("id", id), false)

/** Queue entries being sent right now: two registrations a second apart must not send them twice. */
private val inFlight = java.util.Collections.synchronizedSet(HashSet<Long>())

private fun keep(o: JSONObject, big: Boolean) {
if (big) { queueBig(o); return }
Expand Down Expand Up @@ -151,13 +192,19 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {
for (i in 0 until q.length()) {
val o = q.getJSONObject(i)
val qid = o.optLong("qid")
if (!inFlight.add(qid)) continue
if (o.optString("op") == "__sms") {
val from = o.optString("from").ifBlank { null }
ua.sendMessage(from, o.optString("text"), ContactNames.lookup(app, from),
io.github.sparkcyf.voicesipagent.sip.TextMeta(sim = o.optInt("sim", 0).takeIf { it > 0 })) { ok -> if (ok) unqueue(qid) }
val sent = ua.sendMessage(from, o.optString("text"), o.optString("name").ifBlank { null } ?: ContactNames.lookup(app, from),
io.github.sparkcyf.voicesipagent.sip.TextMeta(ref = o.optString("id").ifBlank { null }, sim = o.optInt("sim", 0).takeIf { it > 0 })) { ok ->
if (ok) unqueue(qid)
inFlight.remove(qid)
}
if (!sent) inFlight.remove(qid)
} else {
val body = JSONObject(o.toString()).apply { remove("qid") }.toString()
ua.sendControl(body) { code -> if (code in 200..299) unqueue(qid) }
val sent = ua.sendControl(body) { code -> if (code in 200..299) unqueue(qid); inFlight.remove(qid) }
if (!sent) inFlight.remove(qid)
}
}
java.io.File(app.filesDir, "outbox").listFiles()?.sortedBy { it.name }?.forEach { f ->
Expand Down Expand Up @@ -206,6 +253,8 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {
o.put("uptimeMin", SystemClock.elapsedRealtime() / 60_000)
o.put("version", runCatching { app.packageManager.getPackageInfo(app.packageName, 0).versionName }.getOrNull() ?: "")
o.put("hotspot", hotspotOn())
privilegedRaw("charge-limit-get", "").takeUnless { it.startsWith("error") }?.let { o.put("chargeLimit", it) }
o.put("dailyReport", prefs.getBoolean("daily_report", true))
o.put("smsApp", MmsGateway.isDefaultSmsApp(app))
o.put("noAnswerSec", noAnswerSec)
if (hasPhoneState()) runCatching { app.getSystemService(TelephonyManager::class.java).voiceMailNumber }.getOrNull()?.let { o.put("voicemail", it) }
Expand Down Expand Up @@ -386,6 +435,44 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {
return runCatching { svc.remoteAction(action, arg) }.getOrElse { "error: ${it.message}" }
}

/** Apps with a launcher icon on this phone: package and name, sorted by name. */
private fun launchableApps(): JSONArray {
val pm = app.packageManager
val i = android.content.Intent(android.content.Intent.ACTION_MAIN).addCategory(android.content.Intent.CATEGORY_LAUNCHER)
return JSONArray().apply {
pm.queryIntentActivities(i, 0).map { it.activityInfo.packageName to it.loadLabel(pm).toString() }
.distinctBy { it.first }.filter { it.first != app.packageName }.sortedBy { it.second.lowercase() }
.forEach { (p, l) -> put(JSONObject().put("pkg", p).put("name", l)) }
}
}

// ------------------------------------------------------------ daily report

/** Once a day (9:00) a short health text: battery, signal, data used, texts kept for later. */
private fun scheduleReport() {
val c = java.util.Calendar.getInstance().apply {
set(java.util.Calendar.HOUR_OF_DAY, 9); set(java.util.Calendar.MINUTE, 0); set(java.util.Calendar.SECOND, 0)
if (timeInMillis <= System.currentTimeMillis()) add(java.util.Calendar.DAY_OF_YEAR, 1)
}
main.postDelayed({ rt.worker { runCatching { sendReport() }; scheduleReport() } }, c.timeInMillis - System.currentTimeMillis())
}

private fun sendReport() {
if (!prefs.getBoolean("daily_report", true)) return
val s = status()
val lines = mutableListOf("📋 SIM phone daily report")
if (s.has("battery")) lines += "Battery ${s.optInt("battery")} %" + (if (s.optBoolean("charging")) ", charging" else "") +
(s.optString("chargeLimit").takeIf { it.isNotEmpty() && it != "off" }?.let { ", stops at $it %" } ?: "")
s.optJSONArray("sims")?.let { a -> for (i in 0 until a.length()) a.getJSONObject(i).let { sim ->
lines += "SIM ${i + 1}: " + listOf(sim.optString("carrier"), sim.optString("network"), sim.optInt("level", -1).let { if (it < 0) "" else "signal $it/4" })
.filter { it.isNotBlank() }.joinToString(", ")
} }
if (s.has("dataToday")) lines += "Mobile data today: ${android.text.format.Formatter.formatShortFileSize(app, s.optLong("dataToday"))}, this month ${android.text.format.Formatter.formatShortFileSize(app, s.optLong("dataMonth"))}"
val kept = runCatching { JSONArray(prefs.getString("queue", "[]")).length() }.getOrDefault(0)
if (kept > 0) lines += "$kept items waiting for the main phone"
rt.alerts.post(lines.joinToString("\n"))
}

// ------------------------------------------------------------ remote screen

/** Opens the encrypted screen stream socket and tells the phone where and with which key. */
Expand Down Expand Up @@ -428,6 +515,11 @@ class GatewayControl(private val app: Context, private val rt: GatewayRuntime) {

/** Called once when the gateway starts. */
fun start() {
scheduleReport()
if (prefs.getBoolean("crashed", false)) {
prefs.edit().putBoolean("crashed", false).apply()
rt.alerts.post("♻️ SimBridge on the SIM phone stopped unexpectedly and restarted itself.")
}
watchWifiLoss()
// After a restart away from every saved place: make sure the main phone can reach us.
main.postDelayed({ rt.worker { hotspotIfNoWifi("started without Wi-Fi") } }, 45_000)
Expand Down
Loading
Loading