Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

fix(android): Elevated no longer asks to choose a device on Android 17

Bee13f86053d89a
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
index a8d0eb9..9c3ee32 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
@@ -26,6 +26,7 @@ import io.github.muntashirakon.adb.AbsAdbConnectionManager
import io.github.muntashirakon.adb.AdbPairingRequiredException
import io.github.muntashirakon.adb.AdbStream
import io.github.muntashirakon.adb.android.AdbMdns
+import kotlin.concurrent.thread
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -254,15 +255,23 @@ object Elevated {
suspend fun pair(code: String): Boolean = withContext(Dispatchers.IO) {
lock.withLock {
_state.value = State.Starting
- val port = discover(AdbMdns.SERVICE_TYPE_TLS_PAIRING)
- if (port == null) {
+ val paired = if (LoopbackAdb.preferred()) {
+ pairOverLoopback(code.trim())
+ } else {
+ val port = discover(AdbMdns.SERVICE_TYPE_TLS_PAIRING)
+ if (port == null) {
+ null
+ } else {
+ runCatching { connection().pair("127.0.0.1", port, code.trim()) }.getOrElse {
+ Log.w(TAG, "pairing failed", it)
+ false
+ }
+ }
+ }
+ if (paired == null) {
_state.value = State.Failed(Reason.NoPairingDialog)
return@withContext false
}
- val paired = runCatching { connection().pair("127.0.0.1", port, code.trim()) }.getOrElse {
- Log.w(TAG, "pairing failed", it)
- false
- }
if (!paired) {
_state.value = State.Failed(Reason.WrongCode)
return@withContext false
@@ -272,6 +281,54 @@ object Elevated {
start()
}
+ /**
+ * Connects to wireless debugging found on 127.0.0.1 (Android 17 and later,
+ * see [LoopbackAdb]), waiting a moment for it to start listening.
+ */
+ private suspend fun connectOverLoopback(adb: Connection): Boolean {
+ val deadline = System.currentTimeMillis() + CONNECT_MS
+ while (true) {
+ val port = LoopbackAdb.connectPort(LoopbackAdb.openPorts())
+ if (port != null) return adb.connect(LoopbackAdb.HOST, port)
+ if (System.currentTimeMillis() >= deadline) return false
+ delay(LOOPBACK_RETRY_MS)
+ }
+ }
+
+ /**
+ * Pairs through the pairing port found on 127.0.0.1: any listening port
+ * that isn't adbd's connection port. `null` when there is none (the
+ * pairing dialog isn't open).
+ */
+ private suspend fun pairOverLoopback(code: String): Boolean? {
+ val deadline = System.currentTimeMillis() + DISCOVERY_MS
+ while (true) {
+ val open = LoopbackAdb.openPorts()
+ val connectPort = LoopbackAdb.connectPort(open)
+ val candidates = open.filter { it != connectPort }
+ for (port in candidates) {
+ if (pairOnPort(port, code)) return true
+ }
+ if (candidates.isNotEmpty()) return false
+ if (System.currentTimeMillis() >= deadline) return null
+ delay(LOOPBACK_RETRY_MS)
+ }
+ }
+
+ /** One pairing attempt, given up after [PAIR_MS] (a port that isn't adb's may never answer). */
+ private suspend fun pairOnPort(port: Int, code: String): Boolean {
+ val result = CompletableDeferred<Boolean>()
+ thread(isDaemon = true, name = "adb-pair") {
+ result.complete(
+ runCatching { connection().pair(LoopbackAdb.HOST, port, code) }.getOrElse {
+ Log.i(TAG, "no pairing on port $port", it)
+ false
+ },
+ )
+ }
+ return withTimeoutOrNull(PAIR_MS) { result.await() } ?: false
+ }
+
/** The port a wireless debugging service is announced on, if it shows up soon. */
private suspend fun discover(service: String): Int? {
val found = CompletableDeferred<Int>()
@@ -314,7 +371,7 @@ object Elevated {
discardConnection()
val adb = connection()
val connected = try {
- adb.connectTls(context, CONNECT_MS)
+ if (LoopbackAdb.preferred()) connectOverLoopback(adb) else adb.connectTls(context, CONNECT_MS)
} catch (e: AdbPairingRequiredException) {
// adbd forgot us (the user revoked the authorizations).
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { putBoolean(PAIRED, false) }
@@ -830,6 +887,8 @@ object Elevated {
private const val ADB_WIFI = "adb_wifi_enabled"
private const val DISCOVERY_MS = 10_000L
+ private const val LOOPBACK_RETRY_MS = 700L
+ private const val PAIR_MS = 4_000L
private const val CONNECT_MS = 10_000L
/** How long a `su` command may take; the first one waits for the root manager's prompt. */
private const val SU_WAIT_S = 30L
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/LoopbackAdb.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/LoopbackAdb.kt
new file mode 100644
index 0000000..cc19b9b
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/LoopbackAdb.kt
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.elevated
+
+import android.os.Build
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.withContext
+import java.io.DataInputStream
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/**
+ * Finds wireless debugging's ports on this phone without searching the
+ * network. adbd listens on random ports in Linux's ephemeral range, which
+ * the usual mDNS lookup finds; from Android 17 that lookup makes the system
+ * ask the user to choose a device each time (local network protection), even
+ * though the ports are on this phone. So the ports on 127.0.0.1 are tried
+ * instead, which isn't the local network and asks nobody.
+ */
+internal object LoopbackAdb {
+ const val HOST = "127.0.0.1"
+
+ /** Where Linux picks listening ports nobody asked a number for. */
+ private val EPHEMERAL = 32768..60999
+
+ /** NectarLink's own fixed ports (LocalSend, USB), never adbd's. */
+ private val OWN = 53317..53322
+
+ private const val OPEN_MS = 50
+ private const val ANSWER_MS = 500
+ private const val SCANNERS = 32
+
+ /** Whether to use this instead of mDNS: Android 17 and later (API 37). */
+ fun preferred(): Boolean = Build.VERSION.SDK_INT >= 37
+
+ /** The ports listening on 127.0.0.1 in the ephemeral range, except NectarLink's own. */
+ suspend fun openPorts(): List<Int> = withContext(Dispatchers.IO) {
+ val ports = EPHEMERAL.filterNot { it in OWN }
+ coroutineScope {
+ ports.chunked(ports.size / SCANNERS + 1)
+ .map { chunk -> async { chunk.filter(::isOpen) } }
+ .awaitAll()
+ .flatten()
+ }
+ }
+
+ /** adbd's port for connecting (it answers an adb hello), among [open]. */
+ suspend fun connectPort(open: List<Int>): Int? = withContext(Dispatchers.IO) {
+ open.firstOrNull(::answersLikeAdbd)
+ }
+
+ private fun isOpen(port: Int): Boolean = runCatching {
+ Socket().use { it.connect(InetSocketAddress(HOST, port), OPEN_MS) }
+ true
+ }.getOrDefault(false)
+
+ /** Sends adb's opening CNXN message and checks the reply is adb's. */
+ private fun answersLikeAdbd(port: Int): Boolean = runCatching {
+ Socket().use { socket ->
+ socket.connect(InetSocketAddress(HOST, port), ANSWER_MS)
+ socket.soTimeout = ANSWER_MS
+ socket.getOutputStream().apply {
+ write(hello())
+ flush()
+ }
+ val header = ByteArray(HEADER_BYTES)
+ DataInputStream(socket.getInputStream()).readFully(header)
+ isAdbReply(header)
+ }
+ }.getOrDefault(false)
+
+ private const val HEADER_BYTES = 24
+ private const val A_CNXN = 0x4e584e43
+ private const val A_AUTH = 0x48545541
+ private const val A_STLS = 0x534c5453
+ private const val VERSION = 0x01000001
+ private const val MAX_DATA = 256 * 1024
+
+ /** adb's CNXN message (`host::`), as a client sends it first. */
+ internal fun hello(): ByteArray {
+ val payload = "host::\u0000".toByteArray(Charsets.US_ASCII)
+ val checksum = payload.sumOf { it.toInt() and 0xff }
+ return ByteBuffer.allocate(HEADER_BYTES + payload.size).order(ByteOrder.LITTLE_ENDIAN)
+ .putInt(A_CNXN)
+ .putInt(VERSION)
+ .putInt(MAX_DATA)
+ .putInt(payload.size)
+ .putInt(checksum)
+ .putInt(A_CNXN.inv())
+ .put(payload)
+ .array()
+ }
+
+ /** Whether a 24-byte message header is adbd answering a hello. */
+ internal fun isAdbReply(header: ByteArray): Boolean {
+ if (header.size < HEADER_BYTES) return false
+ val fields = ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN)
+ val command = fields.getInt(0)
+ val magic = fields.getInt(20)
+ return command in setOf(A_STLS, A_AUTH, A_CNXN) && magic == command.inv()
+ }
+}
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/elevated/LoopbackAdbTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/elevated/LoopbackAdbTest.kt
new file mode 100644
index 0000000..5193ec4
--- /dev/null
+++ b/android/app/src/test/kotlin/app/nectarlink/android/elevated/LoopbackAdbTest.kt
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.elevated
+
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.DataInputStream
+import java.net.InetAddress
+import java.net.ServerSocket
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import kotlin.concurrent.thread
+
+class LoopbackAdbTest {
+ private fun header(command: Int, magic: Int = command.inv()): ByteArray =
+ ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
+ .putInt(command).putInt(0).putInt(0).putInt(0).putInt(0).putInt(magic)
+ .array()
+
+ @Test
+ fun helloIsAnAdbConnectMessage() {
+ val hello = LoopbackAdb.hello()
+ val fields = ByteBuffer.wrap(hello).order(ByteOrder.LITTLE_ENDIAN)
+ assertEquals("CNXN", String(hello, 0, 4, Charsets.US_ASCII))
+ assertEquals(fields.getInt(0).inv(), fields.getInt(20))
+ assertEquals(hello.size - 24, fields.getInt(12))
+ assertEquals("host::\u0000", String(hello, 24, hello.size - 24, Charsets.US_ASCII))
+ }
+
+ @Test
+ fun onlyAdbRepliesCount() {
+ assertTrue(LoopbackAdb.isAdbReply(header(0x534c5453))) // STLS: wireless debugging wants TLS
+ assertTrue(LoopbackAdb.isAdbReply(header(0x48545541))) // AUTH
+ assertFalse(LoopbackAdb.isAdbReply(header(0x534c5453, magic = 0)))
+ assertFalse(LoopbackAdb.isAdbReply("HTTP/1.1 400 Bad Request\r\n".toByteArray()))
+ assertFalse(LoopbackAdb.isAdbReply(ByteArray(3)))
+ }
+
+ /** A loopback server on a port in the range adbd uses, answering each client with [reply]. */
+ private fun server(reply: ByteArray): ServerSocket {
+ val socket = (40_000..50_000).asSequence()
+ .mapNotNull { runCatching { ServerSocket(it, 4, InetAddress.getByName(LoopbackAdb.HOST)) }.getOrNull() }
+ .first()
+ thread(isDaemon = true) {
+ while (!socket.isClosed) {
+ val client = runCatching { socket.accept() }.getOrNull() ?: break
+ client.use {
+ runCatching {
+ DataInputStream(it.getInputStream()).readFully(ByteArray(24))
+ it.getOutputStream().write(reply)
+ it.getOutputStream().flush()
+ }
+ }
+ }
+ }
+ return socket
+ }
+
+ @Test
+ fun findsTheServerThatAnswersLikeAdbd() = runBlocking {
+ server(header(0x534c5453)).use { adbd ->
+ server("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n".toByteArray()).use { other ->
+ assertEquals(adbd.localPort, LoopbackAdb.connectPort(listOf(other.localPort, adbd.localPort)))
+ assertNull(LoopbackAdb.connectPort(listOf(other.localPort)))
+ assertTrue(LoopbackAdb.openPorts().containsAll(listOf(adbd.localPort, other.localPort)))
+ }
+ }
+ }
+}