Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / test / java / com / vayunmathur / communicate / rcs / RcsSlice3Pass2ImsTest.kt
RcsSlice3Pass2ImsTest.kt478 lines · 19.9 KiBRaw
| 1 | package com.vayunmathur.communicate.rcs |
| 2 | |
| 3 | import android.content.Context |
| 4 | import androidx.test.core.app.ApplicationProvider |
| 5 | import com.vayunmathur.communicate.data.rcs.RcsDirectSip |
| 6 | import com.vayunmathur.communicate.data.rcs.RcsImsNetwork |
| 7 | import com.vayunmathur.communicate.data.rcs.RcsMsrp |
| 8 | import com.vayunmathur.communicate.data.rcs.RcsMsrpListen |
| 9 | import com.vayunmathur.communicate.data.rcs.RcsMsrpTls |
| 10 | import java.net.ServerSocket |
| 11 | import java.net.Socket |
| 12 | import java.util.concurrent.CopyOnWriteArrayList |
| 13 | import java.util.concurrent.CountDownLatch |
| 14 | import java.util.concurrent.TimeUnit |
| 15 | import java.util.concurrent.atomic.AtomicReference |
| 16 | import kotlinx.coroutines.test.runTest |
| 17 | import org.junit.runner.RunWith |
| 18 | import org.robolectric.RobolectricTestRunner |
| 19 | import org.robolectric.annotation.Config |
| 20 | import kotlin.test.AfterTest |
| 21 | import kotlin.test.Test |
| 22 | import kotlin.test.assertEquals |
| 23 | import kotlin.test.assertFalse |
| 24 | import kotlin.test.assertNotNull |
| 25 | import kotlin.test.assertNull |
| 26 | import kotlin.test.assertTrue |
| 27 | |
| 28 | /** |
| 29 | * Slice-3 pass 2 on a fake IMS PDN ([RcsSlice3Pass2ImsShadow]): the IMS |
| 30 | * network scan/request, IMS-bound sockets, the MSRP listen/accept loop |
| 31 | * (matched, unknown and TLS-on-plaintext routing), and a full direct-SIP |
| 32 | * REGISTER + MESSAGE exchange against a loopback P-CSCF. |
| 33 | */ |
| 34 | @RunWith(RobolectricTestRunner::class) |
| 35 | @Config(sdk = [34], shadows = [RcsSlice3Pass2ImsShadow::class]) |
| 36 | class RcsSlice3Pass2ImsTest { |
| 37 | |
| 38 | private val context: Context get() = ApplicationProvider.getApplicationContext() |
| 39 | |
| 40 | @AfterTest |
| 41 | fun tearDown() { |
| 42 | RcsMsrpListen.stop() |
| 43 | RcsDirectSip.stop() |
| 44 | RcsImsNetwork.reset() |
| 45 | } |
| 46 | |
| 47 | /** Bind the fake P-CSCF listener on the fixed port 5060. */ |
| 48 | private fun bindPcscf5060(): ServerSocket { |
| 49 | // Attempt-counted, never clock-bounded: Robolectric substitutes |
| 50 | // System.currentTimeMillis with its paused scheduler clock. |
| 51 | var attempts = 0 |
| 52 | while (true) { |
| 53 | try { |
| 54 | return ServerSocket().apply { |
| 55 | reuseAddress = true |
| 56 | bind(java.net.InetSocketAddress(5060)) |
| 57 | } |
| 58 | } catch (e: java.net.BindException) { |
| 59 | if (++attempts >= 600) throw e |
| 60 | Thread.sleep(100) |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | @Test |
| 66 | fun imsNetworkScanFindsFakePdn() = runTest { |
| 67 | RcsImsNetwork.reset() |
| 68 | val network = RcsImsNetwork.imsNetwork(context, 1) |
| 69 | assertNotNull(network) |
| 70 | // Cached on the second call. |
| 71 | assertEquals(network, RcsImsNetwork.imsNetwork(context, 1)) |
| 72 | assertEquals("0.0.0.0", RcsImsNetwork.lastLocalIp) |
| 73 | assertEquals(listOf("0.0.0.0"), RcsImsNetwork.localIps(context, network)) |
| 74 | val listen = RcsImsNetwork.listenSocket(context) |
| 75 | assertNotNull(listen) |
| 76 | assertEquals("0.0.0.0", listen.localIp) |
| 77 | assertTrue(listen.localPort > 0) |
| 78 | assertEquals("msrp://0.0.0.0:${listen.localPort}/sess-9;tcp", listen.msrpPath("sess-9")) |
| 79 | listen.close() |
| 80 | RcsImsNetwork.reset() |
| 81 | assertNull(RcsImsNetwork.lastLocalIp) |
| 82 | } |
| 83 | |
| 84 | @Test |
| 85 | fun imsSocketConnectsToLoopback() = runTest { |
| 86 | val server = ServerSocket(0) |
| 87 | val accepted = CountDownLatch(1) |
| 88 | Thread { |
| 89 | runCatching { server.accept().use { s -> s.getOutputStream().write(42) } } |
| 90 | accepted.countDown() |
| 91 | }.apply { isDaemon = true; start() } |
| 92 | val socket = RcsImsNetwork.createSocket(context, "127.0.0.1", server.localPort, 5_000) |
| 93 | assertNotNull(socket) |
| 94 | assertTrue(socket.isConnected) |
| 95 | assertEquals(42, socket.getInputStream().read()) |
| 96 | socket.close() |
| 97 | assertTrue(accepted.await(10, TimeUnit.SECONDS)) |
| 98 | server.close() |
| 99 | } |
| 100 | |
| 101 | // --- MSRP listen / accept routing --- |
| 102 | |
| 103 | private fun sendHeadAndBody(port: Int, head: String, body: String?): Socket { |
| 104 | val socket = Socket("127.0.0.1", port) |
| 105 | socket.soTimeout = 15_000 |
| 106 | val out = socket.getOutputStream() |
| 107 | out.write(head.toByteArray(Charsets.UTF_8)) |
| 108 | out.flush() |
| 109 | if (body != null) { |
| 110 | out.write(body.toByteArray(Charsets.UTF_8)) |
| 111 | out.flush() |
| 112 | } |
| 113 | return socket |
| 114 | } |
| 115 | |
| 116 | @Test |
| 117 | fun listenAcceptRoutesMatchedPathAndRejectsUnknown() = runTest { |
| 118 | val acceptedLatch = CountDownLatch(1) |
| 119 | val acceptedConv = AtomicReference<String>() |
| 120 | val acceptedHead = AtomicReference<RcsMsrpListen.AcceptedHead>() |
| 121 | var acceptedSocket: Socket? = null |
| 122 | assertTrue( |
| 123 | RcsMsrpListen.ensureListening(context) { conv, socket, head -> |
| 124 | acceptedConv.set(conv) |
| 125 | acceptedHead.set(head) |
| 126 | acceptedSocket = socket |
| 127 | acceptedLatch.countDown() |
| 128 | }, |
| 129 | ) |
| 130 | assertTrue(RcsMsrpListen.isListening()) |
| 131 | val port = RcsMsrpListen.listenPort() |
| 132 | assertNotNull(port) |
| 133 | assertEquals("0.0.0.0", RcsMsrpListen.listenIp()) |
| 134 | // Idempotent. |
| 135 | assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> }) |
| 136 | |
| 137 | val path = RcsMsrpListen.advertisePath(context, "ims-conv-1") { _, _, _ -> } |
| 138 | assertNotNull(path) |
| 139 | assertTrue(path.startsWith("msrp://0.0.0.0:$port/")) |
| 140 | |
| 141 | // Unknown path: 481 and close. |
| 142 | assertUnknownPathRejected(port) |
| 143 | |
| 144 | // Matched path: the accept callback receives the socket + head, and |
| 145 | // wrapping it in an MSRP connection delivers the pending body. |
| 146 | val tx = "matchedtx1" |
| 147 | val client = sendHeadAndBody( |
| 148 | port, |
| 149 | "MSRP $tx SEND\r\nTo-Path: $path\r\nFrom-Path: msrp://10.0.0.9:2855/peer;tcp\r\n" + |
| 150 | "Message-ID: ims-msg-1\r\nByte-Range: 1-5/5\r\nContent-Type: message/cpim\r\n\r\n", |
| 151 | null, |
| 152 | ) |
| 153 | assertTrue(acceptedLatch.await(15, TimeUnit.SECONDS), "no accept callback") |
| 154 | assertEquals("ims-conv-1", acceptedConv.get()) |
| 155 | assertTrue(acceptedHead.get().lines.first().startsWith("MSRP $tx SEND")) |
| 156 | val delivered = CopyOnWriteArrayList<String>() |
| 157 | val conn = RcsMsrp.wrapAccepted( |
| 158 | acceptedSocket!!, acceptedHead.get(), path, |
| 159 | "msrp://10.0.0.9:2855/peer;tcp", |
| 160 | ) { _, body -> delivered += body.toString(Charsets.UTF_8) } |
| 161 | client.getOutputStream().apply { |
| 162 | write("hello".toByteArray(Charsets.UTF_8)) |
| 163 | write("\r\n-------$tx\$\r\n".toByteArray(Charsets.UTF_8)) |
| 164 | flush() |
| 165 | } |
| 166 | val deadline = System.currentTimeMillis() + 15_000 |
| 167 | while (System.currentTimeMillis() < deadline && delivered.isEmpty()) Thread.sleep(25) |
| 168 | assertEquals(listOf("hello"), delivered.toList()) |
| 169 | conn.close() |
| 170 | client.close() |
| 171 | RcsMsrpListen.stop() |
| 172 | assertFalse(RcsMsrpListen.isListening()) |
| 173 | assertNull(RcsMsrpListen.listenPort()) |
| 174 | } |
| 175 | |
| 176 | @Test |
| 177 | fun listenRejectsPlaintextOnSecurePath() = runTest { |
| 178 | val acceptedLatch = CountDownLatch(1) |
| 179 | assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() }) |
| 180 | val port = RcsMsrpListen.listenPort()!! |
| 181 | val securePath = RcsMsrpListen.advertisePath( |
| 182 | context, "ims-conv-secure", secure = true, peerFingerprint = "AA:BB", |
| 183 | ) { _, _, _ -> } |
| 184 | assertNotNull(securePath) |
| 185 | val client = sendHeadAndBody( |
| 186 | port, |
| 187 | "MSRP securetx1 SEND\r\nTo-Path: $securePath\r\n" + |
| 188 | "From-Path: msrp://10.0.0.9/peer;tcp\r\n\r\n", |
| 189 | null, |
| 190 | ) |
| 191 | // The socket is closed without an accept callback or a 481. |
| 192 | val read = runCatching { client.getInputStream().read() }.getOrDefault(-2) |
| 193 | assertEquals(-1, read) |
| 194 | assertEquals(1L, acceptedLatch.count) |
| 195 | client.close() |
| 196 | // Dropping the pending path makes the same path unknown afterwards. |
| 197 | RcsMsrpListen.dropPending("ims-conv-secure") |
| 198 | RcsMsrpListen.stop() |
| 199 | } |
| 200 | |
| 201 | @Test |
| 202 | fun listenTlsByteOnPlainPathAttemptsHandshakeAndCloses() = runTest { |
| 203 | val acceptedLatch = CountDownLatch(1) |
| 204 | assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() }) |
| 205 | val port = RcsMsrpListen.listenPort()!! |
| 206 | val plainPath = RcsMsrpListen.advertisePath(context, "ims-conv-tls") { _, _, _ -> } |
| 207 | assertNotNull(plainPath) |
| 208 | // A TLS ClientHello first byte routes to the TLS branch; the junk |
| 209 | // that follows fails the handshake and the socket closes. |
| 210 | val client = Socket("127.0.0.1", port) |
| 211 | client.soTimeout = 15_000 |
| 212 | client.getOutputStream().apply { |
| 213 | write(0x16) |
| 214 | write("not-a-client-hello".toByteArray(Charsets.UTF_8)) |
| 215 | flush() |
| 216 | } |
| 217 | val read = runCatching { client.getInputStream().read() }.getOrDefault(-1) |
| 218 | assertEquals(-1, read) |
| 219 | assertEquals(1L, acceptedLatch.count) |
| 220 | client.close() |
| 221 | RcsMsrpListen.stop() |
| 222 | } |
| 223 | |
| 224 | @Test |
| 225 | fun listenTlsAcceptWithPinnedClient() = runTest { |
| 226 | val identity = RcsMsrpTls.ensureIdentity(context) |
| 227 | assertNotNull(identity) |
| 228 | val acceptedLatch = CountDownLatch(1) |
| 229 | val acceptedConv = AtomicReference<String>() |
| 230 | val acceptedHead = AtomicReference<RcsMsrpListen.AcceptedHead>() |
| 231 | var acceptedSocket: Socket? = null |
| 232 | assertTrue( |
| 233 | RcsMsrpListen.ensureListening(context) { conv, socket, head -> |
| 234 | acceptedConv.set(conv) |
| 235 | acceptedHead.set(head) |
| 236 | acceptedSocket = socket |
| 237 | acceptedLatch.countDown() |
| 238 | }, |
| 239 | ) |
| 240 | val port = RcsMsrpListen.listenPort()!! |
| 241 | val securePath = RcsMsrpListen.advertisePath( |
| 242 | context, "ims-conv-tls-ok", secure = true, peerFingerprint = identity.fingerprint, |
| 243 | ) { _, _, _ -> } |
| 244 | assertNotNull(securePath) |
| 245 | |
| 246 | val client = RcsMsrpTls.clientSocket(context, "127.0.0.1", port, identity.fingerprint) |
| 247 | assertNotNull(client, "TLS client could not handshake with the listen socket") |
| 248 | val tx = "tlstx12345" |
| 249 | client.getOutputStream().apply { |
| 250 | write( |
| 251 | ("MSRP $tx SEND\r\nTo-Path: $securePath\r\n" + |
| 252 | "From-Path: msrp://10.0.0.9:2855/peer;tcp\r\n" + |
| 253 | "Message-ID: ims-tls-1\r\nByte-Range: 1-4/4\r\n" + |
| 254 | "Content-Type: message/cpim\r\n\r\n").toByteArray(Charsets.UTF_8), |
| 255 | ) |
| 256 | flush() |
| 257 | } |
| 258 | assertTrue(acceptedLatch.await(20, TimeUnit.SECONDS), "TLS accept never routed") |
| 259 | assertEquals("ims-conv-tls-ok", acceptedConv.get()) |
| 260 | assertTrue(acceptedSocket is javax.net.ssl.SSLSocket) |
| 261 | |
| 262 | // The accepted connection delivers the chunk body like a plain one. |
| 263 | val delivered = CopyOnWriteArrayList<String>() |
| 264 | val conn = RcsMsrp.wrapAccepted( |
| 265 | acceptedSocket!!, acceptedHead.get(), securePath, |
| 266 | "msrp://10.0.0.9:2855/peer;tcp", |
| 267 | ) { _, body -> delivered += body.toString(Charsets.UTF_8) } |
| 268 | client.getOutputStream().apply { |
| 269 | write("data".toByteArray(Charsets.UTF_8)) |
| 270 | write("\r\n-------$tx\$\r\n".toByteArray(Charsets.UTF_8)) |
| 271 | flush() |
| 272 | } |
| 273 | val deadline = System.currentTimeMillis() + 20_000 |
| 274 | while (System.currentTimeMillis() < deadline && delivered.isEmpty()) Thread.sleep(25) |
| 275 | assertEquals(listOf("data"), delivered.toList()) |
| 276 | conn.close() |
| 277 | client.close() |
| 278 | RcsMsrpListen.stop() |
| 279 | } |
| 280 | |
| 281 | @Test |
| 282 | fun listenTlsAcceptRejectsWrongFingerprint() = runTest { |
| 283 | val identity = RcsMsrpTls.ensureIdentity(context) |
| 284 | assertNotNull(identity) |
| 285 | val acceptedLatch = CountDownLatch(1) |
| 286 | assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() }) |
| 287 | val port = RcsMsrpListen.listenPort()!! |
| 288 | // The pending path pins a fingerprint our cert does not have. |
| 289 | val securePath = RcsMsrpListen.advertisePath( |
| 290 | context, "ims-conv-tls-bad", secure = true, |
| 291 | peerFingerprint = "00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF", |
| 292 | ) { _, _, _ -> } |
| 293 | assertNotNull(securePath) |
| 294 | val client = RcsMsrpTls.clientSocket(context, "127.0.0.1", port, identity.fingerprint) |
| 295 | assertNotNull(client) |
| 296 | client.getOutputStream().apply { |
| 297 | write( |
| 298 | ("MSRP badtx123 SEND\r\nTo-Path: $securePath\r\n" + |
| 299 | "From-Path: msrp://10.0.0.9:2855/peer;tcp\r\n\r\n").toByteArray(Charsets.UTF_8), |
| 300 | ) |
| 301 | flush() |
| 302 | } |
| 303 | // The server closes after the fingerprint mismatch; no accept fires. |
| 304 | val read = runCatching { client.getInputStream().read() }.getOrDefault(-1) |
| 305 | assertEquals(-1, read) |
| 306 | assertEquals(1L, acceptedLatch.count) |
| 307 | client.close() |
| 308 | RcsMsrpListen.stop() |
| 309 | } |
| 310 | |
| 311 | @Test |
| 312 | fun listenFirstByteEofClosesQuietly() = runTest { |
| 313 | val acceptedLatch = CountDownLatch(1) |
| 314 | assertTrue(RcsMsrpListen.ensureListening(context) { _, _, _ -> acceptedLatch.countDown() }) |
| 315 | val port = RcsMsrpListen.listenPort()!! |
| 316 | // Connect and immediately close: the router reads EOF and drops it. |
| 317 | Socket("127.0.0.1", port).close() |
| 318 | Thread.sleep(500) |
| 319 | assertEquals(1L, acceptedLatch.count) |
| 320 | RcsMsrpListen.stop() |
| 321 | } |
| 322 | |
| 323 | /** An MSRP SEND to an unadvertised path is rejected with 481. */ |
| 324 | private fun assertUnknownPathRejected(port: Int) { |
| 325 | val txUnknown = "unknowntx1" |
| 326 | val rogue = sendHeadAndBody( |
| 327 | port, |
| 328 | "MSRP $txUnknown SEND\r\nTo-Path: msrp://0.0.0.0:$port/nope;tcp\r\n" + |
| 329 | "From-Path: msrp://10.0.0.9/peer;tcp\r\n\r\n", |
| 330 | null, |
| 331 | ) |
| 332 | val rogueIn = rogue.getInputStream().bufferedReader(Charsets.UTF_8) |
| 333 | val responseLine = rogueIn.readLine() |
| 334 | assertTrue(responseLine?.contains("481") == true, "response=$responseLine") |
| 335 | rogue.close() |
| 336 | } |
| 337 | |
| 338 | /** Fake P-CSCF script: REGISTER 200, push an inbound MESSAGE, ack the outbound one, ack deregistration. */ |
| 339 | private fun serveFakePcscf( |
| 340 | pcscf: ServerSocket, |
| 341 | requests: CopyOnWriteArrayList<String>, |
| 342 | inboundSent: CountDownLatch, |
| 343 | ) { |
| 344 | pcscf.accept().use { s -> |
| 345 | s.soTimeout = 20_000 |
| 346 | val input = s.getInputStream().bufferedReader(Charsets.UTF_8) |
| 347 | val out = s.getOutputStream() |
| 348 | // 1) REGISTER -> 200 (no auth challenge in this script). |
| 349 | val register = readSipRequest(input) |
| 350 | requests += register.joinToString("\n") |
| 351 | respondSip(out, register, 200, "OK") |
| 352 | // 2) Inbound MESSAGE pushed to the client. |
| 353 | out.write( |
| 354 | ("MESSAGE sip:me@rcs SIP/2.0\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=z9hG4bKinbound\r\n" + |
| 355 | "From: <sip:peer@rcs>;tag=p1\r\nTo: <sip:me@rcs>\r\n" + |
| 356 | "Call-ID: inbound-1@pcscf\r\nCSeq: 1 MESSAGE\r\n" + |
| 357 | "Content-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello") |
| 358 | .toByteArray(Charsets.UTF_8), |
| 359 | ) |
| 360 | out.flush() |
| 361 | inboundSent.countDown() |
| 362 | // 3) Outbound MESSAGE from the client -> 200 echoing its branch. |
| 363 | val message = readSipRequest(input) |
| 364 | requests += message.joinToString("\n") |
| 365 | respondSip(out, message, 200, "OK") |
| 366 | // 4) Deregistration REGISTER (expires=0) -> 200, then close. |
| 367 | val bye = readSipRequest(input) |
| 368 | requests += bye.joinToString("\n") |
| 369 | respondSip(out, bye, 200, "OK") |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /** Read one SIP request head plus its Content-Length body, when present. */ |
| 374 | private fun readSipRequest(input: java.io.BufferedReader): List<String> { |
| 375 | val lines = mutableListOf<String>() |
| 376 | var line = input.readLine() ?: return lines |
| 377 | var contentLength = 0 |
| 378 | while (line.isNotEmpty()) { |
| 379 | lines += line |
| 380 | if (line.startsWith("Content-Length:", true)) { |
| 381 | contentLength = line.substringAfter(":").trim().toIntOrNull() ?: 0 |
| 382 | } |
| 383 | line = input.readLine() ?: return lines |
| 384 | } |
| 385 | if (contentLength > 0) { |
| 386 | val chars = CharArray(contentLength) |
| 387 | var read = 0 |
| 388 | var eof = false |
| 389 | while (read < contentLength && !eof) { |
| 390 | val r = input.read(chars, read, contentLength - read) |
| 391 | if (r < 0) eof = true else read += r |
| 392 | } |
| 393 | lines += String(chars, 0, read) |
| 394 | } |
| 395 | return lines |
| 396 | } |
| 397 | |
| 398 | /** Write a SIP response echoing Via branch / Call-ID / CSeq. */ |
| 399 | private fun respondSip( |
| 400 | out: java.io.OutputStream, |
| 401 | lines: List<String>, |
| 402 | code: Int, |
| 403 | reason: String, |
| 404 | extra: String = "", |
| 405 | ) { |
| 406 | val branch = lines.firstOrNull { it.startsWith("Via:", true) } |
| 407 | ?.substringAfter("branch=")?.substringBefore(";")?.trim().orEmpty() |
| 408 | val callId = lines.firstOrNull { it.startsWith("Call-ID:", true) }.orEmpty() |
| 409 | val cseq = lines.firstOrNull { it.startsWith("CSeq:", true) } |
| 410 | ?.substringAfter(":")?.trim().orEmpty() |
| 411 | out.write( |
| 412 | ("SIP/2.0 $code $reason\r\nVia: SIP/2.0/TCP 127.0.0.1;branch=$branch\r\n" + |
| 413 | "$callId\r\nCSeq: $cseq\r\n$extra" + |
| 414 | "Contact: <sip:127.0.0.1:5060>;expires=600\r\n" + |
| 415 | "Expires: 600\r\nContent-Length: 0\r\n\r\n").toByteArray(Charsets.UTF_8), |
| 416 | ) |
| 417 | out.flush() |
| 418 | } |
| 419 | |
| 420 | // --- Direct SIP over the fake PDN --- |
| 421 | |
| 422 | @Test |
| 423 | fun directSipRegistersAndExchangesMessages() = kotlinx.coroutines.runBlocking { |
| 424 | val server = ServerSocket(0) |
| 425 | val port = server.localPort |
| 426 | // The IMS shadow advertises the P-CSCF on 127.0.0.1:5060; bind there |
| 427 | // instead by pointing the accepted server at the shadow's port. |
| 428 | server.close() |
| 429 | // Port 5060 is shared with the DirectSip test classes, which Gradle |
| 430 | // workers can run concurrently: SO_REUSEADDR covers TIME_WAIT, the |
| 431 | // bounded retry waits out another class's active listen. |
| 432 | val pcscf = bindPcscf5060() |
| 433 | val requests = CopyOnWriteArrayList<String>() |
| 434 | val inboundSent = CountDownLatch(1) |
| 435 | val serverDone = CountDownLatch(1) |
| 436 | Thread { |
| 437 | try { |
| 438 | serveFakePcscf(pcscf, requests, inboundSent) |
| 439 | } catch (e: Throwable) { |
| 440 | requests += "SERVER-ERROR: $e" |
| 441 | } |
| 442 | serverDone.countDown() |
| 443 | }.apply { isDaemon = true; start() } |
| 444 | |
| 445 | // Shadow P-CSCF is 127.0.0.1 (default SIP port on the link props). |
| 446 | val inbound = CopyOnWriteArrayList<Triple<String, String, String>>() |
| 447 | RcsDirectSip.onInboundMessage = { startLine, headers, body -> |
| 448 | inbound += Triple(startLine, headers, body.toString(Charsets.UTF_8)) |
| 449 | } |
| 450 | val started = RcsDirectSip.start(context, 1) |
| 451 | assertTrue(started, "direct SIP did not register: $requests") |
| 452 | assertTrue(RcsDirectSip.isRegistered()) |
| 453 | assertTrue(inboundSent.await(15, TimeUnit.SECONDS)) |
| 454 | val deadline = System.currentTimeMillis() + 15_000 |
| 455 | while (System.currentTimeMillis() < deadline && inbound.isEmpty()) Thread.sleep(25) |
| 456 | assertEquals(1, inbound.size) |
| 457 | assertEquals("hello", inbound.first().third) |
| 458 | assertTrue(inbound.first().first.startsWith("MESSAGE ")) |
| 459 | |
| 460 | val sentOk = RcsDirectSip.sendMessage( |
| 461 | "MESSAGE sip:peer@rcs SIP/2.0", |
| 462 | "To: <sip:peer@rcs>\r\nContent-Type: message/cpim\r\n", |
| 463 | "direct hello".toByteArray(Charsets.UTF_8), |
| 464 | ) |
| 465 | assertTrue(sentOk, "MESSAGE was not acked: $requests") |
| 466 | |
| 467 | RcsDirectSip.stop() |
| 468 | assertFalse(RcsDirectSip.isRegistered()) |
| 469 | assertTrue(serverDone.await(20, TimeUnit.SECONDS), "server: $requests") |
| 470 | val registerWire = requests.first() |
| 471 | assertTrue(registerWire.contains("REGISTER sip:127.0.0.1 SIP/2.0"), registerWire) |
| 472 | assertTrue(registerWire.contains("Expires: 600"), registerWire) |
| 473 | assertTrue(requests.any { it.contains("MESSAGE sip:peer@rcs SIP/2.0") }, requests.toString()) |
| 474 | assertTrue(requests.any { it.contains("expires=0") }, requests.mapIndexed { i, r -> "[$i] $r" }.toString()) |
| 475 | pcscf.close() |
| 476 | Unit |
| 477 | } |
| 478 | } |