Modern Apps git

← Modern-Apps.git

auto: GAL frame codec, transport interface and control session

Commit
baa8037c9fffc491ed7f644f6c0b9b002c5117a0
Author
vayun-mathur <[email protected]>
When
2026-09-12 01:31 UTC (2 months ago)
Parents
dc060f0

Diff

auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameReader.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameReader.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameReader.ktnew file mode 100644index 0000000000..beed2f2645--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameReader.kt@@ -0,0 +1,106 @@+package com.vayunmathur.auto.protocol++import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer++/** A message reassembled from one or more frames, ready for [MessageCodec.decode]. */+class ReassembledMessage(+    val channelId: Int,+    val isControl: Boolean,+    val payload: ByteArray,+)++/**+ * Turns a byte stream into whole GAL messages.+ *+ * Feed it whatever the transport hands over — the boundaries are arbitrary and a single+ * read can contain half a header or several frames — and it emits messages once their last+ * fragment arrives.+ *+ * Decryption happens per frame, before reassembly, which is the order gearhead uses: the+ * frame's length field counts ciphertext, while the reassembly buffer accumulates plaintext.+ * Getting that backwards would size the buffer against the wrong number.+ *+ * @param decrypt unwraps one frame payload. The default is identity, for the plaintext+ *   frames exchanged before the TLS handshake completes and for tests.+ */+class FrameReader(+    private val decrypt: (ByteArray) -> ByteArray = { it },+) {+    private var pending = ByteBuffer.allocate(0)+    private val partial = mutableMapOf<Int, ByteArrayOutputStream>()++    /** Appends [count] bytes from [bytes] and returns whatever became complete. */+    fun offer(bytes: ByteArray, offset: Int = 0, count: Int = bytes.size): List<ReassembledMessage> {+        append(bytes, offset, count)+        val completed = mutableListOf<ReassembledMessage>()+        while (true) {+            completed += takeFrame() ?: break+        }+        return completed+    }++    private fun append(bytes: ByteArray, offset: Int, count: Int) {+        val combined = ByteBuffer.allocate(pending.remaining() + count)+        combined.put(pending)+        combined.put(bytes, offset, count)+        combined.flip()+        pending = combined+    }++    /**+     * Consumes one frame if a whole one is buffered.+     *+     * @return the message if that frame completed one, null if more bytes are needed or the+     *   frame was a non-final fragment.+     */+    private fun takeFrame(): ReassembledMessage? {+        if (pending.remaining() < FrameHeader.SHORT_HEADER_SIZE) return null++        pending.mark()+        val header = FrameHeader.readFrom(pending)+        if (pending.remaining() < header.payloadLength) {+            // Not all here yet; rewind and wait for more.+            pending.reset()+            return null+        }++        val raw = ByteArray(header.payloadLength)+        pending.get(raw)+        compact()++        val plaintext = if (header.isEncrypted) decrypt(raw) else raw++        if (header.isFirst && header.isLast) {+            return ReassembledMessage(header.channelId, header.isControl, plaintext)+        }++        // `totalLength` is only a capacity hint. The stream grows as needed rather than+        // trusting it, because the field counts one of plaintext or ciphertext depending on+        // where you read it and being wrong there would truncate a message.+        val buffer = partial.getOrPut(header.channelId) {+            ByteArrayOutputStream(header.totalLength ?: plaintext.size)+        }+        buffer.write(plaintext)++        if (!header.isLast) return null+        partial.remove(header.channelId)+        return ReassembledMessage(header.channelId, header.isControl, buffer.toByteArray())+    }++    /** Drops consumed bytes so [pending] does not grow without bound. */+    private fun compact() {+        pending = if (pending.hasRemaining()) {+            ByteBuffer.allocate(pending.remaining()).put(pending).also { it.flip() }+        } else {+            EMPTY+        }+    }++    /** True when a fragmented message is still being assembled on some channel. */+    val hasPartialMessages: Boolean get() = partial.isNotEmpty()++    private companion object {+        val EMPTY: ByteBuffer = ByteBuffer.allocate(0)+    }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameWriter.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameWriter.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameWriter.ktnew file mode 100644index 0000000000..9d93b66311--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameWriter.kt@@ -0,0 +1,56 @@+package com.vayunmathur.auto.protocol++import java.nio.ByteBuffer++/**+ * Turns a whole message into frames on the wire.+ *+ * The counterpart to [FrameReader]. Encryption is applied per fragment, after splitting, so+ * the length written into each header is the ciphertext length while the fragment sizes are+ * chosen against plaintext — see [Fragmenter] for why the default fragment size leaves+ * headroom for the TLS record overhead.+ *+ * @param encrypt wraps one fragment payload. The default is identity, for the plaintext+ *   frames exchanged before the handshake completes and for tests.+ */+class FrameWriter(+    private val maxFrameSize: Int = FrameHeader.DEFAULT_MAX_FRAME_SIZE,+    private val encrypt: (ByteArray) -> ByteArray = { it },+) {++    /**+     * Splits [payload] into complete frames, headers included.+     *+     * @param encrypted whether to mark and encrypt the payload. Kept separate from the+     *   presence of an [encrypt] function so the handshake frames, which travel in the clear+     *   on an otherwise-encrypted session, are explicit at the call site.+     */+    fun frame(+        channelId: Int,+        payload: ByteArray,+        isControl: Boolean = false,+        encrypted: Boolean = false,+    ): List<ByteArray> = Fragmenter+        .split(payload.size, maxFrameSize, isControl)+        .map { fragment ->+            val slice = payload.copyOfRange(fragment.offset, fragment.offset + fragment.length)+            val body = if (encrypted) encrypt(slice) else slice++            var flags = fragment.positionFlags+            if (isControl) flags = flags or FrameFlags.CONTROL+            if (encrypted) flags = flags or FrameFlags.ENCRYPTED++            val header = FrameHeader(+                channelId = channelId,+                flags = flags,+                payloadLength = body.size,+                // Only the first fragment of a fragmented message carries it.+                totalLength = if (fragment.isFirst && !fragment.isLast) payload.size else null,+            )++            ByteBuffer.allocate(header.size + body.size)+                .also { header.writeTo(it) }+                .put(body)+                .array()+        }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.ktnew file mode 100644index 0000000000..b219cc2e58--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt@@ -0,0 +1,277 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AuthComplete+import com.vayunmathur.auto.protocol.gal.ByeByeReason+import com.vayunmathur.auto.protocol.gal.ByeByeRequest+import com.vayunmathur.auto.protocol.gal.ChannelOpenRequest+import com.vayunmathur.auto.protocol.gal.MessageStatus+import com.vayunmathur.auto.protocol.gal.PingRequest+import com.vayunmathur.auto.protocol.gal.PingResponse+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryRequest+import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryResponse+import java.nio.ByteBuffer+import javax.net.ssl.SSLEngine+import javax.net.ssl.SSLEngineResult.HandshakeStatus+import javax.net.ssl.SSLEngineResult.Status++/** A control message the session wants sent. */+class OutboundMessage(+    val type: Int,+    val payload: ByteArray,+    /** Whether the frame should be TLS-wrapped and flagged [FrameFlags.ENCRYPTED]. */+    val encrypted: Boolean,+)++/** Where the session has got to. */+enum class SessionState {+    AWAITING_VERSION,+    HANDSHAKING,+    AWAITING_AUTH_COMPLETE,+    DISCOVERING,+    ACTIVE,+    CLOSED,+}++/**+ * The GAL control channel, driven entirely by messages in and messages out.+ *+ * No transport, no threads and no I/O, so the whole bring-up can be tested against a+ * stand-in head unit on the JVM. A driver reads frames off a [GalTransport], reassembles+ * them with [FrameReader], and feeds the control channel's payloads to [onMessage].+ *+ * The order is not the one you would guess from the phone being the thing that drives+ * projection:+ *+ *  1. The **head unit** sends VersionRequest; we answer VersionResponse.+ *  2. The **head unit** opens TLS as the client; we are the server and pump the engine+ *     through message 3 in both directions.+ *  3. The **head unit** confirms with AuthComplete.+ *  4. Only then do we send ServiceDiscoveryRequest, and only at version >= 1.6.+ *+ * Everything from AuthComplete onwards is TLS-wrapped; versions and the handshake itself+ * travel in the clear.+ */+class GalControlSession(+    private val engine: SSLEngine,+    private val deviceName: String,+    private val supportedVersion: GalVersion = VersionNegotiation.SUPPORTED,+) {+    var state: SessionState = SessionState.AWAITING_VERSION+        private set++    var negotiatedVersion: GalVersion? = null+        private set++    /** Services the head unit advertised, empty until discovery completes. */+    var services: List<Service> = emptyList()+        private set++    /** Set when the session ends abnormally. */+    var failure: String? = null+        private set++    private var tlsInbound: ByteBuffer = ByteBuffer.allocate(0)++    /** Handles one control-channel message and returns whatever should go back. */+    fun onMessage(type: Int, payload: ByteArray): List<OutboundMessage> = when (type) {+        GalMessage.Control.VERSION_REQUEST -> onVersionRequest(payload)+        GalMessage.Control.SSL_HANDSHAKE -> onHandshakeData(payload)+        GalMessage.Control.AUTH_COMPLETE -> onAuthComplete(payload)+        GalMessage.Control.SERVICE_DISCOVERY_RESPONSE -> onServiceDiscovery(payload)+        GalMessage.Control.PING_REQUEST -> onPing(payload)+        GalMessage.Control.BYEBYE_REQUEST -> onByeBye()+        GalMessage.Control.BYEBYE_RESPONSE -> {+            state = SessionState.CLOSED+            emptyList()+        }+        // Focus and status notifications are observed by higher layers; the control channel+        // itself has nothing to answer.+        GalMessage.Control.AUDIO_FOCUS_NOTIFICATION,+        GalMessage.Control.NAVIGATION_FOCUS_NOTIFICATION,+        GalMessage.Control.CALL_AVAILABILITY_STATUS,+        GalMessage.Control.SERVICE_DISCOVERY_UPDATE,+        GalMessage.Control.CHANNEL_OPEN_RESPONSE,+        GalMessage.Control.PING_RESPONSE,+        -> emptyList()++        else -> fail("unexpected control message type 0x${type.toString(16)}")+    }++    /** Asks the head unit to open [service]'s channel. */+    fun openChannel(service: Service, priority: Int = 0): OutboundMessage = OutboundMessage(+        type = GalMessage.Control.CHANNEL_OPEN_REQUEST,+        payload = ChannelOpenRequest.newBuilder()+            .setPriority(priority)+            .setServiceId(service.id)+            .build()+            .toByteArray(),+        encrypted = true,+    )++    /** Ends the session politely. */+    fun disconnect(reason: ByeByeReason = ByeByeReason.USER_SELECTION): OutboundMessage =+        OutboundMessage(+            type = GalMessage.Control.BYEBYE_REQUEST,+            payload = ByeByeRequest.newBuilder().setReason(reason).build().toByteArray(),+            encrypted = true,+        )++    // ---- handlers ----++    private fun onVersionRequest(payload: ByteArray): List<OutboundMessage> {+        val requested = VersionNegotiation.parseRequest(payload)+        val agreed = VersionNegotiation.negotiate(requested, supportedVersion)+        val status = if (agreed == null) {+            MessageStatus.STATUS_NO_COMPATIBLE_VERSION.number+        } else {+            MessageStatus.STATUS_SUCCESS.number+        }++        val response = OutboundMessage(+            type = GalMessage.Control.VERSION_RESPONSE,+            payload = VersionNegotiation.buildResponse(agreed ?: supportedVersion, status),+            encrypted = false,+        )++        if (agreed == null) {+            // Answer before giving up, so the head unit learns why rather than timing out.+            failure = "head unit asked for $requested, we speak $supportedVersion"+            state = SessionState.CLOSED+            return listOf(response)+        }++        negotiatedVersion = agreed+        state = SessionState.HANDSHAKING+        engine.beginHandshake()+        // The head unit is the TLS client, so it sends the first record; nothing to pump yet.+        return listOf(response)+    }++    private fun onHandshakeData(payload: ByteArray): List<OutboundMessage> {+        if (state != SessionState.HANDSHAKING) {+            return fail("handshake data arrived in state $state")+        }+        appendInbound(payload)+        return pumpHandshake()+    }++    private fun onAuthComplete(payload: ByteArray): List<OutboundMessage> {+        val status = AuthComplete.parseFrom(payload).status+        if (status != MessageStatus.STATUS_SUCCESS.number) {+            return fail("head unit rejected authentication: status $status")+        }+        val version = negotiatedVersion+        if (version == null || version < VersionNegotiation.MINIMUM_FOR_DISCOVERY) {+            return fail("negotiated $version is below the service-discovery floor")+        }+        state = SessionState.DISCOVERING+        return listOf(+            OutboundMessage(+                type = GalMessage.Control.SERVICE_DISCOVERY_REQUEST,+                payload = ServiceDiscoveryRequest.newBuilder()+                    .setDeviceName(deviceName)+                    .build()+                    .toByteArray(),+                encrypted = true,+            ),+        )+    }++    private fun onServiceDiscovery(payload: ByteArray): List<OutboundMessage> {+        services = ServiceDiscoveryResponse.parseFrom(payload).servicesList+        state = SessionState.ACTIVE+        return emptyList()+    }++    private fun onPing(payload: ByteArray): List<OutboundMessage> = listOf(+        OutboundMessage(+            type = GalMessage.Control.PING_RESPONSE,+            payload = PingResponse.newBuilder()+                .setTimestamp(PingRequest.parseFrom(payload).timestamp)+                .build()+                .toByteArray(),+            encrypted = true,+        ),+    )++    private fun onByeBye(): List<OutboundMessage> {+        state = SessionState.CLOSED+        return listOf(+            OutboundMessage(+                type = GalMessage.Control.BYEBYE_RESPONSE,+                payload = ByteArray(0),+                encrypted = true,+            ),+        )+    }++    // ---- TLS ----++    private fun appendInbound(payload: ByteArray) {+        val combined = ByteBuffer.allocate(tlsInbound.remaining() + payload.size)+        combined.put(tlsInbound)+        combined.put(payload)+        combined.flip()+        tlsInbound = combined+    }++    /**+     * Runs the engine until it needs more from the head unit, emitting a message 3 for each+     * record it produces.+     */+    private fun pumpHandshake(): List<OutboundMessage> {+        val outgoing = mutableListOf<OutboundMessage>()+        val empty = ByteBuffer.allocate(0)++        while (true) {+            when (engine.handshakeStatus) {+                HandshakeStatus.NEED_TASK -> engine.delegatedTask?.run() ?: return outgoing++                HandshakeStatus.NEED_UNWRAP -> {+                    if (!tlsInbound.hasRemaining()) return outgoing+                    val plain = ByteBuffer.allocate(engine.session.applicationBufferSize)+                    val result = engine.unwrap(tlsInbound, plain)+                    when (result.status) {+                        // Partial record: wait for the next message 3.+                        Status.BUFFER_UNDERFLOW -> return outgoing+                        Status.OK -> Unit+                        else -> return fail("TLS unwrap failed: ${result.status}")+                    }+                }++                HandshakeStatus.NEED_WRAP -> {+                    val record = ByteBuffer.allocate(engine.session.packetBufferSize)+                    val result = engine.wrap(empty, record)+                    if (result.status != Status.OK) {+                        return fail("TLS wrap failed: ${result.status}")+                    }+                    record.flip()+                    val bytes = ByteArray(record.remaining())+                    record.get(bytes)+                    // Handshake records ride in the clear: they ARE the encryption being+                    // set up, so the ENCRYPTED frame flag must stay off.+                    outgoing += OutboundMessage(+                        GalMessage.Control.SSL_HANDSHAKE,+                        bytes,+                        encrypted = false,+                    )+                }++                HandshakeStatus.FINISHED, HandshakeStatus.NOT_HANDSHAKING -> {+                    // The head unit confirms with AuthComplete; we do not send it.+                    state = SessionState.AWAITING_AUTH_COMPLETE+                    return outgoing+                }++                else -> return outgoing+            }+        }+    }++    private fun fail(reason: String): List<OutboundMessage> {+        failure = reason+        state = SessionState.CLOSED+        return emptyList()+    }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalTransport.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalTransport.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalTransport.ktnew file mode 100644index 0000000000..e63fa3d2ad--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalTransport.kt@@ -0,0 +1,26 @@+package com.vayunmathur.auto.protocol++import java.io.Closeable++/**+ * A bidirectional byte stream to a head unit.+ *+ * Both GAL transports reduce to this. USB is an `UsbAccessory` opened as a+ * `ParcelFileDescriptor` and read as an ordinary file descriptor+ * (`carsetup/setup/UsbConnectionHelper.java`); wireless is a TCP socket after the Bluetooth+ * RFCOMM bootstrap hands over the credentials. Nothing above this layer knows which it has.+ */+interface GalTransport : Closeable {++    /**+     * Reads at least one byte, blocking until some arrive.+     *+     * @return the number of bytes read, or -1 at end of stream.+     */+    fun read(buffer: ByteArray, offset: Int, length: Int): Int++    fun write(bytes: ByteArray, offset: Int, length: Int)++    /** Pushes anything buffered to the head unit. */+    fun flush()+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/VersionNegotiation.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/VersionNegotiation.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/VersionNegotiation.ktnew file mode 100644index 0000000000..e7bbd46bc1--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/VersionNegotiation.kt@@ -0,0 +1,91 @@+package com.vayunmathur.auto.protocol++import java.nio.ByteBuffer++/** A GAL protocol version pair. */+data class GalVersion(val major: Int, val minor: Int) : Comparable<GalVersion> {++    override fun compareTo(other: GalVersion): Int =+        compareValuesBy(this, other, GalVersion::major, GalVersion::minor)++    override fun toString(): String = "$major.$minor"+}++/**+ * Version negotiation, control messages 1 and 2.+ *+ * Two things here are unlike the rest of the protocol and are easy to get wrong.+ *+ *  1. **These are not protobuf.** Every other control message carries a protobuf payload;+ *     these carry raw big-endian uint16s. Gearhead writes them a short at a time+ *     (`jcn.v((short) …)`) rather than through a generated builder.+ *  2. **The head unit asks and the phone answers.** The log line in the control endpoint is+ *     "Car requests protocol version %s" — the phone does not open with a version request,+ *     it waits for one. A sender that speaks first will sit unanswered.+ */+object VersionNegotiation {++    /**+     * The highest version this implementation speaks.+     *+     * Gearhead 17.5 advertises 1.7 and treats 1.6 as the floor for service discovery, so+     * anything below that will not get a discovery request out of a real head unit.+     */+    val SUPPORTED: GalVersion = GalVersion(1, 7)++    /** Below this the head unit is not expected to support service discovery. */+    val MINIMUM_FOR_DISCOVERY: GalVersion = GalVersion(1, 6)++    private const val REQUEST_SIZE = 4+    private const val RESPONSE_SIZE = 6++    /** Parses control message 1, sent by the head unit. */+    fun parseRequest(payload: ByteArray): GalVersion {+        require(payload.size >= REQUEST_SIZE) {+            "version request is ${payload.size} bytes, expected at least $REQUEST_SIZE"+        }+        val buffer = ByteBuffer.wrap(payload)+        return GalVersion(+            major = buffer.short.toInt() and 0xFFFF,+            minor = buffer.short.toInt() and 0xFFFF,+        )+    }++    /**+     * Builds the payload of control message 2.+     *+     * [status] is a [com.vayunmathur.auto.protocol.gal.MessageStatus] value written as a+     * short, so the negative error codes wrap — `STATUS_NO_COMPATIBLE_VERSION` (-1) goes out+     * as `0xFFFF`. That is what gearhead does and what a head unit expects.+     */+    fun buildResponse(version: GalVersion, status: Int): ByteArray =+        ByteBuffer.allocate(RESPONSE_SIZE)+            .putShort(version.major.toShort())+            .putShort(version.minor.toShort())+            .putShort(status.toShort())+            .array()++    /** Parses control message 2, for testing against a head unit implementation. */+    fun parseResponse(payload: ByteArray): Triple<GalVersion, Int, Int> {+        require(payload.size >= RESPONSE_SIZE) {+            "version response is ${payload.size} bytes, expected at least $RESPONSE_SIZE"+        }+        val buffer = ByteBuffer.wrap(payload)+        val version = GalVersion(+            major = buffer.short.toInt() and 0xFFFF,+            minor = buffer.short.toInt() and 0xFFFF,+        )+        // Sign-extended: the status is a signed enum value on the wire.+        return Triple(version, buffer.short.toInt(), 0)+    }++    /**+     * Picks the version to run at, or null if the head unit asks for more than we speak.+     *+     * Gearhead refuses to negotiate *down* from what the car asked for beyond its own+     * maximum: if the car requests something newer than [SUPPORTED] it fails the session+     * rather than silently answering with an older version.+     */+    fun negotiate(requested: GalVersion, supported: GalVersion = SUPPORTED): GalVersion? =+        if (requested > supported) null else requested+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameReaderTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameReaderTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameReaderTest.ktnew file mode 100644index 0000000000..4fd9ed83a8--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameReaderTest.kt@@ -0,0 +1,148 @@+package com.vayunmathur.auto.protocol++import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class FrameReaderTest {++    private val writer = FrameWriter()++    private fun payload(size: Int) = Random(size).nextBytes(size)++    @Test+    fun `a single-frame message comes back whole`() {+        val body = payload(64)+        val reader = FrameReader()++        val messages = reader.offer(writer.frame(2, body).single())++        val message = messages.single()+        assertEquals(2, message.channelId)+        assertFalse(message.isControl)+        assertContentEquals(body, message.payload)+    }++    @Test+    fun `a fragmented message is reassembled in order`() {+        val body = payload(50_000)+        val frames = writer.frame(5, body)+        assertTrue(frames.size > 1, "expected this to fragment")++        val reader = FrameReader()+        val collected = frames.flatMap { reader.offer(it) }++        assertContentEquals(body, collected.single().payload)+        assertFalse(reader.hasPartialMessages)+    }++    @Test+    fun `a message split across arbitrary read boundaries still reassembles`() {+        // The transport hands over whatever it has; a read can end mid-header.+        val body = payload(40_000)+        val wire = writer.frame(3, body).reduce { a, b -> a + b }++        val reader = FrameReader()+        val collected = mutableListOf<ReassembledMessage>()+        var offset = 0+        val chunk = 777 // deliberately not a frame or header multiple+        while (offset < wire.size) {+            val count = minOf(chunk, wire.size - offset)+            collected += reader.offer(wire, offset, count)+            offset += count+        }++        assertContentEquals(body, collected.single().payload)+    }++    @Test+    fun `one byte at a time still reassembles`() {+        val body = payload(200)+        val wire = writer.frame(1, body).single()++        val reader = FrameReader()+        val collected = mutableListOf<ReassembledMessage>()+        for (byte in wire) {+            collected += reader.offer(byteArrayOf(byte))+        }++        assertContentEquals(body, collected.single().payload)+    }++    @Test+    fun `several messages in one read all come back`() {+        val first = payload(10)+        val second = payload(20)+        val wire = writer.frame(1, first).single() + writer.frame(2, second).single()++        val messages = FrameReader().offer(wire)++        assertEquals(2, messages.size)+        assertContentEquals(first, messages[0].payload)+        assertContentEquals(second, messages[1].payload)+        assertEquals(listOf(1, 2), messages.map { it.channelId })+    }++    @Test+    fun `fragmented messages on different channels interleave without mixing`() {+        val reader = FrameReader()+        val a = payload(30_000)+        val b = payload(30_000)+        val framesA = writer.frame(3, a)+        val framesB = writer.frame(4, b)++        val collected = mutableListOf<ReassembledMessage>()+        // Interleave: a0 b0 a1 b1 ...+        for (i in 0 until maxOf(framesA.size, framesB.size)) {+            framesA.getOrNull(i)?.let { collected += reader.offer(it) }+            framesB.getOrNull(i)?.let { collected += reader.offer(it) }+        }++        assertEquals(2, collected.size)+        assertContentEquals(a, collected.single { it.channelId == 3 }.payload)+        assertContentEquals(b, collected.single { it.channelId == 4 }.payload)+    }++    @Test+    fun `the control flag survives the round trip`() {+        val message = FrameReader()+            .offer(writer.frame(0, payload(8), isControl = true).single())+            .single()+        assertTrue(message.isControl)+    }++    @Test+    fun `encrypted frames are decrypted per frame before reassembly`() {+        // A stand-in that changes length, which is the property that matters: the header+        // counts ciphertext while the reassembly buffer accumulates plaintext.+        val pad = byteArrayOf(0x7F)+        val writer = FrameWriter(encrypt = { pad + it })+        val reader = FrameReader(decrypt = { it.copyOfRange(1, it.size) })++        val body = payload(40_000)+        val collected = writer+            .frame(2, body, encrypted = true)+            .flatMap { reader.offer(it) }++        assertContentEquals(body, collected.single().payload)+    }++    @Test+    fun `an empty message round-trips`() {+        val message = FrameReader().offer(writer.frame(1, ByteArray(0)).single()).single()+        assertEquals(0, message.payload.size)+    }++    @Test+    fun `a partial frame yields nothing and leaves the reader waiting`() {+        val wire = writer.frame(1, payload(100)).single()+        val reader = FrameReader()++        assertTrue(reader.offer(wire, 0, 3).isEmpty(), "header incomplete")+        assertTrue(reader.offer(wire, 3, 50).isEmpty(), "payload incomplete")+        assertEquals(1, reader.offer(wire, 53, wire.size - 53).size)+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionTest.ktnew file mode 100644index 0000000000..608875a922--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalControlSessionTest.kt@@ -0,0 +1,266 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AuthComplete+import com.vayunmathur.auto.protocol.gal.MediaCodecType+import com.vayunmathur.auto.protocol.gal.MediaSinkService+import com.vayunmathur.auto.protocol.gal.MessageStatus+import com.vayunmathur.auto.protocol.gal.PingRequest+import com.vayunmathur.auto.protocol.gal.PingResponse+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryRequest+import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryResponse+import java.io.File+import java.nio.ByteBuffer+import javax.net.ssl.SSLEngine+import javax.net.ssl.SSLEngineResult.HandshakeStatus+import javax.net.ssl.SSLEngineResult.Status+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.fail++/**+ * Drives the control session through a full bring-up against a stand-in head unit.+ *+ * The head unit here is a real client [SSLEngine] using the same GAL credential, which is+ * what an actual head unit presents, so the TLS half is genuine rather than mocked. The+ * message sequencing above it is scripted to match what gearhead expects.+ */+class GalControlSessionTest {++    private val assetDir = File("src/main/assets/gal")++    private fun context() = GalCredential.create(+        certPem = File(assetDir, "client-cert.pem").readText(),+        keyPem = File(assetDir, "client-key.pem").readText(),+        rootPem = File(assetDir, "root.pem").readText(),+    )++    private fun session(engine: SSLEngine) = GalControlSession(engine, deviceName = "Pixel 8")++    @Test+    fun `a full bring-up reaches ACTIVE with the head unit's services`() {+        val context = context()+        val server = GalCredential.serverEngine(context)+        val car = context.createSSLEngine().apply { useClientMode = true }+        val session = session(server)++        // 1. The head unit asks for a version; we answer.+        assertEquals(SessionState.AWAITING_VERSION, session.state)+        val versionReply = session.onMessage(+            GalMessage.Control.VERSION_REQUEST,+            versionRequest(1, 6),+        ).single()+        assertEquals(GalMessage.Control.VERSION_RESPONSE, versionReply.type)+        assertTrue(!versionReply.encrypted, "version negotiation is in the clear")+        assertEquals(GalVersion(1, 6), session.negotiatedVersion)+        assertEquals(SessionState.HANDSHAKING, session.state)++        // 2. TLS, with the head unit as client.+        runHandshake(session, car)+        assertEquals(+            SessionState.AWAITING_AUTH_COMPLETE,+            session.state,+            "failure: ${session.failure}",+        )+        // We authenticated the head unit's certificate.+        assertNotNull(server.session.peerCertificates.firstOrNull())++        // 3. The head unit confirms, and that is what triggers our discovery request.+        val discovery = session.onMessage(+            GalMessage.Control.AUTH_COMPLETE,+            AuthComplete.newBuilder()+                .setStatus(MessageStatus.STATUS_SUCCESS.number)+                .build()+                .toByteArray(),+        ).single()+        assertEquals(GalMessage.Control.SERVICE_DISCOVERY_REQUEST, discovery.type)+        assertTrue(discovery.encrypted, "everything after auth is wrapped")+        assertEquals(+            "Pixel 8",+            ServiceDiscoveryRequest.parseFrom(discovery.payload).deviceName,+        )+        assertEquals(SessionState.DISCOVERING, session.state)++        // 4. The head unit advertises; we consume.+        val outputs = session.onMessage(+            GalMessage.Control.SERVICE_DISCOVERY_RESPONSE,+            headUnitServices().toByteArray(),+        )+        assertTrue(outputs.isEmpty(), "discovery response needs no reply")+        assertEquals(SessionState.ACTIVE, session.state)+        assertEquals(+            listOf(GalService.VIDEO_SINK.id, GalService.INPUT_SOURCE.id),+            session.services.map { it.id },+        )+        assertNull(session.failure)+    }++    @Test+    fun `we answer a version we cannot speak and then close`() {+        val session = session(GalCredential.serverEngine(context()))++        val reply = session.onMessage(+            GalMessage.Control.VERSION_REQUEST,+            versionRequest(9, 0),+        ).single()++        // Answering rather than dropping means the head unit gets a reason instead of a+        // timeout.+        val (_, status, _) = VersionNegotiation.parseResponse(reply.payload)+        assertEquals(MessageStatus.STATUS_NO_COMPATIBLE_VERSION.number, status)+        assertEquals(SessionState.CLOSED, session.state)+        assertNotNull(session.failure)+    }++    @Test+    fun `a rejected authentication closes the session`() {+        val session = session(GalCredential.serverEngine(context()))+        session.onMessage(GalMessage.Control.VERSION_REQUEST, versionRequest(1, 6))++        session.onMessage(+            GalMessage.Control.AUTH_COMPLETE,+            AuthComplete.newBuilder()+                .setStatus(MessageStatus.STATUS_AUTHENTICATION_FAILURE_CERT_EXPIRED.number)+                .build()+                .toByteArray(),+        )++        assertEquals(SessionState.CLOSED, session.state)+        assertTrue(session.failure!!.contains("-24"), "expected the status in ${session.failure}")+    }++    @Test+    fun `a version below the discovery floor is refused`() {+        val session = session(GalCredential.serverEngine(context()))+        session.onMessage(GalMessage.Control.VERSION_REQUEST, versionRequest(1, 5))++        session.onMessage(+            GalMessage.Control.AUTH_COMPLETE,+            AuthComplete.newBuilder()+                .setStatus(MessageStatus.STATUS_SUCCESS.number)+                .build()+                .toByteArray(),+        )++        assertEquals(SessionState.CLOSED, session.state)+        assertTrue(session.failure!!.contains("discovery floor"))+    }++    @Test+    fun `a ping is answered with the same timestamp`() {+        val session = session(GalCredential.serverEngine(context()))+        val reply = session.onMessage(+            GalMessage.Control.PING_REQUEST,+            PingRequest.newBuilder().setTimestamp(1234567890123L).build().toByteArray(),+        ).single()++        assertEquals(GalMessage.Control.PING_RESPONSE, reply.type)+        assertEquals(1234567890123L, PingResponse.parseFrom(reply.payload).timestamp)+    }++    @Test+    fun `a byebye request is acknowledged and closes the session`() {+        val session = session(GalCredential.serverEngine(context()))+        val reply = session.onMessage(+            GalMessage.Control.BYEBYE_REQUEST,+            byteArrayOf(0x08, 0x01),+        ).single()++        assertEquals(GalMessage.Control.BYEBYE_RESPONSE, reply.type)+        assertEquals(SessionState.CLOSED, session.state)+    }++    @Test+    fun `opening a channel names the service and rides encrypted`() {+        val session = session(GalCredential.serverEngine(context()))+        val service = Service.newBuilder().setId(GalService.VIDEO_SINK.id).build()++        val open = session.openChannel(service, priority = -128)++        assertEquals(GalMessage.Control.CHANNEL_OPEN_REQUEST, open.type)+        assertTrue(open.encrypted)+        val parsed = com.vayunmathur.auto.protocol.gal.ChannelOpenRequest.parseFrom(open.payload)+        assertEquals(GalService.VIDEO_SINK.id, parsed.serviceId)+        assertEquals(-128, parsed.priority)+    }++    // ---- helpers ----++    private fun versionRequest(major: Int, minor: Int): ByteArray =+        ByteBuffer.allocate(4)+            .putShort(major.toShort())+            .putShort(minor.toShort())+            .array()++    private fun headUnitServices(): ServiceDiscoveryResponse = ServiceDiscoveryResponse+        .newBuilder()+        .setHeadUnitName("Test Head Unit")+        .addServices(+            Service.newBuilder()+                .setId(GalService.VIDEO_SINK.id)+                .setMediaSink(+                    MediaSinkService.newBuilder()+                        .setAvailableType(MediaCodecType.MEDIA_CODEC_VIDEO_H264_BP),+                ),+        )+        .addServices(Service.newBuilder().setId(GalService.INPUT_SOURCE.id))+        .build()++    /**+     * Shuttles message-3 payloads between the session and a client engine until the session+     * says the handshake is done.+     */+    private fun runHandshake(session: GalControlSession, car: SSLEngine) {+        car.beginHandshake()+        repeat(MAX_STEPS) {+            if (session.state != SessionState.HANDSHAKING) return++            // Everything the car wants to say.+            for (record in carRecords(car)) {+                for (out in session.onMessage(GalMessage.Control.SSL_HANDSHAKE, record)) {+                    assertEquals(GalMessage.Control.SSL_HANDSHAKE, out.type)+                    feedCar(car, out.payload)+                }+            }+        }+        fail("handshake did not finish in $MAX_STEPS steps: ${session.state} ${session.failure}")+    }++    private fun carRecords(car: SSLEngine): List<ByteArray> {+        val records = mutableListOf<ByteArray>()+        val empty = ByteBuffer.allocate(0)+        while (true) {+            when (car.handshakeStatus) {+                HandshakeStatus.NEED_TASK -> car.delegatedTask?.run() ?: return records+                HandshakeStatus.NEED_WRAP -> {+                    val out = ByteBuffer.allocate(car.session.packetBufferSize)+                    val result = car.wrap(empty, out)+                    if (result.status != Status.OK) fail("car wrap: ${result.status}")+                    out.flip()+                    records += ByteArray(out.remaining()).also { out.get(it) }+                }+                else -> return records+            }+        }+    }++    private fun feedCar(car: SSLEngine, record: ByteArray) {+        val inbound = ByteBuffer.wrap(record)+        while (inbound.hasRemaining()) {+            while (car.handshakeStatus == HandshakeStatus.NEED_TASK) {+                car.delegatedTask?.run() ?: break+            }+            if (car.handshakeStatus != HandshakeStatus.NEED_UNWRAP) return+            val plain = ByteBuffer.allocate(car.session.applicationBufferSize)+            val result = car.unwrap(inbound, plain)+            if (result.status != Status.OK) return+        }+    }++    private companion object {+        const val MAX_STEPS = 50+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/VersionNegotiationTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/VersionNegotiationTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/VersionNegotiationTest.ktnew file mode 100644index 0000000000..936c777b31--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/VersionNegotiationTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.MessageStatus+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue++class VersionNegotiationTest {++    @Test+    fun `a version request is two raw big-endian shorts`() {+        // Not protobuf. A protobuf parse of these four bytes would be garbage.+        val version = VersionNegotiation.parseRequest(byteArrayOf(0x00, 0x01, 0x00, 0x06))+        assertEquals(GalVersion(1, 6), version)+    }++    @Test+    fun `a version response is major, minor, status as raw shorts`() {+        val payload = VersionNegotiation.buildResponse(+            GalVersion(1, 7),+            MessageStatus.STATUS_SUCCESS.number,+        )+        assertContentEquals(byteArrayOf(0x00, 0x01, 0x00, 0x07, 0x00, 0x00), payload)+    }++    @Test+    fun `a negative status wraps to its unsigned short form`() {+        // STATUS_NO_COMPATIBLE_VERSION is -1 and goes out as 0xFFFF.+        val payload = VersionNegotiation.buildResponse(+            GalVersion(1, 7),+            MessageStatus.STATUS_NO_COMPATIBLE_VERSION.number,+        )+        assertContentEquals(+            byteArrayOf(0x00, 0x01, 0x00, 0x07, 0xFF.toByte(), 0xFF.toByte()),+            payload,+        )+    }++    @Test+    fun `the full response frame matches gearhead's eight bytes`() {+        // Gearhead allocates 8: the 2-byte message type plus three shorts.+        val frame = MessageCodec.encode(+            GalMessage.Control.VERSION_RESPONSE,+            VersionNegotiation.buildResponse(GalVersion(1, 7), MessageStatus.STATUS_SUCCESS.number),+        )+        assertEquals(8, frame.size)+        assertContentEquals(+            byteArrayOf(0x00, 0x02, 0x00, 0x01, 0x00, 0x07, 0x00, 0x00),+            frame,+        )+    }++    @Test+    fun `we accept anything at or below what we speak`() {+        assertEquals(GalVersion(1, 6), VersionNegotiation.negotiate(GalVersion(1, 6)))+        assertEquals(GalVersion(1, 7), VersionNegotiation.negotiate(GalVersion(1, 7)))+        assertEquals(GalVersion(1, 1), VersionNegotiation.negotiate(GalVersion(1, 1)))+    }++    @Test+    fun `we refuse a head unit asking for more than we speak`() {+        assertNull(VersionNegotiation.negotiate(GalVersion(1, 8)))+        assertNull(VersionNegotiation.negotiate(GalVersion(2, 0)))+    }++    @Test+    fun `versions order by major then minor`() {+        assertTrue(GalVersion(1, 7) > GalVersion(1, 6))+        assertTrue(GalVersion(2, 0) > GalVersion(1, 99))+        assertTrue(GalVersion(1, 6) >= VersionNegotiation.MINIMUM_FOR_DISCOVERY)+        assertTrue(GalVersion(1, 5) < VersionNegotiation.MINIMUM_FOR_DISCOVERY)+    }++    @Test+    fun `a truncated request is rejected rather than misread`() {+        assertFailsWith<IllegalArgumentException> {+            VersionNegotiation.parseRequest(byteArrayOf(0x00, 0x01))+        }+    }++    @Test+    fun `a response round-trips`() {+        val payload = VersionNegotiation.buildResponse(GalVersion(1, 6), -1)+        val (version, status, _) = VersionNegotiation.parseResponse(payload)+        assertEquals(GalVersion(1, 6), version)+        assertEquals(-1, status)+    }+}