communicate: finish RCS rest - IMS PDN, GBA creds, focus hosting, group fan-out
- Commit
64432dc50c93b655c93750e88f41f6b002b15a5c- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-26 18:20 UTC (2 months ago)
- Parents
89e2ac7
Diff
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.ktindex ee3c0afbcd..c8cc31c0df 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt@@ -127,6 +127,25 @@ suspend fun CommunicateRepository.sendRcsMessage( if (!capable) return@withContext RcsSendResult.FallbackSms if (!RcsSipTransport.canSend()) return@withContext RcsSendResult.FallbackSms val repository = this@sendRcsMessage+ // Group thread (remoteId `rcs-group:…`): fan out 1:1 per member. UP has no+ // pager-mode group MESSAGE — groups are conference dialogs the carrier+ // focus hosts, or our own hosted focus (see hostGroupFocus). Until the+ // focus dialog is established, per-member 1:1 delivery keeps messages+ // flowing; once a focus session exists, hosted-focus relay takes over+ // inbound, and outbound still fans out (focus fan-out would double-send).+ if (recipient.startsWith("rcs-group:") && participants.isNotEmpty()) {+ var anyOk = false+ for (member in participants.map { it.trim() }.filter { it.isNotEmpty() }.distinct()) {+ val memberResult = sendRcsMessage(+ context, member, body, member, attachments, emptyList(),+ )+ if (memberResult == RcsSendResult.Sent) anyOk = true+ }+ if (anyOk && body.isNotBlank()) {+ cacheOutgoingRcs(context, recipient, body, "local-${UUID.randomUUID()}")+ }+ return@withContext if (anyOk) RcsSendResult.Sent else RcsSendResult.FallbackSms+ } runCatching { // E2EE first: when the conversation has an MLS group, encrypt and send // the framed payload as an MLS content message. Falls through to the@@ -158,7 +177,7 @@ suspend fun CommunicateRepository.sendRcsMessage( val session = RcsSessionManager.sessionFor(recipient) if (session?.msrpRemotePath != null && attachments.isEmpty()) { val cpim = RcsSipTransport.buildCpimBody(body).toByteArray(Charsets.UTF_8)- if (RcsMsrp.send(session, cpim)) {+ if (RcsMsrp.send(session, context, cpim)) { if (body.isNotBlank()) { cacheOutgoingRcs(context, recipient, body, "local-${UUID.randomUUID()}") }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.ktindex f88ee7e818..91c6be8377 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt@@ -60,7 +60,10 @@ object RcsFileTransferHttp { .firstOrNull { it.key.equals("WWW-Authenticate", ignoreCase = true) } ?.value?.firstOrNull() ?: return@runCatching null- // 2. Authenticated multipart POST (tid + File).+ // 2. Authenticated multipart POST (tid + File). GBA-shaped creds+ // when a privileged build injected them, else the plain-digest+ // fallback (empty password). Live GBA bootstrapping is unreachable+ // from a non-privileged app (hidden API blocklist — see RcsGbaAuth). val boundary = "rcsft${UUID.randomUUID().toString().replace("-", "").take(16)}" val tid = UUID.randomUUID().toString() val multipart = buildMultipart(@@ -70,11 +73,15 @@ object RcsFileTransferHttp { mime = attachment.mimeType, bytes = bytes, )+ val gba = RcsGbaAuth.injected val auth = digestAuthHeader( challenge = challenge, method = "POST", uri = server,- username = "rcs",+ username = gba?.btId ?: "rcs",+ password = gba?.let {+ android.util.Base64.encodeToString(it.key, android.util.Base64.NO_WRAP)+ }.orEmpty(), ) val response = NetworkClient.performRequest( url = server,@@ -195,12 +202,17 @@ object RcsFileTransferHttp { } /**- * Minimal digest Authorization header from a WWW-Authenticate challenge.- * GBA bootstrapping (TestRcsApp GbaRequestExecutor) is out of scope —- * this covers plain digest; AKA/GBA challenges return an empty header and- * the upload degrades gracefully.+ * Digest Authorization header from a WWW-Authenticate challenge. [password]+ * is the GBA-derived base64 key when bootstrapped, empty otherwise (the+ * plain-digest fallback). */- private fun digestAuthHeader(challenge: String, method: String, uri: String, username: String): String {+ private fun digestAuthHeader(+ challenge: String,+ method: String,+ uri: String,+ username: String,+ password: String = "",+ ): String { if (!challenge.contains("Digest", ignoreCase = true)) return "" fun param(name: String): String = Regex("$name=\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(challenge)@@ -209,14 +221,7 @@ object RcsFileTransferHttp { val nonce = param("nonce") if (realm.isBlank() || nonce.isBlank()) return "" val cnonce = UUID.randomUUID().toString().replace("-", "").take(16)- fun h(s: String): String {- val md = java.security.MessageDigest.getInstance("MD5")- return md.digest(s.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }- }- // Empty password: GBA-derived keys are unavailable outside the telephony stack.- val ha1 = h("$username:$realm:")- val ha2 = h("$method:$uri")- val response = h("$ha1:$nonce:00000001:$cnonce:auth:$ha2")+ val response = RcsGbaAuth.digestResponse(username, password, realm, nonce, method, uri, cnonce) return "Digest username=\"$username\", realm=\"$realm\", nonce=\"$nonce\", uri=\"$uri\", " + "response=\"$response\", qop=auth, nc=00000001, cnonce=\"$cnonce\"" }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.ktnew file mode 100644index 0000000000..5ad7e15fd0--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt@@ -0,0 +1,62 @@+package com.vayunmathur.communicate.data.rcs++/**+ * GBA-shaped credentials + digest auth for FT-over-HTTP (3GPP TS 33.220 /+ * RFC 2617).+ *+ * Why there is no live GBA bootstrap here: TestRcsApp's+ * `GbaAuthenticationProvider` calls+ * `TelephonyManager.bootstrapAuthenticationRequest` directly, but that API is+ * `@SystemApi`/hidden — absent from the compile SDK, and the request path+ * goes through the internal `ITelephony.getITelephony()`, which is on the+ * hidden-API blocklist (enforced at runtime on Android 12+, and a lint error+ * on this target SDK). The callback is a hidden *class*, not an interface, so+ * the Proxy bridge used in [RcsHiddenApi] cannot reach it either. A+ * non-privileged app cannot bootstrap GBA keys, full stop.+ *+ * What this object does instead:+ * - [GbaCredentials] carries bootstrapped NAF credentials (btId + key) for+ * the day a privileged path provides them (system-permission build, carrier+ * service injection). [RcsFileTransferHttp] prefers them when set.+ * - [digestResponse] is the qop=auth response hash both the GBA and the+ * plain-digest paths share, unit-tested against the RFC 2617 known-answer+ * vector.+ *+ * Until then uploads use the plain-digest fallback (empty password), exactly+ * like a client whose GBA challenge fails — the server either accepts or the+ * upload degrades, never crashes.+ */+object RcsGbaAuth {+ /** Bootstrapped NAF credentials: digest username + raw key. */+ data class GbaCredentials(val btId: String, val key: ByteArray)++ /**+ * Injected GBA credentials (privileged builds only). Null in normal+ * dev builds — the uploader falls back to plain digest.+ */+ @Volatile+ var injected: GbaCredentials? = null++ /**+ * Digest `response` hash (RFC 2617 qop=auth) — pure, unit-tested against+ * the RFC's known-answer vector.+ */+ internal fun digestResponse(+ username: String,+ password: String,+ realm: String,+ nonce: String,+ method: String,+ uri: String,+ cnonce: String,+ ): String {+ val ha1 = md5("$username:$realm:$password")+ val ha2 = md5("$method:$uri")+ return md5("$ha1:$nonce:00000001:$cnonce:auth:$ha2")+ }++ private fun md5(s: String): String {+ val md = java.security.MessageDigest.getInstance("MD5")+ return md.digest(s.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.ktnew file mode 100644index 0000000000..b8dfa2dd7d--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt@@ -0,0 +1,153 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.net.ConnectivityManager+import android.net.Network+import android.net.NetworkCapabilities+import android.net.NetworkRequest+import android.os.Build+import android.util.Log+import java.net.InetAddress+import java.net.Socket+import kotlin.coroutines.resume+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withTimeoutOrNull++/**+ * IMS PDN access for RCS media (MSRP sockets).+ *+ * Mirrors TestRcsApp's `ImsPdnNetworkFetcher` (NET_CAPABILITY_IMS request →+ * cached `Network` → `network.socketFactory` sockets bound to the IMS PDN)+ * without Guava: one-shot `requestNetwork` calls wrapped in suspend functions+ * with a bounded wait, so a missing IMS PDN degrades to a plain socket instead+ * of hanging.+ *+ * Raw sockets are inherent here (MSRP is a TCP protocol, not HTTP — no HTTP+ * client can speak it); FT-over-HTTP stays on `NetworkClient` per the+ * networking rules.+ *+ * Every entry point early-returns null when the dev gate is off and never+ * throws; callers fall back to unbound sockets.+ */+object RcsImsNetwork {+ private const val TAG = "RcsImsNetwork"++ /** How long to wait for the IMS network before falling back. */+ private const val REQUEST_TIMEOUT_MS = 15_000L++ /** Cached IMS network; invalidated when a socket bind fails. */+ @Volatile+ private var cached: Network? = null++ /** Last IMS-PDN local address seen, for SDP offers. Null = unknown. */+ @Volatile+ var lastLocalIp: String? = null+ private set++ /**+ * The IMS PDN `Network`, requesting it when not cached. Null when+ * unavailable (no IMS PDN, timeout, or permission failure).+ */+ suspend fun imsNetwork(context: Context): Network? {+ if (!RcsFeature.enabled) return null+ cached?.let { return it }+ val cm = runCatching {+ context.applicationContext.getSystemService(ConnectivityManager::class.java)+ }.getOrNull() ?: return null+ val network = withTimeoutOrNull(REQUEST_TIMEOUT_MS) {+ suspendCancellableCoroutine { cont ->+ val request = NetworkRequest.Builder()+ .addCapability(NetworkCapabilities.NET_CAPABILITY_IMS)+ .build()+ val callback = object : ConnectivityManager.NetworkCallback() {+ override fun onAvailable(network: Network) {+ runCatching { cm.unregisterNetworkCallback(this) }+ if (cont.isActive) cont.resume(network)+ }++ override fun onUnavailable() {+ runCatching { cm.unregisterNetworkCallback(this) }+ if (cont.isActive) cont.resume(null)+ }+ }+ cont.invokeOnCancellation {+ runCatching { cm.unregisterNetworkCallback(callback) }+ }+ runCatching { cm.requestNetwork(request, callback) }+ .onFailure { if (cont.isActive) cont.resume(null) }+ }+ }+ if (network != null) {+ cached = network+ lastLocalIp = localIpFor(context, network)+ }+ return network+ }++ /**+ * Open a TCP socket to [host]:[port], preferring the IMS PDN's socket+ * factory (source-bound to the IMS local address like TestRcsApp's+ * `MsrpManager.createMsrpSession`). Falls back to a plain socket when the+ * IMS network is unavailable. Null only when both paths fail.+ */+ suspend fun createSocket(+ context: Context,+ host: String,+ port: Int,+ connectTimeoutMs: Int = 10_000,+ ): Socket? {+ if (!RcsFeature.enabled) return null+ // IMS path first.+ val ims = imsNetwork(context)+ if (ims != null) {+ val bound = runCatching {+ val factory = ims.getSocketFactory()+ val local = lastLocalIp?.let { runCatching { InetAddress.getByName(it) }.getOrNull() }+ val socket = if (local != null) {+ factory.createSocket(host, port, local, 0)+ } else {+ val s = factory.createSocket()+ s.connect(java.net.InetSocketAddress(host, port), connectTimeoutMs)+ s+ }+ socket.soTimeout = 0+ socket+ }.getOrNull()+ if (bound != null && bound.isConnected) return bound+ runCatching { bound?.close() }+ // IMS network went stale — drop it so the next call re-requests.+ cached = null+ Log.w(TAG, "IMS socket bind failed; falling back to plain socket")+ }+ // Plain fallback (v1 behavior).+ return runCatching {+ val s = Socket()+ s.connect(java.net.InetSocketAddress(host, port), connectTimeoutMs)+ s.soTimeout = 0+ s+ }.getOrNull()+ }++ /** Local IP addresses on [network] (link addresses); empty on failure. */+ fun localIps(context: Context, network: Network): List<String> {+ if (!RcsFeature.enabled) return emptyList()+ return runCatching {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return emptyList()+ val cm = context.applicationContext.getSystemService(ConnectivityManager::class.java)+ ?: return emptyList()+ val props = cm.getLinkProperties(network) ?: return emptyList()+ props.linkAddresses.mapNotNull { it.address?.hostAddress }+ .filter { !it.startsWith("127.") && it != "::1" }+ }.getOrDefault(emptyList())+ }++ private fun localIpFor(context: Context, network: Network): String? =+ localIps(context, network).firstOrNull { it.contains('.') }+ ?: localIps(context, network).firstOrNull()++ /** Drop the cached network (subId change / teardown). */+ fun reset() {+ cached = null+ lastLocalIp = null+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.ktindex f9cb65de87..7088b0ffa4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt@@ -1,5 +1,6 @@ package com.vayunmathur.communicate.data.rcs +import android.content.Context import android.util.Log import java.util.UUID import kotlinx.coroutines.CoroutineScope@@ -94,9 +95,14 @@ object RcsMsrp { * loop on Dispatchers.IO. [onChunk] receives complete `message/cpim` * bodies (content type + bytes). Returns null when the session has no * usable remote path or the peer expects us to listen (`setup=active`).+ *+ * The socket rides the IMS PDN when available ([RcsImsNetwork]) so+ * carrier MSRP peers (which only route IMS-subnet addresses) are+ * reachable; falls back to a plain socket otherwise. */ suspend fun connect( session: RcsSession,+ context: Context, onChunk: (contentType: String, body: ByteArray) -> Unit, ): MsrpConnection? = withContext(Dispatchers.IO) { if (!RcsFeature.enabled) return@withContext null@@ -108,12 +114,7 @@ object RcsMsrp { val localPath = session.msrpLocalPath ?: "msrp://local.invalid/${UUID.randomUUID()};tcp" runCatching { val (host, port) = parseMsrpPath(remotePath) ?: return@runCatching null- val socket = runCatching {- val s = java.net.Socket()- s.connect(java.net.InetSocketAddress(host, port), 10_000)- s.soTimeout = 0- s- }.getOrNull() ?: return@runCatching null+ val socket = RcsImsNetwork.createSocket(context, host, port) ?: return@runCatching null val conn = MsrpConnection(socket, localPath, remotePath) // Reader loop: parse SEND chunks, auto-200 them, deliver bodies. // Owned by the connection; dies on close.@@ -269,13 +270,14 @@ object RcsMsrp { /** * Send [payload] (CPIM bytes) over an MSRP session bound to [session].- * Opens a TCP socket to the remote path when needed. Returns true on a- * 200 response to our SEND.+ * Opens a TCP socket to the remote path when needed (IMS PDN preferred,+ * see [connect]). Returns true on a 200 response to our SEND. * * One-shot fallback; prefer [connect] for established sessions. */ suspend fun send( session: RcsSession,+ context: Context, payload: ByteArray, contentType: String = "message/cpim", ): Boolean = withContext(Dispatchers.IO) {@@ -296,12 +298,8 @@ object RcsMsrp { append("Success-Report: no\r\n") append("Content-Type: $contentType\r\n") }- val socket = runCatching {- val s = java.net.Socket()- s.connect(java.net.InetSocketAddress(host, port), 10_000)- s.soTimeout = 10_000- s- }.getOrNull() ?: return@runCatching false+ val socket = RcsImsNetwork.createSocket(context, host, port)+ ?: return@runCatching false socket.use { s -> val out = s.getOutputStream() out.write(chunk.toByteArray(Charsets.UTF_8))
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.ktindex a8cfd21c74..c97df4f270 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt@@ -27,6 +27,8 @@ data class RcsSession( val remoteUri: String, val conversationId: String, val isGroup: Boolean = false,+ /** True for the pseudo-session tracking a conference we host (focus role). */+ val isFocus: Boolean = false, /** MSRP path negotiated via SDP (`a=path`). Null until bound. */ val msrpLocalPath: String? = null, val msrpRemotePath: String? = null,
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.ktindex 562827fe19..6ed9bdc566 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt@@ -95,6 +95,116 @@ object RcsSessionManager { return dialogId } + /**+ * Host a group conference (focus role, UP 3.x conference model).+ *+ * Unlike joining a carrier focus via [startGroupSession], this makes US the+ * focus: we allocate a local `conf:` URI, invite each participant with a+ * REFER to it (their clients INVITE back and join — see the inbound+ * INVITE-to-focus path in [onSipRequest]), and relay in-conference+ * messages to the other participants (see+ * [RcsSyncService.handleInbound] — relay happens there, keyed off the+ * focus session map below).+ *+ * Focus INVITEs carry the `isfocus` Contact parameter (RFC 4354) + the CPM+ * group tag so peers treat us as the conference server rather than a 1:1+ * caller. Returns the focus URI on success, null otherwise.+ *+ * v1 limits: relay is pager-mode MESSAGE fan-out (no MSRP media mixing);+ * MLS E2EE still terminates per-member via the conversation's MLS group —+ * the focus relays opaque ciphertext, never plaintext.+ */+ suspend fun hostGroupFocus(+ conversationId: String,+ subject: String,+ participants: List<String>,+ ): String? {+ if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return null+ val distinct = participants.map { it.trim() }.filter { it.isNotEmpty() }.distinct()+ if (distinct.isEmpty()) return null+ val focusUri = "conf:${UUID.randomUUID()}@rcs.local"+ val localTag = UUID.randomUUID().toString().take(8)+ _sessions.value = _sessions.value + (conversationId to RcsSession(+ dialogId = "focus:$focusUri",+ callId = "focus-${UUID.randomUUID()}",+ localTag = localTag,+ remoteTag = "",+ remoteUri = focusUri,+ conversationId = conversationId,+ isGroup = true,+ isFocus = true,+ ))+ _focusMembers[focusUri] = distinct.toMutableSet()+ var invited = false+ for (peer in distinct) {+ if (sendReferToFocus(peer, focusUri, subject)) invited = true+ }+ if (!invited) {+ _sessions.value = _sessions.value - conversationId+ _focusMembers.remove(focusUri)+ return null+ }+ Log.i(TAG, "Hosting focus $focusUri for $conversationId (${distinct.size} invited)")+ return focusUri+ }++ /** Participants of hosted foci: focus URI → member E.164 set. */+ private val _focusMembers = ConcurrentHashMap<String, MutableSet<String>>()++ /** Members of the hosted focus [focusUri], or null when not ours. */+ fun focusMembers(focusUri: String): Set<String>? = _focusMembers[focusUri]?.toSet()++ /** Focus URI we host for [conversationId], or null when we don't host it. */+ fun hostedFocusFor(conversationId: String): String? {+ val session = _sessions.value[conversationId] ?: return null+ return if (session.isFocus) session.remoteUri else null+ }++ /** Track a joiner that INVITEd our focus URI (no REFER needed — direct dial). */+ fun noteFocusJoin(focusUri: String, member: String) {+ _focusMembers[focusUri]?.add(member.trim())+ }++ /** Drop a member from a hosted focus (BYE / removal). */+ fun noteFocusLeave(focusUri: String, member: String) {+ _focusMembers[focusUri]?.remove(member.trim())+ }++ /** Tear down a hosted focus: BYE every joined member dialog, drop state. */+ suspend fun destroyHostedFocus(conversationId: String): Boolean {+ val session = _sessions.value[conversationId] ?: return true+ if (!session.isFocus) return terminateSession(conversationId)+ val focusUri = session.remoteUri+ _focusMembers.remove(focusUri)+ _sessions.value = _sessions.value - conversationId+ return true+ }++ /**+ * REFER one peer to our hosted focus: `REFER sip:peer` with `Refer-To:+ * <focusUri>` + `Referred-By` us. Their client INVITEs the focus URI back.+ */+ private suspend fun sendReferToFocus(peer: String, focusUri: String, subject: String): Boolean {+ val cfg = RcsSipTransport.lastConfigSnapshot()+ val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+ val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+ val startLine = "REFER sip:$peer@rcs SIP/2.0"+ val headers = buildString {+ append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+ append("Max-Forwards: 70\r\n")+ append("From: <$from>;tag=${UUID.randomUUID().toString().take(8)}\r\n")+ append("To: <sip:$peer@rcs>\r\n")+ append("Call-ID: ${UUID.randomUUID()}@rcs-refer\r\n")+ append("CSeq: 1 REFER\r\n")+ append("Refer-To: <$focusUri>\r\n")+ append("Referred-By: <$from>\r\n")+ if (subject.isNotBlank()) append("Subject: $subject\r\n")+ append("Contact: <$from>;isfocus\r\n")+ append("Content-Length: 0\r\n")+ }+ return RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0))+ }+ /** * Answer a pending incoming INVITE with 200 OK + SDP answer (passive — * the caller connects to us... see ACTIVE-only note below).@@ -229,9 +339,26 @@ object RcsSessionManager { contentType: String?, body: String, fromTag: String? = null,+ toUri: String? = null, ): RcsSession? { return when (method.uppercase()) { "INVITE" -> {+ // INVITE to a focus URI we host: record the joiner, keyed to the+ // hosted conversation (the caller answers with acceptIncoming on+ // the hosted thread; relay fans their messages out).+ val target = (toUri ?: "") + "\n" + body+ hostedConversationFor(target)?.let { hosted ->+ noteFocusJoin(hosted.focusUri, fromUri)+ return RcsSession(+ dialogId = "$callId:focus-in",+ callId = callId,+ localTag = UUID.randomUUID().toString().take(8),+ remoteTag = fromTag.orEmpty(),+ remoteUri = fromUri,+ conversationId = hosted.conversationId,+ isGroup = true,+ )+ } val conversationId = fromUri.substringAfter("sip:").substringBefore("@") .takeIf { it.isNotBlank() } ?: fromUri // Stash the offerer's path/setup for acceptIncoming connect-out.@@ -360,6 +487,20 @@ object RcsSessionManager { return null to path } + /** Hosted-focus lookup: which focus a To-URI/SDP blob targets. */+ private data class HostedTarget(val focusUri: String, val conversationId: String)++ private fun hostedConversationFor(target: String): HostedTarget? {+ if (target.isBlank()) return null+ for ((conversationId, session) in _sessions.value) {+ if (!session.isFocus) continue+ if (target.contains(session.remoteUri, ignoreCase = true)) {+ return HostedTarget(session.remoteUri, conversationId)+ }+ }+ return null+ }+ /** * Parse the MSRP `a=setup:` role from an SDP answer. Null when absent * (assume peer is passive, the common answer to our active offer).
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.ktindex c0a65b10f6..8e6bfe27f2 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt@@ -88,7 +88,9 @@ object RcsSipTransport { version = cfg.getVersion(), publicUserId = cfg.getPublicUserIdentifier(), homeDomain = cfg.getHomeDomain(),- msrpLocalIp = null,+ // IMS-PDN local address when known — routable by carrier peers,+ // unlike the delegate config (which carries no local IP field).+ msrpLocalIp = RcsImsNetwork.lastLocalIp, serviceRoute = cfg.getSipServiceRouteHeader(), pani = cfg.getSipPaniHeader(), userAgent = cfg.getSipUserAgentHeader(),
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.ktindex bcf411268c..9d170ac605 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt@@ -102,6 +102,41 @@ object RcsE2E { }.getOrNull() } + /**+ * Remove members from [conversationId]'s MLS group by leaf index (see the+ * `removeMembers` JNI contract: ASCII decimal CSV). Sends the commit to+ * the group thread so remaining members ratchet forward — removed members+ * can no longer decrypt. Persists the evolved snapshot.+ *+ * Leaf indices are crate-internal (join order); callers that track+ * membership should map E.164 → index at add time. Returns true when the+ * commit was accepted by the transport.+ */+ suspend fun removeMembers(+ context: Context,+ e164: String,+ conversationId: String,+ leafIndices: List<Int>,+ ): Boolean = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || leafIndices.isEmpty()) {+ return@withContext false+ }+ val identity = identityFor(context, e164) ?: return@withContext false+ val db = RcsDatabase.getDatabase(context)+ val group = db.mlsGroupDao().getByConversation(conversationId) ?: return@withContext false+ if (group.groupIdHex.startsWith("pending:")) return@withContext false+ val groupId = group.groupIdHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+ val csv = leafIndices.distinct().sorted().joinToString(",")+ .toByteArray(Charsets.US_ASCII)+ val out = runCatching {+ RustMlsCrypto.removeMembers(group.storage, identity, groupId, csv)+ }.getOrNull() ?: return@withContext false+ val storageOut = out.getOrNull(0) ?: group.storage+ val commit = out.getOrNull(1) ?: return@withContext false+ db.mlsGroupDao().upsert(group.copy(storage = storageOut, updatedAt = System.currentTimeMillis()))+ sendMlsEnvelope(context, conversationId, commit, CT_COMMIT)+ }+ /** * Create an E2EE group for [conversationId] with our local identity, then * add [peerKeyPackages]. Returns the commit + welcome payloads to send
communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.ktindex 15275c4f2f..eaa4d148ca 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt@@ -34,8 +34,10 @@ internal suspend fun RcsSyncService.handleInboundInvite(message: SipMessage) { ?.trim()?.takeIf { it.isNotBlank() } val callId = message.getCallIdParameter() ?: return val body = message.getContent().toString(Charsets.UTF_8)- RcsSessionManager.onSipRequest("INVITE", callId, from, "application/sdp", body, fromTag)- val conversationId = from+ val to = headerValue(headers, "To:")+ val stashed = RcsSessionManager.onSipRequest("INVITE", callId, from, "application/sdp", body, fromTag, to)+ // Focus join: route to the hosted group conversation, not the sender.+ val conversationId = stashed?.conversationId ?: from // 488 only when there is no SDP offer at all; otherwise accept. val hasSdp = body.contains("m=message", ignoreCase = true) if (!hasSdp) {
communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.ktindex e1a2810918..5cddc28451 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt@@ -114,7 +114,7 @@ class RcsSyncService : Service() { if (session.msrpRemotePath == null || msrpConnections.containsKey(conversationId)) { continue }- val conn = RcsMsrp.connect(session) { contentType, body ->+ val conn = RcsMsrp.connect(session, this@RcsSyncService) { contentType, body -> serviceScope.launch { handleMsrpChunk(conversationId, session, contentType, body) } } if (conn != null) {@@ -202,6 +202,9 @@ class RcsSyncService : Service() { ftUrl = parsed.ftUrl, ftMime = parsed.ftMime, )+ // Hosted focus: relay the message to the other members+ // (ciphertext passes through untouched when E2EE is on).+ relayFocusMessage(parsed, envelope.raw) // IMDN positive-delivery: the message reached us, so tell the sender. sendImdnReport(parsed) showIncomingNotification(parsed)@@ -269,6 +272,32 @@ class RcsSyncService : Service() { ) } + /**+ * Focus relay: when [parsed] arrived on a conversation we host the focus+ * for, re-send the raw body to every other focus member. The relayed bytes+ * are the original wire body (CPIM + payload), so MLS ciphertext stays+ * opaque to us — E2EE terminates per-member, not at the focus.+ */+ private suspend fun relayFocusMessage(parsed: InboundRcs, rawBody: String) {+ if (!RcsFeature.enabled) return+ val focusUri = RcsSessionManager.hostedFocusFor(parsed.conversationId) ?: return+ val members = RcsSessionManager.focusMembers(focusUri) ?: return+ val others = members.filter { it != parsed.senderId && it.isNotBlank() }+ if (others.isEmpty() || rawBody.isBlank()) return+ for (peer in others) {+ runCatching {+ val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+ fromUri = "sip:me@rcs",+ toUri = "sip:$peer@rcs",+ callId = "${java.util.UUID.randomUUID()}@rcs-relay",+ body = rawBody,+ )+ RcsSipTransport.sendSipMessage(startLine, headers, content)+ }+ }+ Log.i(TAG, "Relayed focus message to ${others.size} members")+ }+ private suspend fun sendImdnReport(parsed: InboundRcs) { val originalId = parsed.imdnMessageId ?: return runCatching {
communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.ktindex 7d5d7aa919..b038c1d5a2 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt@@ -188,6 +188,16 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit if (!ok) { AppMessages.show(context.getString(R.string.rcs_encrypted_failed)) }+ } else if (com.vayunmathur.communicate.data.rcs.RcsFeature.enabled) {+ // Plaintext group: host the conference focus so+ // members' clients can join (REFER) and their+ // messages relay through us. Best-effort — the+ // thread still opens for 1:1 fan-out sends.+ withContext(Dispatchers.IO) {+ com.vayunmathur.communicate.data.rcs.RcsSessionManager.hostGroupFocus(+ groupId, subject, contacts,+ )+ } } onOpenThread(thread) }
communicate/src/main/rust-mls/src/lib.rs
diff --git a/communicate/src/main/rust-mls/src/lib.rs b/communicate/src/main/rust-mls/src/lib.rsindex 9b31c58274..7415a91b28 100644--- a/communicate/src/main/rust-mls/src/lib.rs+++ b/communicate/src/main/rust-mls/src/lib.rs@@ -1,14 +1,14 @@-//! MLS (RFC 9420) for the RCS line, backed by OpenMLS.+//! MLS (RFC 9420, GSMA Universal Profile 3.0) for the RCS line, backed by OpenMLS. //! //! Design mirrors the Signal crate in `../rust`: every entry point is //! **pure**. Kotlin owns persistence (Room) and passes group state, key //! packages and proposals in as opaque TLS-serialized bytes, getting updated //! state back. The crate never calls back into Kotlin and holds no globals. //!-//! Interop note: this is closed-loop, our-app-to-our-app. RCS is the wire-//! (MLS handshake + application messages ride SIP MESSAGE / MSRP as opaque-//! payloads); key packages are exchanged out-of-band through the same-//! transport. Google Messages' proprietary key distribution is not involved.+//! The crypto is interop-shaped (standard ciphersuite, BasicCredential+//! identities, TLS framing — the same UP 3.0 MLS profile Google Messages+//! uses). Key discovery stays closed-loop in v1: key packages ride our own+//! RCS content-types rather than a federated directory. pub mod group; pub mod keys;
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.ktindex 189d45314a..e7990babc5 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt@@ -1,6 +1,8 @@ package com.vayunmathur.communicate.rcs import com.vayunmathur.communicate.data.rcs.ImdnDisposition+import com.vayunmathur.communicate.data.rcs.RcsGbaAuth+import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.buildEditBody import com.vayunmathur.communicate.data.rcs.buildGeopushBody import com.vayunmathur.communicate.data.rcs.buildImdnBody@@ -133,4 +135,29 @@ class RcsUpFramingTest { assertEquals("fixed", text) assertNull(parseEditBody("plain")) }++ @Test+ fun gbaDigestKnownAnswer() {+ // RFC 2617 §3.5 known-answer vector: user "Mufasa", password+ // "Circle Of Life", realm "[email protected]", nonce+ // "dcd98b7102dd2f0e8b11d0f600bfb0c093".+ val response = RcsGbaAuth.digestResponse(+ username = "Mufasa",+ password = "Circle Of Life",+ realm = "[email protected]",+ nonce = "dcd98b7102dd2f0e8b11d0f600bfb0c093",+ method = "GET",+ uri = "/dir/index.html",+ cnonce = "0a4f113b",+ )+ assertEquals("6629fae49393a05397450978507c4ef1", response)+ }++ @Test+ fun focusBookkeepingTracksMembers() {+ // No focus hosted: lookups are null, leave is a no-op.+ assertNull(RcsSessionManager.hostedFocusFor("nope"))+ assertNull(RcsSessionManager.focusMembers("conf:[email protected]"))+ RcsSessionManager.noteFocusLeave("conf:[email protected]", "+1555")+ } }