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

Modern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / rcs / DirectSipRcsPass3Test.kt

DirectSipRcsPass3Test.kt210 lines · 8.8 KiBRaw
1package com.vayunmathur.communicate.rcs
2
3import android.content.Context
4import androidx.test.core.app.ApplicationProvider
5import com.vayunmathur.communicate.data.rcs.RcsDirectSip
6import com.vayunmathur.communicate.data.rcs.RcsImsNetwork
7import java.net.ServerSocket
8import java.util.concurrent.CopyOnWriteArrayList
9import java.util.concurrent.CountDownLatch
10import java.util.concurrent.TimeUnit
11import kotlinx.coroutines.runBlocking
12import org.junit.runner.RunWith
13import org.robolectric.RobolectricTestRunner
14import org.robolectric.annotation.Config
15import kotlin.test.AfterTest
16import kotlin.test.Test
17import kotlin.test.assertEquals
18import kotlin.test.assertFalse
19import kotlin.test.assertTrue
20
21/**
22 * Pass 3: direct-SIP registration failure modes against a loopback
23 * P-CSCF on the shadow IMS PDN — rejection, unanswerable AKA
24 * challenge, failed authenticated REGISTER, MESSAGE errors, and
25 * deregistration. (The happy paths live in the pass-2 IMS tests.)
26 */
27@RunWith(RobolectricTestRunner::class)
28@Config(sdk = [34], shadows = [RcsSlice3Pass2ImsShadow::class])
29class DirectSipRcsPass3Test {
30 private val context: Context get() = ApplicationProvider.getApplicationContext()
31
32 @AfterTest fun tearDown() {
33 RcsDirectSip.stop()
34 RcsDirectSip.onInboundMessage = null
35 RcsImsNetwork.reset()
36 }
37
38 /** One-connection P-CSCF script; [handler] maps request text to a response or null (close). */
39 private class Pcscf(private val handler: (String) -> String?) {
40 val requests = CopyOnWriteArrayList<String>()
41 val done = CountDownLatch(1)
42 fun serve(server: ServerSocket) {
43 Thread {
44 try {
45 server.accept().use { s ->
46 s.soTimeout = 20_000
47 val input = s.getInputStream().bufferedReader(Charsets.UTF_8)
48 val out = s.getOutputStream()
49 var request = readRequest(input)
50 while (request != null) {
51 requests += request.first
52 val response = handler(request.first)
53 if (response == null) {
54 request = null
55 } else {
56 writeResponse(out, request.second, response)
57 request = readRequest(input)
58 }
59 }
60 }
61 } catch (_: Throwable) {
62 // Client went away mid-script.
63 }
64 done.countDown()
65 }.apply { isDaemon = true; start() }
66 }
67
68 /** Read one SIP request (head + Content-Length body); null at end of stream. */
69 private fun readRequest(input: java.io.BufferedReader): Pair<String, List<String>>? {
70 val lines = mutableListOf<String>()
71 var line = input.readLine() ?: return null
72 var contentLength = 0
73 while (line.isNotEmpty()) {
74 lines += line
75 if (line.startsWith("Content-Length:", true)) {
76 contentLength = line.substringAfter(":").trim().toIntOrNull() ?: 0
77 }
78 line = input.readLine() ?: return null
79 }
80 if (lines.isEmpty()) return null
81 if (contentLength > 0) {
82 val chars = CharArray(contentLength)
83 var read = 0
84 var eof = false
85 while (read < contentLength && !eof) {
86 val r = input.read(chars, read, contentLength - read)
87 if (r < 0) eof = true else read += r
88 }
89 lines += String(chars, 0, read)
90 }
91 return lines.joinToString("\r\n") to lines
92 }
93
94 /** Write [response], echoing Via branch / Call-ID / CSeq like a real P-CSCF. */
95 private fun writeResponse(out: java.io.OutputStream, lines: List<String>, response: String) {
96 val branch = lines.firstOrNull { it.startsWith("Via:", true) }
97 ?.substringAfter("branch=")?.substringBefore(";")?.trim().orEmpty()
98 val callId = lines.firstOrNull { it.startsWith("Call-ID:", true) }.orEmpty()
99 val cseq = lines.firstOrNull { it.startsWith("CSeq:", true) }.orEmpty()
100 out.write(
101 ("$response\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=$branch\r\n" +
102 "$callId\r\n$cseq\r\nContent-Length: 0\r\n\r\n").toByteArray(Charsets.UTF_8),
103 )
104 out.flush()
105 }
106 }
107
108 /** Bind the fake P-CSCF listener; see [withPcscf] call site for why. */
109 private fun bindPcscf(): ServerSocket {
110 // Attempt-counted, never clock-bounded: Robolectric substitutes
111 // System.currentTimeMillis with its paused scheduler clock.
112 var attempts = 0
113 while (true) {
114 try {
115 return ServerSocket().apply {
116 reuseAddress = true
117 bind(java.net.InetSocketAddress(5060))
118 }
119 } catch (e: java.net.BindException) {
120 if (++attempts >= 600) throw e
121 Thread.sleep(100)
122 }
123 }
124 }
125
126 private suspend fun withPcscf(handler: (String) -> String?, block: suspend (Pcscf) -> Unit) {
127 // Port 5060 is fixed (the shadow advertises it as the P-CSCF) and
128 // shared with RcsSlice3Pass2DirectSipAuthTest / RcsSlice3Pass2ImsTest,
129 // which Gradle workers can run concurrently: SO_REUSEADDR covers
130 // TIME_WAIT, the bounded retry waits out an active listen.
131 val server = bindPcscf()
132 val pcscf = Pcscf(handler)
133 pcscf.serve(server)
134 try {
135 block(pcscf)
136 } finally {
137 runCatching { server.close() }
138 RcsDirectSip.stop()
139 }
140 }
141
142 @Test fun idleEdgesWithoutRegistration() = runBlocking {
143 assertFalse(RcsDirectSip.start(context, -1))
144 assertFalse(RcsDirectSip.isRegistered())
145 assertFalse(
146 RcsDirectSip.sendMessage("MESSAGE sip:x@rcs SIP/2.0", "To: <sip:x@rcs>\r\n", "hi".toByteArray()),
147 )
148 RcsDirectSip.stop()
149 RcsDirectSip.stop()
150 assertFalse(RcsDirectSip.isRegistered())
151 }
152
153 @Test fun registerRejected403FailsStart() = runBlocking {
154 withPcscf(handler = { "SIP/2.0 403 Forbidden" }) { pcscf ->
155 assertFalse(RcsDirectSip.start(context, 1))
156 assertFalse(RcsDirectSip.isRegistered())
157 assertTrue(pcscf.done.await(15, TimeUnit.SECONDS), "requests=${pcscf.requests}")
158 assertTrue(pcscf.requests.first().contains("REGISTER"))
159 }
160 }
161
162 @Test fun challengeWithoutAkaFailsStart() = runBlocking {
163 withPcscf(
164 handler = { request ->
165 if (request.contains("Authorization:")) "SIP/2.0 200 OK"
166 else "SIP/2.0 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"rcs\", nonce=\"abc123\", algorithm=MD5, qop=\"auth\""
167 },
168 ) { pcscf ->
169 // No Telephony shadow here: getIccAuthentication returns null, so
170 // the AKA challenge cannot be answered and start must fail.
171 assertFalse(RcsDirectSip.start(context, 1))
172 assertFalse(RcsDirectSip.isRegistered())
173 assertTrue(pcscf.done.await(15, TimeUnit.SECONDS), "requests=${pcscf.requests}")
174 // Only the initial REGISTER was sent (plus stop()'s deregister).
175 assertTrue(pcscf.requests.none { it.contains("Authorization:") }, "${pcscf.requests}")
176 }
177 }
178
179 @Test fun messageErrorResponseFailsSendAndStopDeregisters() = runBlocking {
180 var sawMessage = false
181 withPcscf(
182 handler = { request ->
183 when {
184 request.startsWith("MESSAGE") -> {
185 sawMessage = true
186 "SIP/2.0 404 Not Found"
187 }
188 request.contains("Expires: 0") -> "SIP/2.0 200 OK"
189 else -> "SIP/2.0 200 OK\r\nContact: <sip:127.0.0.1:5060>;expires=600\r\nExpires: 600"
190 }
191 },
192 ) { pcscf ->
193 assertTrue(RcsDirectSip.start(context, 1))
194 assertTrue(RcsDirectSip.isRegistered())
195 assertFalse(
196 RcsDirectSip.sendMessage(
197 "MESSAGE sip:peer@rcs SIP/2.0",
198 "To: <sip:peer@rcs>\r\nContent-Type: message/cpim\r\n",
199 "hello".toByteArray(Charsets.UTF_8),
200 ),
201 )
202 assertTrue(sawMessage)
203 RcsDirectSip.stop()
204 assertFalse(RcsDirectSip.isRegistered())
205 assertTrue(pcscf.done.await(15, TimeUnit.SECONDS), "requests=${pcscf.requests}")
206 assertTrue(pcscf.requests.any { it.contains("Expires: 0") }, "${pcscf.requests}")
207 assertEquals(3, pcscf.requests.size)
208 }
209 }
210}