communicate: RCS remaining plan - SIP dialogs, MSRP, conference, E2EE, UI
- Commit
fcf15f594b457d77ced078591dc0db3a248f5e10- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-26 23:08 UTC (2 months ago)
- Parents
eb33a44
Diff
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex 3bd26c8105..56e4e14abd 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -76,6 +76,12 @@ sealed interface Route : NavKey { @Serializable data object RcsStatus : Route + @Serializable+ data class RcsVerify(val peerE164: String) : Route++ @Serializable+ data class RcsGroupMembers(val conversationId: String) : Route+ @Serializable data class Conversation( val threadId: Long,@@ -291,6 +297,18 @@ private fun CommunicateApp(initialDeepLink: DeepLink? = null) { onBack = { backStack.pop() }, ) }+ entry<Route.RcsVerify>(metadata = ListDetailPage()) { route ->+ com.vayunmathur.communicate.ui.rcs.RcsVerifyScreen(+ peerE164 = route.peerE164,+ onBack = { backStack.pop() },+ )+ }+ entry<Route.RcsGroupMembers>(metadata = ListDetailPage()) { route ->+ com.vayunmathur.communicate.ui.rcs.RcsGroupMembersScreen(+ conversationId = route.conversationId,+ onBack = { backStack.pop() },+ )+ } entry<Route.Conversation>(metadata = ListDetailPage() + MorphPage()) { route -> ConversationScreen( threadId = route.threadId,@@ -302,6 +320,8 @@ private fun CommunicateApp(initialDeepLink: DeepLink? = null) { participants = route.participants, groupTitle = route.groupTitle, onBack = { backStack.pop() },+ onOpenRcsVerify = { peer -> backStack.add(Route.RcsVerify(peer)) },+ onOpenRcsGroupMembers = { cid -> backStack.add(Route.RcsGroupMembers(cid)) }, ) } }
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 e5d117d6e0..a843854929 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt@@ -12,11 +12,14 @@ import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp import com.vayunmathur.communicate.data.rcs.RcsMsrp import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.ImdnDisposition+import com.vayunmathur.communicate.data.rcs.RcsOutbox import com.vayunmathur.communicate.data.rcs.RcsSipTransport import com.vayunmathur.communicate.data.rcs.buildEditBody import com.vayunmathur.communicate.data.rcs.buildGeopushBody import com.vayunmathur.communicate.data.rcs.buildRevokeBody+import com.vayunmathur.communicate.data.rcs.cacheInboundRcsWithImdn import com.vayunmathur.communicate.data.rcs.chunkLargeMessage+import com.vayunmathur.communicate.data.rcs.sendRcsDisplayReports import com.vayunmathur.library.util.AppMessages import java.util.UUID import kotlinx.coroutines.CoroutineScope@@ -182,7 +185,8 @@ suspend fun CommunicateRepository.sendRcsMessage( // Prefer an established session (MSRP) when one exists; else pager-mode CPIM. // When no session exists yet, kick off session establishment in the // background (best-effort — the pager send below still goes out now;- // later messages upgrade to MSRP once the dialog completes).+ // later messages upgrade to MSRP once the dialog completes). Backoff+ // after dialog errors (§1.6) skips the fast re-INVITE. val session = RcsSessionManager.sessionFor(recipient) if (session?.msrpRemotePath != null && attachments.isEmpty()) { val cpim = RcsSipTransport.buildCpimBody(body).toByteArray(Charsets.UTF_8)@@ -194,7 +198,8 @@ suspend fun CommunicateRepository.sendRcsMessage( } } if (session == null && attachments.isEmpty() && !recipient.startsWith("rcs-group:") &&- !recipient.contains("@") && !recipient.contains(":")+ !recipient.contains("@") && !recipient.contains(":") &&+ !RcsSessionManager.inDialogBackoff(recipient) ) { val peer = recipient sendScope.launch {@@ -223,8 +228,20 @@ suspend fun CommunicateRepository.sendRcsMessage( ) // Large Message: chunk oversized bodies with a shared Message-ID so // the far end reassembles; cache one row per send (snippet = full text).+ // Single-chunk 1:1 messages prefer the confirmed dialog (§1.4) when+ // one exists; multi-chunk stays pager-mode (one dialog CSeq per+ // chunk would serialize poorly and gain nothing). val messageId = "rcs-${UUID.randomUUID()}" val chunks = chunkLargeMessage(messageId, body)+ if (chunks.size == 1) {+ val inDialog = RcsSessionManager.sendInDialogMessage(recipient, content)+ if (inDialog) {+ if (body.isNotBlank()) {+ cacheOutgoingRcs(context, recipient, body, messageId)+ }+ return@withContext RcsSendResult.Sent+ }+ } var ok = true for ((index, chunk) in chunks.withIndex()) { val (line, head, payload) = if (chunks.size == 1) {@@ -239,7 +256,14 @@ suspend fun CommunicateRepository.sendRcsMessage( } ok = RcsSipTransport.sendSipMessage(line, head, payload) && ok }- if (!ok) return@withContext RcsSendResult.FallbackSms+ if (!ok) {+ // Transport accepted the capability check but the SIP leg failed+ // (transient): park for deferred retry (§4.3) AND report+ // FallbackSms so the caller still sends SMS now. Duplicate risk+ // (SMS now + RCS later) beats message loss on a dev-gated line.+ RcsOutbox.enqueue(context, recipient, body)+ return@withContext RcsSendResult.FallbackSms+ } if (body.isNotBlank()) { cacheOutgoingRcs(context, recipient, body, messageId) }@@ -380,6 +404,8 @@ suspend fun CommunicateRepository.markRcsRead( if (it.unreadCount != 0) db.conversationDao().upsert(it.copy(unreadCount = 0)) } }+ // Opening the thread displayed the messages — fire display IMDN (§4.2).+ sendRcsDisplayReports(context, cid) } /** Surface the SMS-fallback notice on the caller's behalf (never `Toast`). */
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.ktindex a25bea27ca..b649b517a6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsCapabilityExchange.kt@@ -45,10 +45,64 @@ object RcsCapabilityExchange { */ suspend fun isContactRcsCapable(context: Context, e164: String): Boolean { if (!RcsFeature.enabled || e164.isBlank()) return false+ // Fast path: single-contact availability (cheaper than capabilities,+ // §7.3). Falls back to the full query when the bridge is missing.+ if (runCatching { isContactAvailable(context, e164) }.getOrDefault(false)) return true val results = queryCapabilities(context, listOf(e164)) return results[e164] == true } + /**+ * Single-contact availability via `requestAvailability` (§7.3): cheaper+ * than `requestCapabilities` (presence-style, no feature-tag fetch).+ * Fail-closed false on any error. Throws SecurityException/ImsException+ * for the caller to map (mirrors the capabilities path).+ */+ private suspend fun isContactAvailable(context: Context, e164: String): Boolean {+ val app = context.applicationContext+ val subId = SubscriptionManager.getDefaultSmsSubscriptionId()+ if (!SubscriptionManager.isValidSubscriptionId(subId)) return false+ val ims = app.getSystemService(ImsManager::class.java) ?: return false+ val adapter = runCatching { ims.getImsRcsManager(subId).getUceAdapter() }.getOrNull()+ ?: return false+ val uri = Uri.fromParts("tel", e164, null)+ val caps: List<Map<String, Any?>> = suspendCancellableCoroutine { cont ->+ val collected = mutableListOf<Map<String, Any?>>()+ val bridged: Boolean = try {+ RcsHiddenApi.requestUceAvailability(+ adapter = adapter,+ contactUri = uri,+ executor = executor,+ callback = object : RcsHiddenApi.UceCallback {+ override fun onCapabilitiesReceived(caps: List<*>) {+ for (cap in caps) {+ readCapability(cap)?.let { collected += it }+ }+ }++ override fun onComplete() {+ if (cont.isActive) cont.resume(collected.toList())+ }++ override fun onError(errorCode: Int, retryAfterMillis: Long) {+ Log.w(TAG, "UCE availability error code=$errorCode")+ if (cont.isActive) cont.resume(collected.toList())+ }+ },+ )+ } catch (e: SecurityException) {+ uceAvailable = false+ if (cont.isActive) cont.resume(emptyList())+ false+ } catch (e: ImsException) {+ if (cont.isActive) cont.resume(emptyList())+ false+ }+ if (!bridged && cont.isActive) cont.resume(collected.toList())+ }+ return caps.any { isStrictlyCapable(it) }+ }+ /** * Batch capability check for group members. Returns the subset that is * RCS-capable. Empty on any failure.@@ -152,4 +206,17 @@ object RcsCapabilityExchange { } return true }++ /**+ * Strict variant for the availability fast path (§7.3): presence-style+ * FOUND without CPM tags does NOT short-circuit true (an RCS-presence+ * contact may still lack the CPM session tag — the full query decides).+ */+ private fun isStrictlyCapable(cap: Map<String, Any?>): Boolean {+ if (cap["result"] as? Int != REQUEST_RESULT_FOUND) return false+ if (cap["mechanism"] as? Int != CAPABILITY_MECHANISM_OPTIONS) return false+ @Suppress("UNCHECKED_CAST")+ val tags = cap["tags"] as? Set<String> ?: emptySet()+ return tags.any { it.contains("cpm.session", ignoreCase = true) }+ } }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsConferenceEvents.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsConferenceEvents.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsConferenceEvents.ktnew file mode 100644index 0000000000..7406d24b67--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsConferenceEvents.kt@@ -0,0 +1,120 @@+package com.vayunmathur.communicate.data.rcs++/**+ * Conference event package (RFC 4575 `conference-info`, RFC 4353 SUBSCRIBE/+ * NOTIFY for conferences).+ *+ * When we join a carrier-hosted focus, SUBSCRIBEing to `Event: conference`+ * at the focus URI yields the real participant list + join/part transitions+ * — without it we only know who we invited and who INVITEd us. When we host+ * (§3.2), we publish minimal NOTIFYs to our subscribers.+ *+ * All parsing/building here is pure string work (no transport, no session+ * map); the dialog flows live in `RcsSessionManager` + `RcsInboundDialog`.+ */+object RcsConferenceEvents {+ /** One participant from a `conference-info` document. */+ data class Participant(+ /** SIP URI of the endpoint. */+ val uri: String,+ /** `full` / `partial` state wrapper is handled by the caller. */+ val state: String,+ /** Display name when present. */+ val displayName: String?,+ )++ /** Parsed `conference-info`: entity (focus URI) + current users. */+ data class ConferenceInfo(+ val entity: String,+ val version: Int,+ val users: List<Participant>,+ )++ /**+ * Parse an `application/conference-info+xml` body. Returns null when the+ * body isn't conference-info. `state="deleted"` users are excluded (the+ * caller reconciles them out of the member set separately via+ * [deletedUris]).+ */+ fun parseConferenceInfo(body: String): ConferenceInfo? {+ if (!body.contains("conference-info", ignoreCase = true)) return null+ val entity = Regex("<conference-info[^>]*\\bentity=\"([^\"]+)\"", RegexOption.IGNORE_CASE)+ .find(body)?.groupValues?.getOrNull(1)?.trim().orEmpty()+ val version = Regex("<conference-info[^>]*\\bversion=\"(\\d+)\"", RegexOption.IGNORE_CASE)+ .find(body)?.groupValues?.getOrNull(1)?.toIntOrNull() ?: 0+ val users = mutableListOf<Participant>()+ val userRe = Regex(+ "<user[^>]*\\bentity=\"([^\"]+)\"[^>]*>(.*?)</user>",+ setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),+ )+ for (m in userRe.findAll(body)) {+ val uri = m.groupValues.getOrNull(1)?.trim() ?: continue+ val inner = m.groupValues.getOrNull(2).orEmpty()+ if (inner.contains("state=\"deleted\"", ignoreCase = true) ||+ inner.contains("<state>deleted</state>", ignoreCase = true)+ ) {+ continue+ }+ val state = Regex("<state>([^<]+)</state>", RegexOption.IGNORE_CASE)+ .find(inner)?.groupValues?.getOrNull(1)?.trim() ?: "full"+ val display = Regex("<display-text>([^<]*)</display-text>", RegexOption.IGNORE_CASE)+ .find(inner)?.groupValues?.getOrNull(1)?.trim()?.takeIf { it.isNotEmpty() }+ users += Participant(uri, state, display)+ }+ return ConferenceInfo(entity, version, users)+ }++ /** URIs in `state="deleted"` (parted members to reconcile out). */+ fun deletedUris(body: String): List<String> {+ if (!body.contains("conference-info", ignoreCase = true)) return emptyList()+ val out = mutableListOf<String>()+ val userRe = Regex(+ "<user[^>]*\\bentity=\"([^\"]+)\"[^>]*>(.*?)</user>",+ setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),+ )+ for (m in userRe.findAll(body)) {+ val inner = m.groupValues.getOrNull(2).orEmpty()+ if (inner.contains("state=\"deleted\"", ignoreCase = true) ||+ inner.contains("<state>deleted</state>", ignoreCase = true)+ ) {+ m.groupValues.getOrNull(1)?.trim()?.takeIf { it.isNotEmpty() }?.let { out += it }+ }+ }+ return out+ }++ /**+ * Build a minimal `conference-info` NOTIFY body for a hosted focus:+ * [focusUri] entity, [version] counter, [members] as full users.+ */+ fun buildConferenceInfo(focusUri: String, version: Int, members: Collection<String>): String =+ buildString {+ append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")+ append("<conference-info xmlns=\"urn:ietf:params:xml:ns:conference-info\"\n")+ append(" entity=\"$focusUri\" version=\"$version\" state=\"full\">\n")+ append(" <users>\n")+ for (member in members) {+ append(" <user entity=\"$member\" state=\"full\">\n")+ append(" <endpoint entity=\"$member\"><state>connected</state></endpoint>\n")+ append(" </user>\n")+ }+ append(" </users>\n")+ append("</conference-info>")+ }++ /**+ * Build a `message/sipfrag` body (RFC 3420) reporting a referral outcome,+ * e.g. `SIP/2.0 200 OK`. Sent inside NOTIFYs to a REFER referrer (§3.3).+ */+ fun buildSipfrag(statusCode: Int, reason: String): String = "SIP/2.0 $statusCode $reason"++ /** Parse a `message/sipfrag` body into (code, reason), or null. */+ fun parseSipfrag(body: String): Pair<Int, String>? {+ val trimmed = body.trim()+ if (!trimmed.startsWith("SIP/2.0")) return null+ val code = trimmed.substringAfter("SIP/2.0").trim().substringBefore(" ")+ .trim().toIntOrNull() ?: return null+ val reason = trimmed.substringAfter("SIP/2.0").trim().substringAfter(" ").trim()+ return code to reason+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.ktindex dd58e59431..d69ad64352 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt@@ -28,8 +28,9 @@ import com.vayunmathur.library.util.DatabaseMigrations RcsCachedMessage::class, RcsMlsIdentity::class, RcsMlsGroup::class,+ RcsOutboxMessage::class, ],- version = 2,+ version = 3, exportSchema = false, ) @ColumnTypeConverters(RcsTypeConverters::class)@@ -38,6 +39,7 @@ abstract class RcsDatabase : RoomDatabase() { abstract fun cachedMessageDao(): RcsCachedMessageDao abstract fun mlsIdentityDao(): RcsMlsIdentityDao abstract fun mlsGroupDao(): RcsMlsGroupDao+ abstract fun outboxDao(): RcsOutboxDao companion object : DatabaseMigrations { /**@@ -61,7 +63,35 @@ abstract class RcsDatabase : RoomDatabase() { } } - override val migrations = listOf(MIGRATION_1_2)+ /**+ * v2 → v3: display-receipt correlation (`imdnId` on cached rows),+ * deferred-delivery outbox, identity verification flag, MLS member+ * leaf-index tracking. Additive only; existing rows get defaults.+ */+ private val MIGRATION_2_3 = object : androidx.room3.migration.Migration(2, 3) {+ override suspend fun migrate(connection: androidx.sqlite.SQLiteConnection) {+ connection.execSQL(+ "ALTER TABLE `rcs_cached_message` ADD COLUMN `imdnId` TEXT NOT NULL DEFAULT ''",+ )+ connection.execSQL(+ "ALTER TABLE `rcs_mls_identity` ADD COLUMN `verified` INTEGER NOT NULL DEFAULT 0",+ )+ connection.execSQL(+ "ALTER TABLE `rcs_mls_group` ADD COLUMN `members` TEXT NOT NULL DEFAULT ''",+ )+ connection.execSQL(+ "CREATE TABLE IF NOT EXISTS `rcs_outbox` (" ++ "`messageId` TEXT NOT NULL, `conversationId` TEXT NOT NULL, " ++ "`kind` TEXT NOT NULL, `body` TEXT NOT NULL, " ++ "`attachments` TEXT NOT NULL, `attempts` INTEGER NOT NULL, " ++ "`nextRetryMs` INTEGER NOT NULL, `expiryMs` INTEGER NOT NULL, " ++ "`createdAt` INTEGER NOT NULL, " ++ "PRIMARY KEY(`messageId`))",+ )+ }+ }++ override val migrations = listOf(MIGRATION_1_2, MIGRATION_2_3) fun getDatabase(context: Context): RcsDatabase = RcsRepository.get(context).database()@@ -148,6 +178,12 @@ data class RcsCachedMessage( val ftMime: String? = null, /** Outgoing delivery status ordinal (MessageStatus ordinal). */ val status: Int = 0,+ /**+ * Inbound `imdn.Message-ID` for this row (outbound rows carry their own+ * id in [messageId]; inbound rows store the sender's id here so+ * display/read reports can reference it, §4.2).+ */+ val imdnId: String = "", ) @Dao@@ -198,12 +234,15 @@ data class RcsMlsIdentity( @PrimaryKey val e164: String, val identity: ByteArray, val updatedAt: Long = 0L,+ /** User-verified safety number (§5.4). Unverified by default. */+ val verified: Boolean = false, ) /** * One MLS group, keyed by hex-encoded MLS group id bytes. [storage] is the * opaque provider snapshot the crate needs on every call; [conversationId]- * maps back to the RCS thread.+ * maps back to the RCS thread. [members] tracks E.164 → leaf index+ * (`e164=index` CSV) for member removal (§5.2). */ @Entity(tableName = "rcs_mls_group") data class RcsMlsGroup(@@ -212,6 +251,7 @@ data class RcsMlsGroup( val conversationId: String, val storage: ByteArray, val updatedAt: Long = 0L,+ val members: String = "", ) @Dao@@ -243,3 +283,48 @@ interface RcsMlsGroupDao { @Query("DELETE FROM rcs_mls_group WHERE conversationId = :conversationId") suspend fun deleteByConversation(conversationId: String) }++// -- Deferred-delivery outbox (§4.3) --++/**+ * A message that failed to send and waits for retry: pager text, FT+ * reference, or group fan-out remainder. [kind] is `text` / `file` / `group`;+ * [body] carries the text (or caption); [attachments] the content URIs CSV+ * for files. Retried with backoff until [expiryMs], then marked failed.+ */+@Entity(tableName = "rcs_outbox")+data class RcsOutboxMessage(+ @PrimaryKey val messageId: String,+ val conversationId: String,+ val kind: String,+ val body: String,+ val attachments: String = "",+ val attempts: Int = 0,+ val nextRetryMs: Long,+ val expiryMs: Long,+ val createdAt: Long = 0L,+)++@Dao+interface RcsOutboxDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(message: RcsOutboxMessage)++ @Query("SELECT * FROM rcs_outbox WHERE nextRetryMs <= :nowMs ORDER BY nextRetryMs ASC LIMIT :limit")+ suspend fun dueForRetry(nowMs: Long, limit: Int = 20): List<RcsOutboxMessage>++ @Query("SELECT * FROM rcs_outbox WHERE messageId = :messageId LIMIT 1")+ suspend fun get(messageId: String): RcsOutboxMessage?++ @Query("DELETE FROM rcs_outbox WHERE messageId = :messageId")+ suspend fun delete(messageId: String)++ @Query("DELETE FROM rcs_outbox WHERE conversationId = :conversationId")+ suspend fun deleteConversation(conversationId: String)++ @Query("DELETE FROM rcs_outbox")+ suspend fun deleteAll()++ @Query("SELECT COUNT(*) FROM rcs_outbox")+ suspend fun count(): Int+}
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 91c6be8377..b747acdd1c 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@@ -125,6 +125,11 @@ object RcsFileTransferHttp { * Send a file to [recipient]: upload, then a CPIM FT message carrying the * URL + metadata, then cache the outgoing row. Returns true when the SIP * leg was accepted.+ *+ * Prefers an established MSRP session (§4.4): the bytes ride chunked+ * SENDs (with resume via REPORT correlation) and the descriptor carries+ * a JPEG thumbnail for images, so the far end renders instantly without+ * a download round-trip. */ suspend fun sendFile( context: Context,@@ -134,6 +139,10 @@ object RcsFileTransferHttp { caption: String = "", ): Boolean = withContext(Dispatchers.IO) { if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return@withContext false+ // MSRP path first when a session is bound.+ if (sendFileOverMsrp(context, repository, recipient, attachment, caption)) {+ return@withContext true+ } val url = upload(context, attachment) ?: return@withContext false val ftCpim = buildString { append("File-URL: $url\r\n")@@ -161,6 +170,121 @@ object RcsFileTransferHttp { ok } + /**+ * FT-over-MSRP (§4.4): when [recipient] has a bound MSRP session, send+ * the file bytes as chunked SENDs (resume via REPORT correlation is+ * inherent — chunks ack individually in `sendCpim`) followed by a CPIM+ * descriptor carrying metadata + a JPEG thumbnail for images. Falls back+ * (false) when no session/connection exists so the caller tries HTTP.+ */+ private suspend fun sendFileOverMsrp(+ context: Context,+ repository: CommunicateRepository,+ recipient: String,+ attachment: CommunicateAttachment,+ caption: String,+ ): Boolean = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext false+ val session = RcsSessionManager.sessionFor(recipient)+ ?.takeIf { it.msrpRemotePath != null } ?: return@withContext false+ val conn = RcsMsrpConnectionFor(context, session) ?: return@withContext false+ runCatching {+ val bytes = context.contentResolver.openInputStream(attachment.contentUri.toUri())+ ?.use { it.readBytes() }?.takeIf { it.isNotEmpty() } ?: return@runCatching false+ // 1. File bytes as application/octet-stream chunks.+ val fileCpim = buildFileCpim(+ fileName = attachment.fileName ?: "file",+ mime = attachment.mimeType,+ size = bytes.size.toLong(),+ caption = caption,+ ).toByteArray(Charsets.UTF_8)+ // 2. Thumbnail for images (small JPEG, base64 in the descriptor).+ val thumbB64 = if (attachment.mimeType.startsWith("image/", ignoreCase = true)) {+ makeThumbnail(bytes)?.let {+ android.util.Base64.encodeToString(it, android.util.Base64.NO_WRAP)+ }+ } else {+ null+ }+ val descriptor = buildString {+ append("File-Name: ${attachment.fileName ?: "file"}\r\n")+ append("File-MIME: ${attachment.mimeType}\r\n")+ append("File-Size: ${bytes.size}\r\n")+ if (!thumbB64.isNullOrBlank()) append("File-Thumb: $thumbB64\r\n")+ if (caption.isNotBlank()) append("\r\n$caption")+ }+ if (!conn.sendCpim(fileCpim, "message/cpim")) return@runCatching false+ if (!conn.sendCpim(descriptor.toByteArray(Charsets.UTF_8), "message/cpim")) {+ return@runCatching false+ }+ repository.cacheOutgoingRcsFile(+ context = context,+ conversationId = recipient,+ body = caption.ifBlank { attachment.fileName ?: "[file]" },+ messageId = "local-msrp-ft-${UUID.randomUUID()}",+ ftUrl = "msrp:${session.callId}",+ ftMime = attachment.mimeType,+ )+ conn.close()+ true+ }.getOrDefault(false)+ }++ /**+ * Live MSRP connection for [session]'s conversation, or null. Reuses the+ * sync service's connection when available is impossible here (no service+ * reference) — so this opens a short-lived connection for the transfer.+ * Prefer the persistent map when calling from service-owned code.+ */+ private suspend fun RcsMsrpConnectionFor(+ context: Context,+ session: com.vayunmathur.communicate.data.rcs.RcsSession,+ ): RcsMsrp.MsrpConnection? = withContext(Dispatchers.IO) {+ // One-shot connect for the transfer. Inbound chunks arriving on this+ // socket during the transfer window forward to the process-wide+ // dispatcher (set by the sync service) so nothing is dropped; the+ // connection closes when the transfer scope ends (see caller).+ val conversationId = session.conversationId+ RcsMsrp.connect(session, context) { contentType, body ->+ RcsMsrp.onInboundFallback?.invoke(conversationId, contentType, body)+ }+ }++ /** CPIM file descriptor (RCC.07 file-selector style metadata block). */+ internal fun buildFileCpim(fileName: String, mime: String, size: Long, caption: String): String =+ buildString {+ append("File-Name: $fileName\r\n")+ append("File-MIME: $mime\r\n")+ append("File-Size: $size\r\n")+ append("Content-Type: application/octet-stream\r\n")+ if (caption.isNotBlank()) append("\r\n$caption")+ }++ /**+ * Downscale [imageBytes] to a ≤320px JPEG thumbnail. Null when undecodable+ * or on any failure. Mirrors the WhatsApp avatar pattern (platform+ * BitmapFactory, recycled).+ */+ internal fun makeThumbnail(imageBytes: ByteArray): ByteArray? {+ return runCatching {+ val opts = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }+ android.graphics.BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size, opts)+ if (opts.outWidth <= 0 || opts.outHeight <= 0) return null+ var sample = 1+ while (opts.outWidth / sample > 320 || opts.outHeight / sample > 320) sample *= 2+ val decode = android.graphics.BitmapFactory.Options().apply { inSampleSize = sample }+ val bmp = android.graphics.BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size, decode)+ ?: return null+ val out = java.io.ByteArrayOutputStream()+ try {+ bmp.compress(android.graphics.Bitmap.CompressFormat.JPEG, 70, out)+ out.toByteArray().takeIf { it.isNotEmpty() }+ } finally {+ bmp.recycle()+ }+ }.getOrNull()+ }+ /** Parse an inbound FT CPIM body into [RcsFtInfo], or null. */ fun parseFtBody(body: String): RcsFtInfo? { val url = Regex("File-URL:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(body)@@ -204,7 +328,8 @@ object RcsFileTransferHttp { /** * Digest Authorization header from a WWW-Authenticate challenge. [password] * is the GBA-derived base64 key when bootstrapped, empty otherwise (the- * plain-digest fallback).+ * plain-digest fallback). Hash construction lives in [RcsGbaAuth] (shared+ * with SIP challenge retries). */ private fun digestAuthHeader( challenge: String,@@ -212,19 +337,13 @@ object RcsFileTransferHttp { 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)- ?.groupValues?.getOrNull(1).orEmpty()- val realm = param("realm")- val nonce = param("nonce")- if (realm.isBlank() || nonce.isBlank()) return ""- val cnonce = UUID.randomUUID().toString().replace("-", "").take(16)- 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\""- }+ ): String = RcsGbaAuth.digestAuthorizationHeader(+ challenge = challenge,+ method = method,+ uri = uri,+ username = username,+ password = password,+ ) /** Pull the FT content-server URI out of RCS config XML (ftHTTPCSURI). */ fun parseContentServer(configXml: ByteArray): String? {
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.ktindex 5ad7e15fd0..1b9839ac8f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsGbaAuth.kt@@ -55,6 +55,33 @@ object RcsGbaAuth { return md5("$ha1:$nonce:00000001:$cnonce:auth:$ha2") } + /**+ * Full digest `Authorization` header *value* from a `WWW-Authenticate` /+ * `Proxy-Authenticate` challenge (RFC 2617 qop=auth). Shared by SIP+ * challenge retries ([RcsSipTransport]) and FT-over-HTTP+ * ([RcsFileTransferHttp]). Empty when the challenge isn't digest or+ * lacks realm/nonce.+ */+ internal fun digestAuthorizationHeader(+ challenge: String,+ method: String,+ uri: String,+ username: String,+ password: String = "",+ cnonce: String = java.util.UUID.randomUUID().toString().replace("-", "").take(16),+ ): String {+ if (!challenge.contains("Digest", ignoreCase = true)) return ""+ fun param(name: String): String =+ Regex("$name=\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(challenge)+ ?.groupValues?.getOrNull(1).orEmpty()+ val realm = param("realm")+ val nonce = param("nonce")+ if (realm.isBlank() || nonce.isBlank()) return ""+ val response = 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\""+ }+ 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/RcsHiddenApi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.ktindex 8866b0eca7..a687eb284b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsHiddenApi.kt@@ -104,6 +104,61 @@ internal object RcsHiddenApi { fun onError(errorCode: Int, retryAfterMillis: Long) } + /**+ * `RcsUceAdapter#requestAvailability(Uri, Executor, CapabilitiesCallback)`+ * (`@SystemApi`, hidden; verified against frameworks/base on main).+ * Same callback interface as `requestCapabilities`, single contact.+ * Cheaper than a full capability fetch — use for the send-path+ * pre-check; full capabilities stay for group setup. Returns false when+ * the bridge itself fails.+ */+ fun requestUceAvailability(+ adapter: Any,+ contactUri: android.net.Uri,+ executor: java.util.concurrent.Executor,+ callback: UceCallback,+ ): Boolean {+ if (!RcsFeature.enabled) return false+ return runCatching {+ val callbackClass = Class.forName("android.telephony.ims.RcsUceAdapter\$CapabilitiesCallback")+ val proxy = java.lang.reflect.Proxy.newProxyInstance(+ adapter.javaClass.classLoader,+ arrayOf(callbackClass),+ ) { _, method, args ->+ when (method.name) {+ "onCapabilitiesReceived" -> {+ @Suppress("UNCHECKED_CAST")+ val caps = (args?.getOrNull(0) as? List<*>) ?: emptyList<Any>()+ callback.onCapabilitiesReceived(caps)+ }+ "onComplete" -> callback.onComplete()+ "onError" -> callback.onError(+ (args?.getOrNull(0) as? Int) ?: -1,+ (args?.getOrNull(1) as? Long) ?: 0L,+ )+ "toString" -> "RcsUceAvailabilityProxy"+ "hashCode" -> System.identityHashCode(callback)+ "equals" -> args?.getOrNull(0) === callback+ else -> null+ }+ }+ val method = adapter.javaClass.getMethod(+ "requestAvailability",+ android.net.Uri::class.java,+ java.util.concurrent.Executor::class.java,+ callbackClass,+ )+ method.invoke(adapter, contactUri, executor, proxy)+ true+ }.getOrElse {+ val cause = (it as? java.lang.reflect.InvocationTargetException)?.cause ?: it+ Log.w(TAG, "requestAvailability failed", cause)+ if (cause is SecurityException) throw cause+ if (cause is ImsException) throw cause+ false+ }+ }+ /** Dynamic-dispatch target for the provisioning proxy (config is raw XML bytes). */ interface ProvisioningCallback { fun onConfigurationChanged(configXml: ByteArray)
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 01e8c9be0e..9c4a49300a 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@@ -28,6 +28,14 @@ import kotlinx.coroutines.withContext object RcsMsrp { private const val TAG = "RcsMsrp" + /**+ * Process-wide fallback for inbound MSRP chunks arriving on transient+ * connections (e.g. FT-over-MSRP transfer sockets). The sync service sets+ * this to route into the inbox; unset (null) drops.+ */+ @Volatile+ var onInboundFallback: ((conversationId: String, contentType: String, body: ByteArray) -> Unit)? = null+ /** * A persistent MSRP connection for one session: one socket, reused across * SENDs, with a reader loop feeding inbound chunks to [onChunk].@@ -44,39 +52,128 @@ object RcsMsrp { internal fun launchReader(block: suspend () -> Unit) { readerScope.launch { block() } }++ /** Last I/O time (any direction); drives the keepalive (§2.5). */+ @Volatile internal var lastActivityMs: Long = System.currentTimeMillis()+ /**- * Send one CPIM payload as an MSRP SEND chunk. Returns true on a 200- * response. Thread-safe (single-writer lock).+ * Send one CPIM payload as chunked MSRP SENDs (§2.2): splits large+ * payloads into `Byte-Range` slices sharing one Message-ID, awaiting+ * a 2xx response per chunk. Returns true when every chunk was acked.+ * Thread-safe (single-writer lock). Acks are completed by the reader+ * loop ([pendingAcks]) — never read here, the stream is single-reader. */ private val writeLock = Any() - fun sendCpim(payload: ByteArray, contentType: String = "message/cpim"): Boolean {+ suspend fun sendCpim(payload: ByteArray, contentType: String = "message/cpim"): Boolean {+ if (closed || payload.isEmpty()) return false+ return runCatching {+ val chunks = RcsMsrpFraming.splitSend(+ toPath = remotePath,+ fromPath = localPath,+ payload = payload,+ contentType = contentType,+ )+ for (chunk in chunks) {+ val ack = kotlinx.coroutines.CompletableDeferred<Boolean>()+ synchronized(writeLock) {+ if (closed) return false+ pendingAcks[chunk.txid] = ack+ runCatching {+ val out = socket.getOutputStream()+ out.write(RcsMsrpFraming.serializeChunk(chunk))+ out.flush()+ lastActivityMs = System.currentTimeMillis()+ }.onFailure {+ pendingAcks.remove(chunk.txid)+ throw it+ }+ }+ val ok = try {+ kotlinx.coroutines.withTimeout(10_000L) { ack.await() }+ } catch (_: kotlinx.coroutines.TimeoutCancellationException) {+ false+ }+ pendingAcks.remove(chunk.txid)+ if (!ok) return false+ }+ true+ }.getOrElse {+ Log.w(TAG, "MSRP chunk send failed", it)+ false+ }+ }++ /**+ * Chunk ack futures, keyed by SEND txid. Completed by the reader loop+ * when the matching response arrives; senders await with timeout.+ */+ internal val pendingAcks =+ java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.CompletableDeferred<Boolean>>()++ /** Inbound REPORT notifications: (messageId, ns, code, reason). */+ internal val inboundReports =+ java.util.concurrent.ConcurrentLinkedQueue<ReportNotice>()++ internal data class ReportNotice(+ val messageId: String,+ val namespace: Int,+ val code: Int,+ val reason: String,+ )++ /** Send a keepalive empty SEND (§2.5). Best-effort. */+ internal fun sendKeepalive(): 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(RcsMsrpFraming.buildKeepalive(remotePath, localPath))+ out.flush()+ lastActivityMs = System.currentTimeMillis() }+ true+ }.getOrDefault(false)+ }++ /** Emit a REPORT for [messageId] (§2.1). Best-effort. */+ internal fun sendReport(+ messageId: String,+ statusCode: Int,+ reason: String,+ byteRange: String,+ ): Boolean {+ if (closed) return false+ return runCatching { 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.write(+ RcsMsrpFraming.buildReport(+ toPath = remotePath,+ fromPath = localPath,+ messageId = messageId,+ statusCode = statusCode,+ reason = reason,+ byteRange = byteRange,+ ),+ ) out.flush()+ lastActivityMs = System.currentTimeMillis() } true- }.getOrElse {- Log.w(TAG, "MSRP chunk send failed", it)- false+ }.getOrDefault(false)+ }++ /** Start the idle keepalive job (§2.5): empty SEND when quiet >60s. */+ internal fun launchKeepalive() {+ readerScope.launch {+ while (!closed) {+ kotlinx.coroutines.delay(30_000L)+ if (closed) break+ if (System.currentTimeMillis() - lastActivityMs >= 60_000L) {+ sendKeepalive()+ }+ } } } @@ -108,6 +205,7 @@ object RcsMsrp { ): MsrpConnection { val conn = MsrpConnection(socket, localPath, remotePath) conn.launchReader { readLoop(conn, socket, onChunk, head.replayBytes()) }+ conn.launchKeepalive() return conn } @@ -163,6 +261,7 @@ object RcsMsrp { // Reader loop: parse SEND chunks, auto-200 them, deliver bodies. // Owned by the connection; dies on close. conn.launchReader { readLoop(conn, socket, onChunk) }+ conn.launchKeepalive() conn }.getOrElse { Log.w(TAG, "MSRP connect failed", it)@@ -226,6 +325,13 @@ object RcsMsrp { } // Consume the end-marker line. runCatching { input.readLine() }+ conn.lastActivityMs = System.currentTimeMillis()+ // Keepalive empty SEND (§2.5): ack quietly, no delivery.+ val range = headers["byte-range"]+ if (range == RcsMsrpFraming.KEEPALIVE_RANGE) {+ sendResponse(socket, txid, 200, "OK", headers["from-path"].orEmpty())+ continue+ } // Auto-200 the peer SEND (RFC 4975 §7.1: To-Path echoes // the sender's From-Path, From-Path is our path). val peerFrom = headers["from-path"].orEmpty()@@ -236,7 +342,6 @@ object RcsMsrp { 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()@@ -245,9 +350,52 @@ object RcsMsrp { } else if (bodyBytes != null && bodyBytes.isNotEmpty()) { onChunk(contentType, bodyBytes) }+ } else if (method.equals("REPORT", ignoreCase = true)) {+ // Inbound REPORT (§2.1): consume through the end-marker,+ // queue the notice for the sync service (delivery+ // correlation), no auto-response needed.+ var guard = 0+ while (guard++ < 32) {+ val l = runCatching { input.readLine() }.getOrNull() ?: break+ if (l.startsWith("-------$txid")) break+ }+ conn.lastActivityMs = System.currentTimeMillis()+ val msgId = headers["message-id"].orEmpty()+ val status = headers["status"]?.let { RcsMsrpFraming.parseStatus(it) }+ if (msgId.isNotEmpty() && status != null) {+ conn.inboundReports.add(+ MsrpConnection.ReportNotice(+ messageId = msgId,+ namespace = status.first,+ code = status.second,+ reason = status.third,+ ),+ )+ }+ } else if (method.equals("AUTH", ignoreCase = true)) {+ // MSRP auth is not negotiated on this line (§2.3):+ // explicit 501, never silent. Consume the frame first.+ var guard = 0+ while (guard++ < 32) {+ val l = runCatching { input.readLine() }.getOrNull() ?: break+ if (l.startsWith("-------$txid")) break+ }+ val peerFrom = headers["from-path"].orEmpty()+ sendAuthNotImplemented(socket, txid, peerFrom) } else {- // Responses to our SENDs (handled inline by sendCpim today).- runCatching { input.readLine() }+ // Responses to our SENDs: complete the chunk ack future+ // (§2.2). Consume through the end-marker.+ val parsed = RcsMsrpFraming.parseResponseStart(line)+ var guard = 0+ while (guard++ < 32) {+ val l = runCatching { input.readLine() }.getOrNull() ?: break+ if (l.startsWith("-------$txid")) break+ }+ conn.lastActivityMs = System.currentTimeMillis()+ if (parsed != null) {+ conn.pendingAcks.remove(parsed.first)+ ?.complete(parsed.second in 200..299)+ } } } }@@ -309,6 +457,16 @@ object RcsMsrp { } } + /** 501 to an MSRP AUTH attempt (§2.3: auth is never negotiated here). */+ private fun sendAuthNotImplemented(socket: java.net.Socket, txid: String, toPath: String) {+ runCatching {+ val out = socket.getOutputStream()+ out.write(RcsMsrpFraming.buildErrorResponse(toPath, txid, 501, "Not Implemented"))+ out.flush()+ }+ Log.i(TAG, "Rejected MSRP AUTH with 501 (tx=$txid)")+ }+ /** Minimal byte buffer (avoids java.io.ByteArrayOutputStream import weight). */ private class ByteArrayOutputStream2 { private var buf = ByteArray(1024)@@ -332,9 +490,9 @@ object RcsMsrp { /** * Send [payload] (CPIM bytes) over an MSRP session bound to [session].- * Opens a TCP socket to the remote path when needed (IMS PDN preferred,- * see [connect]; TLS when [RcsSession.msrpSecure]). Returns true on a- * 200 response to our SEND.+ * Opens a socket to the remote path when needed (IMS PDN preferred, TLS+ * when [RcsSession.msrpSecure]), chunked per §2.2. Returns true when+ * every chunk got a 2xx. * * One-shot fallback; prefer [connect] for established sessions. */@@ -349,18 +507,13 @@ object RcsMsrp { val localPath = session.msrpLocalPath ?: "msrp://local.invalid/${UUID.randomUUID()};tcp" runCatching { val (host, port) = parseMsrpPath(remotePath) ?: return@runCatching false- val txid = UUID.randomUUID().toString().replace("-", "").take(12)- val messageId = UUID.randomUUID().toString()- val chunk = 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")- }+ val chunks = RcsMsrpFraming.splitSend(+ toPath = remotePath,+ fromPath = localPath,+ payload = payload,+ contentType = contentType,+ )+ if (chunks.isEmpty()) return@runCatching false val socket = if (session.msrpSecure) { val peerFp = peerFingerprintFor(session) ?: return@runCatching false RcsMsrpTls.clientSocket(context, host, port, peerFp)@@ -370,15 +523,30 @@ object RcsMsrp { ?: return@runCatching false } socket.use { s ->+ s.soTimeout = 10_000 val out = s.getOutputStream()- out.write(chunk.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()- val reply = s.getInputStream().bufferedReader(Charsets.UTF_8).readLine()- .orEmpty()- reply.contains(" 200 ")+ val input = s.getInputStream().bufferedReader(Charsets.UTF_8)+ for (chunk in chunks) {+ out.write(RcsMsrpFraming.serializeChunk(chunk))+ out.flush()+ // Await this chunk's response (responses are FIFO).+ var ok = false+ var guard = 0+ while (guard++ < 16) {+ val line = runCatching { input.readLine() }.getOrNull() ?: break+ val parsed = RcsMsrpFraming.parseResponseStart(line) ?: continue+ if (parsed.first != chunk.txid) continue+ var end = 0+ while (end++ < 32) {+ val l = runCatching { input.readLine() }.getOrNull() ?: break+ if (l.startsWith("-------${chunk.txid}")) break+ }+ ok = parsed.second in 200..299+ break+ }+ if (!ok) return@runCatching false+ }+ true } }.getOrElse { Log.w(TAG, "MSRP send failed", it)
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpFraming.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpFraming.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpFraming.ktnew file mode 100644index 0000000000..ea97ed837e--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpFraming.kt@@ -0,0 +1,168 @@+package com.vayunmathur.communicate.data.rcs++import java.util.UUID++/**+ * Pure MSRP framing (RFC 4975): SEND chunk splitting, REPORT requests,+ * response matching, AUTH stubs, keepalive shape.+ *+ * Extracted from `RcsMsrp` for unit-testability — no sockets, no coroutines,+ * no Android. The socket object owns I/O; everything byte-shaping lives here.+ */+object RcsMsrpFraming {+ /** Default SEND chunk size for outgoing chunked transfers. */+ const val CHUNK_SIZE = 2048++ /** Keepalive: empty chunk range + no body (RFC 4975 §7.4). */+ const val KEEPALIVE_RANGE = "1-0/0"++ /** One outgoing SEND chunk: headers + body slice. */+ data class OutChunk(+ val txid: String,+ val messageId: String,+ /** Full head bytes (headers + blank line), ready to write. */+ val head: ByteArray,+ /** Body slice bytes. */+ val body: ByteArray,+ ) {+ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is OutChunk) return false+ return txid == other.txid && messageId == other.messageId &&+ head.contentEquals(other.head) && body.contentEquals(other.body)+ }++ override fun hashCode(): Int {+ var result = txid.hashCode()+ result = 31 * result + messageId.hashCode()+ result = 31 * result + head.contentHashCode()+ result = 31 * result + body.contentHashCode()+ return result+ }+ }++ /**+ * Split [payload] into SEND chunks of at most [chunkSize] bytes sharing+ * [messageId], with `Byte-Range: start-end/total` (§2.2). Single chunk+ * for small payloads (identical to the legacy one-shot shape).+ */+ fun splitSend(+ toPath: String,+ fromPath: String,+ payload: ByteArray,+ contentType: String = "message/cpim",+ messageId: String = UUID.randomUUID().toString(),+ chunkSize: Int = CHUNK_SIZE,+ failureReport: Boolean = true,+ successReport: Boolean = false,+ ): List<OutChunk> {+ if (payload.isEmpty()) return emptyList()+ val total = payload.size+ val out = mutableListOf<OutChunk>()+ var offset = 0+ while (offset < total) {+ val end = minOf(offset + chunkSize, total)+ val slice = payload.copyOfRange(offset, end)+ val txid = UUID.randomUUID().toString().replace("-", "").take(12)+ val head = buildString {+ append("MSRP $txid SEND\r\n")+ append("To-Path: $toPath\r\n")+ append("From-Path: $fromPath\r\n")+ append("Message-ID: $messageId\r\n")+ append("Byte-Range: ${offset + 1}-$end/$total\r\n")+ append("Failure-Report: ${if (failureReport) "yes" else "no"}\r\n")+ append("Success-Report: ${if (successReport) "yes" else "no"}\r\n")+ append("Content-Type: $contentType\r\n")+ }.toByteArray(Charsets.UTF_8) + "\r\n".toByteArray(Charsets.UTF_8)+ out += OutChunk(txid, messageId, head, slice)+ offset = end+ }+ return out+ }++ /**+ * Serialize one chunk to wire bytes (head + body + end-marker), the exact+ * bytes the socket layer writes.+ */+ fun serializeChunk(chunk: OutChunk): ByteArray =+ chunk.head + chunk.body ++ "\r\n-------${chunk.txid}\$\r\n".toByteArray(Charsets.UTF_8)++ /**+ * Build a REPORT request (§2.1, RFC 4975 §7.1/§8): [status] is a+ * `namespace + code` pair, e.g. `000 200 OK`. [byteRange] echoes the+ * failed/acked range.+ */+ fun buildReport(+ toPath: String,+ fromPath: String,+ messageId: String,+ statusNamespace: Int = 0,+ statusCode: Int,+ reason: String,+ byteRange: String,+ ): ByteArray {+ val txid = UUID.randomUUID().toString().replace("-", "").take(12)+ return buildString {+ append("MSRP $txid REPORT\r\n")+ append("To-Path: $toPath\r\n")+ append("From-Path: $fromPath\r\n")+ append("Message-ID: $messageId\r\n")+ append("Byte-Range: $byteRange\r\n")+ append("Status: ${"%03d".format(statusNamespace)} $statusCode $reason\r\n")+ }.toByteArray(Charsets.UTF_8) ++ "\r\n-------$txid\$\r\n".toByteArray(Charsets.UTF_8)+ }++ /** Build a keepalive empty SEND (§2.5): no body, `Byte-Range: 1-0/0`. */+ fun buildKeepalive(toPath: String, fromPath: String): ByteArray {+ val txid = UUID.randomUUID().toString().replace("-", "").take(12)+ return buildString {+ append("MSRP $txid SEND\r\n")+ append("To-Path: $toPath\r\n")+ append("From-Path: $fromPath\r\n")+ append("Byte-Range: $KEEPALIVE_RANGE\r\n")+ append("Failure-Report: no\r\n")+ append("Success-Report: no\r\n")+ }.toByteArray(Charsets.UTF_8) ++ "\r\n-------$txid\$\r\n".toByteArray(Charsets.UTF_8)+ }++ /** Build a minimal error response (413/415/481/501…) to [txid]. */+ fun buildErrorResponse(toPath: String, txid: String, code: Int, reason: String): ByteArray =+ buildString {+ append("MSRP $txid $code $reason\r\n")+ if (toPath.isNotBlank()) append("To-Path: $toPath\r\n")+ append("\r\n")+ }.toByteArray(Charsets.UTF_8) ++ "-------$txid\$\r\n".toByteArray(Charsets.UTF_8)++ /** Parse an MSRP response start line into (txid, code, reason), or null. */+ fun parseResponseStart(line: String): Triple<String, Int, String>? {+ if (!line.startsWith("MSRP ")) return null+ val parts = line.split(" ")+ if (parts.size < 3) return null+ // MSRP <txid> SEND/REPORT (request) vs MSRP <txid> <code> (response):+ // requests have an all-alpha method token.+ val third = parts[2]+ if (third.all { it.isLetter() }) return null+ val code = third.toIntOrNull() ?: return null+ return Triple(parts[1], code, parts.drop(3).joinToString(" "))+ }++ /** True when [line] is an MSRP request (SEND/REPORT/AUTH/…). */+ fun isRequest(line: String): Boolean {+ if (!line.startsWith("MSRP ")) return false+ val third = line.split(" ").getOrNull(2).orEmpty()+ return third.isNotEmpty() && third.all { it.isLetter() }+ }++ /** Parse a Status header value into (namespace, code, reason), or null. */+ fun parseStatus(value: String): Triple<Int, Int, String>? {+ val parts = value.trim().split(" ", limit = 3)+ if (parts.size < 2) return null+ val ns = parts[0].toIntOrNull() ?: return null+ val code = parts[1].toIntOrNull() ?: return null+ return Triple(ns, code, parts.getOrElse(2) { "" })+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsOutbox.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsOutbox.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsOutbox.ktnew file mode 100644index 0000000000..3b2b65ce7b--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsOutbox.kt@@ -0,0 +1,161 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.util.Log+import com.vayunmathur.communicate.data.CommunicateAttachment+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.RcsSendResult+import com.vayunmathur.communicate.data.sendRcsMessage+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Deferred-delivery outbox (§4.3, UP deferred messaging): failed sends park+ * here with backoff and retry until expiry (default 7 days), then surface+ * as failed. The sync service pumps [pumpDue] periodically; sends also+ * enqueue on transport failure instead of silently dropping.+ *+ * Kinds: `text` (body re-sent as-is), `file` (attachments CSV re-uploaded),+ * `group` (fan-out re-attempted). Pager-mode sends carry an `Expiry` header+ * (RCC.07 deferred delivery) so the network holds them for offline peers.+ */+object RcsOutbox {+ private const val TAG = "RcsOutbox"++ /** Default deferred-delivery window (UP: up to 7 days store-and-forward). */+ const val DEFAULT_EXPIRY_MS = 7L * 24 * 3600 * 1000++ private const val MAX_ATTEMPTS = 12++ /** Backoff schedule: 1m, 5m, 15m, 1h, 4h, then 12h. */+ private fun backoffMs(attempts: Int): Long = when {+ attempts <= 0 -> 60_000L+ attempts == 1 -> 5 * 60_000L+ attempts == 2 -> 15 * 60_000L+ attempts == 3 -> 3600_000L+ attempts == 4 -> 4 * 3600_000L+ else -> 12 * 3600_000L+ }++ /**+ * Park a failed send for retry. Returns the outbox id, or null when the+ * gate is off / the payload is empty. Never throws.+ */+ suspend fun enqueue(+ context: Context,+ conversationId: String,+ body: String,+ attachments: List<CommunicateAttachment> = emptyList(),+ isGroup: Boolean = false,+ expiryMs: Long = System.currentTimeMillis() + DEFAULT_EXPIRY_MS,+ ): String? = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext null+ if (body.isBlank() && attachments.isEmpty()) return@withContext null+ runCatching {+ val id = "outbox-${UUID.randomUUID()}"+ val kind = when {+ isGroup -> "group"+ attachments.isNotEmpty() -> "file"+ else -> "text"+ }+ RcsDatabase.getDatabase(context).outboxDao().upsert(+ RcsOutboxMessage(+ messageId = id,+ conversationId = conversationId,+ kind = kind,+ body = body,+ attachments = attachments.joinToString(",") { it.contentUri },+ attempts = 0,+ nextRetryMs = System.currentTimeMillis() + backoffMs(0),+ expiryMs = expiryMs,+ createdAt = System.currentTimeMillis(),+ ),+ )+ id+ }.getOrElse {+ Log.w(TAG, "Outbox enqueue failed", it)+ null+ }+ }++ /**+ * Retry due messages (called periodically by the sync service). Each due+ * row re-sends via the normal path; success deletes it, failure bumps+ * attempts + backoff, expiry deletes + marks failed. Returns (retried,+ * sent) counts. Never throws.+ */+ suspend fun pumpDue(+ context: Context,+ repository: CommunicateRepository,+ ): Pair<Int, Int> = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext 0 to 0+ var retried = 0+ var sent = 0+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ val now = System.currentTimeMillis()+ for (row in db.outboxDao().dueForRetry(now)) {+ retried+++ if (now >= row.expiryMs || row.attempts >= MAX_ATTEMPTS) {+ db.outboxDao().delete(row.messageId)+ markOutboxFailed(context, row)+ continue+ }+ val result = runCatching {+ val attachments = row.attachments.split(",")+ .filter { it.isNotBlank() }+ .map { uri ->+ CommunicateAttachment(+ contentUri = uri,+ mimeType = "application/octet-stream",+ )+ }+ repository.sendRcsMessage(+ context = context,+ address = row.conversationId,+ body = row.body,+ threadRemoteId = row.conversationId,+ attachments = attachments,+ participants = emptyList(),+ )+ }.getOrDefault(RcsSendResult.Failed)+ if (result == RcsSendResult.Sent) {+ db.outboxDao().delete(row.messageId)+ sent+++ } else {+ val attempts = row.attempts + 1+ db.outboxDao().upsert(+ row.copy(+ attempts = attempts,+ nextRetryMs = now + backoffMs(attempts),+ ),+ )+ }+ }+ }.onFailure { Log.w(TAG, "Outbox pump failed", it) }+ retried to sent+ }++ /** Pending outbox count (badge for the status screen). */+ suspend fun pendingCount(context: Context): Int = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext 0+ runCatching { RcsDatabase.getDatabase(context).outboxDao().count() }.getOrDefault(0)+ }++ private suspend fun markOutboxFailed(context: Context, row: RcsOutboxMessage) {+ runCatching {+ val db = RcsDatabase.getDatabase(context)+ db.cachedMessageDao().upsert(+ RcsCachedMessage(+ messageId = row.messageId,+ conversationId = row.conversationId,+ body = row.body.ifBlank { "[expired]" },+ timestamp = System.currentTimeMillis(),+ outgoing = true,+ status = 4,+ ),+ )+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.ktindex 9bbcbe2d9b..f95de9aac0 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioning.kt@@ -141,19 +141,31 @@ object RcsProvisioning { } /**- * Optional TS.43 entitlement HTTP check against the carrier config server.- * Best-effort: any failure maps to `Unavailable`, never throws. The carrier- * URL is dynamic, so system trust is used.+ * TS.43 entitlement check against the carrier config server (§7.1).+ * Real flow: GET `<url>?vers=<version>&terminal=<model>` with the+ * proper Accept header; a 200 whose body names an RCS config endpoint+ * means entitled. Best-effort: any failure maps to false, never throws.+ * The carrier URL is dynamic, so system trust is used. */ suspend fun entitlementCheck(context: Context, url: String): Boolean { if (!RcsFeature.enabled || url.isBlank()) return false return runCatching {+ val terminal = "${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}"+ val query = url + (if (url.contains("?")) "&" else "?") ++ "vers=1.0&terminal=${java.net.URLEncoder.encode(terminal, "UTF-8")}" val response = NetworkClient.performRequest(- url = url,+ url = query, method = "GET",+ headers = mapOf("Accept" to "text/xml, application/xml, text/plain"), useSystemTrust = true, )- response.isSuccess+ if (!response.isSuccess) return@runCatching false+ // Entitled responses name the config server / token. Absent both+ // but HTTP-200 → treat as entitled (some carriers return empty).+ val body = response.body+ body.isBlank() || body.contains("config", ignoreCase = true) ||+ body.contains("token", ignoreCase = true) ||+ body.contains("rcs", ignoreCase = true) }.getOrDefault(false) }
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 1e482fc81e..3fe193d50e 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@@ -44,6 +44,22 @@ data class RcsSession( * on either side); plaintext otherwise. Both socket directions honor it. */ val msrpSecure: Boolean = false,+ /**+ * Next CSeq number for in-dialog requests (RFC 3261 §12.2: each new+ * request in the dialog increments; ACK reuses the INVITE's CSeq).+ * Starts at 2 — CSeq 1 is the initial INVITE.+ */+ val nextCseq: Long = 2L,+ /** Peer's Contact URI from the 200 OK (in-dialog Request-URI). */+ val remoteContact: String? = null,+ /** Recorded route set from the 200 OK (`Record-Route`, reversed). */+ val routeSet: List<String> = emptyList(),+ /** True once the dialog is confirmed (ACK sent for our INVITE's 2xx, or+ * ACK received for an incoming INVITE we answered). Unconfirmed dialogs+ * exist for in-dialog MESSAGE but not media. */+ val confirmed: Boolean = false,+ /** CSeq number of our initial INVITE (echoed by the ACK, RFC 3261 §13). */+ val inviteCseq: Long = 1L, val createdAt: Long = System.currentTimeMillis(), )
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionFocus.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionFocus.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionFocus.ktnew file mode 100644index 0000000000..a2c7ba11bb--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionFocus.kt@@ -0,0 +1,339 @@+package com.vayunmathur.communicate.data.rcs++import android.util.Log+import java.util.UUID+import java.util.concurrent.ConcurrentHashMap++/**+ * Conference focus management for [RcsSessionManager], split for file length.+ * Extension functions + focus-owned state (member sets, event subscriptions,+ * subscriber lists, version counters). The dialog/session core stays in the+ * manager; everything focus-shaped lives here.+ */++/** Participants of hosted foci: focus URI → member E.164 set. */+private val focusMembersMap = ConcurrentHashMap<String, MutableSet<String>>()++/**+ * Conference-event subscriptions WE hold (focus URI → dialog data for+ * the SUBSCRIBE dialog to a carrier focus, §3.1).+ */+private data class EventSubscription(+ val focusUri: String,+ val callId: String,+ val localTag: String,+ val remoteTag: String = "",+ val lastVersion: Int = -1,+)++private val eventSubs = ConcurrentHashMap<String, EventSubscription>()++/**+ * SUBSCRIBE dialogs on hosted foci (subscriber Call-ID → focus URI, §3.1+ * publish side). NOTIFYs go out on each membership change.+ */+private val focusSubscribers = ConcurrentHashMap<String, String>()++/** Conference-info version counter per hosted focus. */+private val focusVersions = ConcurrentHashMap<String, Int>()++/**+ * Host a group conference (focus role, UP 3.x conference model).+ *+ * Unlike joining a carrier focus via [RcsSessionManager.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 RcsSessionManager.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,+ ))+ focusMembersMap[focusUri] = distinct.toMutableSet()+ var invited = false+ for (peer in distinct) {+ if (sendReferToFocus(peer, focusUri, subject)) invited = true+ }+ if (!invited) {+ _sessions.value = _sessions.value - conversationId+ focusMembersMap.remove(focusUri)+ return null+ }+ Log.i(TAG, "Hosting focus $focusUri for $conversationId (${distinct.size} invited)")+ return focusUri+}++/** Members of the hosted focus [focusUri], or null when not ours. */+fun RcsSessionManager.focusMembers(focusUri: String): Set<String>? =+ focusMembersMap[focusUri]?.toSet()++/** Focus URI we host for [conversationId], or null when we don't host it. */+fun RcsSessionManager.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 RcsSessionManager.noteFocusJoin(focusUri: String, member: String) {+ focusMembersMap[focusUri]?.add(member.trim())+}++/** Drop a member from a hosted focus (BYE / removal). */+fun RcsSessionManager.noteFocusLeave(focusUri: String, member: String) {+ focusMembersMap[focusUri]?.remove(member.trim())+}++/** Tear down a hosted focus: BYE every joined member dialog, drop state. */+suspend fun RcsSessionManager.destroyHostedFocus(conversationId: String): Boolean {+ val session = _sessions.value[conversationId] ?: return true+ if (!session.isFocus) return terminateSession(conversationId)+ val focusUri = session.remoteUri+ // BYE every joined member dialog first (§3.2), best-effort.+ val members = focusMembersMap.remove(focusUri)?.toList().orEmpty()+ for (member in members) {+ runCatching {+ val dialogEntry = _sessions.value.entries.firstOrNull {+ it.value.callId.endsWith(member.hashCode().toString()) ||+ it.value.remoteUri == member+ }+ if (dialogEntry != null) terminateSession(dialogEntry.key)+ }+ }+ focusSubscribers.entries.removeIf { it.value == focusUri }+ focusVersions.remove(focusUri)+ _sessions.value = _sessions.value - conversationId+ RcsMsrpListen.dropPending(conversationId)+ return true+}++/**+ * Invite [peer] to our hosted [focusUri]: REFER + member-set add (§3.2).+ * Returns true when the REFER was accepted by the transport. Publishes a+ * conference-info NOTIFY to subscribers on change.+ */+suspend fun RcsSessionManager.inviteFocusMember(+ conversationId: String,+ peer: String,+ subject: String = "",+): Boolean {+ if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false+ val session = _sessions.value[conversationId]?.takeIf { it.isFocus } ?: return false+ val member = peer.trim()+ if (member.isEmpty()) return false+ val ok = sendReferToFocus(member, session.remoteUri, subject)+ if (ok) {+ focusMembersMap[session.remoteUri]?.add(member)+ publishConferenceInfo(session.remoteUri)+ }+ return ok+}++/**+ * Remove [peer] from our hosted focus: BYE their dialog + member-set+ * drop (§3.2). Returns true when the member was tracked (BYE itself is+ * best-effort). Publishes a conference-info NOTIFY to subscribers.+ */+suspend fun RcsSessionManager.removeFocusMember(conversationId: String, peer: String): Boolean {+ if (!RcsFeature.enabled) return false+ val session = _sessions.value[conversationId]?.takeIf { it.isFocus } ?: return false+ val member = peer.trim()+ val removed = focusMembersMap[session.remoteUri]?.remove(member) == true+ // BYE any dialog joined by this member.+ val dialogEntry = _sessions.value.entries.firstOrNull {+ !it.value.isFocus && it.value.remoteUri == member &&+ it.value.conversationId == conversationId+ }+ if (dialogEntry != null && RcsSipTransport.canSend()) {+ runCatching { terminateSession(dialogEntry.key) }+ }+ noteFocusLeave(session.remoteUri, member)+ publishConferenceInfo(session.remoteUri)+ return removed+}++/**+ * SUBSCRIBE to `Event: conference` at a carrier [focusUri] (§3.1) so+ * participant joins/parts arrive as NOTIFYs. Out-of-dialog subscription;+ * refresh is the caller's job (see [refreshEventSubscriptions]).+ */+suspend fun RcsSessionManager.subscribeConferenceEvents(focusUri: String, conversationId: String): Boolean {+ if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false+ if (eventSubs.containsKey(conversationId)) return true+ val cfg = RcsSipTransport.lastConfigSnapshot()+ val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+ val callId = "${UUID.randomUUID()}@rcs-sub"+ val localTag = UUID.randomUUID().toString().take(8)+ val branch = RcsSipDialog.newBranch()+ val startLine = "SUBSCRIBE $focusUri 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=$localTag\r\n")+ append("To: <$focusUri>\r\n")+ append("Call-ID: $callId\r\n")+ append("CSeq: 1 SUBSCRIBE\r\n")+ append("Event: conference\r\n")+ append("Accept: application/conference-info+xml\r\n")+ append("Expires: 3600\r\n")+ append("Contact: <$from>\r\n")+ append("Content-Length: 0\r\n")+ }+ val ok = RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0))+ if (ok) {+ eventSubs[conversationId] = EventSubscription(focusUri, callId, localTag)+ }+ return ok+}++/**+ * Refresh conference-event subscriptions (re-SUBSCRIBE before expiry).+ * Called periodically by the sync service; each refresh bumps CSeq.+ */+suspend fun RcsSessionManager.refreshEventSubscriptions() {+ if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return+ for ((conversationId, sub) in eventSubs) {+ runCatching {+ val cfg = RcsSipTransport.lastConfigSnapshot()+ val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+ val branch = RcsSipDialog.newBranch()+ val headers = buildString {+ append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+ append("Max-Forwards: 70\r\n")+ append("From: <$from>;tag=${sub.localTag}\r\n")+ append("To: <${sub.focusUri}>;tag=${sub.remoteTag}\r\n")+ append("Call-ID: ${sub.callId}\r\n")+ append("CSeq: 2 SUBSCRIBE\r\n")+ append("Event: conference\r\n")+ append("Accept: application/conference-info+xml\r\n")+ append("Expires: 3600\r\n")+ append("Contact: <$from>\r\n")+ append("Content-Length: 0\r\n")+ }+ RcsSipTransport.sendSipMessage("SUBSCRIBE ${sub.focusUri} SIP/2.0", headers, ByteArray(0))+ }+ }+}++/**+ * Route an inbound conference-info NOTIFY body for [conversationId]:+ * reconcile added members in + deleted members out, returning the added+ * + removed URI lists. Stale versions (≤ last seen) are ignored.+ */+fun RcsSessionManager.onConferenceNotify(conversationId: String, body: String): Pair<List<String>, List<String>> {+ val info = RcsConferenceEvents.parseConferenceInfo(body) ?: return emptyList<String>() to emptyList()+ val sub = eventSubs[conversationId]+ if (sub != null && info.version <= sub.lastVersion) return emptyList<String>() to emptyList()+ if (sub != null) eventSubs[conversationId] = sub.copy(lastVersion = info.version)+ val added = info.users.map { it.uri }.filter { it.isNotBlank() }+ val removed = RcsConferenceEvents.deletedUris(body)+ // Reconcile hosted-focus membership when the NOTIFY targets our focus.+ val hosted = _sessions.value[conversationId]?.takeIf { it.isFocus }+ if (hosted != null) {+ focusMembersMap[hosted.remoteUri]?.let { set ->+ set.removeAll(removed.toSet())+ set.addAll(added)+ }+ }+ return added to removed+}++/** Record an inbound SUBSCRIBE to our hosted focus (NOTIFY target). */+fun RcsSessionManager.noteFocusSubscriber(subscriberCallId: String, focusUri: String) {+ focusSubscribers[subscriberCallId] = focusUri+}++/** Drop a focus subscriber (unsubscribe / expiry). */+fun RcsSessionManager.dropFocusSubscriber(subscriberCallId: String) {+ focusSubscribers.remove(subscriberCallId)+}++/**+ * Publish `conference-info` NOTIFYs to all subscribers of [focusUri]+ * (§3.1 publish side). Best-effort per subscriber; never throws.+ */+suspend fun RcsSessionManager.publishConferenceInfo(focusUri: String) {+ if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return+ val members = focusMembersMap[focusUri]?.toList() ?: return+ val subscribers = focusSubscribers.entries.filter { it.value == focusUri }+ if (subscribers.isEmpty()) return+ val version = (focusVersions[focusUri] ?: 0) + 1+ focusVersions[focusUri] = version+ val body = RcsConferenceEvents.buildConferenceInfo(focusUri, version, members)+ .toByteArray(Charsets.UTF_8)+ val cfg = RcsSipTransport.lastConfigSnapshot()+ val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+ for ((subCallId, _) in subscribers) {+ runCatching {+ val branch = RcsSipDialog.newBranch()+ 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: <$focusUri>\r\n")+ append("Call-ID: $subCallId\r\n")+ append("CSeq: 1 NOTIFY\r\n")+ append("Event: conference\r\n")+ append("Subscription-State: active;expires=3600\r\n")+ append("Content-Type: application/conference-info+xml\r\n")+ append("Content-Length: ${body.size}\r\n")+ }+ RcsSipTransport.sendSipMessage("NOTIFY $focusUri SIP/2.0", headers, body)+ }+ }+}++/**+ * REFER one peer to our hosted focus: `REFER sip:peer` with `Refer-To:+ * <focusUri>` + `Referred-By` us. Their client INVITEs the focus URI back.+ */+internal suspend fun RcsSessionManager.sendReferToFocus(+ peer: String,+ focusUri: String,+ subject: String,+): Boolean {+ val cfg = RcsSipTransport.lastConfigSnapshot()+ val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+ val branch = RcsSipDialog.newBranch()+ 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))+}
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 fe1c2da521..ebbe0b4c72 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@@ -22,13 +22,13 @@ import kotlinx.coroutines.flow.asStateFlow * established, exactly like ChatManager's session-init gate. */ object RcsSessionManager {- private const val TAG = "RcsSession"+ internal const val TAG = "RcsSession" - private val _sessions = MutableStateFlow<Map<String, RcsSession>>(emptyMap())+ internal val _sessions = MutableStateFlow<Map<String, RcsSession>>(emptyMap()) val sessions: StateFlow<Map<String, RcsSession>> = _sessions.asStateFlow() /** Transaction id (Via branch) → session, for response routing. */- private val transactions = ConcurrentHashMap<String, String>()+ internal val transactions = ConcurrentHashMap<String, String>() /** Typing state per conversation: conversationId → (active, updatedAt). */ private val _typing = MutableStateFlow<Map<String, Boolean>>(emptyMap())@@ -114,91 +114,7 @@ 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- RcsMsrpListen.dropPending(conversationId)- return true- }+ /** Focus state + management live in `RcsSessionFocus.kt` (split for file length). */ /** * Drop sessions that never completed (no remote tag after [maxAgeMs])@@ -233,31 +149,6 @@ object RcsSessionManager { return dropped } - /**- * 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))- }- /** * Advertise our listen path for [conversationId] when the passive * listener can bind. Null when listening is unavailable — callers fall@@ -379,7 +270,7 @@ object RcsSessionManager { } /** Inbound offer details stashed at INVITE time for [acceptIncoming]. */- private data class PendingOffer(+ internal data class PendingOffer( val remotePath: String?, val setup: MsrpSetup?, /** Raw offer SDP (for TLS/fingerprint detection at answer time). */@@ -388,27 +279,61 @@ object RcsSessionManager { val peerFingerprint: String? = null, ) - private val _pendingOffers = ConcurrentHashMap<String, PendingOffer>()+ internal val _pendingOffers = ConcurrentHashMap<String, PendingOffer>() /** Peer's SDP answer fingerprint for an outgoing session ([callId]). */- private val _answerFingerprints = ConcurrentHashMap<String, String>()+ internal val _answerFingerprints = ConcurrentHashMap<String, String>() /** Stashed answer fingerprint for [callId], or null when absent. */ fun peerFingerprint(callId: String): String? = _answerFingerprints[callId] - /** Tear down the session for [conversationId] with BYE. */+ /**+ * Send a MESSAGE inside [conversationId]'s confirmed dialog (in-dialog+ * Request-URI + route set + next CSeq). Returns false when no confirmed+ * session exists (caller uses pager-mode). Advances the dialog CSeq.+ */+ suspend fun sendInDialogMessage(+ conversationId: String,+ body: ByteArray,+ contentType: String = "message/cpim",+ ): Boolean {+ if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false+ val session = _sessions.value[conversationId]+ ?.takeIf { it.confirmed && it.remoteTag.isNotBlank() } ?: return false+ val req = RcsSipDialog.buildInDialogMessage(session, body, contentType)+ val ok = RcsSipTransport.sendSipMessage(req.startLine, req.headers, req.body)+ if (ok) {+ _sessions.value = _sessions.value + (+ conversationId to session.copy(nextCseq = req.nextCseq)+ )+ }+ return ok+ }++ /** Tear down the session for [conversationId] with in-dialog BYE. */ suspend fun terminateSession(conversationId: String): Boolean { val session = _sessions.value[conversationId] ?: return true- val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"- val startLine = "BYE sip:${session.remoteUri} SIP/2.0"- val headers = buildString {- append("Via: SIP/2.0/TCP local;branch=$branch\r\n")- append("Call-ID: ${session.callId}\r\n")- append("CSeq: 2 BYE\r\n")- append("Content-Length: 0\r\n")+ val ok = if (session.confirmed && session.remoteTag.isNotBlank()) {+ // Confirmed dialog: in-dialog BYE with next CSeq + route set.+ val req = RcsSipDialog.buildInDialogBye(session)+ val sent = RcsSipTransport.sendSipMessage(req.startLine, req.headers, req.body)+ _sessions.value = _sessions.value + (+ conversationId to session.copy(nextCseq = req.nextCseq)+ )+ sent+ } else {+ // Unconfirmed/early dialog: best-effort BYE as before.+ val branch = RcsSipDialog.newBranch()+ val startLine = "BYE sip:${session.remoteUri} SIP/2.0"+ val headers = buildString {+ append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+ append("Call-ID: ${session.callId}\r\n")+ append("CSeq: 2 BYE\r\n")+ append("Content-Length: 0\r\n")+ }+ RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0)) }- val ok = RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0))- transactions.remove(branch)+ transactions.entries.removeIf { it.value == session.dialogId } _sessions.value = _sessions.value - conversationId _pendingOffers.remove(session.callId) _answerFingerprints.remove(session.callId)@@ -424,14 +349,24 @@ object RcsSessionManager { /** * Route an inbound SIP response (from the delegate message callback) to * its session: 200 OK to INVITE completes the dialog (remote tag + SDP- * answer), other finals tear the pending session down.+ * answer + route set) and sends the ACK (RFC 3261 §13.2.2.4); other+ * finals tear the pending session down.+ *+ * Suspend: the ACK goes through the transport. Never throws. */- fun onSipResponse(statusCode: Int, callId: String, remoteTag: String?, sdpAnswer: String?) {+ suspend fun onSipResponse(+ statusCode: Int,+ callId: String,+ remoteTag: String?,+ sdpAnswer: String?,+ responseHeaders: String = "",+ ) { val entry = _sessions.value.entries.firstOrNull { it.value.callId == callId } ?: return val session = entry.value if (statusCode in 200..299 && !remoteTag.isNullOrBlank()) { val (localPath, remotePath) = parseSdpPaths(sdpAnswer) val setup = parseSdpSetup(sdpAnswer)+ val (contact, routeSet) = RcsSipDialog.parseDialogRoute(responseHeaders) // TLS sticks when WE offered secure and the answer keeps it // (secure answer SDP); a plaintext answer to our secure offer is // a downgrade — honor it and run plaintext.@@ -442,13 +377,16 @@ object RcsSessionManager { _answerFingerprints[callId] = fp RcsMsrpListen.notePeerFingerprint(entry.key, fp) }- _sessions.value = _sessions.value + (entry.key to session.copy(+ val established = session.copy( remoteTag = remoteTag, msrpLocalPath = localPath ?: session.msrpLocalPath, msrpRemotePath = remotePath, msrpSetup = setup, msrpSecure = session.msrpSecure && answerSecure,- ))+ remoteContact = contact ?: session.remoteContact,+ routeSet = if (routeSet.isNotEmpty()) routeSet else session.routeSet,+ )+ _sessions.value = _sessions.value + (entry.key to established) // Usable when: peer is passive/actpass (we connect out, the v1 // path), OR peer is active and we have a listen path (they // connect to us — the accept loop completes the session), OR our@@ -457,21 +395,69 @@ object RcsSessionManager { val peerActive = setup == MsrpSetup.ACTIVE val usable = remotePath != null && ( !peerActive ||- session.msrpLocalPath?.contains("msrp://") == true &&+ established.msrpLocalPath?.contains("msrp://") == true && RcsMsrpListen.isListening() ) 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))+ (_sessions.value[entry.key] ?: established).copy(msrpRemotePath = null)) }+ // ACK the 2xx (RFC 3261 §13): same CSeq number as the INVITE,+ // Request-URI = answer Contact, confirmed dialog either way.+ val acked = runCatching {+ val (ackLine, ackHeaders) = RcsSipDialog.buildAck(+ (_sessions.value[entry.key] ?: established).copy(remoteTag = remoteTag),+ )+ RcsSipTransport.sendSipMessage(ackLine, ackHeaders, ByteArray(0))+ }.getOrDefault(false)+ _sessions.value = _sessions.value + (entry.key to+ ((_sessions.value[entry.key] ?: established).copy(confirmed = true)))+ if (!acked) Log.w(TAG, "ACK not accepted for $callId (dialog unconfirmed at SIP layer)") } else if (statusCode >= 300) { Log.w(TAG, "Session failed $callId code=$statusCode") transactions.entries.removeIf { it.value == session.dialogId } _sessions.value = _sessions.value - entry.key+ _answerFingerprints.remove(callId)+ RcsMsrpListen.dropPending(entry.key) } } + /**+ * Dialog-mismatch recovery (§1.6): 481/408/480/486/603 against [callId].+ * Closes MSRP state + framework dialog state, drops pending paths, and+ * parks the conversation in backoff so the send path doesn't hammer+ * session re-establishment. Never throws.+ */+ fun onDialogError(callId: String, statusCode: Int) {+ val entry = _sessions.value.entries.firstOrNull { it.value.callId == callId }+ if (entry != null) {+ _sessions.value = _sessions.value - entry.key+ RcsMsrpListen.dropPending(entry.key)+ backoffUntil[entry.key] = System.currentTimeMillis() + DIALOG_ERROR_BACKOFF_MS+ Log.w(TAG, "Dialog error $statusCode for ${entry.key}; backing off")+ }+ _pendingOffers.remove(callId)+ _answerFingerprints.remove(callId)+ transactions.entries.removeIf { it.value.endsWith(callId) }+ RcsSipTransport.cleanupSession(callId)+ }++ /** True when [conversationId] is in dialog-error backoff (skip fast re-INVITE). */+ fun inDialogBackoff(conversationId: String): Boolean {+ val until = backoffUntil[conversationId] ?: return false+ if (System.currentTimeMillis() >= until) {+ backoffUntil.remove(conversationId)+ return false+ }+ return true+ }++ private val backoffUntil = ConcurrentHashMap<String, Long>()++ /** Post-dialog-error quiet period before fast session re-establishment. */+ private const val DIALOG_ERROR_BACKOFF_MS = 5 * 60 * 1000L+ /** * Route an inbound SIP request: INVITE stashes the offer and starts an * incoming session entry (caller answers via [acceptIncoming] or declines@@ -531,6 +517,17 @@ object RcsSessionManager { if (entry != null) _sessions.value = _sessions.value - entry.key null }+ "ACK" -> {+ // ACK to our 200 OK: the incoming dialog is confirmed. Match+ // by Call-ID (the session was stored under the sender id).+ val entry = _sessions.value.entries.firstOrNull { it.value.callId == callId }+ if (entry != null) {+ _sessions.value = _sessions.value + (+ entry.key to entry.value.copy(confirmed = true)+ )+ }+ null+ } "MESSAGE" -> { val conversationId = fromUri.substringAfter("sip:").substringBefore("@") if (contentType?.contains("imdn", ignoreCase = true) == true) {@@ -604,7 +601,7 @@ object RcsSessionManager { * `TCP/MSRP`. The media proto/paths always agree (never a TLS path on a * plaintext `m=` line). */- private fun buildSdpOffer(+ internal fun buildSdpOffer( localIp: String?, listenPath: String?, tlsFingerprint: String? = null,@@ -647,7 +644,7 @@ object RcsSessionManager { * `msrps://`, or `a=fingerprint`) gets a TLS answer with our * fingerprint; otherwise plaintext. */- private fun buildSdpAnswer(+ internal fun buildSdpAnswer( localIp: String?, passivePath: String? = null, secure: Boolean = false,@@ -704,6 +701,63 @@ object RcsSessionManager { RcsMsrpTls.parseFingerprint(sdp) != null } + /** True when [callId] matches a live session dialog (re-INVITE/UPDATE target). */+ fun isKnownDialog(callId: String): Boolean =+ _sessions.value.values.any { it.callId == callId }++ /**+ * Apply a re-INVITE's SDP to a live dialog (§1.5): update the bound+ * path/setup/TLS to the new offer. Media handover (socket swap) is the+ * sync service's job — it observes the session map. Never throws.+ */+ fun onReInvite(callId: String, sdp: String) {+ val entry = _sessions.value.entries.firstOrNull { it.value.callId == callId } ?: return+ val session = entry.value+ val (localPath, remotePath) = parseSdpPaths(sdp)+ val setup = parseSdpSetup(sdp) ?: session.msrpSetup+ val secure = isSecureSdp(sdp)+ RcsMsrpTls.parseFingerprint(sdp)?.second?.let { fp ->+ _answerFingerprints[callId] = fp+ RcsMsrpListen.notePeerFingerprint(entry.key, fp)+ }+ _sessions.value = _sessions.value + (entry.key to session.copy(+ msrpRemotePath = remotePath ?: session.msrpRemotePath,+ msrpSetup = setup,+ msrpSecure = secure,+ msrpLocalPath = localPath ?: session.msrpLocalPath,+ ))+ Log.i(TAG, "Re-INVITE applied for ${entry.key} setup=$setup secure=$secure")+ }++ /**+ * Current SDP for [conversationId]'s session (for UPDATE/re-INVITE+ * answers, §1.5): re-emits our bound path + setup + TLS state. Null when+ * no session exists.+ */+ fun currentSdpFor(conversationId: String): ByteArray? {+ val session = _sessions.value[conversationId] ?: return null+ val cfg = RcsSipTransport.lastConfigSnapshot()+ val ip = cfg?.msrpLocalIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"+ val path = session.msrpLocalPath ?: return null+ val port = RcsMsrp.parseMsrpPath(path)?.second ?: 2855+ // We are the answerer side here: our role is passive when the peer+ // connects to us (their setup=active), else active (we connect out).+ val setup = if (session.msrpSetup == MsrpSetup.ACTIVE) "passive" else "active"+ val proto = if (session.msrpSecure) "TCP/TLS/MSRP" else "TCP/MSRP"+ val sdp = buildString {+ append("v=0\r\n")+ append("o=- ${System.currentTimeMillis()} ${System.currentTimeMillis()} IN IP4 $ip\r\n")+ append("s=-\r\n")+ append("c=IN IP4 $ip\r\n")+ append("t=0 0\r\n")+ append("m=message $port $proto *\r\n")+ append("a=path:$path\r\n")+ append("a=accept-types:message/cpim text/plain message/imdn+xml application/im-iscomposing+xml\r\n")+ append("a=setup:$setup\r\n")+ }+ return sdp.toByteArray(Charsets.UTF_8)+ }+ /** 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? {
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipDialog.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipDialog.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipDialog.ktnew file mode 100644index 0000000000..ac04511778--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipDialog.kt@@ -0,0 +1,169 @@+package com.vayunmathur.communicate.data.rcs++import java.util.UUID++/**+ * Pure SIP dialog builders + parsers (RFC 3261 §12): ACK, in-dialog MESSAGE /+ * BYE / REFER with sequencing, route-set recording.+ *+ * Split from `RcsSessionManager` for file length. All functions are pure+ * string builders/parsers — unit-tested without the transport. Sending stays+ * in the manager (it owns the session map + `RcsSipTransport`).+ */+object RcsSipDialog {+ /**+ * Build an ACK for the 2xx to our INVITE (RFC 3261 §13.2.2.4): same+ * Call-ID/From-tag/To-tag/CSeq-number as the INVITE, Request-URI = the+ * 200 OK's Contact, Route = recorded route set.+ */+ fun buildAck(session: RcsSession, branch: String = newBranch()): Pair<String, String> {+ val target = session.remoteContact?.takeIf { it.isNotBlank() } ?: session.remoteUri+ val startLine = "ACK $target 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: <${session.localUri()}>;tag=${session.localTag}\r\n")+ append("To: <${session.remoteUri}>;tag=${session.remoteTag}\r\n")+ append("Call-ID: ${session.callId}\r\n")+ append("CSeq: ${session.inviteCseq} ACK\r\n")+ session.routeSet.forEach { append("Route: <$it>\r\n") }+ append("Content-Length: 0\r\n")+ }+ return startLine to headers+ }++ /**+ * Build an in-dialog MESSAGE on [session] with the next CSeq+ * (RFC 3261 §12.2.1.1). Returns (startLine, headers, content, nextCseq)+ * — the caller persists `nextCseq` via `session.copy(nextCseq = ...)`.+ */+ fun buildInDialogMessage(+ session: RcsSession,+ body: ByteArray,+ contentType: String = "message/cpim",+ branch: String = newBranch(),+ ): InDialogRequest {+ val cseq = session.nextCseq+ val target = session.remoteContact?.takeIf { it.isNotBlank() } ?: session.remoteUri+ val startLine = "MESSAGE $target 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: <${session.localUri()}>;tag=${session.localTag}\r\n")+ append("To: <${session.remoteUri}>;tag=${session.remoteTag}\r\n")+ append("Call-ID: ${session.callId}\r\n")+ append("CSeq: $cseq MESSAGE\r\n")+ session.routeSet.forEach { append("Route: <$it>\r\n") }+ append("Content-Type: $contentType\r\n")+ append("Content-Length: ${body.size}\r\n")+ }+ return InDialogRequest(startLine, headers, body, cseq + 1)+ }++ /**+ * Build an in-dialog BYE on [session] with the next CSeq. Same return+ * contract as [buildInDialogMessage].+ */+ fun buildInDialogBye(+ session: RcsSession,+ branch: String = newBranch(),+ ): InDialogRequest {+ val cseq = session.nextCseq+ val target = session.remoteContact?.takeIf { it.isNotBlank() } ?: session.remoteUri+ val startLine = "BYE $target 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: <${session.localUri()}>;tag=${session.localTag}\r\n")+ append("To: <${session.remoteUri}>;tag=${session.remoteTag}\r\n")+ append("Call-ID: ${session.callId}\r\n")+ append("CSeq: $cseq BYE\r\n")+ session.routeSet.forEach { append("Route: <$it>\r\n") }+ append("Content-Length: 0\r\n")+ }+ return InDialogRequest(startLine, headers, ByteArray(0), cseq + 1)+ }++ /** An in-dialog request plus the session's next CSeq after sending it. */+ data class InDialogRequest(+ val startLine: String,+ val headers: String,+ val body: ByteArray,+ val nextCseq: Long,+ ) {+ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is InDialogRequest) return false+ return startLine == other.startLine && headers == other.headers &&+ body.contentEquals(other.body) && nextCseq == other.nextCseq+ }++ override fun hashCode(): Int {+ var result = startLine.hashCode()+ result = 31 * result + headers.hashCode()+ result = 31 * result + body.contentHashCode()+ result = 31 * result + nextCseq.hashCode()+ return result+ }+ }++ /**+ * Parse `Contact:` + `Record-Route:` from a 200 OK header section into+ * (contactUri, routeSet). The route set is the Record-Route values in+ * *reverse* order for the UAC (RFC 3261 §12.1.2). Empty route set when+ * absent.+ */+ fun parseDialogRoute(headers: String): Pair<String?, List<String>> {+ var contact: String? = null+ val routes = mutableListOf<String>()+ for (line in headers.lineSequence()) {+ val trimmed = line.trim()+ when {+ trimmed.startsWith("Contact:", ignoreCase = true) -> {+ contact = trimmed.substringAfter(":").trim()+ .substringAfter("<").substringBefore(">")+ .takeIf { it.isNotBlank() }+ ?: trimmed.substringAfter(":").trim().substringBefore(";")+ .takeIf { it.isNotBlank() }+ }+ trimmed.startsWith("Record-Route:", ignoreCase = true) -> {+ trimmed.substringAfter(":").trim()+ .substringAfter("<").substringBefore(">")+ .takeIf { it.isNotBlank() }?.let { routes += it }+ }+ }+ }+ return contact to routes.reversed()+ }++ /** Parse the CSeq number from a header section, or null. */+ /** Parse a header value out of a SIP header section (case-insensitive name + colon). */+ internal fun headerValue(headers: String, name: String): String? {+ for (line in headers.lineSequence()) {+ val trimmed = line.trim()+ if (trimmed.startsWith(name, ignoreCase = true)) {+ return trimmed.substringAfter(":").trim().takeIf { it.isNotEmpty() }+ }+ }+ return null+ }++ /** Parse the CSeq method token from a header section, or null. */+ fun parseCseqMethod(headers: String): String? {+ for (line in headers.lineSequence()) {+ val trimmed = line.trim()+ if (trimmed.startsWith("CSeq:", ignoreCase = true)) {+ return trimmed.substringAfter(":").trim()+ .substringAfter(" ").trim().takeIf { it.isNotEmpty() }+ }+ }+ return null+ }++ fun newBranch(): String = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"++ /** Our local URI for From headers (delegate identity when known). */+ private fun RcsSession.localUri(): String =+ RcsSipTransport.lastConfigSnapshot()?.publicUserId?.takeIf { it.isNotBlank() }+ ?: "sip:local@rcs"+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipResponse.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipResponse.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipResponse.ktnew file mode 100644index 0000000000..d47718da88--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipResponse.kt@@ -0,0 +1,77 @@+package com.vayunmathur.communicate.data.rcs++import android.telephony.ims.SipMessage++/**+ * Pure SIP response parser (RFC 3261 §7.2): `SIP/2.0 <code> <reason>` start+ * line + the dialog identifiers a response routes on.+ *+ * Split from `RcsSipTransport` for testability — no transport, no session+ * map. [parse] returns null when [message] is a request, not a response.+ */+object RcsSipResponse {+ /** A parsed SIP response with its routing keys. */+ data class Parsed(+ val statusCode: Int,+ val reason: String,+ /** Via branch of the top Via (== our transaction id). */+ val branch: String,+ val callId: String,+ /** To-tag (dialog id for 2xx to INVITE). */+ val toTag: String?,+ /** From-tag (echo of our tag). */+ val fromTag: String?,+ /** CSeq method token (INVITE/MESSAGE/BYE/REFER/…). */+ val cseqMethod: String,+ val cseqNumber: Long?,+ /** Raw header section (for Contact/Record-Route/privacy parsing). */+ val headers: String,+ /** Body text (SDP answers). */+ val body: String,+ )++ fun parse(message: SipMessage): Parsed? {+ return runCatching {+ val startLine = message.getStartLine().trim()+ if (!startLine.startsWith("SIP/2.0", ignoreCase = true)) return null+ val statusCode = startLine.substringAfter("SIP/2.0").trim()+ .substringBefore(" ").trim().toIntOrNull() ?: return null+ val reason = startLine.substringAfter("SIP/2.0").trim()+ .substringAfter(" ").trim()+ val headers = message.getHeaderSection()+ val branch = headers.lineSequence()+ .firstOrNull { it.trim().startsWith("Via:", ignoreCase = true) }+ ?.substringAfter("branch=")?.substringBefore(";")?.trim()+ ?.takeIf { it.isNotEmpty() } ?: return null+ val callId = headers.lineSequence()+ .firstOrNull { it.trim().startsWith("Call-ID:", ignoreCase = true) }+ ?.substringAfter(":")?.trim()?.takeIf { it.isNotEmpty() }+ ?: return null+ fun tagOf(name: String): String? = headers.lineSequence()+ .firstOrNull { it.trim().startsWith(name, ignoreCase = true) }+ ?.substringAfter("tag=", "")?.substringBefore(";")?.trim()+ ?.takeIf { it.isNotEmpty() }+ val cseqLine = headers.lineSequence()+ .firstOrNull { it.trim().startsWith("CSeq:", ignoreCase = true) }+ ?.substringAfter(":")?.trim().orEmpty()+ val cseqNumber = cseqLine.substringBefore(" ").trim().toLongOrNull()+ val cseqMethod = cseqLine.substringAfter(" ").trim()+ Parsed(+ statusCode = statusCode,+ reason = reason,+ branch = branch,+ callId = callId,+ toTag = tagOf("To:"),+ fromTag = tagOf("From:"),+ cseqMethod = cseqMethod,+ cseqNumber = cseqNumber,+ headers = headers,+ body = message.getContent().toString(Charsets.UTF_8),+ )+ }.getOrNull()+ }++ /** True when [startLine] is a SIP response rather than a request. */+ fun isResponse(startLine: String): Boolean =+ startLine.trim().startsWith("SIP/2.0", ignoreCase = true)+}
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 2b43ff4663..1ebd6885a6 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@@ -104,7 +104,15 @@ object RcsSipTransport { var onInboundMessage: ((SipMessage) -> Unit)? = null /** Pending outbound sends keyed by Via branch transaction id. */- private val pendingSends = ConcurrentHashMap<String, (Boolean) -> Unit>()+ private data class PendingSend(+ val callback: (Boolean) -> Unit,+ val startLine: String,+ val headers: String,+ val body: ByteArray,+ val authAttempts: Int = 0,+ )++ private val pendingSends = ConcurrentHashMap<String, PendingSend>() private val stateCallback = object : DelegateConnectionStateCallback { override fun onCreated(c: SipDelegateConnection) {@@ -146,12 +154,12 @@ object RcsSipTransport { } override fun onMessageSent(viaTransactionId: String) {- pendingSends.remove(viaTransactionId)?.invoke(true)+ pendingSends.remove(viaTransactionId)?.callback?.invoke(true) } override fun onMessageSendFailure(viaTransactionId: String, reason: Int) { Log.w(TAG, "Message send failed tx=$viaTransactionId reason=$reason")- pendingSends.remove(viaTransactionId)?.invoke(false)+ pendingSends.remove(viaTransactionId)?.callback?.invoke(false) } } @@ -224,6 +232,9 @@ object RcsSipTransport { /** * Send a SIP MESSAGE. Returns true on delegate ack, false otherwise * (caller falls back to SMS). Never throws.+ *+ * The full request is stashed per branch so 401/407 challenges can be+ * retried with digest auth ([onSipResponseMessage]). */ suspend fun sendSipMessage(startLine: String, headerSection: String, body: ByteArray): Boolean { val c = connection@@ -233,15 +244,186 @@ object RcsSipTransport { return runCatching { val message = SipMessage(startLine, headerSection, body) suspendCancellableCoroutine { cont ->- pendingSends[message.getViaBranchParameter()] = { ok -> if (cont.isActive) cont.resume(ok) }+ val branch = message.getViaBranchParameter()+ pendingSends[branch] = PendingSend(+ callback = { ok -> if (cont.isActive) cont.resume(ok) },+ startLine = startLine,+ headers = headerSection,+ body = body,+ ) runCatching { c.sendMessage(message, version) }.onFailure {- pendingSends.remove(message.getViaBranchParameter())+ pendingSends.remove(branch) if (cont.isActive) cont.resume(false) } } }.getOrDefault(false) } + /**+ * Route an inbound SIP *response* (`SIP/2.0 xxx` start line). Returns+ * true when the response was consumed (matched a pending transaction or+ * a session dialog); false when the caller should treat it as an+ * inbound MESSAGE.+ *+ * - 1xx → absorbed (retransmissions/100 Trying need no action).+ * - 2xx to INVITE → session establishment + ACK (§1.1).+ * - 401/407 → one digest-auth retry, then fail (§1.3).+ * - 481/408/480/486/603 → dialog-mismatch recovery (§1.6).+ * - 2xx to anything else → pending send succeeds.+ * - anything else → pending send fails.+ */+ suspend fun onSipResponseMessage(message: SipMessage): Boolean {+ if (!RcsFeature.enabled) return false+ val parsed = RcsSipResponse.parse(message) ?: return false+ // 2xx to our INVITE: complete the dialog + ACK, even if the original+ // branch aged out of pendingSends (responses can arrive late).+ if (parsed.statusCode in 200..299 && parsed.cseqMethod.equals("INVITE", ignoreCase = true)) {+ pendingSends.remove(parsed.branch)?.callback?.invoke(true)+ RcsSessionManager.onSipResponse(+ statusCode = parsed.statusCode,+ callId = parsed.callId,+ remoteTag = parsed.toTag,+ sdpAnswer = parsed.body,+ responseHeaders = parsed.headers,+ )+ return true+ }+ val pending = pendingSends[parsed.branch]+ if (pending == null) {+ // Stray response (late duplicate, CANCEL race): still route+ // dialog finals to the session manager by Call-ID.+ if (parsed.statusCode >= 300) {+ RcsSessionManager.onSipResponse(+ statusCode = parsed.statusCode,+ callId = parsed.callId,+ remoteTag = parsed.toTag,+ sdpAnswer = parsed.body,+ responseHeaders = parsed.headers,+ )+ return true+ }+ return false+ }+ when {+ parsed.statusCode in 100..199 -> Unit // absorbed; ack comes later+ parsed.statusCode in 200..299 -> {+ pendingSends.remove(parsed.branch)?.callback?.invoke(true)+ }+ parsed.statusCode == 401 || parsed.statusCode == 407 -> {+ if (!retryWithDigestAuth(parsed, pending)) {+ pendingSends.remove(parsed.branch)?.callback?.invoke(false)+ }+ // On retry the callback stays parked under the NEW branch.+ }+ parsed.statusCode == 481 || parsed.statusCode == 408 ||+ parsed.statusCode == 480 || parsed.statusCode == 486 ||+ parsed.statusCode == 603 -> {+ pendingSends.remove(parsed.branch)?.callback?.invoke(false)+ RcsSessionManager.onDialogError(parsed.callId, parsed.statusCode)+ }+ else -> {+ pendingSends.remove(parsed.branch)?.callback?.invoke(false)+ if (parsed.statusCode >= 300) {+ RcsSessionManager.onSipResponse(+ statusCode = parsed.statusCode,+ callId = parsed.callId,+ remoteTag = parsed.toTag,+ sdpAnswer = parsed.body,+ responseHeaders = parsed.headers,+ )+ }+ }+ }+ return true+ }++ /**+ * Rebuild a challenged request with digest `Authorization` /+ * `Proxy-Authorization` and resend under a fresh branch (RFC 3261+ * §22.2: same Call-ID/CSeq/From-tag, new Via branch). One retry per+ * transaction max. Returns true when a retry was issued.+ */+ private suspend fun retryWithDigestAuth(+ parsed: RcsSipResponse.Parsed,+ pending: PendingSend,+ ): Boolean {+ if (pending.authAttempts >= 1) return false+ val proxy = parsed.statusCode == 407+ val challengeHeader = if (proxy) "Proxy-Authenticate:" else "WWW-Authenticate:"+ val challenge = RcsSipDialog.headerValue(parsed.headers, challengeHeader) ?: return false+ val gba = RcsGbaAuth.injected+ val username = gba?.btId+ ?: lastConfigSnapshot()?.publicUserId?.substringAfter("sip:")?.substringBefore("@")+ ?.takeIf { it.isNotBlank() } ?: return false+ val password = gba?.let {+ android.util.Base64.encodeToString(it.key, android.util.Base64.NO_WRAP)+ }.orEmpty()+ val method = pending.startLine.substringBefore(" ").trim().ifBlank { return false }+ val uri = pending.startLine.substringAfter(" ").substringBefore(" SIP/").trim()+ .ifBlank { return false }+ val cnonce = UUID.randomUUID().toString().replace("-", "").take(16)+ val authValue = RcsGbaAuth.digestAuthorizationHeader(+ challenge = challenge,+ method = method,+ uri = uri,+ username = username,+ password = password,+ cnonce = cnonce,+ ).ifBlank { return false }+ // Same request, fresh branch, auth header appended (replaces any+ // stale Authorization/Proxy-Authorization from a previous attempt).+ val newBranch = RcsSipDialog.newBranch()+ val baseHeaders = pending.headers.lineSequence()+ .filter { line ->+ val t = line.trim()+ !(t.startsWith("Via:", ignoreCase = true) ||+ t.startsWith("Authorization:", ignoreCase = true) ||+ t.startsWith("Proxy-Authorization:", ignoreCase = true))+ }.joinToString("\r\n")+ val viaHost = pending.headers.lineSequence()+ .firstOrNull { it.trim().startsWith("Via:", ignoreCase = true) }+ ?.substringAfter("SIP/2.0/TCP")?.substringBefore(";")?.trim()+ ?.takeIf { it.isNotEmpty() } ?: "local"+ val rebuilt = buildString {+ append(baseHeaders)+ if (baseHeaders.isNotEmpty()) append("\r\n")+ append("Via: SIP/2.0/TCP $viaHost;branch=$newBranch\r\n")+ append(if (proxy) "Proxy-Authorization: $authValue\r\n" else "Authorization: $authValue\r\n")+ }+ // Re-park the callback BEFORE sending (the ack may arrive inline).+ val oldBranch = parsed.branch+ pendingSends.remove(oldBranch)+ val c = connection ?: run {+ pending.callback(false)+ return false+ }+ val version = configVersi
Diff truncated.