286 lines
10 KiB
Kotlin
286 lines
10 KiB
Kotlin
package com.qft.optical
|
|
|
|
import org.junit.Assert.*
|
|
import org.junit.Test
|
|
import java.nio.ByteBuffer
|
|
import java.nio.ByteOrder
|
|
import java.io.ByteArrayInputStream
|
|
import java.util.concurrent.Callable
|
|
import java.util.concurrent.ExecutorCompletionService
|
|
import java.util.concurrent.Executors
|
|
import java.util.zip.CRC32
|
|
|
|
class ProtocolTest {
|
|
@Test
|
|
fun phoneShareHashRequiresTheAdvertisedExactSize() {
|
|
val bytes = "phone-share-stable-snapshot".toByteArray()
|
|
assertEquals(
|
|
"83511688f11a9cb98da9339966f6a0b97e48913102aaad39ae395d2e88f3f65f",
|
|
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong()),
|
|
)
|
|
assertThrows(IllegalArgumentException::class.java) {
|
|
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong() + 1L)
|
|
}
|
|
assertThrows(IllegalArgumentException::class.java) {
|
|
phoneShareSha256Exact(ByteArrayInputStream(bytes), bytes.size.toLong() - 1L)
|
|
}
|
|
}
|
|
|
|
@Test
|
|
fun directDiscoveryCarriesTheAndroidDeviceName() {
|
|
val request = directDiscoveryRequest(
|
|
session = "abcdefghijklmnopqrstuvwxyz012345",
|
|
deviceName = "HUAWEI CDY-AN90",
|
|
).toString(Charsets.US_ASCII)
|
|
val encoded = request.substringAfterLast(':')
|
|
|
|
assertTrue(request.startsWith("QFTDISC2:abcdefghijklmnopqrstuvwxyz012345:"))
|
|
assertEquals("HUAWEI CDY-AN90", Base64Url.decode(encoded)?.toString(Charsets.UTF_8))
|
|
}
|
|
|
|
@Test
|
|
fun dedicatedWifiNeverProbesQrOrComputerLanAddresses() {
|
|
assertEquals(
|
|
listOf("http://192.168.137.1:39393"),
|
|
EndpointRouting.afterConnection(
|
|
dedicatedWifi = true,
|
|
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
|
|
routedAdvertisedEndpoints = listOf(
|
|
"http://192.168.8.162:39393",
|
|
"http://192.168.49.1:39393",
|
|
),
|
|
),
|
|
)
|
|
}
|
|
|
|
@Test
|
|
fun dedicatedWifiRecoveryStillRejectsAdvertisedAndGuessedAddresses() {
|
|
assertEquals(
|
|
listOf("http://192.168.137.1:39393"),
|
|
EndpointRouting.forRecovery(
|
|
dedicatedWifi = true,
|
|
discoveredEndpoint = null,
|
|
gatewayEndpoints = listOf("http://192.168.137.1:39393"),
|
|
advertisedEndpoints = listOf(
|
|
"http://192.168.8.162:39393",
|
|
"http://192.168.49.1:39393",
|
|
),
|
|
),
|
|
)
|
|
}
|
|
|
|
@Test
|
|
fun currentLanModeCanUseSameSubnetAdvertisedAddresses() {
|
|
assertEquals(
|
|
listOf("http://192.168.8.1:39393", "http://192.168.8.162:39393"),
|
|
EndpointRouting.afterConnection(
|
|
dedicatedWifi = false,
|
|
gatewayEndpoints = listOf("http://192.168.8.1:39393"),
|
|
routedAdvertisedEndpoints = listOf("http://192.168.8.162:39393"),
|
|
),
|
|
)
|
|
}
|
|
|
|
@Test
|
|
fun probeCompletionWaitsForARealResultInsteadOfConsumingAnEmptyPoll() {
|
|
val pool = Executors.newSingleThreadExecutor()
|
|
try {
|
|
val completion = ExecutorCompletionService<String?>(pool)
|
|
completion.submit(Callable {
|
|
Thread.sleep(380)
|
|
"http://192.168.137.1:39393"
|
|
})
|
|
|
|
assertEquals(
|
|
"http://192.168.137.1:39393",
|
|
awaitFirstNonNull(completion, submitted = 1, timeoutMs = 800),
|
|
)
|
|
} finally {
|
|
pool.shutdownNow()
|
|
}
|
|
}
|
|
|
|
@Test
|
|
fun probeCompletionKeepsWaitingAfterAnEarlierAddressFails() {
|
|
val pool = Executors.newFixedThreadPool(2)
|
|
try {
|
|
val completion = ExecutorCompletionService<String?>(pool)
|
|
completion.submit(Callable { null })
|
|
completion.submit(Callable {
|
|
Thread.sleep(30)
|
|
"http://192.168.137.1:39393"
|
|
})
|
|
|
|
assertEquals(
|
|
"http://192.168.137.1:39393",
|
|
awaitFirstNonNull(completion, submitted = 2, timeoutMs = 500),
|
|
)
|
|
} finally {
|
|
pool.shutdownNow()
|
|
}
|
|
}
|
|
|
|
@Test
|
|
fun routeCandidatesOnlyKeepEndpointsOnTheActiveSubnet() {
|
|
val endpoints = listOf(
|
|
"http://192.168.137.1:39393",
|
|
"http://192.168.49.1:39393",
|
|
"http://192.168.1.20:39393",
|
|
"http://10.20.30.40:39393",
|
|
)
|
|
|
|
assertEquals(
|
|
listOf("http://192.168.1.20:39393"),
|
|
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
|
)
|
|
assertEquals(
|
|
listOf("http://10.20.30.40:39393"),
|
|
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("10.20.99.2" to 16)),
|
|
)
|
|
}
|
|
|
|
@Test
|
|
fun routeCandidatesRejectWrongPortsAndMalformedAddresses() {
|
|
val endpoints = listOf(
|
|
"http://192.168.1.20:39394",
|
|
"http://192.168.1.999:39393",
|
|
"http://192.168.1.30:39393",
|
|
)
|
|
assertEquals(
|
|
listOf("http://192.168.1.30:39393"),
|
|
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
|
)
|
|
}
|
|
|
|
@Test
|
|
fun parsesPcToPhoneAutomaticDownloadPairing() {
|
|
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":["http://192.168.49.1:39393"],"d":"d","f":"sample.bin","z":42,"h":"${"00".repeat(32)}"}"""
|
|
val text = "QFTSEND2:" + Base64Url.encode(json.toByteArray())
|
|
val payload = PairingProtocol.parse(text)!!
|
|
assertEquals(TransferDirection.DOWNLOAD_TO_PHONE, payload.direction)
|
|
assertEquals("sample.bin", payload.fileName)
|
|
assertEquals(42L, payload.fileSize)
|
|
}
|
|
|
|
@Test
|
|
fun parsesDedicatedWifiPairingWithoutAdvertisedComputerAddresses() {
|
|
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":[],"w":["QFT-DESKTOP-abc123","0123456789abcdef"]}"""
|
|
val payload = PairingProtocol.parse(
|
|
PairingProtocol.PREFIX_V2 + Base64Url.encode(json.toByteArray()),
|
|
)!!
|
|
|
|
assertNotNull(payload.wifi)
|
|
assertEquals("QFT-DESKTOP-abc123", payload.wifi?.ssid)
|
|
assertTrue(payload.endpoints.isEmpty())
|
|
}
|
|
|
|
@Test
|
|
fun androidPhoneShareQrRoundTripsWithoutEmbeddingTheFileQueue() {
|
|
val text = PairingProtocol.encodePhoneShare(
|
|
session = "abcdefghijklmnopqrstuvwxyz012345",
|
|
senderName = "HUAWEI Mate",
|
|
port = 41888,
|
|
endpoints = emptyList(),
|
|
wifi = WifiCredentials("QFT-Android", "0123456789abcdef", "WPA3"),
|
|
)
|
|
val payload = PairingProtocol.parse(text)!!
|
|
|
|
assertTrue(text.startsWith(PairingProtocol.PREFIX_PHONE_V2))
|
|
assertEquals(TransferDirection.PHONE_TO_PHONE, payload.direction)
|
|
assertEquals("HUAWEI Mate", payload.pcName)
|
|
assertEquals("WPA3", payload.wifi?.security)
|
|
assertNull(payload.fileName)
|
|
assertEquals("/qft/download", payload.downloadPath)
|
|
}
|
|
|
|
@Test
|
|
fun androidPhoneShareAcceptsOnlyBoundedByteRanges() {
|
|
assertEquals(0L to 9L, phoneShareRange(null, 10))
|
|
assertEquals(2L to 9L, phoneShareRange("bytes=2-", 10))
|
|
assertEquals(2L to 6L, phoneShareRange("bytes=2-6", 10))
|
|
assertNull(phoneShareRange("bytes=-3", 10))
|
|
assertNull(phoneShareRange("bytes=8-3", 10))
|
|
assertNull(phoneShareRange("bytes=10-", 10))
|
|
assertNull(phoneShareRange("items=0-2", 10))
|
|
}
|
|
|
|
@Test
|
|
fun base45KnownVectors() {
|
|
assertArrayEquals("AB".toByteArray(), Base45.decode("BB8"))
|
|
assertArrayEquals("Hello!!".toByteArray(), Base45.decode("%69 VD92EX0"))
|
|
assertArrayEquals("base-45".toByteArray(), Base45.decode("UJCLQE7W581"))
|
|
}
|
|
|
|
@Test
|
|
fun parsesQft2DataFrameAndRejectsCorruption() {
|
|
val payload = byteArrayOf(1, 2, 3, 4, 5)
|
|
val text = encodeQft2(kind = 2, session = 7L, seq = 9, total = 11, payload = payload)
|
|
val f = QftProtocol.parseText(text)!!
|
|
assertEquals(FrameKind.DATA, f.kind)
|
|
assertEquals(7L, f.sessionId)
|
|
assertEquals(9L, f.seq)
|
|
assertArrayEquals(payload, f.payload)
|
|
|
|
val corrupted = text.dropLast(1) + if (text.last() == '0') "1" else "0"
|
|
assertNull(QftProtocol.parseText(corrupted))
|
|
}
|
|
|
|
@Test
|
|
fun parsesManifestSenderDevice() {
|
|
val name = "test.txt".toByteArray()
|
|
val device = "DESKTOP-ZHY".toByteArray()
|
|
val sha = ByteArray(32) { it.toByte() }
|
|
val payload = ByteBuffer.allocate(8 + 2 + 32 + 2 + name.size + 2 + device.size)
|
|
.order(ByteOrder.BIG_ENDIAN)
|
|
.putLong(1234L)
|
|
.putShort(450.toShort())
|
|
.put(sha)
|
|
.putShort(name.size.toShort())
|
|
.put(name)
|
|
.putShort(device.size.toShort())
|
|
.put(device)
|
|
.array()
|
|
val text = encodeQft2(kind = 1, session = 77L, seq = 0, total = 3, payload = payload)
|
|
val manifest = QftProtocol.parseManifest(QftProtocol.parseText(text)!!)!!
|
|
assertEquals("DESKTOP-ZHY", manifest.senderDevice)
|
|
assertEquals("test.txt", manifest.fileName)
|
|
assertEquals(1234L, manifest.fileSize)
|
|
assertEquals(450, manifest.chunkSize)
|
|
}
|
|
|
|
private fun encodeQft2(kind: Int, session: Long, seq: Int, total: Int, payload: ByteArray): String {
|
|
val bb = ByteBuffer.allocate(24 + payload.size + 4).order(ByteOrder.BIG_ENDIAN)
|
|
bb.put("QFT2".toByteArray())
|
|
bb.put(2)
|
|
bb.put(kind.toByte())
|
|
bb.putLong(session)
|
|
bb.putInt(seq)
|
|
bb.putInt(total)
|
|
bb.putShort(payload.size.toShort())
|
|
bb.put(payload)
|
|
val bodyLen = bb.position()
|
|
val crc = CRC32().apply { update(bb.array(), 0, bodyLen) }.value
|
|
bb.putInt(crc.toInt())
|
|
return "QFT2:" + base45Encode(bb.array())
|
|
}
|
|
|
|
private fun base45Encode(data: ByteArray): String {
|
|
val alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
|
|
val out = StringBuilder((data.size * 3 + 1) / 2)
|
|
var i = 0
|
|
while (i + 1 < data.size) {
|
|
val value = (data[i].toInt() and 0xff) * 256 + (data[i + 1].toInt() and 0xff)
|
|
out.append(alphabet[value % 45])
|
|
out.append(alphabet[(value / 45) % 45])
|
|
out.append(alphabet[value / 2025])
|
|
i += 2
|
|
}
|
|
if (i < data.size) {
|
|
val value = data[i].toInt() and 0xff
|
|
out.append(alphabet[value % 45])
|
|
out.append(alphabet[value / 45])
|
|
}
|
|
return out.toString()
|
|
}
|
|
}
|