communicate: MSRP passive listen, provisioning watch, session lifecycle
- Commit
251d2dad27e5eb082215b30370e3d1d352651790- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-26 20:45 UTC (2 months ago)
- Parents
64432dc
Diff
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.ktindex c8cc31c0df..e5d117d6e0 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt@@ -19,7 +19,10 @@ import com.vayunmathur.communicate.data.rcs.buildRevokeBody import com.vayunmathur.communicate.data.rcs.chunkLargeMessage import com.vayunmathur.library.util.AppMessages import java.util.UUID+import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /**@@ -40,6 +43,9 @@ enum class RcsSendResult { Failed, } +/** Fire-and-forget scope for background session establishment (never blocks sends). */+private val sendScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ internal suspend fun CommunicateRepository.loadRcsThreads(context: Context): List<SmsThread> { if (!RcsFeature.enabled) return emptyList() return runCatching {@@ -174,6 +180,9 @@ suspend fun CommunicateRepository.sendRcsMessage( return@withContext RcsSendResult.Sent } // 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). val session = RcsSessionManager.sessionFor(recipient) if (session?.msrpRemotePath != null && attachments.isEmpty()) { val cpim = RcsSipTransport.buildCpimBody(body).toByteArray(Charsets.UTF_8)@@ -184,6 +193,14 @@ suspend fun CommunicateRepository.sendRcsMessage( return@withContext RcsSendResult.Sent } }+ if (session == null && attachments.isEmpty() && !recipient.startsWith("rcs-group:") &&+ !recipient.contains("@") && !recipient.contains(":")+ ) {+ val peer = recipient+ sendScope.launch {+ runCatching { RcsSessionManager.startSession("sip:$peer@rcs", peer) }+ }+ } if (attachments.isNotEmpty()) { // FT-over-HTTP when the content server is known, else the v1 envelope. val ftOk = if (RcsFileTransferHttp.contentServerUri != null) {
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.ktindex b8dfa2dd7d..a59c672da5 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImsNetwork.kt@@ -8,6 +8,8 @@ import android.net.NetworkRequest import android.os.Build import android.util.Log import java.net.InetAddress+import java.net.InetSocketAddress+import java.net.ServerSocket import java.net.Socket import kotlin.coroutines.resume import kotlinx.coroutines.suspendCancellableCoroutine@@ -141,6 +143,57 @@ object RcsImsNetwork { }.getOrDefault(emptyList()) } + /**+ * Bound MSRP listen socket on the IMS PDN: a `ServerSocket` on an+ * ephemeral port, bound to the IMS local address when known.+ *+ * Note: `Network` exposes a client `SocketFactory` but no server-socket+ * factory, so this binds a plain `ServerSocket` explicitly to the IMS+ * local address. Inbound TCP to that address arrives on the IMS PDN at+ * the IP layer regardless of which `Network` created the socket — the+ * routing decision is the peer's (it connects to the address we+ * advertise in `a=path`), not ours.+ *+ * Returns the socket + the local (ip, port) to advertise in `a=path` and+ * `c=`, or null when no IMS network / bind fails. The socket is NOT+ * closed here — the caller owns the accept loop and closes on teardown.+ * Plain-network fallback is deliberately absent: advertising an+ * unroutable address is worse than offering active-only.+ */+ suspend fun listenSocket(context: Context): ListenSocket? {+ if (!RcsFeature.enabled) return null+ val ims = imsNetwork(context) ?: return null+ return runCatching {+ val localIp = lastLocalIp+ ?.let { runCatching { InetAddress.getByName(it) }.getOrNull() }+ ?: return null+ val server = ServerSocket()+ // Backlog sized for one peer per pending session plus slack.+ server.bind(InetSocketAddress(localIp, 0), 16)+ val port = server.localPort.takeIf { it > 0 } ?: run {+ runCatching { server.close() }+ return null+ }+ val ip = localIp.hostAddress ?: return null+ ListenSocket(server = server, localIp = ip, localPort = port)+ }.getOrElse {+ Log.w(TAG, "IMS listen bind failed", it)+ null+ }+ }++ /** An owned IMS-PDN listen socket with its advertised address. */+ data class ListenSocket(+ val server: ServerSocket,+ val localIp: String,+ val localPort: Int,+ ) {+ /** `msrp://ip:port/<session>;tcp` path for `a=path`. */+ fun msrpPath(sessionId: String): String = "msrp://$localIp:$localPort/$sessionId;tcp"++ fun close() = runCatching { server.close() }+ }+ private fun localIpFor(context: Context, network: Network): String? = localIps(context, network).firstOrNull { it.contains('.') } ?: localIps(context, network).firstOrNull()
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 7088b0ffa4..cd4659bc50 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@@ -44,7 +44,6 @@ object RcsMsrp { internal fun launchReader(block: suspend () -> Unit) { readerScope.launch { block() } }- /** * Send one CPIM payload as an MSRP SEND chunk. Returns true on a 200 * response. Thread-safe (single-writer lock).@@ -90,11 +89,39 @@ object RcsMsrp { internal fun isClosed(): Boolean = closed || socket.isClosed } + /**+ * Wrap an accepted (passive-side) socket as a session connection: the+ * listener already consumed the first SEND head ([head]) for To-Path+ * routing, so the reader replays it before the live stream. [localPath]+ * is our advertised path (matches the peer's To-Path); [remotePath] is+ * the peer's From-Path, used for our SENDs back on this same socket.+ */+ /**+ * Wrap an accepted (passive-side) socket as a session connection: the+ * listener already consumed the first SEND head ([head]) for To-Path+ * routing, so the reader replays it before the live stream. [localPath]+ * is our advertised path (matches the peer's To-Path); [remotePath] is+ * the peer's From-Path, used for our SENDs back on this same socket+ * (RFC 4975 §5.4 — the passive side reuses the accepted connection).+ */+ fun wrapAccepted(+ socket: java.net.Socket,+ head: RcsMsrpListen.AcceptedHead,+ localPath: String,+ remotePath: String,+ onChunk: (contentType: String, body: ByteArray) -> Unit,+ ): MsrpConnection {+ val conn = MsrpConnection(socket, localPath, remotePath)+ conn.launchReader { readLoop(conn, socket, onChunk, head.replayBytes()) }+ return conn+ }+ /** * Open a persistent active connection for [session] and start the reader * loop on Dispatchers.IO. [onChunk] receives complete `message/cpim` * bodies (content type + bytes). Returns null when the session has no- * usable remote path or the peer expects us to listen (`setup=active`).+ * usable remote path or when neither side can connect (peer is+ * `setup=active` AND we have no listen socket — see [RcsMsrpListen]). * * The socket rides the IMS PDN when available ([RcsImsNetwork]) so * carrier MSRP peers (which only route IMS-subnet addresses) are@@ -107,8 +134,15 @@ object RcsMsrp { ): MsrpConnection? = withContext(Dispatchers.IO) { if (!RcsFeature.enabled) return@withContext null val remotePath = session.msrpRemotePath ?: return@withContext null+ if (session.msrpSetup == MsrpSetup.ACTIVE && !RcsMsrpListen.isListening()) {+ // Peer connects to us, but we have no listen socket — nothing to do.+ // (When listening, the accept loop owns this direction; connect-out+ // is skipped and the session completes on accept.)+ Log.w(TAG, "Peer is active and no listen socket; cannot establish media")+ return@withContext null+ } if (session.msrpSetup == MsrpSetup.ACTIVE) {- Log.w(TAG, "Peer is active; ACTIVE-only cannot listen")+ // Listen-side session: media arrives on the accepted socket. return@withContext null } val localPath = session.msrpLocalPath ?: "msrp://local.invalid/${UUID.randomUUID()};tcp"@@ -130,9 +164,17 @@ object RcsMsrp { conn: MsrpConnection, socket: java.net.Socket, onChunk: (String, ByteArray) -> Unit,+ replayPrefix: ByteArray? = null, ) {- val input = runCatching { socket.getInputStream().bufferedReader(Charsets.UTF_8) }.getOrNull()- ?: return+ val live = runCatching { socket.getInputStream() }.getOrNull() ?: return+ // Accepted sockets already had their first SEND head consumed for+ // To-Path routing — replay it ahead of the live stream.+ val stream = if (replayPrefix != null && replayPrefix.isNotEmpty()) {+ java.io.SequenceInputStream(java.io.ByteArrayInputStream(replayPrefix), live)+ } else {+ live+ }+ val input = stream.bufferedReader(Charsets.UTF_8) val pending = StringBuilder() // Reassembly buffer for multi-chunk SENDs, keyed by Message-ID. val reassembly = mutableMapOf<String, ByteArrayOutputStream2>()@@ -167,8 +209,10 @@ object RcsMsrp { } // Consume the end-marker line. runCatching { input.readLine() }- // Auto-200 the peer SEND.- sendResponse(socket, txid, 200, "OK", conn)+ // 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()+ sendResponse(socket, txid, 200, "OK", peerFrom) val msgId = headers["message-id"].orEmpty() val contentType = headers["content-type"] ?: "message/cpim" if (msgId.isNotEmpty() && bodyBytes != null) {@@ -236,12 +280,13 @@ object RcsMsrp { txid: String, code: Int, reason: String,- conn: MsrpConnection,+ toPath: String = "", ) { runCatching { val out = socket.getOutputStream() out.write("MSRP $txid $code $reason\r\n".toByteArray(Charsets.UTF_8))- out.write("To-Path: placeholder\r\n\r\n".toByteArray(Charsets.UTF_8))+ if (toPath.isNotBlank()) out.write("To-Path: $toPath\r\n".toByteArray(Charsets.UTF_8))+ out.write("\r\n".toByteArray(Charsets.UTF_8)) out.write("-------$txid\$\r\n".toByteArray(Charsets.UTF_8)) out.flush() }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.ktnew file mode 100644index 0000000000..b42ab1c15c--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.kt@@ -0,0 +1,204 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.util.Log+import java.util.UUID+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Passive MSRP listen side (RFC 4975 §5 + RFC 4145 `setup:passive`).+ *+ * Until now we were ACTIVE-only: we always connected out and nulled the+ * remote path when a peer answered `setup:active` (see `RcsMsrp.connect`).+ * This closes that gap: a `ServerSocket` bound to the IMS PDN+ * ([RcsImsNetwork.listenSocket]) lets peers connect TO us, so `setup:active`+ * offers/answers become usable sessions instead of pager-mode fallbacks.+ *+ * Negotiation (RFC 4145, MSRP binding):+ * - Outgoing INVITE: offer `setup:actpass` + our listen `a=path`. A peer+ * answering `active` connects to us; a peer answering `passive` keeps the+ * old connect-out path (we answer `active`... i.e. we connect out).+ * - Incoming INVITE offering `setup:active` (+ a usable remote path): answer+ * `setup:passive` with our listen `a=path` and accept their TCP connection.+ * - Incoming INVITE offering `passive`/`actpass`: keep the v1 behavior+ * (answer `active`, connect out).+ *+ * Accept matching: the first SEND on an accepted socket carries To-Path (our+ * advertised path) + From-Path (the peer). We match To-Path against pending+ * listen paths to route the socket to its session. Unmatched sockets get a+ * 481 and are closed — never left dangling.+ *+ * Lifecycle: [ensureListening] binds on demand (one socket per process,+ * shared across sessions — paths differ per session id); [stop] closes the+ * socket + accept scope. Owned by `RcsSyncService` alongside the MSRP+ * connection map. Never throws; null/false on any failure.+ */+object RcsMsrpListen {+ private const val TAG = "RcsMsrpListen"++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ /** Active listen socket, or null when not listening. */+ @Volatile+ private var listen: RcsImsNetwork.ListenSocket? = null++ /**+ * Pending listen paths: our advertised `a=path` → conversation id, for+ * routing accepted sockets to sessions. Entries are consumed on first+ * match; stale entries are dropped by [stop] / session teardown.+ */+ private val pendingPaths = java.util.concurrent.ConcurrentHashMap<String, String>()++ /** True when a listen socket is currently bound. */+ fun isListening(): Boolean =+ RcsFeature.enabled && listen?.let { !it.server.isClosed } == true++ /** Advertised local IP for SDP `c=` lines, or null when not listening. */+ fun listenIp(): String? = listen?.takeIf { !it.server.isClosed }?.localIp++ /** Advertised local port for SDP `m=` lines, or null when not listening. */+ fun listenPort(): Int? = listen?.takeIf { !it.server.isClosed }?.localPort++ /**+ * Ensure the listen socket is bound. Idempotent — returns true when+ * already listening. Starts the accept loop on first bind.+ *+ * [onAccepted] receives the matched conversation id, the live socket, and+ * the already-consumed request head ([AcceptedHead]) so the MSRP reader+ * can replay it before the live stream.+ */+ suspend fun ensureListening(+ context: Context,+ onAccepted: (conversationId: String, socket: java.net.Socket, head: AcceptedHead) -> Unit,+ ): Boolean = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext false+ if (isListening()) return@withContext true+ val bound = RcsImsNetwork.listenSocket(context) ?: return@withContext false+ listen = bound+ Log.i(TAG, "Listening on ${bound.localIp}:${bound.localPort}")+ scope.launch { acceptLoop(bound, onAccepted) }+ true+ }++ /**+ * Advertise a listen path for [conversationId]: returns the `a=path`+ * value to put in our SDP offer/answer, binding the listen socket first+ * when needed. Null when listening is unavailable (caller falls back to+ * active-only offers).+ */+ suspend fun advertisePath(+ context: Context,+ conversationId: String,+ onAccepted: (String, java.net.Socket, AcceptedHead) -> Unit,+ ): String? = withContext(Dispatchers.IO) {+ if (!RcsFeature.enabled) return@withContext null+ if (!ensureListening(context, onAccepted)) return@withContext null+ val bound = listen ?: return@withContext null+ val path = bound.msrpPath("sess-${UUID.randomUUID().toString().take(8)}")+ pendingPaths[path] = conversationId+ path+ }++ /** Drop the pending path for [conversationId] (session torn down). */+ fun dropPending(conversationId: String) {+ pendingPaths.entries.removeIf { it.value == conversationId }+ }++ /** Close the listen socket + accept loop; drop pending paths. */+ fun stop() {+ runCatching { listen?.close() }+ listen = null+ pendingPaths.clear()+ }++ private suspend fun acceptLoop(+ bound: RcsImsNetwork.ListenSocket,+ onAccepted: (String, java.net.Socket, AcceptedHead) -> Unit,+ ) = withContext(Dispatchers.IO) {+ while (!bound.server.isClosed && RcsFeature.enabled) {+ val socket = runCatching { bound.server.accept() }.getOrNull() ?: break+ runCatching { socket.soTimeout = 0 }+ scope.launch { routeAccepted(socket, onAccepted) }+ }+ if (listen === bound) listen = null+ Log.i(TAG, "Accept loop ended")+ }++ /**+ * Already-consumed request head from an accepted socket: the MSRP start+ * line + header lines + the blank-line terminator. The body + end-marker+ * are still in the live stream. [replayBytes] re-serializes the head so+ * the MSRP reader sees the full first SEND.+ */+ data class AcceptedHead(val lines: List<String>) {+ fun replayBytes(): ByteArray = buildString {+ lines.forEach { append(it).append("\r\n") }+ append("\r\n")+ }.toByteArray(Charsets.UTF_8)+ }++ /**+ * Route one accepted socket: read the first SEND's To-Path, match it+ * against pending listen paths, hand the socket + head to the session.+ * Closes unmatched/failed sockets with a 481 when the framing allows.+ */+ private fun routeAccepted(+ socket: java.net.Socket,+ onAccepted: (String, java.net.Socket, AcceptedHead) -> Unit,+ ) {+ runCatching {+ socket.soTimeout = 15_000+ val input = socket.getInputStream().bufferedReader(Charsets.UTF_8)+ // Peek the first MSRP request head (bounded: 32 lines max).+ val headLines = mutableListOf<String>()+ var line = runCatching { input.readLine() }.getOrNull()+ var guard = 0+ while (line != null && line.isNotEmpty() && guard++ < 32) {+ headLines.add(line)+ line = runCatching { input.readLine() }.getOrNull()+ }+ if (line == null && headLines.isEmpty()) {+ runCatching { socket.close() }+ return+ }+ val first = headLines.firstOrNull() ?: run {+ runCatching { socket.close() }+ return+ }+ if (!first.startsWith("MSRP ")) {+ runCatching { socket.close() }+ return+ }+ val toPath = headLines.firstOrNull { it.startsWith("To-Path:", ignoreCase = true) }+ ?.substringAfter(":")?.trim()+ val conversationId = toPath?.let { pendingPaths.remove(it) }+ if (conversationId == null) {+ // Unknown path: 481 per RFC 4975 §7.1, then close.+ val txid = first.split(" ").getOrNull(1).orEmpty()+ if (txid.isNotEmpty()) {+ runCatching {+ val out = socket.getOutputStream()+ out.write("MSRP $txid 481 Session Does Not Exist\r\n".toByteArray(Charsets.UTF_8))+ out.write("To-Path: $toPath\r\n\r\n".toByteArray(Charsets.UTF_8))+ out.write("-------$txid\$\r\n".toByteArray(Charsets.UTF_8))+ out.flush()+ }+ }+ runCatching { socket.close() }+ Log.w(TAG, "Rejected inbound MSRP for unknown path $toPath")+ return+ }+ // Matched: hand over the live socket + consumed head for replay.+ socket.soTimeout = 0+ onAccepted(conversationId, socket, AcceptedHead(headLines))+ }.onFailure {+ Log.w(TAG, "Accept routing failed", it)+ runCatching { socket.close() }+ }+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioningWatcher.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioningWatcher.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioningWatcher.ktnew file mode 100644index 0000000000..644eab0f20--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsProvisioningWatcher.kt@@ -0,0 +1,108 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.telephony.SubscriptionManager+import android.util.Log+import java.util.concurrent.Executors+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Live provisioning watcher: registers the hidden+ * `ProvisioningManager` RCS callback (see [RcsHiddenApi]) so carrier config+ * changes reach us without re-probing.+ *+ * On `onConfigurationChanged` the raw RCS config XML is parsed for the+ * FT-over-HTTP content-server URI (`ftHTTPCSURI` →+ * [RcsFileTransferHttp.contentServerUri], which is what activates the+ * FT-over-HTTP upload path) and provisioning is re-probed to refresh the+ * transport state. On reset/removal the content-server URI is cleared and+ * the state re-probed.+ *+ * Owned by the transport lifecycle: [watch] at `ensureRegistered` time,+ * [unwatch] on teardown. Best-effort throughout — the bridge returns false+ * without carrier privilege and everything keeps working on the last-known+ * values. Never throws.+ */+object RcsProvisioningWatcher {+ private const val TAG = "RcsProvWatch"++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val executor = Executors.newSingleThreadExecutor()++ @Volatile+ private var manager: Any? = null++ @Volatile+ private var watchingSubId: Int = SubscriptionManager.INVALID_SUBSCRIPTION_ID++ /**+ * Register for provisioning callbacks on [subId]. Idempotent per subId —+ * re-calls for the same subId are no-ops. Call [unwatch] first when+ * switching subscriptions.+ */+ fun watch(context: Context, subId: Int) {+ if (!RcsFeature.enabled) return+ if (!SubscriptionManager.isValidSubscriptionId(subId)) return+ if (subId == watchingSubId && manager != null) return+ unwatch()+ val pm = RcsHiddenApi.provisioningManager(subId) ?: run {+ Log.i(TAG, "No provisioning manager for subId=$subId (no privilege or unsupported)")+ return+ }+ val app = context.applicationContext+ val ok = RcsHiddenApi.registerProvisioningCallback(+ provisioningManager = pm,+ executor = executor,+ rcsVersion = "6.0",+ rcsProfile = "UP_2.0",+ callback = object : RcsHiddenApi.ProvisioningCallback {+ override fun onConfigurationChanged(configXml: ByteArray) {+ scope.launch { applyConfig(app, subId, configXml) }+ }++ override fun onConfigurationReset() {+ scope.launch {+ Log.i(TAG, "Provisioning config reset for subId=$subId")+ RcsFileTransferHttp.contentServerUri = null+ RcsProvisioning.probe(app, subId)+ }+ }++ override fun onRemoved() {+ scope.launch {+ Log.i(TAG, "Provisioning removed for subId=$subId")+ RcsFileTransferHttp.contentServerUri = null+ RcsProvisioning.probe(app, subId)+ }+ }+ },+ )+ if (ok) {+ manager = pm+ watchingSubId = subId+ Log.i(TAG, "Watching provisioning for subId=$subId")+ }+ }++ /** Unregister (best-effort) and drop watcher state. */+ fun unwatch() {+ manager?.let { runCatching { RcsHiddenApi.unregisterProvisioningCallback(it) } }+ manager = null+ watchingSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID+ }++ private suspend fun applyConfig(context: Context, subId: Int, configXml: ByteArray) {+ if (!RcsFeature.enabled || configXml.isEmpty()) return+ RcsFileTransferHttp.parseContentServer(configXml)?.let { uri ->+ if (RcsFileTransferHttp.contentServerUri != uri) {+ Log.i(TAG, "FT content server configured for subId=$subId")+ RcsFileTransferHttp.contentServerUri = uri+ }+ }+ // Config changed under us — refresh the transport state.+ RcsProvisioning.probe(context, subId)+ }+}
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 6ed9bdc566..2ac9684870 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@@ -42,13 +42,19 @@ object RcsSessionManager { * `tel:` URI. Returns the dialog id on accept-tracked send, null when the * transport is unavailable. The 200 OK/ACK/MSRP bind completes * asynchronously via [onSipResponse]/[onSipRequest].+ *+ * The offer carries `setup:actpass` + our listen path when the passive+ * listener is up ([RcsMsrpListen]), so the peer may connect to us;+ * otherwise it is the v1 `setup:active` connect-out offer. */ suspend fun startSession(remoteTelUri: String, conversationId: String): String? { if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return null val callId = "${UUID.randomUUID()}@rcs" val localTag = UUID.randomUUID().toString().take(8) val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"- val (startLine, headers, content) = buildInvite(remoteTelUri, callId, localTag, branch, conversationId)+ val listenPath = listenPathFor(conversationId)+ val (startLine, headers, content) =+ buildInvite(remoteTelUri, callId, localTag, branch, conversationId, listenPath = listenPath) val ok = RcsSipTransport.sendSipMessage(startLine, headers, content) if (!ok) return null val dialogId = "$callId:$localTag"@@ -78,7 +84,9 @@ object RcsSessionManager { val callId = "${UUID.randomUUID()}@rcs" val localTag = UUID.randomUUID().toString().take(8) val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"- val (startLine, headers, content) = buildInvite(focusUri, callId, localTag, branch, conversationId, subject)+ val listenPath = listenPathFor(conversationId)+ val (startLine, headers, content) =+ buildInvite(focusUri, callId, localTag, branch, conversationId, subject, listenPath) val ok = RcsSipTransport.sendSipMessage(startLine, headers, content) if (!ok) return null val dialogId = "$callId:$localTag"@@ -177,9 +185,42 @@ object RcsSessionManager { val focusUri = session.remoteUri _focusMembers.remove(focusUri) _sessions.value = _sessions.value - conversationId+ RcsMsrpListen.dropPending(conversationId) return true } + /**+ * Drop sessions that never completed (no remote tag after [maxAgeMs])+ * and completed sessions idle longer than [maxIdleMs] with no MSRP+ * connection. Returns the dropped conversation ids so the caller can+ * close their connections. Best-effort; never throws.+ */+ fun sweepStaleSessions(+ nowMs: Long = System.currentTimeMillis(),+ maxAgeMs: Long = 5 * 60 * 1000L,+ maxIdleMs: Long = 30 * 60 * 1000L,+ ): List<String> {+ if (!RcsFeature.enabled) return emptyList()+ val dropped = mutableListOf<String>()+ for ((conversationId, session) in _sessions.value) {+ if (session.isFocus) continue+ val age = nowMs - session.createdAt+ val incomplete = session.remoteTag.isBlank() && age > maxAgeMs+ val idle = session.remoteTag.isNotBlank() &&+ session.msrpRemotePath == null && age > maxIdleMs+ if (incomplete || idle) {+ _sessions.value = _sessions.value - conversationId+ _pendingOffers.remove(session.callId)+ RcsMsrpListen.dropPending(conversationId)+ dropped += conversationId+ }+ }+ transactions.entries.removeIf { (_, dialogId) ->+ _sessions.value.values.none { it.dialogId == dialogId }+ }+ 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.@@ -206,15 +247,32 @@ object RcsSessionManager { } /**- * Answer a pending incoming INVITE with 200 OK + SDP answer (passive —- * the caller connects to us... see ACTIVE-only note below).+ * Advertise our listen path for [conversationId] when the passive+ * listener can bind. Null when listening is unavailable — callers fall+ * back to active-only offers. Needs a Context for the IMS request; the+ * session manager is context-free, so the sync service injects it via+ * [listenContextProvider] at startup (null = no passive offers).+ */+ var listenContextProvider: (() -> android.content.Context?)? = null++ private suspend fun listenPathFor(conversationId: String): String? {+ val context = listenContextProvider?.invoke() ?: return null+ // The accept callback is a no-op here: the sync service owns the real+ // accept loop (it calls ensureListening at startup). advertisePath+ // only registers the pending path when already listening.+ if (!RcsMsrpListen.isListening()) return null+ return RcsMsrpListen.advertisePath(context, conversationId) { _, _, _ -> }+ }++ /**+ * Answer a pending incoming INVITE with 200 OK + SDP answer. *- * ACTIVE-only reality: we cannot listen (no ServerSocket, unroutable- * offer IP), so our answer offers `setup:active` too and the session- * proceeds only if the caller tolerates dual-active or falls back. In- * practice acceptance means MSRP connect-out to the offerer's path when- * it answers `passive`/`actpass`; otherwise the dialog exists for- * in-dialog MESSAGE while media stays pager-mode.+ * With the passive listener up and an offerer that wants us to listen+ * (`setup:active` + usable path), we answer `setup:passive` with our+ * listen path and their TCP connection completes the session. Otherwise+ * the v1 behavior holds: answer `setup:active` and connect out when the+ * offerer's path/setup allows, else keep the dialog for in-dialog+ * MESSAGE with media on pager-mode. * * Returns true when the 200 OK was accepted by the transport. */@@ -223,7 +281,14 @@ object RcsSessionManager { val session = _sessions.value[conversationId] ?: return false val cfg = RcsSipTransport.lastConfigSnapshot() val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"- val sdp = buildSdpAnswer(cfg?.msrpLocalIp)+ val offered = _pendingOffers[session.callId]+ // Passive answer when the offerer is active-only and we can listen.+ val passivePath = if (offered?.setup == MsrpSetup.ACTIVE && !offered.remotePath.isNullOrBlank()) {+ listenPathFor(conversationId)+ } else {+ null+ }+ val sdp = buildSdpAnswer(cfg?.msrpLocalIp, passivePath) val bytes = sdp.toByteArray(Charsets.UTF_8) val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}" val startLine = "SIP/2.0 200 OK"@@ -239,12 +304,15 @@ object RcsSessionManager { } val ok = RcsSipTransport.sendSipMessage(startLine, headers, bytes) if (ok) {- // Record the offerer's path/setup for connect-out.- val offered = _pendingOffers.remove(session.callId)- if (offered != null) {+ // Record the offerer's path/setup for connect-out — unless we+ // answered passive, in which case THEY connect to our listen+ // path and the accept loop completes the session.+ val offer = _pendingOffers.remove(session.callId)+ if (offer != null) { _sessions.value = _sessions.value + (conversationId to session.copy(- msrpRemotePath = offered.remotePath,- msrpSetup = offered.setup,+ msrpRemotePath = offer.remotePath,+ msrpSetup = offer.setup,+ msrpLocalPath = passivePath ?: session.msrpLocalPath, )) } }@@ -290,6 +358,13 @@ object RcsSessionManager { val ok = RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0)) transactions.remove(branch) _sessions.value = _sessions.value - conversationId+ _pendingOffers.remove(session.callId)+ RcsMsrpListen.dropPending(conversationId)+ if (session.remoteTag.isNotBlank()) {+ // Tell the framework the dialog is gone so it releases delegate+ // state for this Call-ID (best-effort; stub-covered).+ RcsSipTransport.cleanupSession(session.callId)+ } return ok } @@ -306,14 +381,21 @@ object RcsSessionManager { val setup = parseSdpSetup(sdpAnswer) _sessions.value = _sessions.value + (entry.key to session.copy( remoteTag = remoteTag,- msrpLocalPath = localPath,+ msrpLocalPath = localPath ?: session.msrpLocalPath, msrpRemotePath = remotePath,- // ACTIVE-only: we connect out. A peer answering `active` means- // it expects US to listen, which we cannot — keep the remote- // path nulled so sends stay on pager-mode. msrpSetup = setup, ))- val usable = remotePath != null && setup != MsrpSetup.ACTIVE+ // 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+ // offer carried a listen path and the answer kept any path+ // (actpass negotiation leaves the direction to the answerer).+ val peerActive = setup == MsrpSetup.ACTIVE+ val usable = remotePath != null && (+ !peerActive ||+ session.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@@ -414,10 +496,11 @@ object RcsSessionManager { branch: String, conversationId: String, subject: String? = null,+ listenPath: String? = null, ): Triple<String, String, ByteArray> { val cfg = RcsSipTransport.lastConfigSnapshot() val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"- val sdp = buildSdpOffer(cfg?.msrpLocalIp)+ val sdp = buildSdpOffer(cfg?.msrpLocalIp, listenPath) val bytes = sdp.toByteArray(Charsets.UTF_8) val startLine = "INVITE $targetUri SIP/2.0" val headers = buildString {@@ -443,40 +526,61 @@ object RcsSessionManager { return Triple(startLine, headers, bytes) } - private fun buildSdpOffer(localIp: String?): String {+ /**+ * SDP offer: `setup:actpass` + listen path when we can accept inbound+ * TCP ([listenPath] from [RcsMsrpListen]), else the v1 `setup:active`+ * connect-out offer with an unroutable placeholder path.+ */+ private fun buildSdpOffer(localIp: String?, listenPath: String?): String { val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"- val path = "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp"+ val (path, port, setup) = if (listenPath != null) {+ Triple(listenPath, RcsMsrpListen.listenPort() ?: 2855, "actpass")+ } else {+ Triple(+ "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp",+ 2855,+ "active",+ )+ } return 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 2855 TCP/MSRP *\r\n")+ append("m=message $port TCP/MSRP *\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:active\r\n")+ append("a=setup:$setup\r\n") } } /**- * SDP answer for [acceptIncoming]: same media shape as the offer with our- * (unroutable-by-construction) path; the usable direction is connect-out- * to the offerer's path recorded in [_pendingOffers].+ * SDP answer: `setup:passive` + listen path when we are accepting the+ * offerer's TCP connection ([passivePath] non-null), else the v1+ * `setup:active` answer (we connect out to the offerer). */- private fun buildSdpAnswer(localIp: String?): String {+ private fun buildSdpAnswer(localIp: String?, passivePath: String? = null): String { val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"- val path = "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp"+ val (path, port, setup) = if (passivePath != null) {+ Triple(passivePath, RcsMsrpListen.listenPort() ?: 2855, "passive")+ } else {+ Triple(+ "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp",+ 2855,+ "active",+ )+ } return 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 2855 TCP/MSRP *\r\n")+ append("m=message $port TCP/MSRP *\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:active\r\n")+ append("a=setup:$setup\r\n") } }
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 8e6bfe27f2..2b43ff4663 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@@ -174,6 +174,10 @@ object RcsSipTransport { if (subId == activeSubId && connection != null) return@launch if (subId != activeSubId) tearDown(app) activeSubId = subId+ // Start the live provisioning watch before creating the delegate:+ // config changes (FT server URI, re-provisioning) arrive via+ // callback instead of waiting for the next probe.+ RcsProvisioningWatcher.watch(app, subId) when (val probe = RcsProvisioning.probe(app, subId)) { is RcsRegistrationState.Available -> createDelegate(app, subId) is RcsRegistrationState.Unavailable -> {@@ -194,6 +198,9 @@ object RcsSipTransport { manager?.destroySipDelegate(c, SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP) } }+ RcsProvisioningWatcher.unwatch()+ RcsMsrpListen.stop()+ RcsImsNetwork.reset() connection = null configVersion = -1L activeSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID@@ -203,6 +210,17 @@ object RcsSipTransport { fun canSend(): Boolean = RcsFeature.enabled && _state.value is RcsRegistrationState.Available && connection != null + /**+ * Tell the framework to release delegate state for [callId]+ * (`SipDelegateConnection#cleanupSession`). Best-effort: no connection+ * or any failure is a silent no-op.+ */+ fun cleanupSession(callId: String) {+ val c = connection ?: return+ if (!RcsFeature.enabled || callId.isBlank()) return+ runCatching { c.cleanupSession(callId) }+ }+ /** * Send a SIP MESSAGE. Returns true on delegate ack, false otherwise * (caller falls back to SMS). Never throws.
communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.ktindex eaa4d148ca..0a2fadb3f2 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsInboundDialog.kt@@ -5,10 +5,13 @@ import android.util.Log import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsMsrp+import com.vayunmathur.communicate.data.rcs.RcsMsrpListen import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.RcsSipTransport import com.vayunmathur.communicate.notifications.ConversationSpace import com.vayunmathur.communicate.notifications.ConversationTarget+import kotlinx.coroutines.launch /** * Dialog-forming/method handlers for inbound SIP, split from@@ -59,6 +62,48 @@ internal suspend fun RcsSyncService.handleInboundBye(message: SipMessage) { Log.i(RcsSyncService.TAG, "BYE processed callId=$callId") } +/** Close MSRP connections whose sessions went away (+ drop listen paths). */+internal fun RcsSyncService.closeDeadMsrpConnections() {+ msrpConnections.keys.filter { RcsSessionManager.sessionFor(it) == null }.forEach { id ->+ msrpConnections.remove(id)?.close()+ RcsMsrpListen.dropPending(id)+ }+}++/**+ * Passive-side accept: the peer connected to our listen socket. Wrap it+ * as the session's connection (reusing the accepted TCP per RFC 4975+ * §5.4) and feed inbound chunks to the inbox. The session's local path is+ * what we advertised; the remote path is the peer's From-Path from the+ * first SEND.+ */+internal fun RcsSyncService.onMsrpAccepted(+ conversationId: String,+ socket: java.net.Socket,+ head: RcsMsrpListen.AcceptedHead,+) {+ if (!RcsFeature.enabled) {+ runCatching { socket.close() }+ return+ }+ val session = RcsSessionManager.sessionFor(conversationId) ?: run {+ runCatching { socket.close() }+ return+ }+ // Replace any stale connection for this conversation.+ msrpConnections.remove(conversationId)?.close()+ val peerFrom = head.lines.firstOrNull { it.startsWith("From-Path:", ignoreCase = true) }+ ?.substringAfter(":")?.trim().orEmpty()+ val localPath = session.msrpLocalPath ?: head.lines.firstOrNull {+ it.startsWith("To-Path:", ignoreCase = true)+ }?.substringAfter(":")?.trim().orEmpty()+ val conn = RcsMsrp.wrapAccepted(socket, head, localPath, peerFrom) { contentType, body ->+ serviceScope.launch { handleMsrpChunk(conversationId, session, contentType, body) }+ }+ msrpConnections[conversationId] = conn+ Log.i(RcsSyncService.TAG, "Passive MSRP accepted for $conversationId")+}+ /** * Inbound REFER (UP conference join): the focus (or a peer) asks us to * INVITE the conference URI in `Refer-To`. We start an outgoing group
communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.ktindex 5cddc28451..cbd9746407 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt@@ -25,6 +25,7 @@ import com.vayunmathur.communicate.data.rcs.RcsFeature import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp import com.vayunmathur.communicate.data.rcs.RcsImdn import com.vayunmathur.communicate.data.rcs.RcsMsrp+import com.vayunmathur.communicate.data.rcs.RcsMsrpListen import com.vayunmathur.communicate.data.rcs.RcsRegistrationState import com.vayunmathur.communicate.data.rcs.RcsSession import com.vayunmathur.communicate.data.rcs.RcsSessionManager@@ -59,18 +60,11 @@ import kotlinx.coroutines.launch */ class RcsSyncService : Service() { - private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ internal val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) /** MSRP connections per conversation, owned by this service's lifecycle. */ internal val msrpConnections = java.util.concurrent.ConcurrentHashMap<String, RcsMsrp.MsrpConnection>() - /** Close MSRP connections whose sessions went away. */- internal fun closeDeadMsrpConnections() {- msrpConnections.keys.filter { RcsSessionManager.sessionFor(it) == null }.forEach { id ->- msrpConnections.remove(id)?.close()- }- }- override fun onCreate() { super.onCreate() }@@ -98,18 +92,31 @@ class RcsSyncService : Service() { RcsSipTransport.onInboundMessage = { message -> serviceScope.launch { handleInbound(message) } }+ // Let the session manager offer/answer passive MSRP: the sync+ // service owns the accept loop, so accepted sockets land here.+ RcsSessionManager.listenContextProvider = { this@RcsSyncService }+ RcsMsrpListen.ensureListening(this@RcsSyncService, ::onMsrpAccepted) // Watch for teardown: when the transport goes unavailable, reflect it- // in the sync notification and stop if the gate flips off.+ // in the sync notification and stop if the gate flips off. On+ // (re-)Availability, re-ensure the passive MSRP listener — a+ // subId-switch teardown stops it (IMS PDN is per-sub). launch { RcsSipTransport.state.collect { state -> if (!RcsFeature.enabled) shutdown() updateSyncNotification(state)+ if (state is RcsRegistrationState.Available) {+ RcsSessionManager.listenContextProvider = { this@RcsSyncService }+ RcsMsrpListen.ensureListening(this@RcsSyncService, ::onMsrpAccepted)+ } } } // Own MSRP connection lifecycle: when a session gains a usable // remote path, connect out and feed inbound chunks to the inbox.+ // Also sweep sessions that never completed or idled out, closing+ // their connections so the map cannot leak. launch { RcsSessionManager.sessions.collect { sessions ->+ val stale = RcsSessionManager.sweepStaleSessions() for ((conversationId, session) in sessions) { if (session.msrpRemotePath == null || msrpConnections.containsKey(conversationId)) { continue@@ -123,7 +130,7 @@ class RcsSyncService : Service() { } // Drop connections whose sessions went away. val live = sessions.keys- msrpConnections.keys.filter { it !in live }.forEach { id ->+ msrpConnections.keys.filter { it !in live || it in stale }.forEach { id -> msrpConnections.remove(id)?.close() } }@@ -137,6 +144,8 @@ class RcsSyncService : Service() { override fun onDestroy() { RcsSipTransport.onInboundMessage = null+ RcsSessionManager.listenContextProvider = null+ RcsMsrpListen.stop() msrpConnections.values.forEach { runCatching { it.close() } } msrpConnections.clear() serviceScope.cancel()@@ -230,7 +239,7 @@ class RcsSyncService : Service() { * IMDN/typing ride their trackers. Reuses the SIP parse helpers by * synthesizing the CPIM text path. */- private suspend fun handleMsrpChunk(+ internal suspend fun handleMsrpChunk( conversationId: String, session: RcsSession, contentType: String,@@ -278,7 +287,7 @@ class RcsSyncService : Service() { * are the original wire body (CPIM + payload), so MLS ciphertext stays * opaque to us — E2EE terminates per-member, not at the focus. */- private suspend fun relayFocusMessage(parsed: InboundRcs, rawBody: String) {+ internal suspend fun relayFocusMessage(parsed: InboundRcs, rawBody: String) { if (!RcsFeature.enabled) return val focusUri = RcsSessionManager.hostedFocusFor(parsed.conversationId) ?: return val members = RcsSessionManager.focusMembers(focusUri) ?: return@@ -312,7 +321,7 @@ class RcsSyncService : Service() { } } - private enum class InboundKind { Text, Receipt, Typing }+ internal enum class InboundKind { Text, Receipt, Typing } /** Raw envelope: repaired headers + sender + content type + body + ids. */ private data class Envelope(@@ -622,7 +631,7 @@ class RcsSyncService : Service() { return raw } - private data class InboundRcs(+ internal data class InboundRcs( val conversationId: String, val body: String, val senderId: String,@@ -720,6 +729,8 @@ class RcsSyncService : Service() { private fun shutdown() { RcsSipTransport.onInboundMessage = null+ RcsSessionManager.listenContextProvider = null+ RcsMsrpListen.stop() msrpConnections.values.forEach { runCatching { it.close() } } msrpConnections.clear() runCatching { RcsSipTransport.tearDown(this) }
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.ktindex e7990babc5..7d9960d4b0 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt@@ -1,7 +1,10 @@ package com.vayunmathur.communicate.rcs import com.vayunmathur.communicate.data.rcs.ImdnDisposition+import com.vayunmathur.communicate.data.rcs.MsrpSetup+import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp import com.vayunmathur.communicate.data.rcs.RcsGbaAuth+import com.vayunmathur.communicate.data.rcs.RcsMsrpListen import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.buildEditBody import com.vayunmathur.communicate.data.rcs.buildGeopushBody@@ -160,4 +163,51 @@ class RcsUpFramingTest { assertNull(RcsSessionManager.focusMembers("conf:[email protected]")) RcsSessionManager.noteFocusLeave("conf:[email protected]", "+1555") }++ @Test+ fun sdpSetupParsesAllRoles() {+ assertEquals(+ MsrpSetup.ACTIVE,+ RcsSessionManager.parseSdpSetup("m=message 2855 TCP/MSRP *\r\na=setup:active\r\n"),+ )+ assertEquals(+ MsrpSetup.PASSIVE,+ RcsSessionManager.parseSdpSetup("a=setup:passive"),+ )+ assertEquals(+ MsrpSetup.ACTPASS,+ RcsSessionManager.parseSdpSetup("a=setup:actpass"),+ )+ assertNull(RcsSessionManager.parseSdpSetup("m=message 2855 TCP/MSRP *"))+ assertNull(RcsSessionManager.parseSdpSetup(null))+ assertNull(RcsSessionManager.parseSdpSetup("a=setup:bogus"))+ }++ @Test+ fun acceptedHeadReplays() {+ val head = RcsMsrpListen.AcceptedHead(+ listOf("MSRP abc SEND", "To-Path: msrp://1.2.3.4:2855/x;tcp", "From-Path: msrp://5.6.7.8:9/y;tcp"),+ )+ val replayed = head.replayBytes().toString(Charsets.UTF_8)+ assertTrue(replayed.startsWith("MSRP abc SEND\r\n"))+ assertTrue(replayed.contains("To-Path: msrp://1.2.3.4:2855/x;tcp\r\n"))+ assertTrue(replayed.endsWith("\r\n"))+ }++ @Test+ fun contentServerParses() {+ val xml = "<rcs><ftHTTPCSURI>https://ft.example.com/upload</ftHTTPCSURI></rcs>"+ .toByteArray(Charsets.UTF_8)+ assertEquals(+ "https://ft.example.com/upload",+ RcsFileTransferHttp.parseContentServer(xml),+ )+ assertNull(RcsFileTransferHttp.parseContentServer("<rcs/>".toByteArray(Charsets.UTF_8)))+ }++ @Test+ fun sweepDropsOnlyStale() {+ // Empty manager: nothing to drop, no crash.+ assertTrue(RcsSessionManager.sweepStaleSessions().isEmpty())+ } }