PairingFrames.kt
1// Intended source path: app/src/main/java/com/peachpasswords/sync/PairingFrames.kt2package com.peachpasswords.sync34import kotlinx.coroutines.Dispatchers5import kotlinx.coroutines.withContext6import java.io.DataInputStream7import java.io.EOFException8import java.io.InputStream9import java.io.OutputStream1011/**12 * Length-prefixed framing for the C7 TCP transport, shared by [PairingServer]13 * and [PairingTransport] so neither duplicates the wire format.14 *15 * Frame = [4-byte big-endian length][payload]. This is the framing the existing16 * ChirpPairing.runPairingInitiator/Responder already assume implicitly when they17 * call `transport.send(bytes)` / `transport.receive()` — the WebSocket transport18 * gets framing for free from the protocol; a raw TCP socket does not, so we add19 * it here.20 *21 * A frame length cap guards against a hostile/garbled peer asking us to allocate22 * gigabytes before the Noise layer has authenticated anything.23 */24const val MAX_PAIRING_FRAME_BYTES: Int = 1 shl 20 // 1 MiB2526/** Blocking write of a single length-prefixed frame. */27fun writeFrame(out: OutputStream, payload: ByteArray) {28 require(payload.size <= MAX_PAIRING_FRAME_BYTES) { "frame too large: ${payload.size}" }29 val header = ByteArray(4)30 header[0] = (payload.size ushr 24).toByte()31 header[1] = (payload.size ushr 16).toByte()32 header[2] = (payload.size ushr 8).toByte()33 header[3] = payload.size.toByte()34 out.write(header)35 out.write(payload)36 out.flush()37}3839/** Blocking read of a single length-prefixed frame. Throws on EOF / oversize. */40fun readFrame(input: InputStream): ByteArray {41 val data = if (input is DataInputStream) input else DataInputStream(input)42 val length = try {43 data.readInt()44 } catch (e: EOFException) {45 throw java.io.IOException("peer closed before frame header", e)46 }47 require(length in 0..MAX_PAIRING_FRAME_BYTES) { "invalid frame length: $length" }48 val buf = ByteArray(length)49 data.readFully(buf)50 return buf51}5253/**54 * Adapts a blocking TCP socket pair to the suspend send/receive shape the REAL55 * crypto stack expects:56 * - noiseNKInitiator / noiseNKResponder take `send: suspend (ByteArray)->Unit`57 * and `receive: suspend ()->ByteArray` (see NoiseNK.kt).58 * - ChirpPairing's [PairingTransport] interface is `send/receive/close`.59 *60 * Both the Noise handshake messages and the post-handshake encrypted payloads61 * travel as length-prefixed frames over the same socket, so one [SocketFrameIO]62 * serves the whole session. All IO hops to Dispatchers.IO.63 *64 * This implements the EXISTING [PairingTransport] interface (ChirpPairing.kt),65 * which is the contract `runPairingInitiator` / `runPairingResponder` consume —66 * so a TCP socket can drive the already-written handshake unchanged.67 */68class SocketFrameIO(69 private val input: InputStream,70 private val output: OutputStream,71 private val onClose: suspend () -> Unit = {},72) : PairingTransport {73 private val buffered = DataInputStream(input)7475 /**76 * Synchronous frame write. [ChirpSyncSession.send] is non-suspending (see77 * ChirpSyncTransport.kt), so the sync-exchange bridge needs a blocking send78 * that does NOT wrap a coroutine. Socket writes are bounded by soTimeout.79 */80 fun sendBlocking(msg: ByteArray) {81 writeFrame(output, msg)82 }8384 override suspend fun send(msg: ByteArray) = withContext(Dispatchers.IO) {85 writeFrame(output, msg)86 }8788 override suspend fun receive(): ByteArray = withContext(Dispatchers.IO) {89 readFrame(buffered)90 }9192 override suspend fun close() {93 onClose()94 }95}9697/**98 * Convenience wrappers for the post-handshake encrypted exchange. The Noise99 * [NoiseNKSession] already owns the cipher (encrypt/decrypt); these just splice100 * it onto the frame layer so call sites read clearly.101 *102 * NOTE: the existing ChirpPairing handshake calls `session.encrypt` /103 * `session.decrypt` directly around `transport.send` / `transport.receive`; the104 * post-pairing SYNC exchange (runChirpSyncInitiator/Responder) does the same via105 * a [ChirpSyncSession]. These helpers exist for the raw-frame paths in106 * PairingServer/PairingTransport that don't go through a ChirpSyncSession.107 */108suspend fun PairingTransport.sendEncrypted(session: NoiseNKSession, plaintext: ByteArray) {109 send(session.encrypt(plaintext))110}111112suspend fun PairingTransport.receiveEncrypted(session: NoiseNKSession): ByteArray {113 return session.decrypt(receive())114}