communicate: RCS encrypted groups and MSRP active sessions
- Commit
5cbc513dc18ac5f5f45fb6781f4f1a7e2eb25314- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-25 18:06 UTC (2 months ago)
- Parents
b3ccee6
Diff
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsGroup.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsGroup.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsGroup.ktnew file mode 100644index 0000000000..29641c498a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcsGroup.kt@@ -0,0 +1,55 @@+package com.vayunmathur.communicate.data++import android.content.Context+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.e2e.RcsE2E+import com.vayunmathur.communicate.data.rcs.e2e.RcsKeyDirectory+import com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys+import com.vayunmathur.communicate.data.rcs.e2e.RcsPendingGroups+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Create an encrypted MLS group for [conversationId] with [members].+ *+ * Fast path: every member's key package is cached → create immediately and+ * fan out Welcome + commit. Slow path: publish our package, request the+ * missing ones, park the setup in [RcsPendingGroups]; the sync service+ * completes it as packages arrive (thread opens plaintext meanwhile and+ * upgrades — see the pending banner).+ *+ * Returns true when the setup was created immediately OR parked for later;+ * false only when nothing could be done (gate off, no identity, no transport).+ */+suspend fun CommunicateRepository.createEncryptedRcsGroup(+ context: Context,+ conversationId: String,+ members: List<String>,+): Boolean = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled || members.isEmpty()) return@withContext false+ val local = RcsE2E.localE164(context) ?: return@withContext false+ if (!RcsSipTransport.canSend()) return@withContext false+ // Cached packages first (consumes single-use init keys).+ val cached = members.associateWith { RcsPeerKeys.consume(it) }+ if (cached.values.all { it != null }) {+ @Suppress("UNCHECKED_CAST")+ val ok = RcsE2E.setupEncryptedGroup(context, local, conversationId, cached as Map<String, ByteArray>)+ if (!ok) {+ // Restore what we consumed so a retry can proceed.+ cached.forEach { (peer, kp) -> if (kp != null) RcsPeerKeys.store(context, peer, kp) }+ }+ return@withContext ok+ }+ // Slow path: publish ours, request the missing, park the setup.+ RcsKeyDirectory.publishTo(context, local, members.first())+ cached.forEach { (peer, kp) ->+ if (kp == null) {+ RcsE2E.requestKeyPackage(context, peer)+ } else {+ RcsPeerKeys.store(context, peer, kp)+ }+ }+ RcsPendingGroups.add(conversationId, members)+ true+}
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 0950db9d00..f9cb65de87 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@@ -2,7 +2,11 @@ package com.vayunmathur.communicate.data.rcs import android.util.Log import java.util.UUID+import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /**@@ -15,16 +19,260 @@ import kotlinx.coroutines.withContext * IMDN reports travel inside sessions once established; pager-mode remains * the pre-session path). *- * Sockets open on Dispatchers.IO; every failure returns null/false so callers- * fall back to pager-mode. No Guava — plain suspend functions.+ * ACTIVE-only: we always connect out, never listen (same as TestRcsApp —+ * `MsrpManager` has no accept loop). Sockets open on Dispatchers.IO; every+ * failure returns null/false so callers fall back to pager-mode. No Guava —+ * plain suspend functions. */ object RcsMsrp { private const val TAG = "RcsMsrp" + /**+ * A persistent MSRP connection for one session: one socket, reused across+ * SENDs, with a reader loop feeding inbound chunks to [onChunk].+ * Create via [connect]; [close] on BYE / teardown.+ */+ class MsrpConnection internal constructor(+ private val socket: java.net.Socket,+ private val localPath: String,+ private val remotePath: String,+ ) {+ @Volatile private var closed = false+ private val readerScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ internal fun launchReader(block: suspend () -> Unit) {+ readerScope.launch { block() }+ }++ /**+ * Send one CPIM payload as an MSRP SEND chunk. Returns true on a 200+ * response. Thread-safe (single-writer lock).+ */+ private val writeLock = Any()++ fun sendCpim(payload: ByteArray, contentType: String = "message/cpim"): Boolean {+ if (closed) return false+ return runCatching {+ val txid = UUID.randomUUID().toString().replace("-", "").take(12)+ val messageId = UUID.randomUUID().toString()+ val head = buildString {+ append("MSRP $txid SEND\r\n")+ append("To-Path: $remotePath\r\n")+ append("From-Path: $localPath\r\n")+ append("Message-ID: $messageId\r\n")+ append("Byte-Range: 1-${payload.size}/${payload.size}\r\n")+ append("Failure-Report: yes\r\n")+ append("Success-Report: no\r\n")+ append("Content-Type: $contentType\r\n")+ }+ synchronized(writeLock) {+ val out = socket.getOutputStream()+ out.write(head.toByteArray(Charsets.UTF_8))+ out.write("\r\n".toByteArray(Charsets.UTF_8))+ out.write(payload)+ out.write("\r\n-------$txid\$\r\n".toByteArray(Charsets.UTF_8))+ out.flush()+ }+ true+ }.getOrElse {+ Log.w(TAG, "MSRP chunk send failed", it)+ false+ }+ }++ fun close() {+ closed = true+ runCatching { socket.close() }+ readerScope.cancel()+ }++ internal fun isClosed(): Boolean = closed || socket.isClosed+ }++ /**+ * Open a persistent active connection for [session] and start the reader+ * 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`).+ */+ suspend fun connect(+ session: RcsSession,+ onChunk: (contentType: String, body: ByteArray) -> Unit,+ ): MsrpConnection? = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext null+ val remotePath = session.msrpRemotePath ?: return@withContext null+ if (session.msrpSetup == MsrpSetup.ACTIVE) {+ Log.w(TAG, "Peer is active; ACTIVE-only cannot listen")+ return@withContext null+ }+ 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 conn = MsrpConnection(socket, localPath, remotePath)+ // Reader loop: parse SEND chunks, auto-200 them, deliver bodies.+ // Owned by the connection; dies on close.+ conn.launchReader { readLoop(conn, socket, onChunk) }+ conn+ }.getOrElse {+ Log.w(TAG, "MSRP connect failed", it)+ null+ }+ }++ private fun readLoop(+ conn: MsrpConnection,+ socket: java.net.Socket,+ onChunk: (String, ByteArray) -> Unit,+ ) {+ val input = runCatching { socket.getInputStream().bufferedReader(Charsets.UTF_8) }.getOrNull()+ ?: return+ val pending = StringBuilder()+ // Reassembly buffer for multi-chunk SENDs, keyed by Message-ID.+ val reassembly = mutableMapOf<String, ByteArrayOutputStream2>()+ try {+ while (!conn.isClosed()) {+ val line = runCatching { input.readLine() }.getOrNull() ?: break+ if (line.startsWith("MSRP ")) {+ pending.clear()+ pending.append(line).append("\r\n")+ val headers = mutableMapOf<String, String>()+ var contentLength = -1+ // Header block.+ while (true) {+ val h = runCatching { input.readLine() }.getOrNull() ?: break+ if (h.isEmpty()) break+ pending.append(h).append("\r\n")+ val name = h.substringBefore(":").trim()+ val value = h.substringAfter(":").trim()+ headers[name.lowercase()] = value+ if (name.equals("Content-Length", ignoreCase = true)) {+ contentLength = value.toIntOrNull() ?: -1+ }+ }+ val txid = line.split(" ").getOrNull(1).orEmpty()+ val method = line.split(" ").getOrNull(2).orEmpty()+ if (method.equals("SEND", ignoreCase = true)) {+ // Body: Content-Length bytes when present, else to end-marker.+ val bodyBytes = if (contentLength >= 0) {+ readFixed(input, contentLength)+ } else {+ readToEndMarker(input, txid)+ }+ // Consume the end-marker line.+ runCatching { input.readLine() }+ // Auto-200 the peer SEND.+ sendResponse(socket, txid, 200, "OK", conn)+ val msgId = headers["message-id"].orEmpty()+ val contentType = headers["content-type"] ?: "message/cpim"+ if (msgId.isNotEmpty() && bodyBytes != null) {+ val buf = reassembly.getOrPut(msgId) { ByteArrayOutputStream2() }+ buf.write(bodyBytes)+ // Single-chunk fast path: Byte-Range 1-N/N delivers now.+ val range = headers["byte-range"]+ if (range == null || isCompleteRange(range)) {+ reassembly.remove(msgId)+ val complete = buf.toBytes()+ if (complete.isNotEmpty()) onChunk(contentType, complete)+ }+ } else if (bodyBytes != null && bodyBytes.isNotEmpty()) {+ onChunk(contentType, bodyBytes)+ }+ } else {+ // Responses to our SENDs (handled inline by sendCpim today).+ runCatching { input.readLine() }+ }+ }+ }+ } catch (_: Throwable) {+ // Socket closed — reader exits.+ } finally {+ reassembly.clear()+ conn.close()+ }+ }++ private fun isCompleteRange(range: String): Boolean {+ // "1-N/N" with equal total and end, or "1-0/0" empty handshake.+ val m = Regex("(\\d+)-(\\d+)/(\\d+)").find(range.trim()) ?: return true+ val (_, end, total) = m.destructured+ return end == total+ }++ private fun readFixed(input: java.io.BufferedReader, n: Int): ByteArray? {+ if (n < 0 || n > 8 * 1024 * 1024) return null+ return runCatching {+ val chars = CharArray(n)+ var read = 0+ while (read < n) {+ val r = input.read(chars, read, n - read)+ if (r < 0) break+ read += r+ }+ String(chars, 0, read).toByteArray(Charsets.UTF_8)+ }.getOrNull()+ }++ private fun readToEndMarker(input: java.io.BufferedReader, txid: String): ByteArray? {+ return runCatching {+ val sb = StringBuilder()+ while (true) {+ val line = input.readLine() ?: break+ if (line.startsWith("-------$txid")) break+ sb.append(line).append("\r\n")+ }+ sb.toString().toByteArray(Charsets.UTF_8)+ }.getOrNull()+ }++ private fun sendResponse(+ socket: java.net.Socket,+ txid: String,+ code: Int,+ reason: String,+ conn: MsrpConnection,+ ) {+ runCatching {+ val out = socket.getOutputStream()+ out.write("MSRP $txid $code $reason\r\n".toByteArray(Charsets.UTF_8))+ out.write("To-Path: placeholder\r\n\r\n".toByteArray(Charsets.UTF_8))+ out.write("-------$txid\$\r\n".toByteArray(Charsets.UTF_8))+ out.flush()+ }+ }++ /** Minimal byte buffer (avoids java.io.ByteArrayOutputStream import weight). */+ private class ByteArrayOutputStream2 {+ private var buf = ByteArray(1024)+ private var size = 0++ fun write(bytes: ByteArray) {+ ensure(bytes.size)+ bytes.copyInto(buf, size)+ size += bytes.size+ }++ fun toBytes(): ByteArray = buf.copyOf(size)++ private fun ensure(extra: Int) {+ if (size + extra <= buf.size) return+ var next = buf.size * 2+ while (next < size + extra) next *= 2+ buf = buf.copyOf(next)+ }+ }+ /** * 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.+ *+ * One-shot fallback; prefer [connect] for established sessions. */ suspend fun send( session: RcsSession,
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 fb8618a1fc..a8cfd21c74 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@@ -30,9 +30,22 @@ data class RcsSession( /** MSRP path negotiated via SDP (`a=path`). Null until bound. */ val msrpLocalPath: String? = null, val msrpRemotePath: String? = null,+ /**+ * Peer's MSRP setup role from the SDP answer. ACTIVE-only: we always+ * connect out, so a peer answering `active` keeps `msrpRemotePath`+ * nulled (pager-mode fallback). Null = absent, treated as passive.+ */+ val msrpSetup: MsrpSetup? = null, val createdAt: Long = System.currentTimeMillis(), ) +/** MSRP connection roles (`a=setup:`). */+enum class MsrpSetup {+ ACTIVE,+ PASSIVE,+ ACTPASS,+}+ /** IMDN disposition (RFC 5438) for delivery/display receipts. */ enum class ImdnDisposition(val token: String) { Delivered("positive-delivery"),
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 550aedd8a4..f46638d364 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@@ -122,12 +122,22 @@ object RcsSessionManager { val session = entry.value if (statusCode in 200..299 && !remoteTag.isNullOrBlank()) { val (localPath, remotePath) = parseSdpPaths(sdpAnswer)+ val setup = parseSdpSetup(sdpAnswer) _sessions.value = _sessions.value + (entry.key to session.copy( remoteTag = remoteTag, msrpLocalPath = localPath, msrpRemotePath = remotePath,+ // ACTIVE-only: we connect out. A peer answering `active` means+ // it expects US to listen, which we cannot — keep the remote+ // path nulled so sends stay on pager-mode.+ msrpSetup = setup, ))- Log.i(TAG, "Session established ${session.dialogId}")+ val usable = remotePath != null && setup != MsrpSetup.ACTIVE+ Log.i(TAG, "Session established ${session.dialogId} setup=$setup usable=$usable")+ if (!usable) {+ _sessions.value = _sessions.value + (entry.key to+ (_sessions.value[entry.key] ?: session).copy(msrpRemotePath = null))+ } } else if (statusCode >= 300) { Log.w(TAG, "Session failed $callId code=$statusCode") transactions.entries.removeIf { it.value == session.dialogId }@@ -249,4 +259,20 @@ object RcsSessionManager { ?.groupValues?.getOrNull(1)?.trim() return null to path }++ /**+ * Parse the MSRP `a=setup:` role from an SDP answer. Null when absent+ * (assume peer is passive, the common answer to our active offer).+ */+ fun parseSdpSetup(sdp: String?): MsrpSetup? {+ if (sdp.isNullOrBlank()) return null+ val token = Regex("a=setup:(\\S+)", RegexOption.IGNORE_CASE).find(sdp)+ ?.groupValues?.getOrNull(1)?.trim()?.lowercase() ?: return null+ return when (token) {+ "active" -> MsrpSetup.ACTIVE+ "passive" -> MsrpSetup.PASSIVE+ "actpass" -> MsrpSetup.ACTPASS+ else -> null+ }+ } }
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 c92ea9c924..939b2d5523 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@@ -238,6 +238,40 @@ object RcsE2E { .getOrDefault(false) } + /**+ * Request one peer's key package (public; the peer auto-publishes).+ * Used for N-peer group setup when cached packages are missing.+ */+ suspend fun requestKeyPackage(context: Context, peerE164: String): Boolean {+ if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false+ return sendKeyRequest(context, peerE164)+ }++ /**+ * Create the E2EE group for N peers and fan out: one commit to the group+ * thread ([CT_COMMIT]), one Welcome per peer 1:1 ([CT_WELCOME]). Persists+ * the group under [conversationId]. Returns true when every leg was+ * accepted by the transport.+ */+ suspend fun setupEncryptedGroup(+ context: Context,+ localE164: String,+ conversationId: String,+ peerPackages: Map<String, ByteArray>,+ ): Boolean {+ if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || peerPackages.isEmpty()) return false+ val (commit, welcome) = createEncryptedGroup(+ context, localE164, conversationId, peerPackages.values.toList(),+ ) ?: return false+ var ok = sendMlsEnvelope(context, conversationId, commit, CT_COMMIT)+ for ((peer, _) in peerPackages) {+ ok = sendMlsEnvelope(context, peer, welcome, CT_WELCOME) && ok+ }+ // Rotate our key package now that the previous one may be consumed.+ freshKeyPackage(context, localE164)+ return ok+ }+ /** * Create the E2EE group once the peer's key package is known and send the * Welcome + commit. Called when a key package arrives for a conversation
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPendingGroups.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPendingGroups.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPendingGroups.ktnew file mode 100644index 0000000000..3ba7ab6aae--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPendingGroups.kt@@ -0,0 +1,48 @@+package com.vayunmathur.communicate.data.rcs.e2e++import com.vayunmathur.communicate.data.rcs.RcsFeature++/**+ * Pending encrypted-group setups awaiting member key packages.+ *+ * When the user creates an encrypted group before every member's key package+ * is cached, the conversation id + member set is parked here. Each inbound+ * key package re-checks pending sets; once all members are cached, the group+ * is created and the entry removed. In-memory like [RcsPeerKeys] (v1 scope).+ */+object RcsPendingGroups {+ private data class Pending(val conversationId: String, val members: Set<String>)++ private val pending = java.util.concurrent.ConcurrentHashMap<String, Pending>()++ /** Park [conversationId] with [members] until all key packages arrive. */+ fun add(conversationId: String, members: Collection<String>) {+ if (!RcsFeature.enabled || conversationId.isBlank() || members.isEmpty()) return+ pending[conversationId] = Pending(conversationId, members.toSet())+ }++ /** Drop the pending entry (group created or abandoned). */+ fun remove(conversationId: String) {+ pending.remove(conversationId)+ }++ /**+ * Pending entries whose member set includes [peerE164] and whose every+ * member now has a cached key package. Callers create the group for each+ * returned conversation id, then [remove] it.+ */+ fun readyFor(peerE164: String): List<Pair<String, Map<String, ByteArray>>> {+ if (!RcsFeature.enabled) return emptyList()+ return pending.values.mapNotNull { p ->+ if (!p.members.contains(peerE164)) return@mapNotNull null+ val packages = p.members.associateWith { RcsPeerKeys.get(it) }+ if (packages.values.any { it == null }) return@mapNotNull null+ @Suppress("UNCHECKED_CAST")+ p.conversationId to (packages as Map<String, ByteArray>)+ }+ }++ /** True when [conversationId] is parked awaiting keys ("waiting" banner). */+ fun isPending(conversationId: String): Boolean =+ RcsFeature.enabled && pending.containsKey(conversationId)+}
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 8e1ddd84fa..fdfe76888c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt@@ -22,13 +22,16 @@ import com.vayunmathur.communicate.data.rcs.ImdnDisposition import com.vayunmathur.communicate.data.rcs.RcsFeature import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp import com.vayunmathur.communicate.data.rcs.RcsImdn+import com.vayunmathur.communicate.data.rcs.RcsMsrp import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsSession import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.RcsSipTransport import com.vayunmathur.communicate.data.rcs.buildImdnBody import com.vayunmathur.communicate.data.rcs.e2e.RcsE2E import com.vayunmathur.communicate.data.rcs.e2e.RcsKeyDirectory import com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys+import com.vayunmathur.communicate.data.rcs.e2e.RcsPendingGroups import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto import com.vayunmathur.communicate.data.rcs.extractImdnMessageId import com.vayunmathur.communicate.data.rcs.parseImdnBody@@ -52,6 +55,9 @@ class RcsSyncService : Service() { private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + /** MSRP connections per conversation, owned by this service's lifecycle. */+ private val msrpConnections = java.util.concurrent.ConcurrentHashMap<String, RcsMsrp.MsrpConnection>()+ override fun onCreate() { super.onCreate() }@@ -87,6 +93,28 @@ class RcsSyncService : Service() { updateSyncNotification(state) } }+ // Own MSRP connection lifecycle: when a session gains a usable+ // remote path, connect out and feed inbound chunks to the inbox.+ launch {+ RcsSessionManager.sessions.collect { sessions ->+ for ((conversationId, session) in sessions) {+ if (session.msrpRemotePath == null || msrpConnections.containsKey(conversationId)) {+ continue+ }+ val conn = RcsMsrp.connect(session) { contentType, body ->+ serviceScope.launch { handleMsrpChunk(conversationId, session, contentType, body) }+ }+ if (conn != null) {+ msrpConnections[conversationId] = conn+ }+ }+ // Drop connections whose sessions went away.+ val live = sessions.keys+ msrpConnections.keys.filter { it !in live }.forEach { id ->+ msrpConnections.remove(id)?.close()+ }+ }+ } } return START_STICKY@@ -96,6 +124,8 @@ class RcsSyncService : Service() { override fun onDestroy() { RcsSipTransport.onInboundMessage = null+ msrpConnections.values.forEach { runCatching { it.close() } }+ msrpConnections.clear() serviceScope.cancel() super.onDestroy() }@@ -149,6 +179,53 @@ class RcsSyncService : Service() { } } + /**+ * Inbound MSRP chunk: CPIM text becomes an inbox row (+ notification);+ * IMDN/typing ride their trackers. Reuses the SIP parse helpers by+ * synthesizing the CPIM text path.+ */+ private suspend fun handleMsrpChunk(+ conversationId: String,+ session: RcsSession,+ contentType: String,+ body: ByteArray,+ ) {+ if (!RcsFeature.enabled) return+ val text = body.toString(Charsets.UTF_8)+ if (contentType.contains("imdn", ignoreCase = true)) {+ RcsImdn.onReportReceived(text)+ return+ }+ if (contentType.contains("im-composing", ignoreCase = true)) {+ RcsSessionManager.onSipRequest("MESSAGE", session.callId, conversationId, contentType, text)+ return+ }+ val display = if (contentType.contains("cpim", ignoreCase = true)) {+ extractTextBody(body) ?: text+ } else {+ text+ }+ if (display.isBlank()) return+ val ft = RcsFileTransferHttp.parseFtBody(display)+ CommunicateRepository.cacheInboundRcs(+ context = this,+ conversationId = conversationId,+ body = ft?.let { display.substringAfter("\r\n").ifBlank { "[file]" } } ?: display,+ senderId = conversationId,+ messageId = "in-msrp-${display.hashCode()}-${System.currentTimeMillis()}",+ ftUrl = ft?.url,+ ftMime = ft?.mime,+ )+ showIncomingNotification(+ InboundRcs(+ conversationId = conversationId,+ body = display,+ senderId = conversationId,+ messageId = "in-msrp-${display.hashCode()}",+ ),+ )+ }+ private suspend fun sendImdnReport(parsed: InboundRcs) { val originalId = parsed.imdnMessageId ?: return runCatching {@@ -268,17 +345,28 @@ class RcsSyncService : Service() { } return InboundRcs(from, "", from, "in-kreq-${System.currentTimeMillis()}", InboundKind.Typing) }- // Key package publication → stash, and create the group if none exists yet.+ // Key package publication → stash, satisfy pending groups, and create+ // the 1:1 group if none exists yet. if (contentType?.contains(RcsE2E.CT_KEY_PACKAGE, ignoreCase = true) == true || body.contains(RcsE2E.CT_KEY_PACKAGE, ignoreCase = true) ) { RcsKeyDirectory.parsePublished(body)?.let { kp -> RcsPeerKeys.store(this, from, kp)- // Auto-setup: first key package for a conversation with no group- // creates it and sends Welcome. Closed-loop peers opt in by- // running this code; no group forms with non-participants.+ // Pending encrypted groups: create each ready one now.+ for ((pendingId, packages) in RcsPendingGroups.readyFor(from)) {+ RcsE2E.localE164(this)?.let { local ->+ if (RcsE2E.setupEncryptedGroup(this, local, pendingId, packages)) {+ RcsPendingGroups.remove(pendingId)+ }+ }+ }+ // Auto-setup: first key package for a 1:1 conversation with no+ // group creates it and sends Welcome. Closed-loop peers opt in+ // by running this code; no group forms with non-participants. val conversationId = from- if (RcsE2E.groupIdFor(this, conversationId) == null) {+ if (RcsE2E.groupIdFor(this, conversationId) == null &&+ !RcsPendingGroups.isPending(conversationId)+ ) { RcsE2E.localE164(this)?.let { local -> RcsE2E.setupGroupWithPeer(this, local, conversationId, from, kp) }@@ -457,6 +545,8 @@ class RcsSyncService : Service() { private fun shutdown() { RcsSipTransport.onInboundMessage = null+ msrpConnections.values.forEach { runCatching { it.close() } }+ msrpConnections.clear() runCatching { RcsSipTransport.tearDown(this) } stopForeground(STOP_FOREGROUND_REMOVE) stopSelf()
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationMessagesList.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationMessagesList.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationMessagesList.ktindex 2ec845b843..cadaf85a67 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationMessagesList.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationMessagesList.kt@@ -90,3 +90,27 @@ internal fun SafetyNumberBanner( } } }++/**+ * RCS encryption state banner: locked once the MLS group exists, pending+ * while parked awaiting member keys. Informational only (no action).+ */+@Composable+internal fun EncryptedChatBanner(+ pending: Boolean,+ modifier: Modifier = Modifier,+) {+ Surface(+ color = MaterialTheme.colorScheme.tertiaryContainer,+ contentColor = MaterialTheme.colorScheme.onTertiaryContainer,+ modifier = modifier.fillMaxWidth(),+ ) {+ Text(+ stringResource(+ if (pending) R.string.rcs_encrypted_pending else R.string.rcs_encrypted_banner,+ ),+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),+ )+ }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex 052d07d4f8..7cf44a86f3 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -276,6 +276,43 @@ fun ConversationScreen( modifier = Modifier.padding(padding), ) }+ // RCS encryption state: lock banner when the MLS group exists, pending+ // notice while parked awaiting member keys.+ if (line == CommunicateLine.Rcs &&+ com.vayunmathur.communicate.data.rcs.RcsFeature.enabled+ ) {+ val convoId = remoteId?.takeIf { it.isNotBlank() } ?: address+ var encryptedState by remember(convoId, refresh) { mutableStateOf<Boolean?>(null) }+ androidx.compose.runtime.LaunchedEffect(line, convoId, refresh) {+ encryptedState = try {+ withContext(Dispatchers.IO) {+ com.vayunmathur.communicate.data.rcs.e2e.RcsE2E+ .groupIdFor(context, convoId) != null+ }+ } catch (_: Throwable) {+ null+ }+ }+ val isEncrypted = encryptedState+ if (isEncrypted == true) {+ EncryptedChatBanner(+ pending = false,+ modifier = Modifier.padding(padding),+ )+ } else if (isEncrypted == false) {+ val isPending = try {+ com.vayunmathur.communicate.data.rcs.e2e.RcsPendingGroups.isPending(convoId)+ } catch (_: Throwable) {+ false+ }+ if (isPending) {+ EncryptedChatBanner(+ pending = true,+ modifier = Modifier.padding(padding),+ )+ }+ }+ } // Google Voice threads don't require the default-SMS role or READ_SMS; only SIM does. if (line == CommunicateLine.GoogleVoice) { MessagesList(padding, refresh) {
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 889f885149..7d5d7aa919 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt@@ -21,6 +21,7 @@ import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.CommunicateRepository import com.vayunmathur.communicate.data.SmsThread+import com.vayunmathur.communicate.data.createEncryptedRcsGroup import com.vayunmathur.communicate.data.createSignalGroup import com.vayunmathur.communicate.data.createWhatsAppGroup import com.vayunmathur.communicate.data.deleteConversation@@ -77,7 +78,7 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit ), ) },- onCreateGroup = { choice, subject, contacts ->+ onCreateGroup = { choice, subject, contacts, encrypted -> showPicker = false scope.launch { when (choice.category) {@@ -160,24 +161,35 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit } } CommunicateLine.Rcs -> {- // v1: no conference setup — open a group thread addressed by the- // participant list; sends fan out per-recipient with SMS fallback. val groupId = "rcs-group:${contacts.sorted().joinToString(",")}"- onOpenThread(- SmsThread(- threadId = CommunicateRepository.stableThreadId(groupId),- address = groupId,- displayName = subject.ifBlank { null },- snippet = "",- timestampMillis = System.currentTimeMillis(),- unreadCount = 0,- line = CommunicateLine.Rcs,- remoteId = groupId,- isGroup = true,- participants = contacts,- groupTitle = subject.ifBlank { null },- ),+ val thread = SmsThread(+ threadId = CommunicateRepository.stableThreadId(groupId),+ address = groupId,+ displayName = subject.ifBlank { null },+ snippet = "",+ timestampMillis = System.currentTimeMillis(),+ unreadCount = 0,+ line = CommunicateLine.Rcs,+ remoteId = groupId,+ isGroup = true,+ participants = contacts,+ groupTitle = subject.ifBlank { null }, )+ if (encrypted &&+ com.vayunmathur.communicate.data.rcs.RcsFeature.enabled &&+ com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto.isAvailable+ ) {+ // Encrypted group: set up MLS now (fast path) or park+ // for key arrival (slow path). Thread opens either+ // way; the banner shows the pending state.+ val ok = withContext(Dispatchers.IO) {+ CommunicateRepository.createEncryptedRcsGroup(context, groupId, contacts)+ }+ if (!ok) {+ AppMessages.show(context.getString(R.string.rcs_encrypted_failed))+ }+ }+ onOpenThread(thread) } else -> AppMessages.show("Groups aren't supported on this line") }
communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesThreadRow.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesThreadRow.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesThreadRow.ktindex 0c8a15e982..b5bcf4dd1b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesThreadRow.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesThreadRow.kt@@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip@@ -32,6 +33,7 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.sharedText+import kotlinx.coroutines.withContext @Composable internal fun MessageThreadRow(thread: SmsThread, onClick: () -> Unit, onDelete: () -> Unit = {}) {@@ -56,6 +58,26 @@ internal fun MessageThreadRow(thread: SmsThread, onClick: () -> Unit, onDelete: .sharedText("communicate-thread-title-${thread.threadId}"), ) LineBadge(thread.line, thread.subscriptionId, modifier = Modifier.padding(start = 6.dp))+ if (thread.line == com.vayunmathur.communicate.data.CommunicateLine.Rcs &&+ com.vayunmathur.communicate.data.rcs.RcsFeature.enabled+ ) {+ val rowId = thread.remoteId ?: thread.address+ val encrypted by androidx.compose.runtime.produceState(+ initialValue = false, rowId,+ ) {+ value = withContext(kotlinx.coroutines.Dispatchers.IO) {+ com.vayunmathur.communicate.data.rcs.e2e.RcsE2E+ .groupIdFor(context, rowId) != null+ }+ }+ if (encrypted) {+ com.vayunmathur.library.ui.IconLock(+ modifier = Modifier+ .padding(start = 4.dp)+ .size(14.dp),+ )+ }+ } Spacer(Modifier.weight(1f)) Spacer(Modifier.width(8.dp)) Text(
communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.ktindex 1f8c58ba03..03a2d8690f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt@@ -54,13 +54,14 @@ internal fun NewMessagePicker( choices: List<LineChoice>, onDismiss: () -> Unit, onCompose: (LineChoice, String) -> Unit,- onCreateGroup: (LineChoice, String, List<String>) -> Unit,+ onCreateGroup: (LineChoice, String, List<String>, Boolean) -> Unit, ) { val context = LocalContext.current val region = remember { deviceRegion(context) } var query by remember { mutableStateOf("") } var groupMode by remember { mutableStateOf(false) } var groupName by remember { mutableStateOf("") }+ var encryptedGroup by remember { mutableStateOf(false) } // Selected recipients for group mode, keyed by phone number (value = display label). val selectedContacts = remember { mutableStateListOf<Pair<String, String>>() } // Lines that support group chats: WhatsApp, Signal, RCS, and SIM (MMS). GV is 1:1 only.@@ -128,6 +129,35 @@ internal fun NewMessagePicker( singleLine = true, ) Spacer(Modifier.size(6.dp))+ // Closed-loop MLS encryption, RCS groups only (dev-gated,+ // needs the native library present).+ if (selected?.category == CommunicateLine.Rcs &&+ com.vayunmathur.communicate.data.rcs.RcsFeature.enabled &&+ com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto.isAvailable+ ) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp),+ ) {+ Text(+ stringResource(R.string.rcs_encrypted_group_toggle),+ style = MaterialTheme.typography.labelLarge,+ )+ Spacer(Modifier.weight(1f))+ com.vayunmathur.library.ui.Switch(+ checked = encryptedGroup,+ onCheckedChange = { encryptedGroup = it },+ )+ }+ if (encryptedGroup) {+ Text(+ stringResource(R.string.rcs_encrypted_group_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Spacer(Modifier.size(6.dp))+ }+ } if (selectedContacts.isNotEmpty()) { LazyRow( modifier = Modifier.fillMaxWidth(),@@ -198,7 +228,9 @@ internal fun NewMessagePicker( onClick = { val choice = selected if (choice != null && selectedContacts.isNotEmpty()) {- onCreateGroup(choice, groupName.trim(), selectedContacts.map { it.first })+ // Encryption only applies to RCS (toggle is hidden otherwise).+ val encrypted = encryptedGroup && choice.category == CommunicateLine.Rcs+ onCreateGroup(choice, groupName.trim(), selectedContacts.map { it.first }, encrypted) } }, enabled = selected != null && selectedContacts.size >= 1,
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex d57c1cd8ea..ca3aa0ced8 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -174,6 +174,10 @@ <string name="rcs_start_encrypted">Start encrypted chat</string> <string name="rcs_encrypted_started">Encrypted chat requested — messages lock once the peer joins</string> <string name="rcs_encrypted_failed">Couldn\'t start encrypted chat</string>+ <string name="rcs_encrypted_group_toggle">Encrypted group</string>+ <string name="rcs_encrypted_group_hint">Only members running this app can read messages. Set up once everyone\'s keys arrive.</string>+ <string name="rcs_encrypted_banner">🔒 Encrypted — only members can read these messages</string>+ <string name="rcs_encrypted_pending">🔒 Waiting for members\' keys — messages send plaintext until then</string> <string name="inapp_ongoing_call">Ongoing call</string> <string name="inapp_call_channel_name">Calls</string> <string name="inapp_incoming_call_channel_name">Incoming calls</string>