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

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

RcsSipDialog.kt170 lines · 7.1 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import java.util.UUID
4
5/**
6 * Pure SIP dialog builders + parsers (RFC 3261 §12): ACK, in-dialog MESSAGE /
7 * BYE / REFER with sequencing, route-set recording.
8 *
9 * Split from `RcsSessionManager` for file length. All functions are pure
10 * string builders/parsers — unit-tested without the transport. Sending stays
11 * in the manager (it owns the session map + `RcsSipTransport`).
12 */
13object RcsSipDialog {
14 private const val BRANCH_TOKEN_LENGTH = 16
15 /**
16 * Build an ACK for the 2xx to our INVITE (RFC 3261 §13.2.2.4): same
17 * Call-ID/From-tag/To-tag/CSeq-number as the INVITE, Request-URI = the
18 * 200 OK's Contact, Route = recorded route set.
19 */
20 fun buildAck(session: RcsSession, branch: String = newBranch()): Pair<String, String> {
21 val target = session.remoteContact?.takeIf { it.isNotBlank() } ?: session.remoteUri
22 val startLine = "ACK $target SIP/2.0"
23 val headers = buildString {
24 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
25 append("Max-Forwards: 70\r\n")
26 append("From: <${session.localUri()}>;tag=${session.localTag}\r\n")
27 append("To: <${session.remoteUri}>;tag=${session.remoteTag}\r\n")
28 append("Call-ID: ${session.callId}\r\n")
29 append("CSeq: ${session.inviteCseq} ACK\r\n")
30 session.routeSet.forEach { append("Route: <$it>\r\n") }
31 append("Content-Length: 0\r\n")
32 }
33 return startLine to headers
34 }
35
36 /**
37 * Build an in-dialog MESSAGE on [session] with the next CSeq
38 * (RFC 3261 §12.2.1.1). Returns (startLine, headers, content, nextCseq)
39 * — the caller persists `nextCseq` via `session.copy(nextCseq = ...)`.
40 */
41 fun buildInDialogMessage(
42 session: RcsSession,
43 body: ByteArray,
44 contentType: String = "message/cpim",
45 branch: String = newBranch(),
46 ): InDialogRequest {
47 val cseq = session.nextCseq
48 val target = session.remoteContact?.takeIf { it.isNotBlank() } ?: session.remoteUri
49 val startLine = "MESSAGE $target SIP/2.0"
50 val headers = buildString {
51 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
52 append("Max-Forwards: 70\r\n")
53 append("From: <${session.localUri()}>;tag=${session.localTag}\r\n")
54 append("To: <${session.remoteUri}>;tag=${session.remoteTag}\r\n")
55 append("Call-ID: ${session.callId}\r\n")
56 append("CSeq: $cseq MESSAGE\r\n")
57 session.routeSet.forEach { append("Route: <$it>\r\n") }
58 append("Content-Type: $contentType\r\n")
59 append("Content-Length: ${body.size}\r\n")
60 }
61 return InDialogRequest(startLine, headers, body, cseq + 1)
62 }
63
64 /**
65 * Build an in-dialog BYE on [session] with the next CSeq. Same return
66 * contract as [buildInDialogMessage].
67 */
68 fun buildInDialogBye(
69 session: RcsSession,
70 branch: String = newBranch(),
71 ): InDialogRequest {
72 val cseq = session.nextCseq
73 val target = session.remoteContact?.takeIf { it.isNotBlank() } ?: session.remoteUri
74 val startLine = "BYE $target SIP/2.0"
75 val headers = buildString {
76 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
77 append("Max-Forwards: 70\r\n")
78 append("From: <${session.localUri()}>;tag=${session.localTag}\r\n")
79 append("To: <${session.remoteUri}>;tag=${session.remoteTag}\r\n")
80 append("Call-ID: ${session.callId}\r\n")
81 append("CSeq: $cseq BYE\r\n")
82 session.routeSet.forEach { append("Route: <$it>\r\n") }
83 append("Content-Length: 0\r\n")
84 }
85 return InDialogRequest(startLine, headers, ByteArray(0), cseq + 1)
86 }
87
88 /** An in-dialog request plus the session's next CSeq after sending it. */
89 data class InDialogRequest(
90 val startLine: String,
91 val headers: String,
92 val body: ByteArray,
93 val nextCseq: Long,
94 ) {
95 override fun equals(other: Any?): Boolean {
96 if (this === other) return true
97 if (other !is InDialogRequest) return false
98 return startLine == other.startLine && headers == other.headers &&
99 body.contentEquals(other.body) && nextCseq == other.nextCseq
100 }
101
102 override fun hashCode(): Int {
103 var result = startLine.hashCode()
104 result = 31 * result + headers.hashCode()
105 result = 31 * result + body.contentHashCode()
106 result = 31 * result + nextCseq.hashCode()
107 return result
108 }
109 }
110
111 /**
112 * Parse `Contact:` + `Record-Route:` from a 200 OK header section into
113 * (contactUri, routeSet). The route set is the Record-Route values in
114 * *reverse* order for the UAC (RFC 3261 §12.1.2). Empty route set when
115 * absent.
116 */
117 fun parseDialogRoute(headers: String): Pair<String?, List<String>> {
118 var contact: String? = null
119 val routes = mutableListOf<String>()
120 for (line in headers.lineSequence()) {
121 val trimmed = line.trim()
122 when {
123 trimmed.startsWith("Contact:", ignoreCase = true) -> {
124 contact = trimmed.substringAfter(":").trim()
125 .substringAfter("<").substringBefore(">")
126 .takeIf { it.isNotBlank() }
127 ?: trimmed.substringAfter(":").trim().substringBefore(";")
128 .takeIf { it.isNotBlank() }
129 }
130 trimmed.startsWith("Record-Route:", ignoreCase = true) -> {
131 trimmed.substringAfter(":").trim()
132 .substringAfter("<").substringBefore(">")
133 .takeIf { it.isNotBlank() }?.let { routes += it }
134 }
135 }
136 }
137 return contact to routes.reversed()
138 }
139
140 /** Parse the CSeq number from a header section, or null. */
141 /** Parse a header value out of a SIP header section (case-insensitive name + colon). */
142 internal fun headerValue(headers: String, name: String): String? {
143 for (line in headers.lineSequence()) {
144 val trimmed = line.trim()
145 if (trimmed.startsWith(name, ignoreCase = true)) {
146 return trimmed.substringAfter(":").trim().takeIf { it.isNotEmpty() }
147 }
148 }
149 return null
150 }
151
152 /** Parse the CSeq method token from a header section, or null. */
153 fun parseCseqMethod(headers: String): String? {
154 for (line in headers.lineSequence()) {
155 val trimmed = line.trim()
156 if (trimmed.startsWith("CSeq:", ignoreCase = true)) {
157 return trimmed.substringAfter(":").trim()
158 .substringAfter(" ").trim().takeIf { it.isNotEmpty() }
159 }
160 }
161 return null
162 }
163
164 fun newBranch(): String = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(BRANCH_TOKEN_LENGTH)}"
165
166 /** Our local URI for From headers (delegate identity when known). */
167 private fun RcsSession.localUri(): String =
168 RcsSipTransport.lastConfigSnapshot()?.publicUserId?.takeIf { it.isNotBlank() }
169 ?: "sip:local@rcs"
170}