Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsSipTransport.kt
RcsSipTransport.kt676 lines · 29.4 KiBRaw
| 1 | package com.vayunmathur.communicate.data.rcs |
| 2 | |
| 3 | import android.content.Context |
| 4 | import android.telephony.SubscriptionManager |
| 5 | import android.telephony.ims.DelegateRegistrationState |
| 6 | import android.telephony.ims.DelegateRequest |
| 7 | import android.telephony.ims.FeatureTagState |
| 8 | import android.telephony.ims.ImsException |
| 9 | import android.telephony.ims.SipDelegateConfiguration |
| 10 | import android.telephony.ims.SipDelegateConnection |
| 11 | import android.telephony.ims.SipDelegateManager |
| 12 | import android.telephony.ims.SipMessage |
| 13 | import android.telephony.ims.stub.DelegateConnectionMessageCallback |
| 14 | import android.telephony.ims.stub.DelegateConnectionStateCallback |
| 15 | import com.vayunmathur.library.log.Log |
| 16 | import java.util.UUID |
| 17 | import java.util.concurrent.ConcurrentHashMap |
| 18 | import java.util.concurrent.Executor |
| 19 | import java.util.concurrent.Executors |
| 20 | import kotlin.coroutines.resume |
| 21 | import kotlinx.coroutines.CoroutineScope |
| 22 | import kotlinx.coroutines.Dispatchers |
| 23 | import kotlinx.coroutines.SupervisorJob |
| 24 | import kotlinx.coroutines.flow.MutableStateFlow |
| 25 | import kotlinx.coroutines.flow.StateFlow |
| 26 | import kotlinx.coroutines.flow.asStateFlow |
| 27 | import kotlinx.coroutines.launch |
| 28 | import kotlinx.coroutines.suspendCancellableCoroutine |
| 29 | |
| 30 | /** |
| 31 | * Per-subscription `SipDelegateManager` wrapper (single-registration transport). |
| 32 | * |
| 33 | * One delegate per active [SubscriptionManager] subId, tied to |
| 34 | * [SimManager]'s active subscription. CPM feature tags only. Every platform |
| 35 | * call catches `SecurityException` (no carrier privilege on a normal |
| 36 | * dev-build install) and maps to `Unavailable(NoCarrierPrivilege)` — never |
| 37 | * crashes. Until the transport is `Available`, sends fall back to SMS. |
| 38 | */ |
| 39 | object RcsSipTransport { |
| 40 | private const val TAG = "RcsSipTransport" |
| 41 | private val SUCCESS_CODES = 200..299 |
| 42 | private val PROVISIONAL_CODES = 100..199 |
| 43 | private const val FAILURE_CODES = 300 |
| 44 | private const val UNAUTHORIZED = 401 |
| 45 | private const val PROXY_AUTH_REQUIRED = 407 |
| 46 | private const val CALL_LEG_GONE = 481 |
| 47 | private const val REQUEST_TIMEOUT = 408 |
| 48 | private const val TEMP_UNAVAILABLE = 480 |
| 49 | private const val BUSY_HERE = 486 |
| 50 | private const val DECLINE = 603 |
| 51 | |
| 52 | /** |
| 53 | * CPM feature tags for RCS chat + file transfer (RCC.07 §2.6.1.3). Must be |
| 54 | * allowed by the carrier (`KEY_RCS_FEATURE_TAG_ALLOWED_STRING_ARRAY`) or |
| 55 | * the request is denied. Tag set mirrors TestRcsApp's DelegateActivity: |
| 56 | * session + pager-mode variants + FT. |
| 57 | */ |
| 58 | val CPM_FEATURE_TAGS: Set<String> = setOf( |
| 59 | "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"", |
| 60 | "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.msg\"", |
| 61 | "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.largemsg\"", |
| 62 | "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.deferred\"", |
| 63 | "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.fthttp\"", |
| 64 | ) |
| 65 | |
| 66 | private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) |
| 67 | private val executor: Executor = Executors.newSingleThreadExecutor() |
| 68 | |
| 69 | private val _state = MutableStateFlow<RcsRegistrationState>(RcsRegistrationState.Unknown) |
| 70 | val state: StateFlow<RcsRegistrationState> = _state.asStateFlow() |
| 71 | |
| 72 | @Volatile private var connection: SipDelegateConnection? = null |
| 73 | @Volatile private var configVersion: Long = -1L |
| 74 | @Volatile private var activeSubId: Int = SubscriptionManager.INVALID_SUBSCRIPTION_ID |
| 75 | /** Last IMS configuration (identity, server, route headers for sends). */ |
| 76 | @Volatile private var lastConfig: SipDelegateConfiguration? = null |
| 77 | |
| 78 | /** |
| 79 | * Snapshot of the fields SIP construction needs, decoupled from the hidden |
| 80 | * config class so callers never touch framework types. |
| 81 | */ |
| 82 | data class ConfigSnapshot( |
| 83 | val version: Long, |
| 84 | val publicUserId: String?, |
| 85 | val homeDomain: String?, |
| 86 | val msrpLocalIp: String?, |
| 87 | val serviceRoute: String?, |
| 88 | val pani: String?, |
| 89 | val userAgent: String?, |
| 90 | val imei: String?, |
| 91 | ) |
| 92 | |
| 93 | fun lastConfigSnapshot(): ConfigSnapshot? { |
| 94 | val cfg = lastConfig ?: return null |
| 95 | return runCatching { |
| 96 | ConfigSnapshot( |
| 97 | version = cfg.getVersion(), |
| 98 | publicUserId = cfg.getPublicUserIdentifier(), |
| 99 | homeDomain = cfg.getHomeDomain(), |
| 100 | // IMS-PDN local address when known — routable by carrier peers, |
| 101 | // unlike the delegate config (which carries no local IP field). |
| 102 | msrpLocalIp = RcsImsNetwork.lastLocalIp, |
| 103 | serviceRoute = cfg.getSipServiceRouteHeader(), |
| 104 | pani = cfg.getSipPaniHeader(), |
| 105 | userAgent = cfg.getSipUserAgentHeader(), |
| 106 | imei = cfg.getImei(), |
| 107 | ) |
| 108 | }.getOrNull() |
| 109 | } |
| 110 | |
| 111 | /** Inbound SIP MESSAGE listener (sync service writes to Room + notifies). */ |
| 112 | @Volatile |
| 113 | var onInboundMessage: ((SipMessage) -> Unit)? = null |
| 114 | |
| 115 | /** Pending outbound sends keyed by Via branch transaction id. */ |
| 116 | private data class PendingSend( |
| 117 | val callback: (Boolean) -> Unit, |
| 118 | val startLine: String, |
| 119 | val headers: String, |
| 120 | val body: ByteArray, |
| 121 | val authAttempts: Int = 0, |
| 122 | ) |
| 123 | |
| 124 | private val pendingSends = ConcurrentHashMap<String, PendingSend>() |
| 125 | |
| 126 | /** |
| 127 | * Hidden-API callbacks, loaded on first use only. They are created by |
| 128 | * [transportCallbacks], whose signature is hidden-API-free: the callback |
| 129 | * types appear only as `Any` here, so neither the property types nor the |
| 130 | * `<clinit>` reference the missing classes. Call sites cast back to the |
| 131 | * framework types (safe on-device, where the framework provides them). |
| 132 | */ |
| 133 | private val stateCallback: Any by lazy { transportCallbacks().first } |
| 134 | private val messageCallback: Any by lazy { transportCallbacks().second } |
| 135 | |
| 136 | /** Test seam: the lazily-built delegate callbacks, for JVM tests. */ |
| 137 | internal fun callbacksForTest(): Pair<Any, Any> = stateCallback to messageCallback |
| 138 | |
| 139 | /** |
| 140 | * Test seam: install (or clear, with null) a delegate connection plus |
| 141 | * its config version/snapshot, mirroring what `onCreated` + |
| 142 | * `onConfigurationChanged` set on device. Production code never calls |
| 143 | * this; the framework callbacks remain the only real installers. |
| 144 | */ |
| 145 | fun installConnectionForTest( |
| 146 | connection: SipDelegateConnection?, |
| 147 | version: Long, |
| 148 | config: SipDelegateConfiguration?, |
| 149 | ) { |
| 150 | this.connection = connection |
| 151 | configVersion = version |
| 152 | lastConfig = config |
| 153 | _state.value = if (connection != null) { |
| 154 | RcsRegistrationState.Available |
| 155 | } else { |
| 156 | RcsRegistrationState.Unknown |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * Build the two delegate callbacks. The anonymous classes — and hence the |
| 162 | * hidden-API callback types — load only when this function runs |
| 163 | * on-device, never during the outer object's `<clinit>`. |
| 164 | */ |
| 165 | private fun transportCallbacks(): Pair<Any, Any> { |
| 166 | val state = object : DelegateConnectionStateCallback { |
| 167 | override fun onCreated(c: SipDelegateConnection) { |
| 168 | connection = c |
| 169 | _state.value = RcsRegistrationState.Available |
| 170 | Log.status(TAG, "SipDelegate created") |
| 171 | } |
| 172 | |
| 173 | override fun onFeatureTagStatusChanged( |
| 174 | registrationState: DelegateRegistrationState, |
| 175 | deniedFeatureTags: Set<FeatureTagState>, |
| 176 | ) { |
| 177 | if (deniedFeatureTags.isNotEmpty()) { |
| 178 | Log.status(TAG, "Feature tags denied: ${deniedFeatureTags.map { it.getFeatureTag() }}") |
| 179 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.TransportDenied) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | override fun onConfigurationChanged(registeredSipConfig: SipDelegateConfiguration) { |
| 184 | configVersion = registeredSipConfig.getVersion() |
| 185 | lastConfig = registeredSipConfig |
| 186 | } |
| 187 | |
| 188 | override fun onDestroyed(reason: Int) { |
| 189 | Log.status(TAG, "SipDelegate destroyed reason=$reason") |
| 190 | connection = null |
| 191 | configVersion = -1L |
| 192 | lastConfig = null |
| 193 | if (_state.value is RcsRegistrationState.Available) { |
| 194 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable) |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | val message = object : DelegateConnectionMessageCallback { |
| 199 | override fun onMessageReceived(message: SipMessage) { |
| 200 | runCatching { connection?.notifyMessageReceived(message.getViaBranchParameter()) } |
| 201 | onInboundMessage?.invoke(message) |
| 202 | } |
| 203 | |
| 204 | override fun onMessageSent(viaTransactionId: String) { |
| 205 | pendingSends.remove(viaTransactionId)?.callback?.invoke(true) |
| 206 | } |
| 207 | |
| 208 | override fun onMessageSendFailure(viaTransactionId: String, reason: Int) { |
| 209 | Log.status(TAG, "Message send failed tx=$viaTransactionId reason=$reason") |
| 210 | pendingSends.remove(viaTransactionId)?.callback?.invoke(false) |
| 211 | } |
| 212 | } |
| 213 | return state to message |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * Bring up the transport for the active subscription. Runs provisioning |
| 218 | * first; only creates the delegate when provisioned. Never throws. |
| 219 | */ |
| 220 | fun ensureRegistered(context: Context) { |
| 221 | if (!RcsFeature.enabled) { |
| 222 | _state.value = RcsRegistrationState.Disabled |
| 223 | return |
| 224 | } |
| 225 | scope.launch { |
| 226 | val app = context.applicationContext |
| 227 | val subId = activeSubId(app) |
| 228 | if (!SubscriptionManager.isValidSubscriptionId(subId)) { |
| 229 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NoSubscription) |
| 230 | return@launch |
| 231 | } |
| 232 | if (subId == activeSubId && connection != null) return@launch |
| 233 | if (subId != activeSubId) tearDown(app) |
| 234 | activeSubId = subId |
| 235 | // Start the live provisioning watch before creating the delegate: |
| 236 | // config changes (FT server URI, re-provisioning) arrive via |
| 237 | // callback instead of waiting for the next probe. |
| 238 | RcsProvisioningWatcher.watch(app, subId) |
| 239 | when (val probe = RcsProvisioning.probe(app, subId)) { |
| 240 | is RcsRegistrationState.Available -> createDelegate(app, subId) |
| 241 | is RcsRegistrationState.Unavailable -> { |
| 242 | // Carrier says no to single-reg but the device supports |
| 243 | // it: fall back to the direct SIP stack over the IMS PDN |
| 244 | // (P-CSCF + ISIM AKA, no delegate). Any other Unavailable |
| 245 | // reason stands. |
| 246 | if (probe.reason == RcsUnavailableReason.NotSupported && |
| 247 | RcsProvisioning.deviceSupportsSingleReg(app) |
| 248 | ) { |
| 249 | startDirectSip(app, subId) |
| 250 | } else { |
| 251 | _state.value = probe |
| 252 | } |
| 253 | } |
| 254 | else -> Unit |
| 255 | } |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | fun tearDown(context: Context? = null) { |
| 260 | directSipUp = false |
| 261 | RcsDirectSip.onInboundMessage = null |
| 262 | RcsDirectSip.stop() |
| 263 | val c = connection |
| 264 | if (c != null && context != null && RcsFeature.enabled) { |
| 265 | runCatching { |
| 266 | // Requires the same privileged permission; failure just orphans the |
| 267 | // delegate, which the framework reaps. |
| 268 | val manager = RcsHiddenApi.sipDelegateManager(context, activeSubId) |
| 269 | manager?.destroySipDelegate(c, SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP) |
| 270 | } |
| 271 | } |
| 272 | RcsProvisioningWatcher.unwatch() |
| 273 | RcsMsrpListen.stop() |
| 274 | RcsImsNetwork.reset() |
| 275 | connection = null |
| 276 | configVersion = -1L |
| 277 | activeSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID |
| 278 | } |
| 279 | |
| 280 | /** |
| 281 | * Test seam: when set, [canSend] is true and [sendSipMessage] routes to |
| 282 | * this sender instead of a live delegate/direct-SIP leg. Lets JVM tests |
| 283 | * drive the session/focus/typing layers that sit above the transport |
| 284 | * without an IMS PDN. Production code never sets it. |
| 285 | */ |
| 286 | @Volatile |
| 287 | var fakeSenderForTest: ((startLine: String, headers: String, body: ByteArray) -> Boolean)? = null |
| 288 | |
| 289 | /** True when a SIP MESSAGE can be sent right now (either leg). */ |
| 290 | fun canSend(): Boolean = |
| 291 | RcsFeature.enabled && ( |
| 292 | fakeSenderForTest != null || |
| 293 | (_state.value is RcsRegistrationState.Available && connection != null) || |
| 294 | directSipUp |
| 295 | ) |
| 296 | |
| 297 | /** True when the direct-SIP fallback leg is REGISTERed. */ |
| 298 | @Volatile |
| 299 | private var directSipUp: Boolean = false |
| 300 | |
| 301 | /** Which leg carries traffic: delegate (carrier single-reg) or direct SIP. */ |
| 302 | val activeLeg: String |
| 303 | get() = when { |
| 304 | !RcsFeature.enabled -> "none" |
| 305 | connection != null -> "single-reg delegate" |
| 306 | directSipUp -> "direct SIP (IMS PDN)" |
| 307 | else -> "none" |
| 308 | } |
| 309 | |
| 310 | /** |
| 311 | * Start the direct-SIP fallback leg (IMS PDN → P-CSCF → AKA REGISTER). |
| 312 | * On success the transport reports `Available` with no delegate |
| 313 | * connection; sends route to [RcsDirectSip]. On failure the probe's |
| 314 | * original `Unavailable` stands. |
| 315 | */ |
| 316 | private suspend fun startDirectSip(app: Context, subId: Int) { |
| 317 | _state.value = RcsRegistrationState.Provisioning |
| 318 | val ok = RcsDirectSip.start(app, subId) |
| 319 | if (ok) { |
| 320 | directSipUp = true |
| 321 | RcsDirectSip.onInboundMessage = { startLine, headers, body -> |
| 322 | // Reuse the delegate-path inbound pipeline: synthesize the |
| 323 | // SipMessage shape the sync service parses. |
| 324 | runCatching { |
| 325 | val msg = SipMessage(startLine, headers, body) |
| 326 | onInboundMessage?.invoke(msg) |
| 327 | } |
| 328 | } |
| 329 | _state.value = RcsRegistrationState.Available |
| 330 | Log.status(TAG, "Direct SIP leg up (fallback)") |
| 331 | } else { |
| 332 | directSipUp = false |
| 333 | Log.status(TAG, "Direct SIP leg failed; transport unavailable") |
| 334 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | /** |
| 339 | * Tell the framework to release delegate state for [callId] |
| 340 | * (`SipDelegateConnection#cleanupSession`). Best-effort: no connection |
| 341 | * or any failure is a silent no-op. |
| 342 | */ |
| 343 | fun cleanupSession(callId: String) { |
| 344 | val c = connection ?: return |
| 345 | if (!RcsFeature.enabled || callId.isBlank()) return |
| 346 | runCatching { c.cleanupSession(callId) } |
| 347 | } |
| 348 | |
| 349 | /** |
| 350 | * Send a SIP MESSAGE. Returns true on delegate ack, false otherwise |
| 351 | * (caller falls back to SMS). Never throws. |
| 352 | * |
| 353 | * The full request is stashed per branch so 401/407 challenges can be |
| 354 | * retried with digest auth ([onSipResponseMessage]). |
| 355 | */ |
| 356 | suspend fun sendSipMessage(startLine: String, headerSection: String, body: ByteArray): Boolean { |
| 357 | // Test seam (never set in production): record/accept the send. |
| 358 | fakeSenderForTest?.let { return it(startLine, headerSection, body) } |
| 359 | // Direct-SIP leg: route to the P-CSCF socket (no delegate). |
| 360 | if (directSipUp && RcsFeature.enabled) { |
| 361 | return RcsDirectSip.sendMessage(startLine, headerSection, body) |
| 362 | } |
| 363 | val c = connection |
| 364 | if (!canSend() || c == null) return false |
| 365 | val version = configVersion |
| 366 | if (version < 0) return false |
| 367 | return runCatching { |
| 368 | val message = SipMessage(startLine, headerSection, body) |
| 369 | suspendCancellableCoroutine { cont -> |
| 370 | val branch = message.getViaBranchParameter() |
| 371 | pendingSends[branch] = PendingSend( |
| 372 | callback = { ok -> if (cont.isActive) cont.resume(ok) }, |
| 373 | startLine = startLine, |
| 374 | headers = headerSection, |
| 375 | body = body, |
| 376 | ) |
| 377 | runCatching { c.sendMessage(message, version) }.onFailure { |
| 378 | pendingSends.remove(branch) |
| 379 | if (cont.isActive) cont.resume(false) |
| 380 | } |
| 381 | } |
| 382 | }.getOrDefault(false) |
| 383 | } |
| 384 | |
| 385 | /** |
| 386 | * Route an inbound SIP *response* (`SIP/2.0 xxx` start line). Returns |
| 387 | * true when the response was consumed (matched a pending transaction or |
| 388 | * a session dialog); false when the caller should treat it as an |
| 389 | * inbound MESSAGE. |
| 390 | * |
| 391 | * - 1xx → absorbed (retransmissions/100 Trying need no action). |
| 392 | * - 2xx to INVITE → session establishment + ACK (§1.1). |
| 393 | * - 401/407 → one digest-auth retry, then fail (§1.3). |
| 394 | * - 481/408/480/486/603 → dialog-mismatch recovery (§1.6). |
| 395 | * - 2xx to anything else → pending send succeeds. |
| 396 | * - anything else → pending send fails. |
| 397 | */ |
| 398 | suspend fun onSipResponseMessage(message: SipMessage): Boolean { |
| 399 | if (!RcsFeature.enabled) return false |
| 400 | val parsed = RcsSipResponse.parse(message) ?: return false |
| 401 | // 2xx to our INVITE: complete the dialog + ACK, even if the original |
| 402 | // branch aged out of pendingSends (responses can arrive late). |
| 403 | if (parsed.statusCode in SUCCESS_CODES && parsed.cseqMethod.equals("INVITE", ignoreCase = true)) { |
| 404 | pendingSends.remove(parsed.branch)?.callback?.invoke(true) |
| 405 | forwardToSessionManager(parsed) |
| 406 | return true |
| 407 | } |
| 408 | val pending = pendingSends[parsed.branch] |
| 409 | if (pending == null) { |
| 410 | return handleStrayResponse(parsed) |
| 411 | } |
| 412 | handlePendingResponse(parsed, pending) |
| 413 | return true |
| 414 | } |
| 415 | |
| 416 | /** Route a parsed response to the session manager. */ |
| 417 | private suspend fun forwardToSessionManager(parsed: RcsSipResponse.Parsed) { |
| 418 | RcsSessionManager.onSipResponse( |
| 419 | statusCode = parsed.statusCode, |
| 420 | callId = parsed.callId, |
| 421 | remoteTag = parsed.toTag, |
| 422 | sdpAnswer = parsed.body, |
| 423 | responseHeaders = parsed.headers, |
| 424 | ) |
| 425 | } |
| 426 | |
| 427 | /** Stray response (late duplicate, CANCEL race): route dialog finals by Call-ID. */ |
| 428 | private suspend fun handleStrayResponse(parsed: RcsSipResponse.Parsed): Boolean { |
| 429 | if (parsed.statusCode >= FAILURE_CODES) { |
| 430 | forwardToSessionManager(parsed) |
| 431 | return true |
| 432 | } |
| 433 | return false |
| 434 | } |
| 435 | |
| 436 | /** Route a response with a pending transaction. */ |
| 437 | private suspend fun handlePendingResponse(parsed: RcsSipResponse.Parsed, pending: PendingSend) { |
| 438 | when { |
| 439 | parsed.statusCode in PROVISIONAL_CODES -> Unit // absorbed; ack comes later |
| 440 | parsed.statusCode in SUCCESS_CODES -> { |
| 441 | pendingSends.remove(parsed.branch)?.callback?.invoke(true) |
| 442 | } |
| 443 | parsed.statusCode == UNAUTHORIZED || parsed.statusCode == PROXY_AUTH_REQUIRED -> { |
| 444 | if (!retryWithDigestAuth(parsed, pending)) { |
| 445 | pendingSends.remove(parsed.branch)?.callback?.invoke(false) |
| 446 | } |
| 447 | // On retry the callback stays parked under the NEW branch. |
| 448 | } |
| 449 | parsed.statusCode == CALL_LEG_GONE || parsed.statusCode == REQUEST_TIMEOUT || |
| 450 | parsed.statusCode == TEMP_UNAVAILABLE || parsed.statusCode == BUSY_HERE || |
| 451 | parsed.statusCode == DECLINE -> { |
| 452 | pendingSends.remove(parsed.branch)?.callback?.invoke(false) |
| 453 | RcsSessionManager.onDialogError(parsed.callId, parsed.statusCode) |
| 454 | } |
| 455 | else -> { |
| 456 | pendingSends.remove(parsed.branch)?.callback?.invoke(false) |
| 457 | if (parsed.statusCode >= FAILURE_CODES) { |
| 458 | forwardToSessionManager(parsed) |
| 459 | } |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | /** |
| 465 | * Rebuild a challenged request with digest `Authorization` / |
| 466 | * `Proxy-Authorization` and resend under a fresh branch (RFC 3261 |
| 467 | * §22.2: same Call-ID/CSeq/From-tag, new Via branch). One retry per |
| 468 | * transaction max. Returns true when a retry was issued. |
| 469 | */ |
| 470 | private suspend fun retryWithDigestAuth( |
| 471 | parsed: RcsSipResponse.Parsed, |
| 472 | pending: PendingSend, |
| 473 | ): Boolean { |
| 474 | if (pending.authAttempts >= 1) return false |
| 475 | val request = digestAuthRequest(parsed, pending) ?: return false |
| 476 | // Re-park the callback BEFORE sending (the ack may arrive inline). |
| 477 | val oldBranch = parsed.branch |
| 478 | pendingSends.remove(oldBranch) |
| 479 | val c = connection ?: run { |
| 480 | pending.callback(false) |
| 481 | return false |
| 482 | } |
| 483 | val version = configVersion |
| 484 | if (version < 0) { |
| 485 | pending.callback(false) |
| 486 | return false |
| 487 | } |
| 488 | var issued = false |
| 489 | runCatching { |
| 490 | val message = SipMessage(pending.startLine, request.rebuilt, pending.body) |
| 491 | // SipMessage computes its own branch from the header section; |
| 492 | // our rebuilt headers carry newBranch, so key on it. |
| 493 | pendingSends[request.newBranch] = pending.copy( |
| 494 | headers = request.rebuilt, |
| 495 | authAttempts = pending.authAttempts + 1, |
| 496 | ) |
| 497 | runCatching { c.sendMessage(message, version) }.onFailure { |
| 498 | pendingSends.remove(request.newBranch) |
| 499 | pending.callback(false) |
| 500 | } |
| 501 | issued = true |
| 502 | }.onFailure { |
| 503 | pendingSends.remove(request.newBranch) |
| 504 | pending.callback(false) |
| 505 | } |
| 506 | Log.status(TAG, "Digest auth retry issued for ${parsed.statusCode} (proxy=${request.proxy})") |
| 507 | return issued |
| 508 | } |
| 509 | |
| 510 | private data class DigestAuthRequest( |
| 511 | val rebuilt: String, |
| 512 | val newBranch: String, |
| 513 | val proxy: Boolean, |
| 514 | ) |
| 515 | |
| 516 | /** Build the authed re-send headers for a 401/407 challenge, or null when unbuildable. */ |
| 517 | private fun digestAuthRequest(parsed: RcsSipResponse.Parsed, pending: PendingSend): DigestAuthRequest? { |
| 518 | val proxy = parsed.statusCode == 407 |
| 519 | val challengeHeader = if (proxy) "Proxy-Authenticate:" else "WWW-Authenticate:" |
| 520 | val challenge = RcsSipDialog.headerValue(parsed.headers, challengeHeader) ?: return null |
| 521 | val gba = RcsGbaAuth.injected |
| 522 | val username = gba?.btId |
| 523 | ?: lastConfigSnapshot()?.publicUserId?.substringAfter("sip:")?.substringBefore("@") |
| 524 | ?.takeIf { it.isNotBlank() } ?: return null |
| 525 | val password = gba?.let { |
| 526 | android.util.Base64.encodeToString(it.key, android.util.Base64.NO_WRAP) |
| 527 | }.orEmpty() |
| 528 | val method = pending.startLine.substringBefore(" ").trim().ifBlank { return null } |
| 529 | val uri = pending.startLine.substringAfter(" ").substringBefore(" SIP/").trim() |
| 530 | .ifBlank { return null } |
| 531 | val cnonce = UUID.randomUUID().toString().replace("-", "").take(16) |
| 532 | val authValue = RcsGbaAuth.digestAuthorizationHeader( |
| 533 | challenge = challenge, |
| 534 | method = method, |
| 535 | uri = uri, |
| 536 | username = username, |
| 537 | password = password, |
| 538 | cnonce = cnonce, |
| 539 | ).ifBlank { return null } |
| 540 | // Same request, fresh branch, auth header appended (replaces any |
| 541 | // stale Authorization/Proxy-Authorization from a previous attempt). |
| 542 | val newBranch = RcsSipDialog.newBranch() |
| 543 | val baseHeaders = pending.headers.lineSequence() |
| 544 | .filter { line -> |
| 545 | val t = line.trim() |
| 546 | !(t.startsWith("Via:", ignoreCase = true) || |
| 547 | t.startsWith("Authorization:", ignoreCase = true) || |
| 548 | t.startsWith("Proxy-Authorization:", ignoreCase = true)) |
| 549 | }.joinToString("\r\n") |
| 550 | val viaHost = pending.headers.lineSequence() |
| 551 | .firstOrNull { it.trim().startsWith("Via:", ignoreCase = true) } |
| 552 | ?.substringAfter("SIP/2.0/TCP")?.substringBefore(";")?.trim() |
| 553 | ?.takeIf { it.isNotEmpty() } ?: "local" |
| 554 | val rebuilt = buildString { |
| 555 | append(baseHeaders) |
| 556 | if (baseHeaders.isNotEmpty()) append("\r\n") |
| 557 | append("Via: SIP/2.0/TCP $viaHost;branch=$newBranch\r\n") |
| 558 | append(if (proxy) "Proxy-Authorization: $authValue\r\n" else "Authorization: $authValue\r\n") |
| 559 | } |
| 560 | return DigestAuthRequest(rebuilt, newBranch, proxy) |
| 561 | } |
| 562 | |
| 563 | /** |
| 564 | * Build a pager-mode SIP MESSAGE start line + headers for a 1:1 CPM chat |
| 565 | * message. The branch parameter doubles as the send ack key. |
| 566 | * |
| 567 | * The body is a `message/cpim` envelope (TestRcsApp CpimUtils) carrying |
| 568 | * IMDN metadata; the From identity comes from the delegate configuration |
| 569 | * (public user identifier) when known, else the [fromUri] fallback. |
| 570 | */ |
| 571 | fun buildChatMessage( |
| 572 | fromUri: String, |
| 573 | toUri: String, |
| 574 | callId: String = "${UUID.randomUUID()}@rcs", |
| 575 | body: String, |
| 576 | ): Triple<String, String, ByteArray> { |
| 577 | val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}" |
| 578 | val from = lastConfig?.getPublicUserIdentifier()?.takeIf { it.isNotBlank() } ?: fromUri |
| 579 | val cpim = buildCpimBody(body) |
| 580 | val bytes = cpim.toByteArray(Charsets.UTF_8) |
| 581 | val startLine = "MESSAGE $toUri SIP/2.0" |
| 582 | val headers = buildString { |
| 583 | append("Via: SIP/2.0/TCP $from;branch=$branch\r\n") |
| 584 | append("From: <$from>;tag=${UUID.randomUUID().toString().take(8)}\r\n") |
| 585 | append("To: <$toUri>\r\n") |
| 586 | append("Call-ID: $callId\r\n") |
| 587 | append("CSeq: 1 MESSAGE\r\n") |
| 588 | append("Content-Type: message/cpim\r\n") |
| 589 | append("Content-Length: ${bytes.size}\r\n") |
| 590 | } |
| 591 | return Triple(startLine, headers, bytes) |
| 592 | } |
| 593 | |
| 594 | /** |
| 595 | * Minimal `message/cpim` envelope for a text message (TestRcsApp |
| 596 | * CpimUtils.createForText): IMDN namespace + delivery/display disposition, |
| 597 | * anonymous From/To (routing uses the SIP headers), ISO-instant DateTime. |
| 598 | */ |
| 599 | fun buildCpimBody(text: String): String = buildString { |
| 600 | append("NS: imdn <urn:ietf:params:imdn>\r\n") |
| 601 | append("imdn.Message-ID: rcs-${UUID.randomUUID()}\r\n") |
| 602 | append("imdn.Disposition-Notification: positive-delivery, display\r\n") |
| 603 | append("To: <sip:[email protected]>\r\n") |
| 604 | append("From: <sip:[email protected]>\r\n") |
| 605 | append("DateTime: ${java.time.Instant.now()}\r\n") |
| 606 | append("Content-Type: text/plain;charset=UTF-8\r\n") |
| 607 | append("Content-Length: ${text.toByteArray(Charsets.UTF_8).size}\r\n") |
| 608 | append("\r\n") |
| 609 | append(text) |
| 610 | } |
| 611 | |
| 612 | private fun createDelegate(context: Context, subId: Int) { |
| 613 | try { |
| 614 | val manager = RcsHiddenApi.sipDelegateManager(context, subId) |
| 615 | ?: run { |
| 616 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable) |
| 617 | return |
| 618 | } |
| 619 | val supported: Boolean = runCatching { manager.isSupported() }.getOrElse { |
| 620 | _state.value = mapSetupFailure(it) |
| 621 | return |
| 622 | } |
| 623 | if (!supported) { |
| 624 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported) |
| 625 | return |
| 626 | } |
| 627 | manager.createSipDelegate( |
| 628 | DelegateRequest(CPM_FEATURE_TAGS), |
| 629 | executor, |
| 630 | stateCallback as DelegateConnectionStateCallback, |
| 631 | messageCallback as DelegateConnectionMessageCallback, |
| 632 | ) |
| 633 | } catch (e: SecurityException) { |
| 634 | Log.status(TAG, "No carrier privilege for single registration", e) |
| 635 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NoCarrierPrivilege) |
| 636 | } catch (e: ImsException) { |
| 637 | Log.status(TAG, "IMS service unavailable", e) |
| 638 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable) |
| 639 | } catch (e: IllegalArgumentException) { |
| 640 | Log.status(TAG, "Invalid subscription", e) |
| 641 | _state.value = RcsRegistrationState.Unavailable(RcsUnavailableReason.NoSubscription) |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | private fun mapSetupFailure(t: Throwable): RcsRegistrationState.Unavailable = |
| 646 | when (t) { |
| 647 | is SecurityException -> RcsRegistrationState.Unavailable(RcsUnavailableReason.NoCarrierPrivilege) |
| 648 | is ImsException -> RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable) |
| 649 | else -> RcsRegistrationState.Unavailable(RcsUnavailableReason.Unknown) |
| 650 | } |
| 651 | |
| 652 | private fun activeSubId(context: Context): Int { |
| 653 | if (!RcsProvisioning.hasPhoneStatePermission(context)) { |
| 654 | // TestRcsApp keys everything off the default SMS subscription. |
| 655 | return SubscriptionManager.getDefaultSmsSubscriptionId() |
| 656 | } |
| 657 | // Active subscription ids, inlined from the host's SimManager (which |
| 658 | // stays with the SIM line): only the ids are needed here, and the |
| 659 | // READ_PHONE_STATE gate above already matches SimManager's. |
| 660 | if (androidx.core.content.ContextCompat.checkSelfPermission( |
| 661 | context, android.Manifest.permission.READ_PHONE_STATE, |
| 662 | ) != android.content.pm.PackageManager.PERMISSION_GRANTED |
| 663 | ) { |
| 664 | return SubscriptionManager.INVALID_SUBSCRIPTION_ID |
| 665 | } |
| 666 | val subIds = runCatching { |
| 667 | context.getSystemService(SubscriptionManager::class.java) |
| 668 | ?.activeSubscriptionInfoList?.map { it.subscriptionId }.orEmpty() |
| 669 | }.getOrDefault(emptyList()) |
| 670 | if (subIds.isEmpty()) return SubscriptionManager.INVALID_SUBSCRIPTION_ID |
| 671 | val current = activeSubId |
| 672 | return subIds.firstOrNull { it == current } |
| 673 | ?: subIds.firstOrNull() |
| 674 | ?: SubscriptionManager.INVALID_SUBSCRIPTION_ID |
| 675 | } |
| 676 | } |