diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt index 55aaaab..5637cd1 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipActivity.kt @@ -118,7 +118,7 @@ class GearslipActivity : ComponentActivity(), Projection { GearslipLog.w("accessory detached") deferredAccessory = null // A wireless session has no accessory to lose; leave it running. - if (wirelessSocket == null) closeAccessory() + if (wirelessSocket == null) closeAccessory("the cable was unplugged", goodbye = false) } } } @@ -206,7 +206,7 @@ class GearslipActivity : ComponentActivity(), Projection { setContent { GearslipTheme { - GearslipApp(onDisconnect = { closeAccessory() }, onRequestCallScreening = ::requestCallScreeningRole) + GearslipApp(onDisconnect = { closeAccessory("Disconnect was pressed on the phone") }, onRequestCallScreening = ::requestCallScreeningRole) val offer by offerBluetooth.collectAsState() if (offer) { fun close() { @@ -297,7 +297,7 @@ class GearslipActivity : ComponentActivity(), Projection { CarAudio.onConsentRequested = null CarAudio.release() PhoneMirror.requestStop() - closeAccessory() + closeAccessory("Gearslip's screen on the phone closed") GearslipLog.flush() } @@ -506,7 +506,7 @@ class GearslipActivity : ComponentActivity(), Projection { GearslipLog.i("auto-connect: a session is already running") return } - if (runner != null) closeAccessory(stopWireless = false) + if (runner != null) closeAccessory("a wireless connection takes over", stopWireless = false) if (checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED) { GearslipLog.w("auto-connect: needs the Nearby devices permission") return @@ -531,7 +531,7 @@ class GearslipActivity : ComponentActivity(), Projection { // The cable is here, so a cable-first wait for it is over. cableWait?.let(mainHandler::removeCallbacks) cableWait = null - closeAccessory() + closeAccessory("a new cable connection replaces it") describe(accessory) val manager = getSystemService(UsbManager::class.java) @@ -563,7 +563,7 @@ class GearslipActivity : ComponentActivity(), Projection { /** A wireless session: the same runner, on the socket [WirelessLink] opened to the car. */ private fun startWireless(socket: java.net.Socket) { - closeAccessory(stopWireless = false) + closeAccessory("a wireless connection replaces it", stopWireless = false) if (!AppSettings.gearslipEnabled(this)) { GearslipLog.i("wireless: Gearslip is switched off - not connecting") runCatching { socket.close() } @@ -604,11 +604,13 @@ class GearslipActivity : ComponentActivity(), Projection { GearslipLog.i(" version=${accessory.version} description=${accessory.description}") } - private fun closeAccessory() = closeAccessory(stopWireless = true) - - /** Ends the session, wired or wireless. [stopWireless] also drops the car's Bluetooth and Wi-Fi. */ - private fun closeAccessory(stopWireless: Boolean) { - runner?.stop() + /** + * Ends the session, wired or wireless, for [why], which goes to the log. [goodbye] tells a car + * still in the session first (see [GearslipRunner.stop]); [stopWireless] also drops the car's + * Bluetooth and Wi-Fi. + */ + private fun closeAccessory(why: String, goodbye: Boolean = true, stopWireless: Boolean = true) { + runner?.stop(why, goodbye) SessionReport.print() runCatching { descriptor?.close() } descriptor = null diff --git a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt index 35cd52e..718fcc0 100644 --- a/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt +++ b/gearslip/src/main/java/app/seb3thehacker/gearslip/GearslipRunner.kt @@ -21,6 +21,7 @@ import java.io.IOException import app.seb3thehacker.gearslip.protocol.InputProtocol import java.io.InputStream import java.io.OutputStream +import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.FutureTask import java.util.concurrent.RejectedExecutionException @@ -193,7 +194,18 @@ class GearslipRunner( } } - fun stop() { + /** + * Ends the session from the phone's side, for [why]. With [goodbye], a car in the middle of a + * session is told first, as Android Auto does: a head unit that wasn't kept on sending into + * the next connection, which then never got its VersionRequest until the cable was pulled. + * No goodbye when the cable is already gone: there is nobody to tell. + */ + fun stop(why: String = "Gearslip ended it", goodbye: Boolean = true) { + if (goodbye && running && !stopped && (state == State.DONE || state == State.WAIT_SDR)) { + sayGoodbye(why) + } else { + log.i("ending the session: $why") + } stopped = true running = false writer.shutdownNow() @@ -230,12 +242,49 @@ class GearslipRunner( SessionStatus.disconnected() } + /** Set while [sayGoodbye] waits for the car's ByeByeResponse. */ + @Volatile private var goodbyeAnswer: CountDownLatch? = null + + /** ByeByeRequest(USER_SELECTION), then a short wait for the car to close its side. */ + private fun sayGoodbye(why: String) { + val answer = CountDownLatch(1) + goodbyeAnswer = answer + log.i("-> ByeByeRequest(USER_SELECTION): $why") + send(MSG_BYEBYE_REQUEST, Protobuf.varintField(1, BYEBYE_USER_SELECTION), encrypted = true) + val answered = answer.await(GOODBYE_WAIT_MS, TimeUnit.MILLISECONDS) + goodbyeAnswer = null + log.i(if (answered) "<- ByeByeResponse: the car closed its side" else "no ByeByeResponse after ${GOODBYE_WAIT_MS}ms - closing anyway") + } + + /** Frames from a connection before this one, and the goodbyes sent to end it. */ + private var staleFrames = 0 + private var staleGoodbyes = 0 + private var lastStaleGoodbyeAt = 0L + + /** + * Encrypted frames before this connection has said hello: the car is still in an older one, + * closed on the phone without telling it. Its keys are gone, so the car is told in the clear + * that it's over, a few times at most, and this connection waits for the VersionRequest the + * car sends when it starts again. Unplugging did the same, and an app can't unplug the cable. + */ + private fun onStaleFrame() { + staleFrames++ + if (staleFrames == 1) log.w("the car is still talking in an earlier connection - telling it that one is over") + val now = System.currentTimeMillis() + if (staleGoodbyes >= MAX_STALE_GOODBYES || now - lastStaleGoodbyeAt < STALE_GOODBYE_GAP_MS) return + staleGoodbyes++ + lastStaleGoodbyeAt = now + send(MSG_BYEBYE_REQUEST, Protobuf.varintField(1, BYEBYE_USER_SELECTION), encrypted = false) + log.i("-> ByeByeRequest(USER_SELECTION) in the clear, for the earlier connection ($staleGoodbyes of $MAX_STALE_GOODBYES, $staleFrames old frames so far)") + } + private fun handleFrame(frame: Frames.Frame) { // A rejected handshake cannot consume later messages as if authentication succeeded. if (authenticationFailed || stopped || !running) return val payload = if (frame.encrypted) { if (!tls.handshakeComplete) { - log.w("encrypted frame arrived before the handshake finished - ignoring") + if (state == State.WAIT_VERSION) onStaleFrame() + else log.w("encrypted frame arrived before the handshake finished - ignoring") return } tls.decrypt(frame.payload) @@ -301,7 +350,7 @@ class GearslipRunner( return } if (messageId !in setOf(MSG_VERSION_REQUEST, MSG_ENCAPSULATED_SSL, MSG_AUTH_COMPLETE, - MSG_BYEBYE_REQUEST, MSG_UNEXPECTED_MESSAGE, MSG_FRAMING_ERROR) && + MSG_BYEBYE_REQUEST, MSG_BYEBYE_RESPONSE, MSG_UNEXPECTED_MESSAGE, MSG_FRAMING_ERROR) && (!frame.encrypted || state != State.DONE && state != State.WAIT_SDR)) return when (messageId) { @@ -312,6 +361,7 @@ class GearslipRunner( MSG_PING_REQUEST -> onPingRequest(body) MSG_PING_RESPONSE -> onPingResponse() MSG_BYEBYE_REQUEST -> onByeByeRequest(body) + MSG_BYEBYE_RESPONSE -> goodbyeAnswer?.countDown() ?: log.i("<- ByeByeResponse") MSG_UNEXPECTED_MESSAGE, MSG_FRAMING_ERROR -> onProtocolError(messageId) AudioLink.MSG_FOCUS_RESPONSE -> { // One answer for both sinks: it is the directions' while they wait on one. @@ -1720,6 +1770,12 @@ class GearslipRunner( private const val PING_LOG_EVERY = 60 const val MSG_BYEBYE_REQUEST = 15 const val MSG_BYEBYE_RESPONSE = 16 + const val BYEBYE_USER_SELECTION = 1L + /** How long a goodbye waits for the car's answer; the phone's screen waits with it. */ + const val GOODBYE_WAIT_MS = 400L + /** Goodbyes to a car stuck in an earlier connection, and the gap between them. */ + const val MAX_STALE_GOODBYES = 3 + const val STALE_GOODBYE_GAP_MS = 3_000L const val MSG_VOICE_SESSION_NOTIFICATION = 17 const val MSG_UNEXPECTED_MESSAGE = 255 const val MSG_FRAMING_ERROR = 65535 diff --git a/gearslip/src/test/java/app/seb3thehacker/gearslip/StaleCarTest.kt b/gearslip/src/test/java/app/seb3thehacker/gearslip/StaleCarTest.kt new file mode 100644 index 0000000..10bff3a --- /dev/null +++ b/gearslip/src/test/java/app/seb3thehacker/gearslip/StaleCarTest.kt @@ -0,0 +1,88 @@ +package app.seb3thehacker.gearslip + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A head unit kept sending encrypted frames from a connection Gearslip had closed without telling + * it, and the new connection waited for a VersionRequest that never came, until the cable was + * pulled. Gearslip should tell the car the old connection is over, once and in the clear, as the + * old one's keys are gone, and carry on as normal when the car starts again. + */ +class StaleCarTest { + + private fun message(id: Int, body: ByteArray = byteArrayOf(), encrypted: Boolean = false) = Frames.build( + Frames.CHANNEL_CONTROL, encrypted, byteArrayOf((id ushr 8).toByte(), id.toByte()) + body, + ) + + /** Frames from the old connection: encrypted, and meaningless to a new one. */ + private fun stale(count: Int) = (1..count).fold(byteArrayOf()) { all, i -> + all + Frames.build(3, true, ByteArray(32) { (it + i).toByte() }) + } + + private val version = message(1, byteArrayOf(0, 1, 0, 3)) + + private fun identity(): CertProvider.Identity { + val generated = SelfSignedCert.generate() + return CertProvider.Identity(generated.keyStore, generated.certificate, SelfSignedCert.PASSWORD, "test") + } + + /** Runs a connection on [input] and returns the messages Gearslip sent, as (id, encrypted, body). */ + private fun sent(input: ByteArray, also: (GearslipRunner) -> Unit = {}): List> { + val output = ByteArrayOutputStream() + val runner = GearslipRunner(ByteArrayInputStream(input), output, ::identity) + // Let what was sent reach the output before the connection closes. + GearslipRunner::class.java.getDeclaredField("drainWriterOnExit").apply { isAccessible = true }.setBoolean(runner, true) + also(runner) + runner.run() + val parser = Frames.Parser() + parser.append(output.toByteArray(), output.size()) + return generateSequence { parser.next() }.map { f -> + val id = ((f.payload[0].toInt() and 0xFF) shl 8) or (f.payload[1].toInt() and 0xFF) + Triple(id, f.encrypted, f.payload.copyOfRange(2, f.payload.size)) + }.toList() + } + + @Test + fun aCarStillInTheOldConnectionIsToldItIsOver() { + val out = sent(stale(5)) + val bye = out.single { it.first == MSG_BYEBYE_REQUEST } + assertFalse("sent in the clear: the old connection's keys are gone", bye.second) + assertEquals(1L, Protobuf.readInt32Field(bye.third, 1)?.toLong()) + } + + @Test + fun manyOldFramesGetOneGoodbyeNotOneEach() { + val out = sent(stale(200)) + assertEquals(1, out.count { it.first == MSG_BYEBYE_REQUEST }) + } + + @Test + fun theCarStartingOverAfterTheGoodbyeConnectsAsNormal() { + val out = sent(stale(5) + version) + assertTrue("goodbye first: $out", out.first().first == MSG_BYEBYE_REQUEST) + assertTrue("then the version answer: ${out.map { it.first }}", out.any { it.first == MSG_VERSION_RESPONSE }) + } + + @Test + fun aFreshCarGetsNoGoodbye() { + val out = sent(version) + assertTrue(out.none { it.first == MSG_BYEBYE_REQUEST }) + } + + @Test + fun endingAConnectionTheCarNeverStartedSaysNoGoodbye() { + // Before the secure session is up there is nothing for the car to close. + val out = sent(byteArrayOf()) { it.stop("a test ended it") } + assertTrue(out.none { it.first == MSG_BYEBYE_REQUEST }) + } + + private companion object { + const val MSG_VERSION_RESPONSE = 2 + const val MSG_BYEBYE_REQUEST = 15 + } +}