Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsMsrp.kt
RcsMsrp.kt667 lines · 26.9 KiBRaw
| 1 | package com.vayunmathur.communicate.data.rcs |
| 2 | |
| 3 | import android.content.Context |
| 4 | import com.vayunmathur.library.log.Log |
| 5 | import java.util.UUID |
| 6 | import kotlinx.coroutines.CoroutineScope |
| 7 | import kotlinx.coroutines.Dispatchers |
| 8 | import kotlinx.coroutines.SupervisorJob |
| 9 | import kotlinx.coroutines.cancel |
| 10 | import kotlinx.coroutines.launch |
| 11 | import kotlinx.coroutines.withContext |
| 12 | |
| 13 | /** |
| 14 | * Minimal MSRP (RFC 4975) over the negotiated session socket. |
| 15 | * |
| 16 | * TestRcsApp's `MsrpManager`/`MsrpSession` ride a raw TCP socket to the |
| 17 | * negotiated `a=path`; chunks are `MSRP <txid> SEND` with To-Path/From-Path, |
| 18 | * Byte-Range, Message-ID and Content-Type headers. This port covers the |
| 19 | * SEND + 200-response subset needed for CPM chat payloads (CPIM text and |
| 20 | * IMDN reports travel inside sessions once established; pager-mode remains |
| 21 | * the pre-session path). |
| 22 | * |
| 23 | * ACTIVE-only: we always connect out, never listen (same as TestRcsApp — |
| 24 | * `MsrpManager` has no accept loop). Sockets open on Dispatchers.IO; every |
| 25 | * failure returns null/false so callers fall back to pager-mode. No Guava — |
| 26 | * plain suspend functions. |
| 27 | */ |
| 28 | object RcsMsrp { |
| 29 | private const val TAG = "RcsMsrp" |
| 30 | private const val ACK_TIMEOUT_MS = 10_000L |
| 31 | private const val KEEPALIVE_MS = 30_000L |
| 32 | private const val IDLE_TIMEOUT_MS = 60_000L |
| 33 | private const val FRAME_GUARD = 32 |
| 34 | private const val RESPONSE_GUARD = 16 |
| 35 | private const val STATUS_OK = 200 |
| 36 | private const val STATUS_NOT_IMPLEMENTED = 501 |
| 37 | private const val MAX_BODY_BYTES = 8 * 1024 * 1024 |
| 38 | private const val SOCKET_TIMEOUT_MS = 10_000 |
| 39 | private val SUCCESS_CODES = STATUS_OK..299 |
| 40 | |
| 41 | /** |
| 42 | * Process-wide fallback for inbound MSRP chunks arriving on transient |
| 43 | * connections (e.g. FT-over-MSRP transfer sockets). The sync service sets |
| 44 | * this to route into the inbox; unset (null) drops. |
| 45 | */ |
| 46 | @Volatile |
| 47 | var onInboundFallback: ((conversationId: String, contentType: String, body: ByteArray) -> Unit)? = null |
| 48 | |
| 49 | /** |
| 50 | * A persistent MSRP connection for one session: one socket, reused across |
| 51 | * SENDs, with a reader loop feeding inbound chunks to [onChunk]. |
| 52 | * Create via [connect]; [close] on BYE / teardown. |
| 53 | */ |
| 54 | class MsrpConnection internal constructor( |
| 55 | private val socket: java.net.Socket, |
| 56 | private val localPath: String, |
| 57 | private val remotePath: String, |
| 58 | ) { |
| 59 | @Volatile private var closed = false |
| 60 | private val readerScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) |
| 61 | |
| 62 | internal fun launchReader(block: suspend () -> Unit) { |
| 63 | readerScope.launch { block() } |
| 64 | } |
| 65 | |
| 66 | /** Last I/O time (any direction); drives the keepalive (§2.5). */ |
| 67 | @Volatile internal var lastActivityMs: Long = System.currentTimeMillis() |
| 68 | |
| 69 | /** |
| 70 | * Send one CPIM payload as chunked MSRP SENDs (§2.2): splits large |
| 71 | * payloads into `Byte-Range` slices sharing one Message-ID, awaiting |
| 72 | * a 2xx response per chunk. Returns true when every chunk was acked. |
| 73 | * Thread-safe (single-writer lock). Acks are completed by the reader |
| 74 | * loop ([pendingAcks]) — never read here, the stream is single-reader. |
| 75 | */ |
| 76 | private val writeLock = Any() |
| 77 | |
| 78 | suspend fun sendCpim(payload: ByteArray, contentType: String = "message/cpim"): Boolean { |
| 79 | if (closed || payload.isEmpty()) return false |
| 80 | return runCatching { |
| 81 | val chunks = RcsMsrpFraming.splitSend( |
| 82 | toPath = remotePath, |
| 83 | fromPath = localPath, |
| 84 | payload = payload, |
| 85 | contentType = contentType, |
| 86 | ) |
| 87 | for (chunk in chunks) { |
| 88 | val ack = kotlinx.coroutines.CompletableDeferred<Boolean>() |
| 89 | synchronized(writeLock) { |
| 90 | if (closed) return false |
| 91 | pendingAcks[chunk.txid] = ack |
| 92 | runCatching { |
| 93 | val out = socket.getOutputStream() |
| 94 | out.write(RcsMsrpFraming.serializeChunk(chunk)) |
| 95 | out.flush() |
| 96 | lastActivityMs = System.currentTimeMillis() |
| 97 | }.onFailure { |
| 98 | pendingAcks.remove(chunk.txid) |
| 99 | throw it |
| 100 | } |
| 101 | } |
| 102 | val ok = try { |
| 103 | kotlinx.coroutines.withTimeout(ACK_TIMEOUT_MS) { ack.await() } |
| 104 | } catch (_: kotlinx.coroutines.TimeoutCancellationException) { |
| 105 | false |
| 106 | } |
| 107 | pendingAcks.remove(chunk.txid) |
| 108 | if (!ok) return false |
| 109 | } |
| 110 | true |
| 111 | }.getOrElse { |
| 112 | Log.status(TAG, "MSRP chunk send failed", it) |
| 113 | false |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /** |
| 118 | * Chunk ack futures, keyed by SEND txid. Completed by the reader loop |
| 119 | * when the matching response arrives; senders await with timeout. |
| 120 | */ |
| 121 | internal val pendingAcks = |
| 122 | java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.CompletableDeferred<Boolean>>() |
| 123 | |
| 124 | /** Inbound REPORT notifications: (messageId, ns, code, reason). */ |
| 125 | internal val inboundReports = |
| 126 | java.util.concurrent.ConcurrentLinkedQueue<ReportNotice>() |
| 127 | |
| 128 | internal data class ReportNotice( |
| 129 | val messageId: String, |
| 130 | val namespace: Int, |
| 131 | val code: Int, |
| 132 | val reason: String, |
| 133 | ) |
| 134 | |
| 135 | /** Send a keepalive empty SEND (§2.5). Best-effort. */ |
| 136 | internal fun sendKeepalive(): Boolean { |
| 137 | if (closed) return false |
| 138 | return runCatching { |
| 139 | synchronized(writeLock) { |
| 140 | val out = socket.getOutputStream() |
| 141 | out.write(RcsMsrpFraming.buildKeepalive(remotePath, localPath)) |
| 142 | out.flush() |
| 143 | lastActivityMs = System.currentTimeMillis() |
| 144 | } |
| 145 | true |
| 146 | }.getOrDefault(false) |
| 147 | } |
| 148 | |
| 149 | /** Emit a REPORT for [messageId] (§2.1). Best-effort. */ |
| 150 | internal fun sendReport( |
| 151 | messageId: String, |
| 152 | statusCode: Int, |
| 153 | reason: String, |
| 154 | byteRange: String, |
| 155 | ): Boolean { |
| 156 | if (closed) return false |
| 157 | return runCatching { |
| 158 | synchronized(writeLock) { |
| 159 | val out = socket.getOutputStream() |
| 160 | out.write( |
| 161 | RcsMsrpFraming.buildReport( |
| 162 | toPath = remotePath, |
| 163 | fromPath = localPath, |
| 164 | messageId = messageId, |
| 165 | statusCode = statusCode, |
| 166 | reason = reason, |
| 167 | byteRange = byteRange, |
| 168 | ), |
| 169 | ) |
| 170 | out.flush() |
| 171 | lastActivityMs = System.currentTimeMillis() |
| 172 | } |
| 173 | true |
| 174 | }.getOrDefault(false) |
| 175 | } |
| 176 | |
| 177 | /** Start the idle keepalive job (§2.5): empty SEND when quiet >60s. */ |
| 178 | internal fun launchKeepalive() { |
| 179 | readerScope.launch { |
| 180 | while (!closed) { |
| 181 | kotlinx.coroutines.delay(KEEPALIVE_MS) |
| 182 | if (closed) break |
| 183 | if (System.currentTimeMillis() - lastActivityMs >= IDLE_TIMEOUT_MS) { |
| 184 | sendKeepalive() |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | fun close() { |
| 191 | closed = true |
| 192 | runCatching { socket.close() } |
| 193 | readerScope.cancel() |
| 194 | } |
| 195 | |
| 196 | fun isClosed(): Boolean = closed || socket.isClosed |
| 197 | } |
| 198 | |
| 199 | /** |
| 200 | * Wrap an accepted (passive-side) socket as a session connection: the |
| 201 | * listener already consumed the first SEND head ([head]) for To-Path |
| 202 | * routing, so the reader replays it before the live stream. [localPath] |
| 203 | * is our advertised path (matches the peer's To-Path); [remotePath] is |
| 204 | * the peer's From-Path, used for our SENDs back on this same socket |
| 205 | * (RFC 4975 §5.4 — the passive side reuses the accepted connection). |
| 206 | * [socket] may already be a TLS `SSLSocket` (secure sessions) — the |
| 207 | * reader only needs the byte stream. |
| 208 | */ |
| 209 | fun wrapAccepted( |
| 210 | socket: java.net.Socket, |
| 211 | head: RcsMsrpListen.AcceptedHead, |
| 212 | localPath: String, |
| 213 | remotePath: String, |
| 214 | onChunk: (contentType: String, body: ByteArray) -> Unit, |
| 215 | ): MsrpConnection { |
| 216 | val conn = MsrpConnection(socket, localPath, remotePath) |
| 217 | conn.launchReader { readLoop(conn, socket, onChunk, head.replayBytes()) } |
| 218 | conn.launchKeepalive() |
| 219 | return conn |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * Open a persistent active connection for [session] and start the reader |
| 224 | * loop on Dispatchers.IO. [onChunk] receives complete `message/cpim` |
| 225 | * bodies (content type + bytes). Returns null when the session has no |
| 226 | * usable remote path or when neither side can connect (peer is |
| 227 | * `setup=active` AND we have no listen socket — see [RcsMsrpListen]). |
| 228 | * |
| 229 | * The socket rides the IMS PDN when available ([RcsImsNetwork]) so |
| 230 | * carrier MSRP peers (which only route IMS-subnet addresses) are |
| 231 | * reachable; falls back to a plain socket otherwise. |
| 232 | */ |
| 233 | suspend fun connect( |
| 234 | session: RcsSession, |
| 235 | context: Context, |
| 236 | onChunk: (contentType: String, body: ByteArray) -> Unit, |
| 237 | ): MsrpConnection? = withContext(Dispatchers.IO) { |
| 238 | if (!RcsFeature.enabled) return@withContext null |
| 239 | val remotePath = session.msrpRemotePath ?: return@withContext null |
| 240 | if (session.msrpSetup == MsrpSetup.ACTIVE && !RcsMsrpListen.isListening()) { |
| 241 | // Peer connects to us, but we have no listen socket — nothing to do. |
| 242 | // (When listening, the accept loop owns this direction; connect-out |
| 243 | // is skipped and the session completes on accept.) |
| 244 | Log.status(TAG, "Peer is active and no listen socket; cannot establish media") |
| 245 | return@withContext null |
| 246 | } |
| 247 | if (session.msrpSetup == MsrpSetup.ACTIVE) { |
| 248 | // Listen-side session: media arrives on the accepted socket. |
| 249 | return@withContext null |
| 250 | } |
| 251 | val localPath = session.msrpLocalPath ?: "msrp://local.invalid/${UUID.randomUUID()};tcp" |
| 252 | runCatching { |
| 253 | val (host, port) = parseMsrpPath(remotePath) ?: return@runCatching null |
| 254 | val socket = if (session.msrpSecure) { |
| 255 | // TLS client: pin the peer against the fingerprint from its |
| 256 | // SDP answer (stashed at response time — see session lookup). |
| 257 | // Falls back to plaintext connect when no fingerprint is |
| 258 | // known (downgrade, never a hard failure here). |
| 259 | val peerFp = peerFingerprintFor(session) |
| 260 | if (peerFp != null) { |
| 261 | RcsMsrpTls.clientSocket(context, host, port, peerFp) |
| 262 | ?: return@runCatching null |
| 263 | } else { |
| 264 | Log.status(TAG, "Secure session without peer fingerprint; downgrading to plaintext") |
| 265 | RcsImsNetwork.createSocket(context, host, port) ?: return@runCatching null |
| 266 | } |
| 267 | } else { |
| 268 | RcsImsNetwork.createSocket(context, host, port) ?: return@runCatching null |
| 269 | } |
| 270 | val conn = MsrpConnection(socket, localPath, remotePath) |
| 271 | // Reader loop: parse SEND chunks, auto-200 them, deliver bodies. |
| 272 | // Owned by the connection; dies on close. |
| 273 | conn.launchReader { readLoop(conn, socket, onChunk) } |
| 274 | conn.launchKeepalive() |
| 275 | conn |
| 276 | }.getOrElse { |
| 277 | Log.status(TAG, "MSRP connect failed", it) |
| 278 | null |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | /** |
| 283 | * Peer's TLS fingerprint for an outgoing secure session, from the SDP |
| 284 | * answer stashed at response time. Null when unknown (caller downgrades). |
| 285 | */ |
| 286 | private fun peerFingerprintFor(session: RcsSession): String? = |
| 287 | RcsSessionManager.peerFingerprint(session.callId) |
| 288 | |
| 289 | private fun readLoop( |
| 290 | conn: MsrpConnection, |
| 291 | socket: java.net.Socket, |
| 292 | onChunk: (String, ByteArray) -> Unit, |
| 293 | replayPrefix: ByteArray? = null, |
| 294 | ) { |
| 295 | val live = runCatching { socket.getInputStream() }.getOrNull() ?: return |
| 296 | // Accepted sockets already had their first SEND head consumed for |
| 297 | // To-Path routing — replay it ahead of the live stream. |
| 298 | val stream = if (replayPrefix != null && replayPrefix.isNotEmpty()) { |
| 299 | java.io.SequenceInputStream(java.io.ByteArrayInputStream(replayPrefix), live) |
| 300 | } else { |
| 301 | live |
| 302 | } |
| 303 | val input = stream.bufferedReader(Charsets.UTF_8) |
| 304 | val pending = StringBuilder() |
| 305 | // Reassembly buffer for multi-chunk SENDs, keyed by Message-ID. |
| 306 | val reassembly = mutableMapOf<String, ByteArrayOutputStream2>() |
| 307 | try { |
| 308 | while (!conn.isClosed()) { |
| 309 | val line = runCatching { input.readLine() }.getOrNull() ?: break |
| 310 | if (line.startsWith("MSRP ")) { |
| 311 | readFrame(conn, socket, input, pending, reassembly, line, onChunk) |
| 312 | } |
| 313 | } |
| 314 | } catch (_: Throwable) { |
| 315 | // Socket closed — reader exits. |
| 316 | } finally { |
| 317 | reassembly.clear() |
| 318 | conn.close() |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /** Read one MSRP frame (start line already consumed) and dispatch it. */ |
| 323 | private fun readFrame( |
| 324 | conn: MsrpConnection, |
| 325 | socket: java.net.Socket, |
| 326 | input: java.io.BufferedReader, |
| 327 | pending: StringBuilder, |
| 328 | reassembly: MutableMap<String, ByteArrayOutputStream2>, |
| 329 | line: String, |
| 330 | onChunk: (String, ByteArray) -> Unit, |
| 331 | ) { |
| 332 | pending.clear() |
| 333 | pending.append(line).append("\r\n") |
| 334 | val headers = readHeaders(input, pending) |
| 335 | val contentLength = headers["content-length"]?.toIntOrNull() ?: -1 |
| 336 | val txid = line.split(" ").getOrNull(1).orEmpty() |
| 337 | val method = line.split(" ").getOrNull(2).orEmpty() |
| 338 | if (method.equals("SEND", ignoreCase = true)) { |
| 339 | handleSendFrame(conn, socket, input, reassembly, headers, contentLength, txid, onChunk) |
| 340 | } else if (method.equals("REPORT", ignoreCase = true)) { |
| 341 | handleReportFrame(conn, input, headers, txid) |
| 342 | } else if (method.equals("AUTH", ignoreCase = true)) { |
| 343 | handleAuthFrame(socket, input, headers, txid) |
| 344 | } else { |
| 345 | handleResponseFrame(conn, input, line, txid) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | /** Read a header block into a lowercase-keyed map. */ |
| 350 | private fun readHeaders( |
| 351 | input: java.io.BufferedReader, |
| 352 | pending: StringBuilder, |
| 353 | ): Map<String, String> { |
| 354 | val headers = mutableMapOf<String, String>() |
| 355 | while (true) { |
| 356 | val h = runCatching { input.readLine() }.getOrNull() |
| 357 | if (h == null || h.isEmpty()) break |
| 358 | pending.append(h).append("\r\n") |
| 359 | val name = h.substringBefore(":").trim() |
| 360 | val value = h.substringAfter(":").trim() |
| 361 | headers[name.lowercase()] = value |
| 362 | } |
| 363 | return headers |
| 364 | } |
| 365 | |
| 366 | /** Consume lines through the frame end-marker (bounded). */ |
| 367 | private fun consumeToEndMarker(input: java.io.BufferedReader, txid: String) { |
| 368 | var guard = 0 |
| 369 | var done = false |
| 370 | while (guard++ < FRAME_GUARD && !done) { |
| 371 | val l = runCatching { input.readLine() }.getOrNull() ?: break |
| 372 | done = l.startsWith("-------$txid") |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | /** Inbound SEND: body, keepalive, reassembly, auto-200. */ |
| 377 | private fun handleSendFrame( |
| 378 | conn: MsrpConnection, |
| 379 | socket: java.net.Socket, |
| 380 | input: java.io.BufferedReader, |
| 381 | reassembly: MutableMap<String, ByteArrayOutputStream2>, |
| 382 | headers: Map<String, String>, |
| 383 | contentLength: Int, |
| 384 | txid: String, |
| 385 | onChunk: (String, ByteArray) -> Unit, |
| 386 | ) { |
| 387 | // Body: Content-Length bytes when present, else to end-marker. |
| 388 | val bodyBytes = if (contentLength >= 0) { |
| 389 | readFixed(input, contentLength) |
| 390 | } else { |
| 391 | readToEndMarker(input, txid) |
| 392 | } |
| 393 | // Consume the end-marker line — but only on the Content-Length path, |
| 394 | // where it is still queued. readToEndMarker already consumed it, so |
| 395 | // consuming again there would eat the next frame's start line and |
| 396 | // park delivery until another frame arrives. |
| 397 | if (contentLength >= 0) runCatching { input.readLine() } |
| 398 | conn.lastActivityMs = System.currentTimeMillis() |
| 399 | // Keepalive empty SEND (§2.5): ack quietly, no delivery. |
| 400 | val range = headers["byte-range"] |
| 401 | if (range == RcsMsrpFraming.KEEPALIVE_RANGE) { |
| 402 | sendResponse(socket, txid, STATUS_OK, "OK", headers["from-path"].orEmpty()) |
| 403 | return |
| 404 | } |
| 405 | // Auto-200 the peer SEND (RFC 4975 §7.1: To-Path echoes |
| 406 | // the sender's From-Path, From-Path is our path). |
| 407 | val peerFrom = headers["from-path"].orEmpty() |
| 408 | sendResponse(socket, txid, STATUS_OK, "OK", peerFrom) |
| 409 | val msgId = headers["message-id"].orEmpty() |
| 410 | val contentType = headers["content-type"] ?: "message/cpim" |
| 411 | if (msgId.isNotEmpty() && bodyBytes != null) { |
| 412 | val buf = reassembly.getOrPut(msgId) { ByteArrayOutputStream2() } |
| 413 | buf.write(bodyBytes) |
| 414 | // Single-chunk fast path: Byte-Range 1-N/N delivers now. |
| 415 | if (range == null || isCompleteRange(range)) { |
| 416 | reassembly.remove(msgId) |
| 417 | val complete = buf.toBytes() |
| 418 | if (complete.isNotEmpty()) onChunk(contentType, complete) |
| 419 | } |
| 420 | } else if (bodyBytes != null && bodyBytes.isNotEmpty()) { |
| 421 | onChunk(contentType, bodyBytes) |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | /** Inbound REPORT (§2.1): queue the notice, no auto-response. */ |
| 426 | private fun handleReportFrame( |
| 427 | conn: MsrpConnection, |
| 428 | input: java.io.BufferedReader, |
| 429 | headers: Map<String, String>, |
| 430 | txid: String, |
| 431 | ) { |
| 432 | consumeToEndMarker(input, txid) |
| 433 | conn.lastActivityMs = System.currentTimeMillis() |
| 434 | val msgId = headers["message-id"].orEmpty() |
| 435 | val status = headers["status"]?.let { RcsMsrpFraming.parseStatus(it) } |
| 436 | if (msgId.isNotEmpty() && status != null) { |
| 437 | conn.inboundReports.add( |
| 438 | MsrpConnection.ReportNotice( |
| 439 | messageId = msgId, |
| 440 | namespace = status.first, |
| 441 | code = status.second, |
| 442 | reason = status.third, |
| 443 | ), |
| 444 | ) |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | /** MSRP auth is not negotiated on this line (§2.3): explicit 501, never silent. */ |
| 449 | private fun handleAuthFrame( |
| 450 | socket: java.net.Socket, |
| 451 | input: java.io.BufferedReader, |
| 452 | headers: Map<String, String>, |
| 453 | txid: String, |
| 454 | ) { |
| 455 | consumeToEndMarker(input, txid) |
| 456 | val peerFrom = headers["from-path"].orEmpty() |
| 457 | sendAuthNotImplemented(socket, txid, peerFrom) |
| 458 | } |
| 459 | |
| 460 | /** Responses to our SENDs: complete the chunk ack future (§2.2). */ |
| 461 | private fun handleResponseFrame( |
| 462 | conn: MsrpConnection, |
| 463 | input: java.io.BufferedReader, |
| 464 | line: String, |
| 465 | txid: String, |
| 466 | ) { |
| 467 | val parsed = RcsMsrpFraming.parseResponseStart(line) |
| 468 | consumeToEndMarker(input, txid) |
| 469 | conn.lastActivityMs = System.currentTimeMillis() |
| 470 | if (parsed != null) { |
| 471 | conn.pendingAcks.remove(parsed.first) |
| 472 | ?.complete(parsed.second in SUCCESS_CODES) |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | private fun isCompleteRange(range: String): Boolean { |
| 477 | // "1-N/N" with equal total and end, or "1-0/0" empty handshake. |
| 478 | val m = Regex("(\\d+)-(\\d+)/(\\d+)").find(range.trim()) ?: return true |
| 479 | val (_, end, total) = m.destructured |
| 480 | return end == total |
| 481 | } |
| 482 | |
| 483 | private fun readFixed(input: java.io.BufferedReader, n: Int): ByteArray? { |
| 484 | if (n < 0 || n > MAX_BODY_BYTES) return null |
| 485 | return runCatching { |
| 486 | val chars = CharArray(n) |
| 487 | var read = 0 |
| 488 | while (read < n) { |
| 489 | val r = input.read(chars, read, n - read) |
| 490 | if (r < 0) break |
| 491 | read += r |
| 492 | } |
| 493 | String(chars, 0, read).toByteArray(Charsets.UTF_8) |
| 494 | }.getOrNull() |
| 495 | } |
| 496 | |
| 497 | private fun readToEndMarker(input: java.io.BufferedReader, txid: String): ByteArray? { |
| 498 | return runCatching { |
| 499 | val sb = StringBuilder() |
| 500 | while (true) { |
| 501 | val line = input.readLine() |
| 502 | if (line == null || line.startsWith("-------$txid")) break |
| 503 | sb.append(line).append("\r\n") |
| 504 | } |
| 505 | // The CRLF immediately before the end-marker is framing, not |
| 506 | // body: drop exactly one so delivered bytes match what was sent. |
| 507 | if (sb.endsWith("\r\n")) sb.setLength(sb.length - 2) |
| 508 | sb.toString().toByteArray(Charsets.UTF_8) |
| 509 | }.getOrNull() |
| 510 | } |
| 511 | |
| 512 | private fun sendResponse( |
| 513 | socket: java.net.Socket, |
| 514 | txid: String, |
| 515 | code: Int, |
| 516 | reason: String, |
| 517 | toPath: String = "", |
| 518 | ) { |
| 519 | runCatching { |
| 520 | val out = socket.getOutputStream() |
| 521 | out.write("MSRP $txid $code $reason\r\n".toByteArray(Charsets.UTF_8)) |
| 522 | if (toPath.isNotBlank()) out.write("To-Path: $toPath\r\n".toByteArray(Charsets.UTF_8)) |
| 523 | out.write("\r\n".toByteArray(Charsets.UTF_8)) |
| 524 | out.write("-------$txid\$\r\n".toByteArray(Charsets.UTF_8)) |
| 525 | out.flush() |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | /** 501 to an MSRP AUTH attempt (§2.3: auth is never negotiated here). */ |
| 530 | private fun sendAuthNotImplemented(socket: java.net.Socket, txid: String, toPath: String) { |
| 531 | runCatching { |
| 532 | val out = socket.getOutputStream() |
| 533 | out.write(RcsMsrpFraming.buildErrorResponse(toPath, txid, STATUS_NOT_IMPLEMENTED, "Not Implemented")) |
| 534 | out.flush() |
| 535 | } |
| 536 | Log.status(TAG, "Rejected MSRP AUTH with 501 (tx=$txid)") |
| 537 | } |
| 538 | |
| 539 | /** Minimal byte buffer (avoids java.io.ByteArrayOutputStream import weight). */ |
| 540 | private class ByteArrayOutputStream2 { |
| 541 | private var buf = ByteArray(1024) |
| 542 | private var size = 0 |
| 543 | |
| 544 | fun write(bytes: ByteArray) { |
| 545 | ensure(bytes.size) |
| 546 | bytes.copyInto(buf, size) |
| 547 | size += bytes.size |
| 548 | } |
| 549 | |
| 550 | fun toBytes(): ByteArray = buf.copyOf(size) |
| 551 | |
| 552 | private fun ensure(extra: Int) { |
| 553 | if (size + extra <= buf.size) return |
| 554 | var next = buf.size * 2 |
| 555 | while (next < size + extra) next *= 2 |
| 556 | buf = buf.copyOf(next) |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | /** |
| 561 | * Send [payload] (CPIM bytes) over an MSRP session bound to [session]. |
| 562 | * Opens a socket to the remote path when needed (IMS PDN preferred, TLS |
| 563 | * when [RcsSession.msrpSecure]), chunked per §2.2. Returns true when |
| 564 | * every chunk got a 2xx. |
| 565 | * |
| 566 | * One-shot fallback; prefer [connect] for established sessions. |
| 567 | */ |
| 568 | suspend fun send( |
| 569 | session: RcsSession, |
| 570 | context: Context, |
| 571 | payload: ByteArray, |
| 572 | contentType: String = "message/cpim", |
| 573 | ): Boolean = withContext(Dispatchers.IO) { |
| 574 | if (!RcsFeature.enabled) return@withContext false |
| 575 | val remotePath = session.msrpRemotePath ?: return@withContext false |
| 576 | val localPath = session.msrpLocalPath ?: "msrp://local.invalid/${UUID.randomUUID()};tcp" |
| 577 | runCatching { |
| 578 | val (host, port) = parseMsrpPath(remotePath) ?: return@runCatching false |
| 579 | val chunks = RcsMsrpFraming.splitSend( |
| 580 | toPath = remotePath, |
| 581 | fromPath = localPath, |
| 582 | payload = payload, |
| 583 | contentType = contentType, |
| 584 | ) |
| 585 | if (chunks.isEmpty()) return@runCatching false |
| 586 | val socket = if (session.msrpSecure) { |
| 587 | val peerFp = peerFingerprintFor(session) ?: return@runCatching false |
| 588 | RcsMsrpTls.clientSocket(context, host, port, peerFp) |
| 589 | ?: return@runCatching false |
| 590 | } else { |
| 591 | RcsImsNetwork.createSocket(context, host, port) |
| 592 | ?: return@runCatching false |
| 593 | } |
| 594 | socket.use { s -> |
| 595 | s.soTimeout = SOCKET_TIMEOUT_MS |
| 596 | val out = s.getOutputStream() |
| 597 | val input = s.getInputStream().bufferedReader(Charsets.UTF_8) |
| 598 | for (chunk in chunks) { |
| 599 | out.write(RcsMsrpFraming.serializeChunk(chunk)) |
| 600 | out.flush() |
| 601 | // Await this chunk's response (responses are FIFO). |
| 602 | if (!awaitChunkAck(input, chunk)) return@runCatching false |
| 603 | } |
| 604 | true |
| 605 | } |
| 606 | }.getOrElse { |
| 607 | Log.status(TAG, "MSRP send failed", it) |
| 608 | false |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | /** Await one chunk's 2xx response (responses are FIFO). */ |
| 613 | private fun awaitChunkAck( |
| 614 | input: java.io.BufferedReader, |
| 615 | chunk: RcsMsrpFraming.OutChunk, |
| 616 | ): Boolean { |
| 617 | var guard = 0 |
| 618 | while (guard++ < RESPONSE_GUARD) { |
| 619 | val line = runCatching { input.readLine() }.getOrNull() ?: break |
| 620 | val parsed = RcsMsrpFraming.parseResponseStart(line) |
| 621 | if (parsed != null && parsed.first == chunk.txid) { |
| 622 | consumeToEndMarker(input, chunk.txid) |
| 623 | if (parsed.second in SUCCESS_CODES) return true |
| 624 | } |
| 625 | } |
| 626 | return false |
| 627 | } |
| 628 | |
| 629 | /** |
| 630 | * Parse an `msrp(s)://host[:port]/...` path into (host, port). Default |
| 631 | * MSRP port 2855 when absent. Scheme-agnostic (covers `msrps://`); use |
| 632 | * [isSecurePath] for the TLS decision. |
| 633 | * |
| 634 | * Manual parse — no `android.net.Uri`, whose unit-test android.jar stub |
| 635 | * throws ("not mocked") on the JVM. |
| 636 | */ |
| 637 | fun parseMsrpPath(path: String): Pair<String, Int>? { |
| 638 | val afterScheme = path.substringAfter("://", "").ifEmpty { return null } |
| 639 | // Authority ends at the first '/' or ';' (';'-params belong to the session part). |
| 640 | val authority = afterScheme.substringBefore("/").substringBefore(";").substringAfterLast("@") |
| 641 | if (authority.isBlank()) return null |
| 642 | val (host, rawPort) = if (authority.startsWith("[")) { |
| 643 | // Bracketed IPv6 literal: [::1]:2855. |
| 644 | val end = authority.indexOf(']') |
| 645 | if (end < 0) return null |
| 646 | val h = authority.substring(1, end) |
| 647 | if (h.isBlank()) return null |
| 648 | h to authority.substring(end + 1).removePrefix(":") |
| 649 | } else { |
| 650 | val h = authority.substringBefore(":") |
| 651 | if (h.isBlank()) return null |
| 652 | h to authority.substringAfter(":", "") |
| 653 | } |
| 654 | val port = rawPort.toIntOrNull()?.takeIf { it > 0 } ?: 2855 |
| 655 | return host to port |
| 656 | } |
| 657 | |
| 658 | /** |
| 659 | * True when [path] uses the `msrps://` scheme (TLS media, RFC 4976). |
| 660 | * Manual scheme check — see [parseMsrpPath] for why `android.net.Uri` |
| 661 | * is not used here. |
| 662 | */ |
| 663 | fun isSecurePath(path: String?): Boolean { |
| 664 | if (path.isNullOrBlank()) return false |
| 665 | return path.trim().substringBefore(":").trim().equals("msrps", ignoreCase = true) |
| 666 | } |
| 667 | } |