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 / RcsSessionInvite.kt

RcsSessionInvite.kt209 lines · 8.1 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import com.vayunmathur.library.log.Log
4import java.util.UUID
5
6/**
7 * SIP/SDP builders for [RcsSessionManager] (split for file length).
8 * Extension functions on [RcsSessionManager]; behavior identical, call sites unchanged.
9 */
10
11internal fun RcsSessionManager.buildInvite(
12 targetUri: String,
13 callId: String,
14 localTag: String,
15 branch: String,
16 conversationId: String,
17 subject: String? = null,
18 listenPath: String? = null,
19 tlsFingerprint: String? = null,
20): Triple<String, String, ByteArray> {
21 val cfg = RcsSipTransport.lastConfigSnapshot()
22 val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"
23 val sdp = buildSdpOffer(cfg?.msrpLocalIp, listenPath, tlsFingerprint)
24 val bytes = sdp.toByteArray(Charsets.UTF_8)
25 val startLine = "INVITE $targetUri SIP/2.0"
26 val headers = buildString {
27 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
28 append("Max-Forwards: 70\r\n")
29 append("From: <$from>;tag=$localTag\r\n")
30 append("To: <$targetUri>\r\n")
31 append("Call-ID: $callId\r\n")
32 append("CSeq: 1 INVITE\r\n")
33 append(contactHeader(from, cfg?.imei))
34 append("Conversation-ID: $conversationId\r\n")
35 append("Contribution-ID: ${UUID.randomUUID()}\r\n")
36 append("Accept-Contact: *;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"\r\n")
37 append("P-Preferred-Identity: <$from>\r\n")
38 append("P-Preferred-Service: urn:urn-7:3gpp-service.ims.icsi.oma.cpm.session\r\n")
39 if (subject != null) append("Subject: $subject\r\n")
40 cfg?.serviceRoute?.takeIf { it.isNotBlank() }?.let { append("Route: <$it>\r\n") }
41 cfg?.pani?.takeIf { it.isNotBlank() }?.let { append("P-Access-Network-Info: $it\r\n") }
42 append("User-Agent: ${cfg?.userAgent ?: "Communicate-RCS/1.0"}\r\n")
43 append("Content-Type: application/sdp\r\n")
44 append("Content-Length: ${bytes.size}\r\n")
45 }
46 return Triple(startLine, headers, bytes)
47}
48
49/**
50 * SDP offer: `setup:actpass` + listen path when we can accept inbound
51 * TCP ([listenPath] from [RcsMsrpListen]), else the v1 `setup:active`
52 * connect-out offer with an unroutable placeholder path.
53 *
54 * TLS (RFC 4976): when our identity is available ([tlsFingerprint]
55 * non-null) the offer is `TCP/TLS/MSRP` with an `msrps://` path +
56 * `a=fingerprint`, so a TLS-capable peer answers secure; otherwise plain
57 * `TCP/MSRP`. The media proto/paths always agree (never a TLS path on a
58 * plaintext `m=` line).
59 */
60fun RcsSessionManager.buildSdpOffer(
61 localIp: String?,
62 listenPath: String?,
63 tlsFingerprint: String? = null,
64 ): String {
65 val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"
66 val secure = tlsFingerprint != null
67 val (path, port, setup) = sdpPathPortSetup(listenPath, secure, "actpass")
68 val proto = if (secure) "TCP/TLS/MSRP" else "TCP/MSRP"
69 return buildSdpBody(ip, port, proto, path, setup, secure, tlsFingerprint)
70}
71
72/** Path/port/setup triple for an offer or answer. */
73private fun sdpPathPortSetup(
74 listenPath: String?,
75 secure: Boolean,
76 listenSetup: String,
77): Triple<String, Int, String> {
78 if (listenPath != null) {
79 return Triple(
80 if (secure) listenPath.withScheme("msrps") else listenPath,
81 RcsMsrpListen.listenPort() ?: RcsSessionManager.DEFAULT_MSRP_PORT,
82 listenSetup,
83 )
84 }
85 val scheme = if (secure) "msrps" else "msrp"
86 return Triple(
87 "$scheme://${UUID.randomUUID()}.invalid:" +
88 "${RcsSessionManager.DEFAULT_MSRP_PORT}/${UUID.randomUUID()};tcp",
89 RcsSessionManager.DEFAULT_MSRP_PORT,
90 "active",
91 )
92}
93
94/** Render the SDP body. */
95private fun buildSdpBody(
96 ip: String,
97 port: Int,
98 proto: String,
99 path: String,
100 setup: String,
101 secure: Boolean,
102 tlsFingerprint: String?,
103): String {
104 return buildString {
105 append("v=0\r\n")
106 append("o=- ${System.currentTimeMillis()} ${System.currentTimeMillis()} IN IP4 $ip\r\n")
107 append("s=-\r\n")
108 append("c=IN IP4 $ip\r\n")
109 append("t=0 0\r\n")
110 append("m=message $port $proto *\r\n")
111 append("a=path:$path\r\n")
112 append("a=accept-types:message/cpim text/plain message/imdn+xml application/im-iscomposing+xml\r\n")
113 append("a=setup:$setup\r\n")
114 if (secure) append("a=fingerprint:${RcsMsrpTls.FINGERPRINT_HASH} $tlsFingerprint\r\n")
115 }
116}
117
118 /**
119 * SDP answer: `setup:passive` + listen path when we are accepting the
120 * offerer's TCP connection ([passivePath] non-null), else the v1
121 * `setup:active` answer (we connect out to the offerer). [secure]
122 * mirrors the offerer's choice: a TLS offer (`TCP/TLS/MSRP`,
123 * `msrps://`, or `a=fingerprint`) gets a TLS answer with our
124 * fingerprint; otherwise plaintext.
125 */
126fun RcsSessionManager.buildSdpAnswer(
127 localIp: String?,
128 passivePath: String? = null,
129 secure: Boolean = false,
130 tlsFingerprint: String? = null,
131 ): String {
132 val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"
133 val useTls = secure && tlsFingerprint != null
134 val (path, port, setup) = sdpPathPortSetup(passivePath, useTls, "passive")
135 val proto = if (useTls) "TCP/TLS/MSRP" else "TCP/MSRP"
136 return buildSdpBody(ip, port, proto, path, setup, useTls, tlsFingerprint)
137}
138/** Inbound INVITE: focus join or new incoming session. */
139internal fun RcsSessionManager.onInviteRequest(
140 callId: String,
141 fromUri: String,
142 body: String,
143 fromTag: String?,
144 toUri: String?,
145): RcsSession {
146 // INVITE to a focus URI we host: record the joiner, keyed to the
147 // hosted conversation (the caller answers with acceptIncoming on
148 // the hosted thread; relay fans their messages out).
149 val target = (toUri ?: "") + "\n" + body
150 hostedConversationFor(target)?.let { hosted ->
151 noteFocusJoin(hosted.focusUri, fromUri)
152 return RcsSession(
153 dialogId = "$callId:focus-in",
154 callId = callId,
155 localTag = UUID.randomUUID().toString().take(TAG_LENGTH),
156 remoteTag = fromTag.orEmpty(),
157 remoteUri = fromUri,
158 conversationId = hosted.conversationId,
159 isGroup = true,
160 )
161 }
162 val conversationId = fromUri.substringAfter("sip:").substringBefore("@")
163 .takeIf { it.isNotBlank() } ?: fromUri
164 // Stash the offerer's path/setup for acceptIncoming connect-out.
165 pendingOffersMutable[callId] = RcsSessionManager.PendingOffer(
166 remotePath = Regex("a=path:(\\S+)", RegexOption.IGNORE_CASE).find(body)
167 ?.groupValues?.getOrNull(1)?.trim(),
168 setup = parseSdpSetup(body),
169 sdp = body,
170 peerFingerprint = RcsMsrpTls.parseFingerprint(body)?.second,
171 )
172 val session = RcsSession(
173 dialogId = "$callId:in",
174 callId = callId,
175 localTag = UUID.randomUUID().toString().take(TAG_LENGTH),
176 remoteTag = fromTag.orEmpty(),
177 remoteUri = fromUri,
178 conversationId = conversationId,
179 )
180 sessionsMutable.value = sessionsMutable.value + (conversationId to session)
181 return session
182}
183
184/** Inbound MESSAGE: IMDN reports and typing notifications. */
185internal fun RcsSessionManager.onMessageRequest(fromUri: String, contentType: String?, body: String) {
186 val conversationId = fromUri.substringAfter("sip:").substringBefore("@")
187 if (contentType?.contains("imdn", ignoreCase = true) == true) {
188 RcsImdn.onReportReceived(body)
189 } else if (contentType?.contains("im-composing", ignoreCase = true) == true ||
190 parseIsComposingBody(body) != null
191 ) {
192 val active = parseIsComposingBody(body) ?: false
193 typingMutable.value = typingMutable.value + (conversationId to active)
194 }
195}
196
197/** Tear down a failed session (>= 300). */
198internal fun RcsSessionManager.failSession(
199 key: String,
200 session: RcsSession,
201 callId: String,
202 statusCode: Int,
203) {
204 Log.status(RcsSessionManager.TAG, "Session failed $callId code=$statusCode")
205 transactions.entries.removeIf { it.value == session.dialogId }
206 sessionsMutable.value = sessionsMutable.value - key
207 answerFingerprintsMutable.remove(callId)
208 RcsMsrpListen.dropPending(key)
209}