Skip to content

Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.

Pair: use the pairing port the TV advertises now, not the one from the scan

jesse-agent-3625a86705cadbe
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
index d57c0b8..984ce97 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
@@ -36,6 +36,20 @@ sealed interface PairResult {
data class Unreachable(val reason: String) : PairResult
}
+/**
+ * Pairs on the port the TV advertises now: [find] browses for it first, and [hint] (a port seen in an
+ * earlier scan, or one the user typed) is only the fallback, since every reopen of the TV's pairing
+ * dialog picks a new port. A refused port gets one more browse before giving up. Never guesses the
+ * connect port: that one doesn't answer pairing.
+ */
+suspend fun pairOnFreshPort(hint: Int?, find: suspend () -> Int?, pair: suspend (Int) -> PairResult): PairResult {
+ val port = find() ?: hint
+ ?: return PairResult.Unreachable("the TV isn't offering pairing; keep \"Pair device with pairing code\" open on it")
+ val r = pair(port)
+ if (r !is PairResult.Unreachable) return r
+ return find()?.takeIf { it != port }?.let { pair(it) } ?: r
+}
+
/**
* Opens ADB connections with one persisted host key, so the TV's "always allow" survives restarts.
* Call [init] once per process before anything else.
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/LanScanner.kt b/adb/src/main/kotlin/app/tellyscope/adb/LanScanner.kt
index 80c78d8..5d5658f 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/LanScanner.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/LanScanner.kt
@@ -8,6 +8,8 @@ import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
@@ -92,6 +94,24 @@ class LanScanner(
}
}
+ /**
+ * The port [host] advertises for "pair with code" right now, or null when none shows up within the
+ * mDNS window. The TV only advertises it while that dialog is open, and picks a new one each time.
+ */
+ suspend fun pairingPort(host: String): Int? {
+ val mdns = mdns ?: return null
+ withContext(Dispatchers.IO) { mdns.start() }
+ return try {
+ withTimeoutOrNull(mdnsWindow) {
+ mdns.state.mapNotNull { s ->
+ s.allDevices.firstOrNull { it.host == host && it.serviceType == MdnsServiceType.TLS_PAIRING }?.port
+ }.first()
+ }
+ } finally {
+ withContext(NonCancellable + Dispatchers.IO) { mdns.stop() }
+ }
+ }
+
private fun isOpen(host: String): Boolean = try {
Socket().use { it.connect(InetSocketAddress(host, port), probeTimeout.inWholeMilliseconds.toInt()); true }
} catch (_: Exception) {
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/PairingPortTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/PairingPortTest.kt
new file mode 100644
index 0000000..b7f7a80
--- /dev/null
+++ b/adb/src/test/kotlin/app/tellyscope/adb/PairingPortTest.kt
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package app.tellyscope.adb
+
+import com.flyfishxu.kadb.mdns.KadbMdns
+import com.flyfishxu.kadb.mdns.MdnsDiscoveryState
+import com.flyfishxu.kadb.mdns.MdnsEndpoint
+import com.flyfishxu.kadb.mdns.MdnsServiceType
+import com.flyfishxu.kadb.mdns.MdnsStatus
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.runBlocking
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertIs
+import kotlin.test.assertNull
+import kotlin.time.Duration.Companion.milliseconds
+
+/** mDNS that already sees [endpoints]. */
+private class FakeMdns(vararg endpoints: MdnsEndpoint) : KadbMdns {
+ override val state = MutableStateFlow(
+ MdnsDiscoveryState(MdnsStatus.STARTED, false, endpoints.filter { it.serviceType == MdnsServiceType.TLS_CONNECT }, endpoints.filter { it.serviceType == MdnsServiceType.TLS_PAIRING }),
+ )
+ var running = false
+ override fun start() { running = true }
+ override fun stop() { running = false }
+}
+
+class PairingPortTest {
+ private val tv = "192.0.2.30"
+
+ /** Pairs only on [open]; every other port refuses. Records the ports tried. */
+ private class Tv(private val open: Int) {
+ val tried = mutableListOf<Int>()
+ suspend fun pair(port: Int): PairResult {
+ tried += port
+ return if (port == open) PairResult.Paired else PairResult.Unreachable("Connection refused")
+ }
+ }
+
+ @Test fun findsThePairingPortForThatTvOnly() = runBlocking {
+ val mdns = FakeMdns(
+ MdnsEndpoint("adb-other", "192.0.2.31", 37001, MdnsServiceType.TLS_PAIRING),
+ MdnsEndpoint("adb-tv", tv, 46237, MdnsServiceType.TLS_CONNECT),
+ MdnsEndpoint("adb-tv", tv, 41089, MdnsServiceType.TLS_PAIRING),
+ )
+ assertEquals(41089, LanScanner(mdns, mdnsWindow = 200.milliseconds).pairingPort(tv))
+ assertFalse(mdns.running)
+ }
+
+ @Test fun noPairingDialogMeansNoPort() = runBlocking {
+ val mdns = FakeMdns(MdnsEndpoint("adb-tv", tv, 46237, MdnsServiceType.TLS_CONNECT))
+ assertNull(LanScanner(mdns, mdnsWindow = 200.milliseconds).pairingPort(tv))
+ assertFalse(mdns.running)
+ }
+
+ @Test fun unknownPortIsFoundAtPairTime() = runBlocking {
+ val t = Tv(open = 41089)
+ assertEquals(PairResult.Paired, pairOnFreshPort(hint = null, find = { 41089 }, pair = t::pair))
+ assertEquals(listOf(41089), t.tried)
+ }
+
+ @Test fun aFreshPortBeatsTheCachedOne() = runBlocking {
+ val t = Tv(open = 40211)
+ assertEquals(PairResult.Paired, pairOnFreshPort(hint = 41089, find = { 40211 }, pair = t::pair))
+ assertEquals(listOf(40211), t.tried)
+ }
+
+ @Test fun cachedPortRefusedThenAFreshOneIsFound() = runBlocking {
+ // The first browse misses; the dialog was reopened, so the cached port is gone.
+ val finds = ArrayDeque(listOf(null, 40211))
+ val t = Tv(open = 40211)
+ assertEquals(PairResult.Paired, pairOnFreshPort(hint = 41089, find = { finds.removeFirst() }, pair = t::pair))
+ assertEquals(listOf(41089, 40211), t.tried)
+ }
+
+ @Test fun nothingAdvertisedAndNoHintNeverTriesTheConnectPort() = runBlocking {
+ val t = Tv(open = 46237)
+ assertIs<PairResult.Unreachable>(pairOnFreshPort(hint = null, find = { null }, pair = t::pair))
+ assertEquals(emptyList(), t.tried)
+ }
+
+ @Test fun aWrongCodeIsNotRetried() = runBlocking {
+ var finds = 0
+ val r = pairOnFreshPort(hint = null, find = { finds++; 41089 }, pair = { PairResult.WrongCode("bad code") })
+ assertEquals(PairResult.WrongCode("bad code"), r)
+ assertEquals(1, finds)
+ }
+}
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index 8eb694c..99f0ca2 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -28,6 +28,7 @@ import app.tellyscope.adb.ProtectedReason
import app.tellyscope.adb.Remote
import app.tellyscope.adb.RemoteKey
import app.tellyscope.adb.PairResult
+import app.tellyscope.adb.pairOnFreshPort
import app.tellyscope.adb.Tweak
import app.tellyscope.adb.Tweaks
import com.flyfishxu.kadb.mdns.KadbMdnsAndroid
@@ -208,7 +209,14 @@ class AdbDeviceSource(context: Context) : DeviceSource {
}
override suspend fun pair(hit: ScanHit, code: String): ConnectResult {
- when (val r = Connector.pair(hit.ip, pairingPorts[hit.ip] ?: hit.port, code)) {
+ // A port typed for add-by-IP, else the last one a scan saw; never the connect port.
+ val hint = hit.port.takeIf { it != hits[hit.ip]?.port } ?: pairingPorts[hit.ip]
+ val r = pairOnFreshPort(
+ hint,
+ find = { LanScanner(KadbMdnsAndroid(appContext)).pairingPort(hit.ip) },
+ pair = { Connector.pair(hit.ip, it, code) },
+ )
+ when (r) {
PairResult.Paired -> Unit
is PairResult.WrongCode -> return ConnectResult.WrongCode(r.reason)
is PairResult.Unreachable -> return ConnectResult.Unreachable(r.reason)