Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsDirectSip.kt
RcsDirectSip.kt572 lines · 24.5 KiBRaw
| 1 | package com.vayunmathur.communicate.data.rcs |
| 2 | |
| 3 | import android.annotation.SuppressLint |
| 4 | import android.content.Context |
| 5 | import android.net.ConnectivityManager |
| 6 | import android.net.LinkProperties |
| 7 | import android.net.Network |
| 8 | import android.os.Build |
| 9 | import android.telephony.SubscriptionManager |
| 10 | import android.telephony.TelephonyManager |
| 11 | import com.vayunmathur.library.log.Log |
| 12 | import java.net.Inet6Address |
| 13 | import java.net.InetSocketAddress |
| 14 | import java.util.UUID |
| 15 | import java.util.concurrent.ConcurrentHashMap |
| 16 | import kotlin.coroutines.resume |
| 17 | import kotlinx.coroutines.CoroutineScope |
| 18 | import kotlinx.coroutines.Dispatchers |
| 19 | import kotlinx.coroutines.SupervisorJob |
| 20 | import kotlinx.coroutines.cancelChildren |
| 21 | import kotlinx.coroutines.launch |
| 22 | import kotlinx.coroutines.suspendCancellableCoroutine |
| 23 | import kotlinx.coroutines.withTimeoutOrNull |
| 24 | |
| 25 | /** |
| 26 | * Direct SIP stack over the IMS PDN (fallback when the carrier's |
| 27 | * single-registration verdict is negative). |
| 28 | * |
| 29 | * Why this exists: `SipDelegateManager` requires the framework's |
| 30 | * `isRcsVolteSingleRegistrationCapable()` to return true. Some carriers |
| 31 | * (verified: US Mobile eSIM, subId=1) report false while still running a |
| 32 | * fully working IMS PDN (P-CSCF reachable, feature tags allowed). This stack |
| 33 | * speaks SIP directly to the P-CSCF over a TCP socket bound to the IMS |
| 34 | * network — no delegate, no carrier privilege, no hidden APIs: |
| 35 | * |
| 36 | * - Transport: `RcsImsNetwork`-style IMS `Network` request → TCP to the |
| 37 | * P-CSCF taken from the IMS link properties (`getPcscfAddresses`). |
| 38 | * - Auth: IMS-AKA via public `TelephonyManager.getIccAuthentication` |
| 39 | * (`APPTYPE_ISIM` + `AUTHTYPE_EAP_AKA`), feeding the 401's nonce into a |
| 40 | * Digest `Authorization` built by [RcsGbaAuth]. |
| 41 | * - Dialogs: REGISTER (+ 200 OK + Expires refresh at half-life), MESSAGE |
| 42 | * (pager-mode CPIM, reusing [RcsSipTransport.buildChatMessage]), inbound |
| 43 | * MESSAGE routed to the same sync-service handler. |
| 44 | * |
| 45 | * State is exposed through the same [RcsRegistrationState] vocabulary so the |
| 46 | * UI needs no changes: `Available` means REGISTERed with 200 OK. |
| 47 | * Best-effort throughout; every failure maps to `Unavailable(reason)` and |
| 48 | * never throws. |
| 49 | */ |
| 50 | object RcsDirectSip { |
| 51 | private const val TAG = "RcsDirectSip" |
| 52 | |
| 53 | /** REGISTER lifetime requested (carrier clamps; we refresh at half). */ |
| 54 | private const val REGISTER_EXPIRES = 600 |
| 55 | |
| 56 | /** Socket/read timeout for the SIP TCP leg. */ |
| 57 | private const val SOCKET_TIMEOUT_MS = 15_000 |
| 58 | private const val SIP_OK = 200 |
| 59 | private const val SIP_UNAUTHORIZED = 401 |
| 60 | private const val SIP_PROXY_AUTH_REQUIRED = 407 |
| 61 | private val SIP_SUCCESS = 200..299 |
| 62 | private const val REFRESH_MIN_MS = 30_000L |
| 63 | private const val REFRESH_HALF_FACTOR = 500L |
| 64 | private const val HEAD_GUARD = 64 |
| 65 | private const val DEFAULT_SIP_PORT = 5060 |
| 66 | private const val MAX_FORWARDS = 70 |
| 67 | private const val TAG_TOKEN_LENGTH = 8 |
| 68 | |
| 69 | private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) |
| 70 | |
| 71 | @Volatile private var running = false |
| 72 | @Volatile private var socket: java.net.Socket? = null |
| 73 | @Volatile private var pcscf: InetSocketAddress? = null |
| 74 | @Volatile private var localContact: String = "" |
| 75 | @Volatile private var publicIdentity: String = "" |
| 76 | @Volatile private var callIdBase: String = "" |
| 77 | @Volatile private var cseq: Long = 1L |
| 78 | @Volatile private var registeredExpires = 0 |
| 79 | |
| 80 | /** Inbound SIP MESSAGE listener (same contract as the delegate path). */ |
| 81 | @Volatile |
| 82 | var onInboundMessage: ((startLine: String, headers: String, body: ByteArray) -> Unit)? = null |
| 83 | |
| 84 | /** Pending MESSAGE transactions keyed by Via branch. */ |
| 85 | private val pendingSends = ConcurrentHashMap<String, (Boolean) -> Unit>() |
| 86 | |
| 87 | /** |
| 88 | * Start the direct stack for [subId]: request the IMS network, connect |
| 89 | * TCP to the P-CSCF, REGISTER with AKA. Suspends until the first 200 OK |
| 90 | * (or failure). Idempotent while running. |
| 91 | */ |
| 92 | // Own subscriber number as the SIP public identity (RFC 3261 REGISTER): |
| 93 | // this is the user's own line, not a device identifier, and RCS cannot |
| 94 | // register without it. |
| 95 | @SuppressLint("HardwareIds") |
| 96 | suspend fun start(context: Context, subId: Int): Boolean { |
| 97 | if (!RcsFeature.enabled) return false |
| 98 | if (running) return true |
| 99 | val conn = prepareConnection(context, subId) ?: return false |
| 100 | // Public identity: derive from the line-1 number when readable, else |
| 101 | // the IMSI-derived placeholder the P-CSCF will challenge anyway. |
| 102 | // The 401 + AKA exchange establishes the real identity. |
| 103 | publicIdentity = try { |
| 104 | conn.tm.line1Number?.takeIf { it.isNotBlank() } |
| 105 | } catch (_: SecurityException) { |
| 106 | null |
| 107 | } catch (_: Exception) { |
| 108 | null |
| 109 | } ?: "" |
| 110 | callIdBase = "${UUID.randomUUID()}@rcs-direct" |
| 111 | running = true |
| 112 | val ok = runCatching { |
| 113 | connectAndRegister(conn.app, conn.tm, conn.pcscfAddr) |
| 114 | }.getOrElse { |
| 115 | Log.status(TAG, "Direct SIP start failed", it) |
| 116 | false |
| 117 | } |
| 118 | if (!ok) stop() |
| 119 | return ok |
| 120 | } |
| 121 | |
| 122 | private data class DirectConnection( |
| 123 | val app: Context, |
| 124 | val tm: TelephonyManager, |
| 125 | val subId: Int, |
| 126 | val pcscfAddr: InetSocketAddress, |
| 127 | ) |
| 128 | |
| 129 | /** Resolve network/P-CSCF/telephone pieces, or null when any is unavailable. */ |
| 130 | private suspend fun prepareConnection(context: Context, subId: Int): DirectConnection? { |
| 131 | if (!SubscriptionManager.isValidSubscriptionId(subId)) return null |
| 132 | val app = context.applicationContext |
| 133 | val network = RcsImsNetwork.imsNetwork(app, subId) ?: run { |
| 134 | Log.status(TAG, "No IMS network for direct SIP") |
| 135 | return null |
| 136 | } |
| 137 | val pcscfAddr = pcscfAddress(app, network) ?: run { |
| 138 | Log.status(TAG, "No P-CSCF address on IMS network") |
| 139 | return null |
| 140 | } |
| 141 | val tm = app.getSystemService(TelephonyManager::class.java)?.let { base -> |
| 142 | runCatching { base.createForSubscriptionId(subId) }.getOrNull() ?: base |
| 143 | } ?: return null |
| 144 | return DirectConnection(app, tm, subId, pcscfAddr) |
| 145 | } |
| 146 | |
| 147 | /** Stop: deregister (best-effort), close the socket, drop state. */ |
| 148 | fun stop() { |
| 149 | running = false |
| 150 | runCatching { |
| 151 | socket?.let { s -> |
| 152 | runCatching { |
| 153 | val out = s.getOutputStream() |
| 154 | val bye = buildRegister(publicIdentity, localContact, pcscf, 0) |
| 155 | out.write(bye) |
| 156 | out.flush() |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | runCatching { socket?.close() } |
| 161 | socket = null |
| 162 | pcscf = null |
| 163 | pendingSends.values.forEach { runCatching { it(false) } } |
| 164 | pendingSends.clear() |
| 165 | // Cancel children only, never the scope itself: cancelling the |
| 166 | // process-wide scope would leave every later start() without a |
| 167 | // reader loop (transact writes, then waits out its full timeout), |
| 168 | // making the stack un-restartable after any teardown. |
| 169 | scope.coroutineContext.cancelChildren() |
| 170 | } |
| 171 | |
| 172 | /** True when REGISTERed with a live socket. */ |
| 173 | fun isRegistered(): Boolean = |
| 174 | RcsFeature.enabled && running && socket?.isConnected == true && registeredExpires > 0 |
| 175 | |
| 176 | /** |
| 177 | * Send a pager-mode MESSAGE over the direct leg. Returns true on 200 OK. |
| 178 | * Same framing as the delegate path ([RcsSipTransport.buildChatMessage] |
| 179 | * output is re-targeted at the P-CSCF with our dialog headers). |
| 180 | */ |
| 181 | suspend fun sendMessage(startLine: String, headers: String, body: ByteArray): Boolean { |
| 182 | if (!isRegistered()) return false |
| 183 | val s = socket ?: return false |
| 184 | return runCatching { |
| 185 | suspendCancellableCoroutine { cont -> |
| 186 | // Retarget: Request-URI stays the peer URI; Route the P-CSCF; |
| 187 | // From our public identity; fresh branch per transaction. |
| 188 | val branch = RcsSipDialog.newBranch() |
| 189 | val target = pendingTarget(startLine, headers) |
| 190 | val rebuilt = rebuildMessageHeaders(headers, branch) |
| 191 | val requestLine = "MESSAGE ${target.first} SIP/2.0" |
| 192 | val wire = "$requestLine\r\n$rebuilt\r\n".toByteArray(Charsets.UTF_8) + body |
| 193 | pendingSends[branch] = { ok -> if (cont.isActive) cont.resume(ok) } |
| 194 | runCatching { |
| 195 | synchronized(s) { |
| 196 | val out = s.getOutputStream() |
| 197 | out.write(wire) |
| 198 | out.flush() |
| 199 | } |
| 200 | }.onFailure { |
| 201 | pendingSends.remove(branch) |
| 202 | if (cont.isActive) cont.resume(false) |
| 203 | } |
| 204 | } |
| 205 | }.getOrDefault(false) |
| 206 | } |
| 207 | |
| 208 | // -- internals -- |
| 209 | |
| 210 | private suspend fun connectAndRegister( |
| 211 | app: Context, |
| 212 | tm: TelephonyManager, |
| 213 | pcscfAddr: InetSocketAddress, |
| 214 | ): Boolean { |
| 215 | val s = RcsImsNetwork.createSocket(app, pcscfAddr.hostString, pcscfAddr.port, SOCKET_TIMEOUT_MS) |
| 216 | ?: return false |
| 217 | socket = s |
| 218 | pcscf = pcscfAddr |
| 219 | s.soTimeout = SOCKET_TIMEOUT_MS |
| 220 | // Reader loop for responses + inbound MESSAGEs. |
| 221 | scope.launch { readLoop(s) } |
| 222 | // Unauthenticated REGISTER → 401 with nonce → AKA → REGISTER w/auth. |
| 223 | val first = buildRegister(publicIdentity, localContact, pcscfAddr, REGISTER_EXPIRES) |
| 224 | val challenge = transact(first, "REGISTER") ?: run { |
| 225 | Log.status(TAG, "No response to initial REGISTER") |
| 226 | return false |
| 227 | } |
| 228 | if (challenge.statusCode == SIP_OK) { |
| 229 | onRegistered(challenge) |
| 230 | return true |
| 231 | } |
| 232 | if (challenge.statusCode != SIP_UNAUTHORIZED && challenge.statusCode != SIP_PROXY_AUTH_REQUIRED) { |
| 233 | Log.status(TAG, "REGISTER rejected: ${challenge.statusCode} ${challenge.reason}") |
| 234 | return false |
| 235 | } |
| 236 | return finishRegistration(tm, challenge) |
| 237 | } |
| 238 | |
| 239 | /** AKA handshake + authed REGISTER after a 401/407 challenge. */ |
| 240 | private suspend fun finishRegistration(tm: TelephonyManager, challenge: SipResponse): Boolean { |
| 241 | val authed = buildAuthedRegister(tm, challenge) ?: return false |
| 242 | val final = transact(authed, "REGISTER") ?: run { |
| 243 | Log.status(TAG, "No response to authed REGISTER") |
| 244 | return false |
| 245 | } |
| 246 | if (final.statusCode != SIP_OK) { |
| 247 | Log.status(TAG, "Authed REGISTER rejected: ${final.statusCode} ${final.reason}") |
| 248 | return false |
| 249 | } |
| 250 | onRegistered(final) |
| 251 | return true |
| 252 | } |
| 253 | |
| 254 | private fun onRegistered(resp: SipResponse) { |
| 255 | registeredExpires = resp.expires ?: REGISTER_EXPIRES |
| 256 | // Our Contact (for inbound routing correlation + re-REGISTER). |
| 257 | resp.contact?.let { localContact = it } |
| 258 | Log.status(TAG, "Direct SIP REGISTERed (expires=$registeredExpires)") |
| 259 | // Refresh at half-life. |
| 260 | scope.launch { |
| 261 | while (running) { |
| 262 | kotlinx.coroutines.delay((registeredExpires * REFRESH_HALF_FACTOR).coerceAtLeast(REFRESH_MIN_MS)) |
| 263 | if (!running) break |
| 264 | runCatching { refreshRegister() } |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | private suspend fun refreshRegister(): Boolean { |
| 270 | val s = socket ?: return false |
| 271 | val req = buildRegister(publicIdentity, localContact, pcscf, REGISTER_EXPIRES) |
| 272 | val resp = transact(req, "REGISTER") ?: return false |
| 273 | if (resp.statusCode == SIP_UNAUTHORIZED || resp.statusCode == SIP_PROXY_AUTH_REQUIRED) { |
| 274 | // Re-auth on refresh challenge (nonce rotation); needs TM — the |
| 275 | // sync-service path re-runs start() instead. Report failure. |
| 276 | Log.status(TAG, "Refresh challenged; full re-register required") |
| 277 | return false |
| 278 | } |
| 279 | if (resp.statusCode == SIP_OK) { |
| 280 | registeredExpires = resp.expires ?: REGISTER_EXPIRES |
| 281 | return true |
| 282 | } |
| 283 | return false |
| 284 | } |
| 285 | |
| 286 | /** One request → first response (matched loosely: any response). */ |
| 287 | private suspend fun transact(wire: ByteArray, method: String): SipResponse? = |
| 288 | withTimeoutOrNull(SOCKET_TIMEOUT_MS.toLong()) { |
| 289 | suspendCancellableCoroutine { cont -> |
| 290 | val s = socket ?: run { |
| 291 | if (cont.isActive) cont.resume(null) |
| 292 | return@suspendCancellableCoroutine |
| 293 | } |
| 294 | // Tag the continuation for the reader loop to complete. |
| 295 | pendingTransactions[method + "@" + System.identityHashCode(wire)] = |
| 296 | { resp: SipResponse -> if (cont.isActive) cont.resume(resp) } |
| 297 | runCatching { |
| 298 | synchronized(s) { |
| 299 | val out = s.getOutputStream() |
| 300 | out.write(wire) |
| 301 | out.flush() |
| 302 | } |
| 303 | }.onFailure { |
| 304 | if (cont.isActive) cont.resume(null) |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | private val pendingTransactions = ConcurrentHashMap<String, (SipResponse) -> Unit>() |
| 310 | |
| 311 | private fun buildRegister( |
| 312 | identity: String, |
| 313 | contact: String, |
| 314 | via: InetSocketAddress?, |
| 315 | expires: Int, |
| 316 | ): ByteArray { |
| 317 | val from = identity.ifBlank { "sip:[email protected]" } |
| 318 | val branch = RcsSipDialog.newBranch() |
| 319 | val callId = callIdBase |
| 320 | val seq = cseq++ |
| 321 | val contactHdr = contact.ifBlank { "<sip:rcs-direct@${via?.hostString ?: "localhost"}>" } |
| 322 | return buildString { |
| 323 | append("REGISTER sip:${via?.hostString ?: "localhost"} SIP/2.0\r\n") |
| 324 | append("Via: SIP/2.0/TCP ${via?.hostString ?: "localhost"};branch=$branch\r\n") |
| 325 | append("Max-Forwards: $MAX_FORWARDS\r\n") |
| 326 | append("From: <$from>;tag=${UUID.randomUUID().toString().take(TAG_TOKEN_LENGTH)}\r\n") |
| 327 | append("To: <$from>\r\n") |
| 328 | append("Call-ID: $callId\r\n") |
| 329 | append("CSeq: $seq REGISTER\r\n") |
| 330 | append("Contact: $contactHdr;expires=$expires\r\n") |
| 331 | append("Expires: $expires\r\n") |
| 332 | append("Content-Length: 0\r\n") |
| 333 | append("\r\n") |
| 334 | }.toByteArray(Charsets.UTF_8) |
| 335 | } |
| 336 | |
| 337 | private fun buildAuthedRegister( |
| 338 | tm: TelephonyManager, |
| 339 | challenge: SipResponse, |
| 340 | ): ByteArray? { |
| 341 | val wwwAuth = challenge.headers.lines() |
| 342 | .firstOrNull { it.trim().startsWith("WWW-Authenticate:", ignoreCase = true) } |
| 343 | ?.substringAfter(":")?.trim() ?: return null |
| 344 | // IMS-AKA: nonce → ISIM challenge → RES/CK/IK → Digest response. |
| 345 | // getIccAuthentication(APPTYPE_ISIM, AUTHTYPE_EAP_AKA, nonceB64). |
| 346 | val nonce = Regex("nonce=\"([^\"]+)\"").find(wwwAuth) |
| 347 | ?.groupValues?.getOrNull(1)?.trim() ?: return null |
| 348 | val akaRes = runCatching { |
| 349 | tm.getIccAuthentication( |
| 350 | TelephonyManager.APPTYPE_ISIM, |
| 351 | TelephonyManager.AUTHTYPE_EAP_AKA, |
| 352 | nonce, |
| 353 | ) |
| 354 | }.getOrNull()?.takeIf { it.isNotBlank() } ?: run { |
| 355 | Log.status(TAG, "ISIM AKA challenge failed (no ISIM app?)") |
| 356 | return null |
| 357 | } |
| 358 | // akaRes is base64 RES||CK||IK per 3GPP TS 31.102; the Digest |
| 359 | // password for AKA is RES-based — reuse the shared digest builder |
| 360 | // with the AKA response as the password material. |
| 361 | val username = publicIdentity.substringAfter("sip:").substringBefore("@") |
| 362 | .takeIf { it.isNotBlank() } ?: "anonymous" |
| 363 | val uri = "sip:${pcscf?.hostString ?: "localhost"}" |
| 364 | val authValue = RcsGbaAuth.digestAuthorizationHeader( |
| 365 | challenge = wwwAuth, |
| 366 | method = "REGISTER", |
| 367 | uri = uri, |
| 368 | username = username, |
| 369 | password = akaRes, |
| 370 | ).ifBlank { return null } |
| 371 | val branch = RcsSipDialog.newBranch() |
| 372 | val from = publicIdentity.ifBlank { "sip:[email protected]" } |
| 373 | val seq = cseq++ |
| 374 | return buildString { |
| 375 | append("REGISTER sip:${pcscf?.hostString ?: "localhost"} SIP/2.0\r\n") |
| 376 | append("Via: SIP/2.0/TCP ${pcscf?.hostString ?: "localhost"};branch=$branch\r\n") |
| 377 | append("Max-Forwards: $MAX_FORWARDS\r\n") |
| 378 | append("From: <$from>;tag=${UUID.randomUUID().toString().take(TAG_TOKEN_LENGTH)}\r\n") |
| 379 | append("To: <$from>\r\n") |
| 380 | append("Call-ID: $callIdBase\r\n") |
| 381 | append("CSeq: $seq REGISTER\r\n") |
| 382 | append("Contact: ${localContact.ifBlank { "<sip:rcs-direct@localhost>" }};expires=$REGISTER_EXPIRES\r\n") |
| 383 | append("Expires: $REGISTER_EXPIRES\r\n") |
| 384 | append("Authorization: $authValue\r\n") |
| 385 | append("Content-Length: 0\r\n") |
| 386 | append("\r\n") |
| 387 | }.toByteArray(Charsets.UTF_8) |
| 388 | } |
| 389 | |
| 390 | /** Minimal SIP response model for the state machine. */ |
| 391 | private data class SipResponse( |
| 392 | val statusCode: Int, |
| 393 | val reason: String, |
| 394 | val callId: String, |
| 395 | val cseqMethod: String, |
| 396 | val branch: String, |
| 397 | val headers: String, |
| 398 | val expires: Int?, |
| 399 | val contact: String?, |
| 400 | ) |
| 401 | |
| 402 | private fun parseResponse(head: String): SipResponse? { |
| 403 | return runCatching { |
| 404 | val lines = head.lines() |
| 405 | val start = lines.firstOrNull()?.trim() ?: return null |
| 406 | if (!start.startsWith("SIP/2.0")) return null |
| 407 | val code = start.substringAfter("SIP/2.0").trim().substringBefore(" ") |
| 408 | .trim().toIntOrNull() ?: return null |
| 409 | val reason = start.substringAfter("SIP/2.0").trim().substringAfter(" ").trim() |
| 410 | fun header(name: String): String? = lines |
| 411 | .firstOrNull { it.trim().startsWith(name, ignoreCase = true) } |
| 412 | ?.substringAfter(":")?.trim() |
| 413 | val via = header("Via:").orEmpty() |
| 414 | val branch = via.substringAfter("branch=").substringBefore(";").trim() |
| 415 | val callId = header("Call-ID:").orEmpty() |
| 416 | val cseqLine = header("CSeq:").orEmpty() |
| 417 | SipResponse( |
| 418 | statusCode = code, |
| 419 | reason = reason, |
| 420 | callId = callId, |
| 421 | cseqMethod = cseqLine.substringAfter(" ").trim(), |
| 422 | branch = branch, |
| 423 | headers = head, |
| 424 | expires = header("Expires:")?.toIntOrNull() |
| 425 | ?: Regex("expires=(\\d+)", RegexOption.IGNORE_CASE) |
| 426 | .find(header("Contact:").orEmpty())?.groupValues |
| 427 | ?.getOrNull(1)?.toIntOrNull(), |
| 428 | contact = header("Contact:") |
| 429 | ?.substringAfter("<")?.substringBefore(">") |
| 430 | ?.takeIf { it.isNotBlank() }, |
| 431 | ) |
| 432 | }.getOrNull() |
| 433 | } |
| 434 | |
| 435 | private fun readLoop(s: java.net.Socket) { |
| 436 | val input = runCatching { s.getInputStream().bufferedReader(Charsets.UTF_8) }.getOrNull() |
| 437 | ?: return |
| 438 | try { |
| 439 | while (running && !s.isClosed) { |
| 440 | val headLines = readHeadLines(input) ?: break |
| 441 | if (headLines.isNotEmpty()) { |
| 442 | handleHeadLines(headLines, input) |
| 443 | } |
| 444 | } |
| 445 | } catch (_: Throwable) { |
| 446 | // Socket closed — loop exits. |
| 447 | } finally { |
| 448 | if (running) { |
| 449 | Log.status(TAG, "Direct SIP read loop ended unexpectedly") |
| 450 | running = false |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | /** Read one SIP head block; null on EOF, empty list on blank keepalive. */ |
| 456 | private fun readHeadLines(input: java.io.BufferedReader): MutableList<String>? { |
| 457 | val headLines = mutableListOf<String>() |
| 458 | var line = runCatching { input.readLine() }.getOrNull() ?: return null |
| 459 | // Skip stray blank lines (keepalive CRLF). |
| 460 | if (line.isBlank()) return headLines |
| 461 | var guard = 0 |
| 462 | while (line.isNotEmpty() && guard++ < HEAD_GUARD) { |
| 463 | headLines.add(line) |
| 464 | line = runCatching { input.readLine() }.getOrNull() ?: break |
| 465 | } |
| 466 | return headLines |
| 467 | } |
| 468 | |
| 469 | /** Route one parsed head block + body. */ |
| 470 | private fun handleHeadLines(headLines: MutableList<String>, input: java.io.BufferedReader) { |
| 471 | val first = headLines.first() |
| 472 | // Read body per Content-Length. |
| 473 | val contentLength = headLines |
| 474 | .firstOrNull { it.trim().startsWith("Content-Length:", ignoreCase = true) } |
| 475 | ?.substringAfter(":")?.trim()?.toIntOrNull() ?: 0 |
| 476 | val body = if (contentLength in 1..(4 shl 20)) { |
| 477 | readFixed(input, contentLength) |
| 478 | } else { |
| 479 | ByteArray(0) |
| 480 | } |
| 481 | if (first.startsWith("SIP/2.0")) { |
| 482 | val resp = parseResponse(headLines.joinToString("\r\n")) |
| 483 | if (resp != null) { |
| 484 | // Complete any parked transaction + pending MESSAGE acks. |
| 485 | val branch = resp.branch |
| 486 | if (branch.isNotBlank()) { |
| 487 | pendingSends.remove(branch)?.invoke(resp.statusCode in SIP_SUCCESS) |
| 488 | } |
| 489 | // Wake the oldest parked transact (FIFO fallback). |
| 490 | pendingTransactions.entries.firstOrNull()?.let { (k, cb) -> |
| 491 | pendingTransactions.remove(k) |
| 492 | cb(resp) |
| 493 | } |
| 494 | } |
| 495 | } else if (first.startsWith("MESSAGE ")) { |
| 496 | val headers = headLines.drop(1).joinToString("\r\n") |
| 497 | onInboundMessage?.invoke(first, headers, body) |
| 498 | } |
| 499 | // (NOTIFY/OPTIONS/BYE on the direct leg: absorbed for now; |
| 500 | // BYE handling can reuse RcsSessionManager when sessions exist.) |
| 501 | } |
| 502 | |
| 503 | private fun readFixed(input: java.io.BufferedReader, n: Int): ByteArray { |
| 504 | return runCatching { |
| 505 | val chars = CharArray(n) |
| 506 | var read = 0 |
| 507 | while (read < n) { |
| 508 | val r = input.read(chars, read, n - read) |
| 509 | if (r < 0) break |
| 510 | read += r |
| 511 | } |
| 512 | String(chars, 0, read).toByteArray(Charsets.UTF_8) |
| 513 | }.getOrDefault(ByteArray(0)) |
| 514 | } |
| 515 | |
| 516 | private fun pendingTarget(startLine: String, headers: String): Pair<String, String> { |
| 517 | val requestUri = startLine.substringAfter(" ").substringBefore(" SIP/").trim() |
| 518 | return requestUri to headers |
| 519 | } |
| 520 | |
| 521 | private fun rebuildMessageHeaders(headers: String, branch: String): String { |
| 522 | val from = publicIdentity.ifBlank { "sip:[email protected]" } |
| 523 | val filtered = headers.lineSequence().filter { line -> |
| 524 | val t = line.trim() |
| 525 | // Blank lines must go too: callers pass a header block ending in |
| 526 | // CRLF, and keeping its trailing empty line would end the head |
| 527 | // here, pushing the Via/From/Route below into the body. |
| 528 | !(t.isBlank() || |
| 529 | t.startsWith("Via:", ignoreCase = true) || |
| 530 | t.startsWith("From:", ignoreCase = true) || |
| 531 | t.startsWith("Route:", ignoreCase = true)) |
| 532 | }.joinToString("\r\n") |
| 533 | val pcscfHost = pcscf?.hostString ?: "localhost" |
| 534 | return buildString { |
| 535 | if (filtered.isNotEmpty()) { |
| 536 | append(filtered) |
| 537 | append("\r\n") |
| 538 | } |
| 539 | append("Via: SIP/2.0/TCP $pcscfHost;branch=$branch\r\n") |
| 540 | append("From: <$from>;tag=${UUID.randomUUID().toString().take(TAG_TOKEN_LENGTH)}\r\n") |
| 541 | append("Route: <sip:$pcscfHost;lr>\r\n") |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | private fun pcscfAddress(app: Context, network: Network): InetSocketAddress? { |
| 546 | return runCatching { |
| 547 | val cm = app.getSystemService(ConnectivityManager::class.java) ?: return null |
| 548 | val props: LinkProperties = cm.getLinkProperties(network) ?: return null |
| 549 | // `getPcscfServers()` is @SystemApi/hidden (absent from android.jar): |
| 550 | // reflect it, else parse the same addresses out of toString() |
| 551 | // (which renders `PcscfAddresses: [ /2001:db8::1, ... ]`). |
| 552 | val addrs: List<java.net.InetAddress> = |
| 553 | runCatching { |
| 554 | @Suppress("UNCHECKED_CAST") |
| 555 | props.javaClass.getMethod("getPcscfServers").invoke(props) as? List<java.net.InetAddress> |
| 556 | }.getOrNull() ?: parsePcscfFromString(props.toString()) |
| 557 | val addr = addrs.firstOrNull() ?: return null |
| 558 | // P-CSCF SIP default 5060. |
| 559 | InetSocketAddress(addr, DEFAULT_SIP_PORT) |
| 560 | }.getOrNull() |
| 561 | } |
| 562 | |
| 563 | private fun parsePcscfFromString(linkProps: String): List<java.net.InetAddress> { |
| 564 | val section = Regex("PcscfAddresses:\\s*\\[([^\\]]*)\\]", RegexOption.IGNORE_CASE) |
| 565 | .find(linkProps)?.groupValues?.getOrNull(1) ?: return emptyList() |
| 566 | return section.split(",").mapNotNull { token -> |
| 567 | val ip = token.trim().trimStart('/').trim() |
| 568 | if (ip.isEmpty()) return@mapNotNull null |
| 569 | runCatching { java.net.InetAddress.getByName(ip) }.getOrNull() |
| 570 | } |
| 571 | } |
| 572 | } |