Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsSessionManager.kt
RcsSessionManager.kt639 lines · 28.9 KiBRaw
| 1 | package com.vayunmathur.communicate.data.rcs |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import java.util.UUID |
| 5 | import java.util.concurrent.ConcurrentHashMap |
| 6 | import kotlinx.coroutines.flow.MutableStateFlow |
| 7 | import kotlinx.coroutines.flow.StateFlow |
| 8 | import kotlinx.coroutines.flow.asStateFlow |
| 9 | |
| 10 | /** Rewrite an `msrp(s)://` path's scheme (e.g. advertise `msrps://`). */ |
| 11 | internal fun String.withScheme(scheme: String): String { |
| 12 | val rest = substringAfter("://", missingDelimiterValue = this) |
| 13 | return if (rest === this) this else "$scheme://$rest" |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * CPM session manager: INVITE/MSRP 1:1 dialogs + group conference dialogs. |
| 18 | * |
| 19 | * Mirrors TestRcsApp's `MinimalCpmChatService` (transaction → session routing, |
| 20 | * dialog cache for in-dialog requests) without the jain-sip/Guava stack: |
| 21 | * SIP construction is string-based from the delegate configuration, sends go |
| 22 | * through [RcsSipTransport.sendSipMessage]. |
| 23 | * |
| 24 | * v1 scope: outgoing 1:1 INVITE with SDP-for-MSRP offer, incoming INVITE auto |
| 25 | * handling (200 OK + local SDP or 488), BYE teardown, and group conference |
| 26 | * INVITE to the focus URI. MSRP media itself rides the negotiated socket |
| 27 | * (see [RcsMsrp]); text falls back to pager-mode CPIM until the session is |
| 28 | * established, exactly like ChatManager's session-init gate. |
| 29 | */ |
| 30 | object RcsSessionManager { |
| 31 | internal const val TAG = "RcsSession" |
| 32 | private const val MAX_SESSION_AGE_MS = 5 * 60 * 1000L |
| 33 | private const val MAX_SESSION_IDLE_MS = 30 * 60 * 1000L |
| 34 | internal const val TAG_LENGTH = 8 |
| 35 | internal const val DEFAULT_MSRP_PORT = 2855 |
| 36 | private val SUCCESS_CODES = 200..299 |
| 37 | private const val REDIRECT_CODES = 300 |
| 38 | |
| 39 | private const val CPM_ICSI_REF = "urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session" |
| 40 | |
| 41 | /** CPM session Contact header for [from] with this device's IMEI instance id. */ |
| 42 | internal fun contactHeader(from: String, imei: String?): String = |
| 43 | "Contact: <$from>;+sip.instance=\"<urn:gsma:imei:${imei ?: "unknown"}>\"" + |
| 44 | ";+g.3gpp.icsi-ref=\"$CPM_ICSI_REF\"\r\n" |
| 45 | |
| 46 | val sessionsMutable = MutableStateFlow<Map<String, RcsSession>>(emptyMap()) |
| 47 | val sessions: StateFlow<Map<String, RcsSession>> = sessionsMutable.asStateFlow() |
| 48 | |
| 49 | /** Transaction id (Via branch) → session, for response routing. */ |
| 50 | internal val transactions = ConcurrentHashMap<String, String>() |
| 51 | |
| 52 | /** Typing state per conversation: conversationId → (active, updatedAt). */ |
| 53 | internal val typingMutable = MutableStateFlow<Map<String, Boolean>>(emptyMap()) |
| 54 | val typing: StateFlow<Map<String, Boolean>> = typingMutable.asStateFlow() |
| 55 | |
| 56 | /** Active session for [conversationId], or null. */ |
| 57 | fun sessionFor(conversationId: String): RcsSession? = sessionsMutable.value[conversationId] |
| 58 | |
| 59 | /** |
| 60 | * Start an outgoing 1:1 CPM session: INVITE with SDP-for-MSRP offer to the |
| 61 | * `tel:` URI. Returns the dialog id on accept-tracked send, null when the |
| 62 | * transport is unavailable. The 200 OK/ACK/MSRP bind completes |
| 63 | * asynchronously via [onSipResponse]/[onSipRequest]. |
| 64 | * |
| 65 | * The offer carries `setup:actpass` + our listen path when the passive |
| 66 | * listener is up ([RcsMsrpListen]), so the peer may connect to us; |
| 67 | * otherwise it is the v1 `setup:active` connect-out offer. |
| 68 | */ |
| 69 | suspend fun startSession(remoteTelUri: String, conversationId: String): String? { |
| 70 | if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return null |
| 71 | val callId = "${UUID.randomUUID()}@rcs" |
| 72 | val localTag = UUID.randomUUID().toString().take(8) |
| 73 | val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}" |
| 74 | val tlsFingerprint = tlsFingerprintFor() |
| 75 | val secureOffer = tlsFingerprint != null |
| 76 | val listenPath = listenPathFor(conversationId, secureOffer) |
| 77 | val (startLine, headers, content) = |
| 78 | buildInvite( |
| 79 | remoteTelUri, callId, localTag, branch, conversationId, |
| 80 | listenPath = listenPath, tlsFingerprint = tlsFingerprint, |
| 81 | ) |
| 82 | val ok = RcsSipTransport.sendSipMessage(startLine, headers, content) |
| 83 | if (!ok) return null |
| 84 | val dialogId = "$callId:$localTag" |
| 85 | transactions[branch] = dialogId |
| 86 | sessionsMutable.value = sessionsMutable.value + (conversationId to RcsSession( |
| 87 | dialogId = dialogId, |
| 88 | callId = callId, |
| 89 | localTag = localTag, |
| 90 | remoteTag = "", |
| 91 | remoteUri = remoteTelUri, |
| 92 | conversationId = conversationId, |
| 93 | msrpSecure = secureOffer, |
| 94 | )) |
| 95 | return dialogId |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * Start a group conference session: INVITE to the conference focus URI |
| 100 | * with `Conversation-ID` + subject. Members join via the focus; per-UP the |
| 101 | * focus own the participant list (no re-INVITE fan-out from us). |
| 102 | */ |
| 103 | suspend fun startGroupSession( |
| 104 | focusUri: String, |
| 105 | subject: String, |
| 106 | conversationId: String, |
| 107 | ): String? { |
| 108 | if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return null |
| 109 | val callId = "${UUID.randomUUID()}@rcs" |
| 110 | val localTag = UUID.randomUUID().toString().take(8) |
| 111 | val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}" |
| 112 | val tlsFingerprint = tlsFingerprintFor() |
| 113 | val listenPath = listenPathFor(conversationId, tlsFingerprint != null) |
| 114 | val (startLine, headers, content) = |
| 115 | buildInvite( |
| 116 | focusUri, callId, localTag, branch, conversationId, subject, |
| 117 | listenPath, tlsFingerprint, |
| 118 | ) |
| 119 | val ok = RcsSipTransport.sendSipMessage(startLine, headers, content) |
| 120 | if (!ok) return null |
| 121 | val dialogId = "$callId:$localTag" |
| 122 | transactions[branch] = dialogId |
| 123 | sessionsMutable.value = sessionsMutable.value + (conversationId to RcsSession( |
| 124 | dialogId = dialogId, |
| 125 | callId = callId, |
| 126 | localTag = localTag, |
| 127 | remoteTag = "", |
| 128 | remoteUri = focusUri, |
| 129 | conversationId = conversationId, |
| 130 | isGroup = true, |
| 131 | msrpSecure = tlsFingerprint != null, |
| 132 | )) |
| 133 | return dialogId |
| 134 | } |
| 135 | |
| 136 | /** Focus state + management live in `RcsSessionFocus.kt` (split for file length). */ |
| 137 | |
| 138 | /** |
| 139 | * Drop sessions that never completed (no remote tag after [maxAgeMs]) |
| 140 | * and completed sessions idle longer than [maxIdleMs] with no MSRP |
| 141 | * connection. Returns the dropped conversation ids so the caller can |
| 142 | * close their connections. Best-effort; never throws. |
| 143 | */ |
| 144 | fun sweepStaleSessions( |
| 145 | nowMs: Long = System.currentTimeMillis(), |
| 146 | maxAgeMs: Long = MAX_SESSION_AGE_MS, |
| 147 | maxIdleMs: Long = MAX_SESSION_IDLE_MS, |
| 148 | ): List<String> { |
| 149 | if (!RcsFeature.enabled) return emptyList() |
| 150 | val dropped = mutableListOf<String>() |
| 151 | for ((conversationId, session) in sessionsMutable.value) { |
| 152 | if (session.isFocus) continue |
| 153 | val age = nowMs - session.createdAt |
| 154 | val incomplete = session.remoteTag.isBlank() && age > maxAgeMs |
| 155 | val idle = session.remoteTag.isNotBlank() && |
| 156 | session.msrpRemotePath == null && age > maxIdleMs |
| 157 | if (incomplete || idle) { |
| 158 | sessionsMutable.value = sessionsMutable.value - conversationId |
| 159 | pendingOffersMutable.remove(session.callId) |
| 160 | answerFingerprintsMutable.remove(session.callId) |
| 161 | RcsMsrpListen.dropPending(conversationId) |
| 162 | dropped += conversationId |
| 163 | } |
| 164 | } |
| 165 | transactions.entries.removeIf { (_, dialogId) -> |
| 166 | sessionsMutable.value.values.none { it.dialogId == dialogId } |
| 167 | } |
| 168 | return dropped |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Advertise our listen path for [conversationId] when the passive |
| 173 | * listener can bind. Null when listening is unavailable — callers fall |
| 174 | * back to active-only offers. Needs a Context for the IMS request; the |
| 175 | * session manager is context-free, so the sync service injects it via |
| 176 | * [listenContextProvider] at startup (null = no passive offers). |
| 177 | */ |
| 178 | var listenContextProvider: (() -> android.content.Context?)? = null |
| 179 | |
| 180 | private suspend fun listenPathFor( |
| 181 | conversationId: String, |
| 182 | secure: Boolean = false, |
| 183 | peerFingerprint: String? = null, |
| 184 | ): String? { |
| 185 | val context = listenContextProvider?.invoke() ?: return null |
| 186 | // The accept callback is a no-op here: the sync service owns the real |
| 187 | // accept loop (it calls ensureListening at startup). advertisePath |
| 188 | // only registers the pending path when already listening. |
| 189 | if (!RcsMsrpListen.isListening()) return null |
| 190 | return RcsMsrpListen.advertisePath( |
| 191 | context, conversationId, secure, peerFingerprint, |
| 192 | ) { _, _, _ -> } |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * Our TLS fingerprint for SDP offers/answers, or null when the identity |
| 197 | * is unavailable (caller falls back to plaintext `msrp://`). |
| 198 | */ |
| 199 | private suspend fun tlsFingerprintFor(): String? { |
| 200 | val context = listenContextProvider?.invoke() ?: return null |
| 201 | return RcsMsrpTls.ensureIdentity(context)?.fingerprint |
| 202 | } |
| 203 | |
| 204 | /** |
| 205 | * Answer a pending incoming INVITE with 200 OK + SDP answer. |
| 206 | * |
| 207 | * With the passive listener up and an offerer that wants us to listen |
| 208 | * (`setup:active` + usable path), we answer `setup:passive` with our |
| 209 | * listen path and their TCP connection completes the session. Otherwise |
| 210 | * the v1 behavior holds: answer `setup:active` and connect out when the |
| 211 | * offerer's path/setup allows, else keep the dialog for in-dialog |
| 212 | * MESSAGE with media on pager-mode. |
| 213 | * |
| 214 | * Returns true when the 200 OK was accepted by the transport. |
| 215 | */ |
| 216 | suspend fun acceptIncoming(conversationId: String): Boolean { |
| 217 | if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false |
| 218 | val session = sessionsMutable.value[conversationId] ?: return false |
| 219 | val cfg = RcsSipTransport.lastConfigSnapshot() |
| 220 | val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs" |
| 221 | val offered = pendingOffersMutable[session.callId] |
| 222 | // Passive answer when the offerer is active-only and we can listen. |
| 223 | // The offer's fingerprint (when present) pins the accept-side TLS. |
| 224 | val offerSdp = offered?.sdp.orEmpty() |
| 225 | val answerSecure = isSecureSdp(offerSdp) |
| 226 | val tlsFingerprint = if (answerSecure) tlsFingerprintFor() else null |
| 227 | val useTls = answerSecure && tlsFingerprint != null |
| 228 | val passivePath = if (offered?.setup == MsrpSetup.ACTIVE && !offered.remotePath.isNullOrBlank()) { |
| 229 | listenPathFor(conversationId, useTls, offered.peerFingerprint) |
| 230 | } else { |
| 231 | null |
| 232 | } |
| 233 | // Offered TLS but identity unavailable: answer plaintext (downgrade) |
| 234 | // rather than failing the dialog — pager-mode still works. |
| 235 | val sdp = buildSdpAnswer( |
| 236 | cfg?.msrpLocalIp, passivePath, |
| 237 | secure = useTls, tlsFingerprint = tlsFingerprint, |
| 238 | ) |
| 239 | val bytes = sdp.toByteArray(Charsets.UTF_8) |
| 240 | val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}" |
| 241 | val startLine = "SIP/2.0 200 OK" |
| 242 | val headers = buildString { |
| 243 | append("Via: SIP/2.0/TCP local;branch=$branch\r\n") |
| 244 | append("From: <${session.remoteUri}>;tag=${session.remoteTag.ifBlank { "unknown" }}\r\n") |
| 245 | append("To: <$from>;tag=${session.localTag}\r\n") |
| 246 | append("Call-ID: ${session.callId}\r\n") |
| 247 | append("CSeq: 1 INVITE\r\n") |
| 248 | append(contactHeader(from, cfg?.imei)) |
| 249 | append("Content-Type: application/sdp\r\n") |
| 250 | append("Content-Length: ${bytes.size}\r\n") |
| 251 | } |
| 252 | val ok = RcsSipTransport.sendSipMessage(startLine, headers, bytes) |
| 253 | if (ok) { |
| 254 | // Record the offerer's path/setup for connect-out — unless we |
| 255 | // answered passive, in which case THEY connect to our listen |
| 256 | // path and the accept loop completes the session. |
| 257 | val offer = pendingOffersMutable.remove(session.callId) |
| 258 | if (offer != null) { |
| 259 | sessionsMutable.value = sessionsMutable.value + (conversationId to session.copy( |
| 260 | msrpRemotePath = offer.remotePath, |
| 261 | msrpSetup = offer.setup, |
| 262 | msrpLocalPath = passivePath ?: session.msrpLocalPath, |
| 263 | msrpSecure = useTls, |
| 264 | )) |
| 265 | } |
| 266 | } |
| 267 | return ok |
| 268 | } |
| 269 | |
| 270 | /** |
| 271 | * Decline a pending incoming INVITE with 488 (used when the offer |
| 272 | * requires passive-us, i.e. `setup:active` with no usable path). |
| 273 | */ |
| 274 | suspend fun declineIncoming(conversationId: String): Boolean { |
| 275 | if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false |
| 276 | val session = sessionsMutable.value[conversationId] ?: return true |
| 277 | val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}" |
| 278 | val startLine = "SIP/2.0 488 Not Acceptable Here" |
| 279 | val headers = buildString { |
| 280 | append("Via: SIP/2.0/TCP local;branch=$branch\r\n") |
| 281 | append("Call-ID: ${session.callId}\r\n") |
| 282 | append("CSeq: 1 INVITE\r\n") |
| 283 | append("Content-Length: 0\r\n") |
| 284 | } |
| 285 | val ok = RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0)) |
| 286 | pendingOffersMutable.remove(session.callId) |
| 287 | sessionsMutable.value = sessionsMutable.value - conversationId |
| 288 | return ok |
| 289 | } |
| 290 | |
| 291 | /** Inbound offer details stashed at INVITE time for [acceptIncoming]. */ |
| 292 | internal data class PendingOffer( |
| 293 | val remotePath: String?, |
| 294 | val setup: MsrpSetup?, |
| 295 | /** Raw offer SDP (for TLS/fingerprint detection at answer time). */ |
| 296 | val sdp: String = "", |
| 297 | /** Peer's SDP fingerprint value, when offered (for TLS pinning). */ |
| 298 | val peerFingerprint: String? = null, |
| 299 | ) |
| 300 | |
| 301 | internal val pendingOffersMutable = ConcurrentHashMap<String, PendingOffer>() |
| 302 | |
| 303 | /** Peer's SDP answer fingerprint for an outgoing session ([callId]). */ |
| 304 | internal val answerFingerprintsMutable = ConcurrentHashMap<String, String>() |
| 305 | |
| 306 | /** Stashed answer fingerprint for [callId], or null when absent. */ |
| 307 | fun peerFingerprint(callId: String): String? = answerFingerprintsMutable[callId] |
| 308 | |
| 309 | /** |
| 310 | * Send a MESSAGE inside [conversationId]'s confirmed dialog (in-dialog |
| 311 | * Request-URI + route set + next CSeq). Returns false when no confirmed |
| 312 | * session exists (caller uses pager-mode). Advances the dialog CSeq. |
| 313 | */ |
| 314 | suspend fun sendInDialogMessage( |
| 315 | conversationId: String, |
| 316 | body: ByteArray, |
| 317 | contentType: String = "message/cpim", |
| 318 | ): Boolean { |
| 319 | if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false |
| 320 | val session = sessionsMutable.value[conversationId] |
| 321 | ?.takeIf { it.confirmed && it.remoteTag.isNotBlank() } ?: return false |
| 322 | val req = RcsSipDialog.buildInDialogMessage(session, body, contentType) |
| 323 | val ok = RcsSipTransport.sendSipMessage(req.startLine, req.headers, req.body) |
| 324 | if (ok) { |
| 325 | sessionsMutable.value = sessionsMutable.value + ( |
| 326 | conversationId to session.copy(nextCseq = req.nextCseq) |
| 327 | ) |
| 328 | } |
| 329 | return ok |
| 330 | } |
| 331 | |
| 332 | /** Tear down the session for [conversationId] with in-dialog BYE. */ |
| 333 | suspend fun terminateSession(conversationId: String): Boolean { |
| 334 | val session = sessionsMutable.value[conversationId] ?: return true |
| 335 | val ok = if (session.confirmed && session.remoteTag.isNotBlank()) { |
| 336 | // Confirmed dialog: in-dialog BYE with next CSeq + route set. |
| 337 | val req = RcsSipDialog.buildInDialogBye(session) |
| 338 | val sent = RcsSipTransport.sendSipMessage(req.startLine, req.headers, req.body) |
| 339 | sessionsMutable.value = sessionsMutable.value + ( |
| 340 | conversationId to session.copy(nextCseq = req.nextCseq) |
| 341 | ) |
| 342 | sent |
| 343 | } else { |
| 344 | // Unconfirmed/early dialog: best-effort BYE as before. |
| 345 | val branch = RcsSipDialog.newBranch() |
| 346 | val startLine = "BYE sip:${session.remoteUri} SIP/2.0" |
| 347 | val headers = buildString { |
| 348 | append("Via: SIP/2.0/TCP local;branch=$branch\r\n") |
| 349 | append("Call-ID: ${session.callId}\r\n") |
| 350 | append("CSeq: 2 BYE\r\n") |
| 351 | append("Content-Length: 0\r\n") |
| 352 | } |
| 353 | RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0)) |
| 354 | } |
| 355 | transactions.entries.removeIf { it.value == session.dialogId } |
| 356 | sessionsMutable.value = sessionsMutable.value - conversationId |
| 357 | pendingOffersMutable.remove(session.callId) |
| 358 | answerFingerprintsMutable.remove(session.callId) |
| 359 | RcsMsrpListen.dropPending(conversationId) |
| 360 | if (session.remoteTag.isNotBlank()) { |
| 361 | // Tell the framework the dialog is gone so it releases delegate |
| 362 | // state for this Call-ID (best-effort; stub-covered). |
| 363 | RcsSipTransport.cleanupSession(session.callId) |
| 364 | } |
| 365 | return ok |
| 366 | } |
| 367 | |
| 368 | /** |
| 369 | * Route an inbound SIP response (from the delegate message callback) to |
| 370 | * its session: 200 OK to INVITE completes the dialog (remote tag + SDP |
| 371 | * answer + route set) and sends the ACK (RFC 3261 §13.2.2.4); other |
| 372 | * finals tear the pending session down. |
| 373 | * |
| 374 | * Suspend: the ACK goes through the transport. Never throws. |
| 375 | */ |
| 376 | suspend fun onSipResponse( |
| 377 | statusCode: Int, |
| 378 | callId: String, |
| 379 | remoteTag: String?, |
| 380 | sdpAnswer: String?, |
| 381 | responseHeaders: String = "", |
| 382 | ) { |
| 383 | val entry = sessionsMutable.value.entries.firstOrNull { it.value.callId == callId } ?: return |
| 384 | val session = entry.value |
| 385 | if (statusCode in SUCCESS_CODES && !remoteTag.isNullOrBlank()) { |
| 386 | establishSession(entry.key, session, remoteTag, sdpAnswer, callId, responseHeaders) |
| 387 | } else if (statusCode >= REDIRECT_CODES) { |
| 388 | failSession(entry.key, session, callId, statusCode) |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | /** Apply a 2xx answer: paths, fingerprint, usability, ACK. */ |
| 393 | private suspend fun establishSession( |
| 394 | key: String, |
| 395 | session: RcsSession, |
| 396 | remoteTag: String, |
| 397 | sdpAnswer: String?, |
| 398 | callId: String, |
| 399 | responseHeaders: String, |
| 400 | ) { |
| 401 | val (localPath, remotePath) = parseSdpPaths(sdpAnswer) |
| 402 | val setup = parseSdpSetup(sdpAnswer) |
| 403 | val (contact, routeSet) = RcsSipDialog.parseDialogRoute(responseHeaders) |
| 404 | // TLS sticks when WE offered secure and the answer keeps it |
| 405 | // (secure answer SDP); a plaintext answer to our secure offer is |
| 406 | // a downgrade — honor it and run plaintext. |
| 407 | val answerSecure = isSecureSdp(sdpAnswer) |
| 408 | // Stash the answer's fingerprint for the TLS client pin check |
| 409 | // and the listen-side accept pin check. |
| 410 | RcsMsrpTls.parseFingerprint(sdpAnswer)?.second?.let { fp -> |
| 411 | answerFingerprintsMutable[callId] = fp |
| 412 | RcsMsrpListen.notePeerFingerprint(key, fp) |
| 413 | } |
| 414 | val established = session.copy( |
| 415 | remoteTag = remoteTag, |
| 416 | msrpLocalPath = localPath ?: session.msrpLocalPath, |
| 417 | msrpRemotePath = remotePath, |
| 418 | msrpSetup = setup, |
| 419 | msrpSecure = session.msrpSecure && answerSecure, |
| 420 | remoteContact = contact ?: session.remoteContact, |
| 421 | routeSet = if (routeSet.isNotEmpty()) routeSet else session.routeSet, |
| 422 | ) |
| 423 | sessionsMutable.value = sessionsMutable.value + (key to established) |
| 424 | // Usable when: peer is passive/actpass (we connect out, the v1 |
| 425 | // path), OR peer is active and we have a listen path (they |
| 426 | // connect to us — the accept loop completes the session), OR our |
| 427 | // offer carried a listen path and the answer kept any path |
| 428 | // (actpass negotiation leaves the direction to the answerer). |
| 429 | val peerActive = setup == MsrpSetup.ACTIVE |
| 430 | val usable = remotePath != null && ( |
| 431 | !peerActive || |
| 432 | established.msrpLocalPath?.contains("msrp://") == true && |
| 433 | RcsMsrpListen.isListening() |
| 434 | ) |
| 435 | Log.status(TAG, "Session established ${session.dialogId} setup=$setup usable=$usable") |
| 436 | if (!usable) { |
| 437 | sessionsMutable.value = sessionsMutable.value + (key to |
| 438 | (sessionsMutable.value[key] ?: established).copy(msrpRemotePath = null)) |
| 439 | } |
| 440 | // ACK the 2xx (RFC 3261 §13): same CSeq number as the INVITE, |
| 441 | // Request-URI = answer Contact, confirmed dialog either way. |
| 442 | val acked = runCatching { |
| 443 | val (ackLine, ackHeaders) = RcsSipDialog.buildAck( |
| 444 | (sessionsMutable.value[key] ?: established).copy(remoteTag = remoteTag), |
| 445 | ) |
| 446 | RcsSipTransport.sendSipMessage(ackLine, ackHeaders, ByteArray(0)) |
| 447 | }.getOrDefault(false) |
| 448 | sessionsMutable.value = sessionsMutable.value + (key to |
| 449 | ((sessionsMutable.value[key] ?: established).copy(confirmed = true))) |
| 450 | if (!acked) Log.status(TAG, "ACK not accepted for $callId (dialog unconfirmed at SIP layer)") |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * Dialog-mismatch recovery (§1.6): 481/408/480/486/603 against [callId]. |
| 455 | * Closes MSRP state + framework dialog state, drops pending paths, and |
| 456 | * parks the conversation in backoff so the send path doesn't hammer |
| 457 | * session re-establishment. Never throws. |
| 458 | */ |
| 459 | fun onDialogError(callId: String, statusCode: Int) { |
| 460 | val entry = sessionsMutable.value.entries.firstOrNull { it.value.callId == callId } |
| 461 | if (entry != null) { |
| 462 | sessionsMutable.value = sessionsMutable.value - entry.key |
| 463 | RcsMsrpListen.dropPending(entry.key) |
| 464 | backoffUntil[entry.key] = System.currentTimeMillis() + DIALOG_ERROR_BACKOFF_MS |
| 465 | Log.status(TAG, "Dialog error $statusCode for ${entry.key}; backing off") |
| 466 | } |
| 467 | pendingOffersMutable.remove(callId) |
| 468 | answerFingerprintsMutable.remove(callId) |
| 469 | transactions.entries.removeIf { it.value.endsWith(callId) } |
| 470 | RcsSipTransport.cleanupSession(callId) |
| 471 | } |
| 472 | |
| 473 | /** True when [conversationId] is in dialog-error backoff (skip fast re-INVITE). */ |
| 474 | fun inDialogBackoff(conversationId: String): Boolean { |
| 475 | val until = backoffUntil[conversationId] ?: return false |
| 476 | if (System.currentTimeMillis() >= until) { |
| 477 | backoffUntil.remove(conversationId) |
| 478 | return false |
| 479 | } |
| 480 | return true |
| 481 | } |
| 482 | |
| 483 | private val backoffUntil = ConcurrentHashMap<String, Long>() |
| 484 | |
| 485 | /** Post-dialog-error quiet period before fast session re-establishment. */ |
| 486 | private const val DIALOG_ERROR_BACKOFF_MS = 5 * 60 * 1000L |
| 487 | |
| 488 | /** |
| 489 | * Route an inbound SIP request: INVITE stashes the offer and starts an |
| 490 | * incoming session entry (caller answers via [acceptIncoming] or declines |
| 491 | * via [declineIncoming]), BYE tears down, MESSAGE with |
| 492 | * `message/imdn+xml` updates receipts, `im-iscomposing` updates typing. |
| 493 | */ |
| 494 | fun onSipRequest( |
| 495 | method: String, |
| 496 | callId: String, |
| 497 | fromUri: String, |
| 498 | contentType: String?, |
| 499 | body: String, |
| 500 | fromTag: String? = null, |
| 501 | toUri: String? = null, |
| 502 | ): RcsSession? { |
| 503 | return when (method.uppercase()) { |
| 504 | "INVITE" -> onInviteRequest(callId, fromUri, body, fromTag, toUri) |
| 505 | "BYE" -> { |
| 506 | val entry = sessionsMutable.value.entries.firstOrNull { it.value.callId == callId } |
| 507 | if (entry != null) sessionsMutable.value = sessionsMutable.value - entry.key |
| 508 | null |
| 509 | } |
| 510 | "ACK" -> { |
| 511 | // ACK to our 200 OK: the incoming dialog is confirmed. Match |
| 512 | // by Call-ID (the session was stored under the sender id). |
| 513 | val entry = sessionsMutable.value.entries.firstOrNull { it.value.callId == callId } |
| 514 | if (entry != null) { |
| 515 | sessionsMutable.value = sessionsMutable.value + ( |
| 516 | entry.key to entry.value.copy(confirmed = true) |
| 517 | ) |
| 518 | } |
| 519 | null |
| 520 | } |
| 521 | "MESSAGE" -> { |
| 522 | onMessageRequest(fromUri, contentType, body) |
| 523 | null |
| 524 | } |
| 525 | else -> null |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | |
| 530 | /** |
| 531 | * Build an INVITE with SDP-for-MSRP offer (TestRcsApp SipUtils.buildInvite |
| 532 | * header set, string-built): From (P-Preferred-Identity), To, Via, |
| 533 | * Max-Forwards, Call-ID, CSeq, Contact (+sip.instance + CPM tag), |
| 534 | * Conversation-ID, Contribution-ID, Accept-Contact (CPM session), |
| 535 | * P-Preferred-Service (CPM URN), Route (Service-Route), User-Agent, |
| 536 | * P-Access-Network-Info when configured. |
| 537 | */ |
| 538 | |
| 539 | private fun parseSdpPaths(sdp: String?): Pair<String?, String?> { |
| 540 | if (sdp.isNullOrBlank()) return null to null |
| 541 | val path = Regex("a=path:(\\S+)", RegexOption.IGNORE_CASE).find(sdp) |
| 542 | ?.groupValues?.getOrNull(1)?.trim() |
| 543 | return null to path |
| 544 | } |
| 545 | |
| 546 | /** True when the SDP negotiates TLS media (`TCP/TLS/MSRP`, `msrps`, or fingerprint). */ |
| 547 | fun isSecureSdp(sdp: String?): Boolean { |
| 548 | if (sdp.isNullOrBlank()) return false |
| 549 | return sdp.contains("TCP/TLS/MSRP", ignoreCase = true) || |
| 550 | Regex("a=path:msrps://", RegexOption.IGNORE_CASE).containsMatchIn(sdp) || |
| 551 | RcsMsrpTls.parseFingerprint(sdp) != null |
| 552 | } |
| 553 | |
| 554 | /** True when [callId] matches a live session dialog (re-INVITE/UPDATE target). */ |
| 555 | fun isKnownDialog(callId: String): Boolean = |
| 556 | sessionsMutable.value.values.any { it.callId == callId } |
| 557 | |
| 558 | /** |
| 559 | * Apply a re-INVITE's SDP to a live dialog (§1.5): update the bound |
| 560 | * path/setup/TLS to the new offer. Media handover (socket swap) is the |
| 561 | * sync service's job — it observes the session map. Never throws. |
| 562 | */ |
| 563 | fun onReInvite(callId: String, sdp: String) { |
| 564 | val entry = sessionsMutable.value.entries.firstOrNull { it.value.callId == callId } ?: return |
| 565 | val session = entry.value |
| 566 | val (localPath, remotePath) = parseSdpPaths(sdp) |
| 567 | val setup = parseSdpSetup(sdp) ?: session.msrpSetup |
| 568 | val secure = isSecureSdp(sdp) |
| 569 | RcsMsrpTls.parseFingerprint(sdp)?.second?.let { fp -> |
| 570 | answerFingerprintsMutable[callId] = fp |
| 571 | RcsMsrpListen.notePeerFingerprint(entry.key, fp) |
| 572 | } |
| 573 | sessionsMutable.value = sessionsMutable.value + (entry.key to session.copy( |
| 574 | msrpRemotePath = remotePath ?: session.msrpRemotePath, |
| 575 | msrpSetup = setup, |
| 576 | msrpSecure = secure, |
| 577 | msrpLocalPath = localPath ?: session.msrpLocalPath, |
| 578 | )) |
| 579 | Log.status(TAG, "Re-INVITE applied for ${entry.key} setup=$setup secure=$secure") |
| 580 | } |
| 581 | |
| 582 | /** |
| 583 | * Current SDP for [conversationId]'s session (for UPDATE/re-INVITE |
| 584 | * answers, §1.5): re-emits our bound path + setup + TLS state. Null when |
| 585 | * no session exists. |
| 586 | */ |
| 587 | fun currentSdpFor(conversationId: String): ByteArray? { |
| 588 | val session = sessionsMutable.value[conversationId] ?: return null |
| 589 | val cfg = RcsSipTransport.lastConfigSnapshot() |
| 590 | val ip = cfg?.msrpLocalIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0" |
| 591 | val path = session.msrpLocalPath ?: return null |
| 592 | val port = RcsMsrp.parseMsrpPath(path)?.second ?: 2855 |
| 593 | // We are the answerer side here: our role is passive when the peer |
| 594 | // connects to us (their setup=active), else active (we connect out). |
| 595 | val setup = if (session.msrpSetup == MsrpSetup.ACTIVE) "passive" else "active" |
| 596 | val proto = if (session.msrpSecure) "TCP/TLS/MSRP" else "TCP/MSRP" |
| 597 | val sdp = buildString { |
| 598 | append("v=0\r\n") |
| 599 | append("o=- ${System.currentTimeMillis()} ${System.currentTimeMillis()} IN IP4 $ip\r\n") |
| 600 | append("s=-\r\n") |
| 601 | append("c=IN IP4 $ip\r\n") |
| 602 | append("t=0 0\r\n") |
| 603 | append("m=message $port $proto *\r\n") |
| 604 | append("a=path:$path\r\n") |
| 605 | append("a=accept-types:message/cpim text/plain message/imdn+xml application/im-iscomposing+xml\r\n") |
| 606 | append("a=setup:$setup\r\n") |
| 607 | } |
| 608 | return sdp.toByteArray(Charsets.UTF_8) |
| 609 | } |
| 610 | |
| 611 | /** Hosted-focus lookup: which focus a To-URI/SDP blob targets. */ |
| 612 | internal data class HostedTarget(val focusUri: String, val conversationId: String) |
| 613 | internal fun hostedConversationFor(target: String): HostedTarget? { |
| 614 | if (target.isBlank()) return null |
| 615 | for ((conversationId, session) in sessionsMutable.value) { |
| 616 | if (!session.isFocus) continue |
| 617 | if (target.contains(session.remoteUri, ignoreCase = true)) { |
| 618 | return HostedTarget(session.remoteUri, conversationId) |
| 619 | } |
| 620 | } |
| 621 | return null |
| 622 | } |
| 623 | |
| 624 | /** |
| 625 | * Parse the MSRP `a=setup:` role from an SDP answer. Null when absent |
| 626 | * (assume peer is passive, the common answer to our active offer). |
| 627 | */ |
| 628 | fun parseSdpSetup(sdp: String?): MsrpSetup? { |
| 629 | if (sdp.isNullOrBlank()) return null |
| 630 | val token = Regex("a=setup:(\\S+)", RegexOption.IGNORE_CASE).find(sdp) |
| 631 | ?.groupValues?.getOrNull(1)?.trim()?.lowercase() ?: return null |
| 632 | return when (token) { |
| 633 | "active" -> MsrpSetup.ACTIVE |
| 634 | "passive" -> MsrpSetup.PASSIVE |
| 635 | "actpass" -> MsrpSetup.ACTPASS |
| 636 | else -> null |
| 637 | } |
| 638 | } |
| 639 | } |