Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsMsrpFraming.kt

RcsMsrpFraming.kt169 lines · 6.8 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import java.util.UUID
4
5/**
6 * Pure MSRP framing (RFC 4975): SEND chunk splitting, REPORT requests,
7 * response matching, AUTH stubs, keepalive shape.
8 *
9 * Extracted from `RcsMsrp` for unit-testability — no sockets, no coroutines,
10 * no Android. The socket object owns I/O; everything byte-shaping lives here.
11 */
12object RcsMsrpFraming {
13 private const val MIN_RESPONSE_PARTS = 3
14 /** Default SEND chunk size for outgoing chunked transfers. */
15 const val CHUNK_SIZE = 2048
16
17 /** Keepalive: empty chunk range + no body (RFC 4975 §7.4). */
18 const val KEEPALIVE_RANGE = "1-0/0"
19
20 /** One outgoing SEND chunk: headers + body slice. */
21 data class OutChunk(
22 val txid: String,
23 val messageId: String,
24 /** Full head bytes (headers + blank line), ready to write. */
25 val head: ByteArray,
26 /** Body slice bytes. */
27 val body: ByteArray,
28 ) {
29 override fun equals(other: Any?): Boolean {
30 if (this === other) return true
31 if (other !is OutChunk) return false
32 return txid == other.txid && messageId == other.messageId &&
33 head.contentEquals(other.head) && body.contentEquals(other.body)
34 }
35
36 override fun hashCode(): Int {
37 var result = txid.hashCode()
38 result = 31 * result + messageId.hashCode()
39 result = 31 * result + head.contentHashCode()
40 result = 31 * result + body.contentHashCode()
41 return result
42 }
43 }
44
45 /**
46 * Split [payload] into SEND chunks of at most [chunkSize] bytes sharing
47 * [messageId], with `Byte-Range: start-end/total` (§2.2). Single chunk
48 * for small payloads (identical to the legacy one-shot shape).
49 */
50 fun splitSend(
51 toPath: String,
52 fromPath: String,
53 payload: ByteArray,
54 contentType: String = "message/cpim",
55 messageId: String = UUID.randomUUID().toString(),
56 chunkSize: Int = CHUNK_SIZE,
57 failureReport: Boolean = true,
58 successReport: Boolean = false,
59 ): List<OutChunk> {
60 if (payload.isEmpty()) return emptyList()
61 val total = payload.size
62 val out = mutableListOf<OutChunk>()
63 var offset = 0
64 while (offset < total) {
65 val end = minOf(offset + chunkSize, total)
66 val slice = payload.copyOfRange(offset, end)
67 val txid = UUID.randomUUID().toString().replace("-", "").take(12)
68 val head = buildString {
69 append("MSRP $txid SEND\r\n")
70 append("To-Path: $toPath\r\n")
71 append("From-Path: $fromPath\r\n")
72 append("Message-ID: $messageId\r\n")
73 append("Byte-Range: ${offset + 1}-$end/$total\r\n")
74 append("Failure-Report: ${if (failureReport) "yes" else "no"}\r\n")
75 append("Success-Report: ${if (successReport) "yes" else "no"}\r\n")
76 append("Content-Type: $contentType\r\n")
77 }.toByteArray(Charsets.UTF_8) + "\r\n".toByteArray(Charsets.UTF_8)
78 out += OutChunk(txid, messageId, head, slice)
79 offset = end
80 }
81 return out
82 }
83
84 /**
85 * Serialize one chunk to wire bytes (head + body + end-marker), the exact
86 * bytes the socket layer writes.
87 */
88 fun serializeChunk(chunk: OutChunk): ByteArray =
89 chunk.head + chunk.body +
90 "\r\n-------${chunk.txid}\$\r\n".toByteArray(Charsets.UTF_8)
91
92 /**
93 * Build a REPORT request (§2.1, RFC 4975 §7.1/§8): [status] is a
94 * `namespace + code` pair, e.g. `000 200 OK`. [byteRange] echoes the
95 * failed/acked range.
96 */
97 fun buildReport(
98 toPath: String,
99 fromPath: String,
100 messageId: String,
101 statusNamespace: Int = 0,
102 statusCode: Int,
103 reason: String,
104 byteRange: String,
105 ): ByteArray {
106 val txid = UUID.randomUUID().toString().replace("-", "").take(12)
107 return buildString {
108 append("MSRP $txid REPORT\r\n")
109 append("To-Path: $toPath\r\n")
110 append("From-Path: $fromPath\r\n")
111 append("Message-ID: $messageId\r\n")
112 append("Byte-Range: $byteRange\r\n")
113 append("Status: ${"%03d".format(statusNamespace)} $statusCode $reason\r\n")
114 }.toByteArray(Charsets.UTF_8) +
115 "\r\n-------$txid\$\r\n".toByteArray(Charsets.UTF_8)
116 }
117
118 /** Build a keepalive empty SEND (§2.5): no body, `Byte-Range: 1-0/0`. */
119 fun buildKeepalive(toPath: String, fromPath: String): ByteArray {
120 val txid = UUID.randomUUID().toString().replace("-", "").take(12)
121 return buildString {
122 append("MSRP $txid SEND\r\n")
123 append("To-Path: $toPath\r\n")
124 append("From-Path: $fromPath\r\n")
125 append("Byte-Range: $KEEPALIVE_RANGE\r\n")
126 append("Failure-Report: no\r\n")
127 append("Success-Report: no\r\n")
128 }.toByteArray(Charsets.UTF_8) +
129 "\r\n-------$txid\$\r\n".toByteArray(Charsets.UTF_8)
130 }
131
132 /** Build a minimal error response (413/415/481/501…) to [txid]. */
133 fun buildErrorResponse(toPath: String, txid: String, code: Int, reason: String): ByteArray =
134 buildString {
135 append("MSRP $txid $code $reason\r\n")
136 if (toPath.isNotBlank()) append("To-Path: $toPath\r\n")
137 append("\r\n")
138 }.toByteArray(Charsets.UTF_8) +
139 "-------$txid\$\r\n".toByteArray(Charsets.UTF_8)
140
141 /** Parse an MSRP response start line into (txid, code, reason), or null. */
142 fun parseResponseStart(line: String): Triple<String, Int, String>? {
143 if (!line.startsWith("MSRP ")) return null
144 val parts = line.split(" ")
145 if (parts.size < MIN_RESPONSE_PARTS) return null
146 // MSRP <txid> SEND/REPORT (request) vs MSRP <txid> <code> (response):
147 // requests have an all-alpha method token.
148 val third = parts[2]
149 if (third.all { it.isLetter() }) return null
150 val code = third.toIntOrNull() ?: return null
151 return Triple(parts[1], code, parts.drop(MIN_RESPONSE_PARTS).joinToString(" "))
152 }
153
154 /** True when [line] is an MSRP request (SEND/REPORT/AUTH/…). */
155 fun isRequest(line: String): Boolean {
156 if (!line.startsWith("MSRP ")) return false
157 val third = line.split(" ").getOrNull(2).orEmpty()
158 return third.isNotEmpty() && third.all { it.isLetter() }
159 }
160
161 /** Parse a Status header value into (namespace, code, reason), or null. */
162 fun parseStatus(value: String): Triple<Int, Int, String>? {
163 val parts = value.trim().split(" ", limit = 3)
164 if (parts.size < 2) return null
165 val ns = parts[0].toIntOrNull() ?: return null
166 val code = parts[1].toIntOrNull() ?: return null
167 return Triple(ns, code, parts.getOrElse(2) { "" })
168 }
169}