Modern Apps git

← Modern-Apps.git

cast: serve media over a session-pinned HTTPS proxy

Commit
47043bcb75a8dbe69443e6362de8cd8fc634ccec
Author
vayun-mathur <[email protected]>
When
2026-08-23 17:48 UTC (3 months ago)
Parents
3548064

Diff

cast/protocol/src/main/java/com/vayunmathur/cast/protocol/EphemeralTls.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/EphemeralTls.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/EphemeralTls.ktnew file mode 100644index 0000000000..ea28bc7ecf--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/EphemeralTls.kt@@ -0,0 +1,294 @@+package com.vayunmathur.cast.protocol++import java.io.ByteArrayInputStream+import java.math.BigInteger+import java.net.InetAddress+import java.security.KeyPairGenerator+import java.security.KeyStore+import java.security.MessageDigest+import java.security.SecureRandom+import java.security.Signature+import java.security.cert.CertificateException+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import java.security.spec.ECGenParameterSpec+import java.time.Instant+import java.time.ZoneOffset+import java.time.temporal.ChronoUnit+import javax.net.ssl.KeyManagerFactory+import javax.net.ssl.SSLContext+import javax.net.ssl.X509TrustManager++/**+ * TLS for the media proxy, pinned to the session instead of to a certificate authority.+ *+ * The phone mints a fresh self-signed certificate per session and sends its fingerprint to the+ * TV over the control channel, which is already AES-256-GCM under a key derived from the ML-KEM+ * handshake. The TV pins that fingerprint and trusts nothing else. That is stronger than PKI+ * here rather than weaker: a CA would only attest to a name, while the fingerprint arrives over+ * a channel the pairing already authenticated.+ *+ * It also avoids the two things a name-based scheme would have cost - a cleartext exemption in+ * the network security config, which `targetSdk 37` would otherwise require, and a certificate+ * that outlives the session it was made for.+ *+ * The certificate is assembled by hand out of `java.security` primitives. `AndroidKeyStore`+ * would generate one for us, but its keys cannot leave the device and it does not exist off it,+ * so the whole proxy would then be untestable without a TV in the room. Nothing here needs+ * hardware key storage: the key is thrown away when the session ends.+ */+object EphemeralTls {++    /** Server credentials plus the fingerprint the TV has to be told. */+    class ServerCredentials(+        val sslContext: SSLContext,+        val certificate: X509Certificate,+    ) {+        /** SHA-256 over the certificate's DER encoding - what the TV pins. */+        val fingerprint: ByteArray get() = fingerprintOf(certificate)+    }++    /**+     * A certificate is valid from a day ago because the two ends do not share a clock.+     *+     * A TV that has just been unplugged for a week can come up minutes or hours behind. Our own+     * trust manager pins a fingerprint and never looks at the dates, but anything else in the+     * stack that does look would reject a certificate stamped in what it believes is the future.+     */+    private val BACKDATE = 1L to ChronoUnit.DAYS++    /** Long enough for any session, short enough that a leaked key is worth little. */+    private val LIFETIME = 7L to ChronoUnit.DAYS++    private const val SIGNATURE_ALGORITHM = "SHA256withECDSA"++    /** ecdsa-with-SHA256. */+    private const val OID_ECDSA_SHA256 = "1.2.840.10045.4.3.2"++    /** id-at-commonName. */+    private const val OID_COMMON_NAME = "2.5.4.3"++    /** id-ce-subjectAltName. */+    private const val OID_SUBJECT_ALT_NAME = "2.5.29.17"++    /** id-ce-extKeyUsage. */+    private const val OID_EXT_KEY_USAGE = "2.5.29.37"++    /** id-kp-serverAuth. */+    private const val OID_SERVER_AUTH = "1.3.6.1.5.5.7.3.1"++    /**+     * Mints a key pair and a self-signed certificate covering [addresses].+     *+     * The addresses go in as `iPAddress` subject alternative names because the TV reaches the+     * phone by address, not by name. Without them the certificate would be trusted by our pin+     * and then rejected by the hostname check that runs afterwards, which is a confusing way to+     * fail and one no amount of pinning fixes.+     */+    fun server(addresses: List<InetAddress>): ServerCredentials {+        val generator = KeyPairGenerator.getInstance("EC")+        generator.initialize(ECGenParameterSpec("secp256r1"), SecureRandom())+        val keyPair = generator.generateKeyPair()++        val now = Instant.now()+        val tbs = tbsCertificate(+            publicKeyInfo = keyPair.public.encoded,+            commonName = "Modern Apps cast",+            addresses = addresses,+            notBefore = now.minus(BACKDATE.first, BACKDATE.second),+            notAfter = now.plus(LIFETIME.first, LIFETIME.second),+        )++        val signer = Signature.getInstance(SIGNATURE_ALGORITHM)+        signer.initSign(keyPair.private)+        signer.update(tbs)+        val signature = signer.sign()++        val der = Der.sequence(tbs, algorithmIdentifier(), Der.bitString(signature))+        val certificate = CertificateFactory.getInstance("X.509")+            .generateCertificate(ByteArrayInputStream(der)) as X509Certificate++        // PKCS12 rather than JKS: JKS is not a type Android's provider offers, and the store+        // never leaves memory so the password is a formality the API insists on.+        val password = CharArray(32) { (SecureRandom().nextInt(26) + 'a'.code).toChar() }+        val store = KeyStore.getInstance("PKCS12")+        store.load(null, null)+        store.setKeyEntry("cast-proxy", keyPair.private, password, arrayOf(certificate))++        val keyManagers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())+            .apply { init(store, password) }+            .keyManagers+        password.fill('\u0000')++        val context = SSLContext.getInstance("TLS")+        context.init(keyManagers, null, SecureRandom())+        return ServerCredentials(context, certificate)+    }++    /**+     * A client context that trusts exactly one certificate, by fingerprint.+     *+     * Not a permissive trust manager. The control channel exists so that this end can be told+     * precisely which certificate to expect, and accepting any certificate would throw away the+     * only guarantee the pairing bought.+     */+    fun client(fingerprint: ByteArray): SSLContext {+        val pinned = PinnedTrustManager(fingerprint.copyOf())+        val context = SSLContext.getInstance("TLS")+        context.init(null, arrayOf<javax.net.ssl.TrustManager>(pinned), SecureRandom())+        return context+    }++    fun fingerprintOf(certificate: X509Certificate): ByteArray =+        MessageDigest.getInstance("SHA-256").digest(certificate.encoded)++    private class PinnedTrustManager(private val fingerprint: ByteArray) : X509TrustManager {++        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {+            val leaf = chain?.firstOrNull() ?: throw CertificateException("no certificate offered")+            // The chain is irrelevant beyond its leaf: there is no issuer to walk up to, and+            // the pin already says which single certificate is acceptable.+            if (!MessageDigest.isEqual(fingerprint, fingerprintOf(leaf))) {+                throw CertificateException("certificate does not match the pinned session fingerprint")+            }+        }++        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {+            // The proxy never asks for a client certificate, so being asked to check one means+            // this context is being used for something it was not built for.+            throw CertificateException("the media proxy does not authenticate clients by certificate")+        }++        override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()+    }++    // ------------------------------------------------------------------+    // Certificate assembly+    // ------------------------------------------------------------------++    private fun algorithmIdentifier(): ByteArray = Der.sequence(Der.oid(OID_ECDSA_SHA256))++    private fun tbsCertificate(+        publicKeyInfo: ByteArray,+        commonName: String,+        addresses: List<InetAddress>,+        notBefore: Instant,+        notAfter: Instant,+    ): ByteArray {+        // 20 bytes, forced positive: a negative serial number is malformed and some parsers say+        // so only by failing to read the certificate at all.+        val serial = BigInteger(159, SecureRandom()).add(BigInteger.ONE)+        val name = Der.sequence(Der.set(Der.sequence(Der.oid(OID_COMMON_NAME), Der.utf8(commonName))))++        val extensions = buildList {+            if (addresses.isNotEmpty()) {+                val names = addresses.map { Der.tagged(0x87, it.address) }+                add(extension(OID_SUBJECT_ALT_NAME, Der.sequence(*names.toTypedArray())))+            }+            add(extension(OID_EXT_KEY_USAGE, Der.sequence(Der.oid(OID_SERVER_AUTH))))+        }++        return Der.sequence(+            // v3, which is what having extensions at all requires.+            Der.explicit(0, Der.integer(2)),+            Der.integer(serial),+            algorithmIdentifier(),+            name,+            Der.sequence(Der.utcTime(notBefore), Der.utcTime(notAfter)),+            // Issuer and subject are the same name: this certificate signs itself.+            name,+            publicKeyInfo,+            Der.explicit(3, Der.sequence(*extensions.toTypedArray())),+        )+    }++    private fun extension(oid: String, value: ByteArray): ByteArray =+        Der.sequence(Der.oid(oid), Der.octetString(value))++    /**+     * Just enough DER to write one certificate.+     *+     * A public key already arrives as a DER `SubjectPublicKeyInfo` from [java.security.Key.getEncoded],+     * so it is embedded verbatim and none of the elliptic-curve parameter encoding has to be+     * written out here.+     */+    private object Der {++        fun tagged(tag: Int, content: ByteArray): ByteArray =+            byteArrayOf(tag.toByte()) + length(content.size) + content++        fun sequence(vararg parts: ByteArray): ByteArray = tagged(0x30, concat(parts))++        fun set(vararg parts: ByteArray): ByteArray = tagged(0x31, concat(parts))++        /** Context-specific, constructed - the `[n] EXPLICIT` of the X.509 definitions. */+        fun explicit(number: Int, content: ByteArray): ByteArray = tagged(0xA0 or number, content)++        fun integer(value: Int): ByteArray = integer(BigInteger.valueOf(value.toLong()))++        /** [BigInteger.toByteArray] is already two's-complement big-endian, which is DER's INTEGER. */+        fun integer(value: BigInteger): ByteArray = tagged(0x02, value.toByteArray())++        /** The leading zero is the count of unused bits in the final byte, always none here. */+        fun bitString(bytes: ByteArray): ByteArray = tagged(0x03, byteArrayOf(0) + bytes)++        fun octetString(bytes: ByteArray): ByteArray = tagged(0x04, bytes)++        fun utf8(text: String): ByteArray = tagged(0x0C, text.toByteArray(Charsets.UTF_8))++        /** UTCTime, which X.509 requires for anything before 2050. */+        fun utcTime(instant: Instant): ByteArray {+            val time = instant.atOffset(ZoneOffset.UTC)+            val text = "%02d%02d%02d%02d%02d%02dZ".format(+                time.year % 100,+                time.monthValue,+                time.dayOfMonth,+                time.hour,+                time.minute,+                time.second,+            )+            return tagged(0x17, text.toByteArray(Charsets.US_ASCII))+        }++        /** The first two arcs share a byte; the rest are base-128 with a continuation bit. */+        fun oid(dotted: String): ByteArray {+            val arcs = dotted.split('.').map { it.toLong() }+            val out = ArrayList<Byte>()+            out.add((arcs[0] * 40 + arcs[1]).toByte())+            for (arc in arcs.drop(2)) {+                val septets = ArrayList<Byte>()+                var value = arc+                do {+                    septets.add(0, (value and 0x7f).toByte())+                    value = value ushr 7+                } while (value > 0)+                for (i in septets.indices) {+                    val last = i == septets.size - 1+                    out.add(if (last) septets[i] else (septets[i].toInt() or 0x80).toByte())+                }+            }+            return tagged(0x06, out.toByteArray())+        }++        private fun length(size: Int): ByteArray {+            if (size < 0x80) return byteArrayOf(size.toByte())+            val bytes = ArrayList<Byte>()+            var value = size+            while (value > 0) {+                bytes.add(0, (value and 0xff).toByte())+                value = value ushr 8+            }+            return byteArrayOf((0x80 or bytes.size).toByte()) + bytes.toByteArray()+        }++        private fun concat(parts: Array<out ByteArray>): ByteArray {+            val out = ByteArray(parts.sumOf { it.size })+            var at = 0+            for (part in parts) {+                part.copyInto(out, at)+                at += part.size+            }+            return out+        }+    }+}
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.ktnew file mode 100644index 0000000000..fdad5f0ec3--- /dev/null+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/MediaProxy.kt@@ -0,0 +1,371 @@+package com.vayunmathur.cast.protocol++import java.io.InputStream+import java.io.OutputStream+import java.security.MessageDigest++/** Big enough that a range serve is a handful of writes, small enough to hold per connection. */+private const val COPY_BUFFER_BYTES = 64 * 1024++/**+ * The HTTP half of the media proxy: how a request is read, checked and answered.+ *+ * The phone serves app media to the TV over HTTPS instead of re-encoding it into RTP, so this+ * is the wire format for that. It lives in `:cast:protocol` rather than beside the listener in+ * `:cast` for the same reason the handshake rules do: the rules have to be testable without a+ * device, and `android.util.Log` is not available to a JVM unit test. The listener in `:cast`+ * owns the sockets and the logging; everything that decides what bytes come back is here.+ *+ * Only what a player actually sends is implemented. `GET` and `HEAD`, one byte range at a time,+ * no chunked bodies and no redirects - ExoPlayer asks for nothing else, and a proxy that+ * answers requests nobody makes is a proxy with untested code paths in it.+ */+object MediaProxy {++    /**+     * The capability token is a path segment rather than a header because it has to survive+     * being handed to a player as a plain URL. `DefaultHttpDataSource` will carry default+     * request properties, but a manifest's `<BaseURL>` and a subtitle URL are just strings, and+     * a token in the path travels with them for free.+     */+    fun url(host: String, port: Int, token: String, resourceId: String): String =+        "https://$host:$port/$token/$resourceId"++    /** Longest request line or header line accepted, to bound what an unauthenticated peer can make us buffer. */+    const val MAX_LINE_BYTES = 8 * 1024++    /** Most header lines accepted, for the same reason. */+    const val MAX_HEADERS = 64++    /**+     * Compares tokens in constant time.+     *+     * A byte-at-a-time comparison leaks the length of the matching prefix, and the token is the+     * only thing standing between a LAN peer and the user's media. Length is compared first+     * because [MessageDigest.isEqual] short-circuits on mismatched lengths, which is fine: the+     * length is not the secret.+     */+    fun tokenMatches(expected: String, offered: String): Boolean = MessageDigest.isEqual(+        expected.toByteArray(Charsets.US_ASCII),+        offered.toByteArray(Charsets.US_ASCII),+    )+}++/** A resource the proxy can serve: a known length and a stream that can start part-way in. */+interface MediaResource {++    /**+     * Total length in bytes.+     *+     * Known up front even when the bytes are not all present yet - a SABR segment still on its+     * way down has a length from its index. That is why [open] is allowed to end early and why+     * the caller has to notice when it does.+     */+    val length: Long++    val contentType: String++    /** A stream positioned at [offset]. The caller closes it. */+    fun open(offset: Long): InputStream+}++/** Maps the resource id in a request path to something servable, or null if there is no such resource. */+fun interface MediaResourceResolver {+    fun resolve(resourceId: String): MediaResource?+}++/** What a byte range in a request turned out to mean. */+sealed interface RangeSpec {++    /** No `Range` header, or one this proxy chooses not to honour. The whole resource, `200`. */+    object Whole : RangeSpec++    /** Both ends inclusive, as HTTP counts them. */+    data class Satisfiable(val first: Long, val last: Long) : RangeSpec {+        val length: Long get() = last - first + 1+    }++    /** Syntactically fine but outside the resource, which is a `416` rather than a clamp. */+    object Unsatisfiable : RangeSpec+}++/** How an exchange ended, for the listener to log. */+sealed interface ExchangeOutcome {++    data class Served(val resourceId: String, val range: RangeSpec, val bytes: Long) : ExchangeOutcome++    /** Answered with an error status. [detail] is for the log, never for the client. */+    data class Rejected(val status: Int, val detail: String) : ExchangeOutcome++    /**+     * Fewer bytes arrived from the resource than its length promised.+     *+     * The response has already been committed with a `Content-Length` by then, so there is no+     * way to turn this into an error status; the connection must be closed so the client sees a+     * truncated body instead of waiting for bytes that are not coming.+     */+    data class Truncated(val resourceId: String, val expected: Long, val actual: Long) : ExchangeOutcome++    /** The peer closed before sending a request. Ordinary at the end of a keep-alive connection. */+    object Closed : ExchangeOutcome+}++/**+ * Serves requests for one connection.+ *+ * Keep-alive is supported deliberately. Scrubbing turns into a burst of range requests, and a+ * fresh TLS handshake for each one would put the cost of a seek back into the same place the+ * RTP path had it.+ */+class MediaProxyExchange(+    private val token: String,+    private val resolver: MediaResourceResolver,+) {++    /**+     * Reads one request and writes one response.+     *+     * Returns whether the connection may be reused, alongside the outcome. Anything that leaves+     * the stream in an unknown state - a malformed request, a truncated body - ends the+     * connection, because the alternative is misreading the next request off a desynchronised+     * stream.+     */+    fun serve(input: InputStream, output: OutputStream): Result {+        val requestLine = readLine(input) ?: return Result(ExchangeOutcome.Closed, reusable = false)++        val parts = requestLine.split(' ')+        if (parts.size != 3 || !parts[2].startsWith("HTTP/1.")) {+            respondError(output, 400)+            return Result(ExchangeOutcome.Rejected(400, "malformed request line"), reusable = false)+        }+        val method = parts[0]+        val target = parts[1]++        val headers = readHeaders(input)+            ?: run {+                respondError(output, 431)+                return Result(ExchangeOutcome.Rejected(431, "too many or too long headers"), reusable = false)+            }++        if (method != "GET" && method != "HEAD") {+            respondError(output, 405)+            return Result(ExchangeOutcome.Rejected(405, "method $method"), reusable = true)+        }++        val path = parsePath(target)+        if (path == null || !MediaProxy.tokenMatches(token, path.token)) {+            // Deliberately the same answer for a bad token and an unparseable path: telling a+            // peer which of the two it got wrong tells it the shape of a valid URL.+            respondError(output, 403)+            return Result(ExchangeOutcome.Rejected(403, "bad token or path '$target'"), reusable = true)+        }++        val resource = resolver.resolve(path.resourceId)+        if (resource == null) {+            respondError(output, 404)+            return Result(ExchangeOutcome.Rejected(404, "no resource '${path.resourceId}'"), reusable = true)+        }++        val range = parseRange(headers["range"], resource.length)+        if (range is RangeSpec.Unsatisfiable) {+            respondError(+                output,+                416,+                extraHeaders = listOf("Content-Range: bytes */${resource.length}"),+            )+            return Result(ExchangeOutcome.Rejected(416, "range outside ${resource.length}"), reusable = true)+        }++        val first = if (range is RangeSpec.Satisfiable) range.first else 0L+        val bodyLength = if (range is RangeSpec.Satisfiable) range.length else resource.length++        val head = StringBuilder()+        head.append(if (range is RangeSpec.Satisfiable) "HTTP/1.1 206 Partial Content\r\n" else "HTTP/1.1 200 OK\r\n")+        head.append("Content-Type: ").append(resource.contentType).append("\r\n")+        head.append("Content-Length: ").append(bodyLength).append("\r\n")+        // Without this ExoPlayer assumes the server cannot seek and refuses to scrub at all.+        head.append("Accept-Ranges: bytes\r\n")+        if (range is RangeSpec.Satisfiable) {+            head.append("Content-Range: bytes ")+                .append(range.first).append('-').append(range.last)+                .append('/').append(resource.length).append("\r\n")+        }+        head.append("\r\n")+        output.write(head.toString().toByteArray(Charsets.ISO_8859_1))++        if (method == "HEAD") {+            output.flush()+            return Result(ExchangeOutcome.Served(path.resourceId, range, 0), reusable = true)+        }++        val written = resource.open(first).use { body -> copy(body, output, bodyLength) }+        output.flush()++        return if (written < bodyLength) {+            Result(+                ExchangeOutcome.Truncated(path.resourceId, bodyLength, written),+                reusable = false,+            )+        } else {+            Result(ExchangeOutcome.Served(path.resourceId, range, written), reusable = true)+        }+    }++    data class Result(val outcome: ExchangeOutcome, val reusable: Boolean)++    // ------------------------------------------------------------------+    // Request reading+    // ------------------------------------------------------------------++    /**+     * Reads a CRLF-terminated line a byte at a time.+     *+     * Byte at a time rather than a buffered reader because the body must be left untouched for+     * [copy] - and on a keep-alive connection, over-reading past the headers would swallow the+     * start of the next request.+     */+    private fun readLine(input: InputStream): String? {+        val out = StringBuilder()+        while (true) {+            val byte = input.read()+            if (byte == -1) return if (out.isEmpty()) null else out.toString()+            if (byte == '\n'.code) {+                if (out.isNotEmpty() && out.last() == '\r') out.setLength(out.length - 1)+                return out.toString()+            }+            if (out.length >= MediaProxy.MAX_LINE_BYTES) return null+            out.append(byte.toChar())+        }+    }++    /** Header names lowercased, because HTTP does not promise a case and clients do not agree on one. */+    private fun readHeaders(input: InputStream): Map<String, String>? {+        val headers = HashMap<String, String>()+        while (true) {+            val line = readLine(input) ?: return null+            if (line.isEmpty()) return headers+            if (headers.size >= MediaProxy.MAX_HEADERS) return null+            val colon = line.indexOf(':')+            if (colon <= 0) return null+            headers[line.substring(0, colon).trim().lowercase()] = line.substring(colon + 1).trim()+        }+    }++    private fun copy(from: InputStream, to: OutputStream, limit: Long): Long {+        val buffer = ByteArray(COPY_BUFFER_BYTES)+        var remaining = limit+        while (remaining > 0) {+            val want = minOf(remaining, buffer.size.toLong()).toInt()+            val read = from.read(buffer, 0, want)+            if (read == -1) break+            to.write(buffer, 0, read)+            remaining -= read+        }+        return limit - remaining+    }++    private fun respondError(output: OutputStream, status: Int, extraHeaders: List<String> = emptyList()) {+        val head = StringBuilder()+        head.append("HTTP/1.1 ").append(status).append(' ').append(reasonPhrase(status)).append("\r\n")+        head.append("Content-Length: 0\r\n")+        extraHeaders.forEach { head.append(it).append("\r\n") }+        head.append("\r\n")+        output.write(head.toString().toByteArray(Charsets.ISO_8859_1))+        output.flush()+    }++    private fun reasonPhrase(status: Int): String = when (status) {+        400 -> "Bad Request"+        403 -> "Forbidden"+        404 -> "Not Found"+        405 -> "Method Not Allowed"+        416 -> "Range Not Satisfiable"+        431 -> "Request Header Fields Too Large"+        else -> "Error"+    }++    companion object {++        data class ProxyPath(val token: String, val resourceId: String)++        /**+         * Splits `/<token>/<resourceId>` and drops any query string.+         *+         * The resource id may itself contain slashes: a SABR segment is naturally addressed as+         * `<itag>/<sequence>`, so everything after the token is the id.+         */+        fun parsePath(target: String): ProxyPath? {+            val withoutQuery = target.substringBefore('?')+            if (!withoutQuery.startsWith('/')) return null+            val rest = withoutQuery.substring(1)+            val slash = rest.indexOf('/')+            if (slash <= 0 || slash == rest.length - 1) return null+            return ProxyPath(+                token = percentDecode(rest.substring(0, slash)),+                resourceId = percentDecode(rest.substring(slash + 1)),+            )+        }++        /**+         * Interprets a `Range` header against a known [length].+         *+         * Multi-range requests are answered with the whole resource rather than a multipart+         * body. HTTP permits ignoring a `Range` you do not want to honour, ExoPlayer never asks+         * for more than one range, and a multipart encoder would be code with no caller.+         */+        fun parseRange(header: String?, length: Long): RangeSpec {+            if (header == null) return RangeSpec.Whole+            val value = header.trim()+            if (!value.startsWith("bytes=", ignoreCase = true)) return RangeSpec.Whole+            val spec = value.substring("bytes=".length).trim()+            if (spec.contains(',')) return RangeSpec.Whole++            val dash = spec.indexOf('-')+            if (dash < 0) return RangeSpec.Unsatisfiable+            val fromText = spec.substring(0, dash).trim()+            val toText = spec.substring(dash + 1).trim()++            // A zero-length resource can satisfy no range at all, not even `bytes=0-`.+            if (length <= 0L) return RangeSpec.Unsatisfiable++            if (fromText.isEmpty()) {+                // A suffix range: the last N bytes.+                val suffix = toText.toLongOrNull() ?: return RangeSpec.Unsatisfiable+                if (suffix <= 0L) return RangeSpec.Unsatisfiable+                val first = maxOf(0L, length - suffix)+                return RangeSpec.Satisfiable(first, length - 1)+            }++            val first = fromText.toLongOrNull() ?: return RangeSpec.Unsatisfiable+            if (first < 0L || first >= length) return RangeSpec.Unsatisfiable+            val last = if (toText.isEmpty()) {+                length - 1+            } else {+                val stated = toText.toLongOrNull() ?: return RangeSpec.Unsatisfiable+                if (stated < first) return RangeSpec.Unsatisfiable+                minOf(stated, length - 1)+            }+            return RangeSpec.Satisfiable(first, last)+        }++        private fun percentDecode(text: String): String {+            if (!text.contains('%')) return text+            val out = java.io.ByteArrayOutputStream(text.length)+            var i = 0+            while (i < text.length) {+                val c = text[i]+                if (c == '%' && i + 2 < text.length) {+                    val hex = text.substring(i + 1, i + 3).toIntOrNull(16)+                    if (hex != null) {+                        out.write(hex)+                        i += 3+                        continue+                    }+                }+                out.write(c.code)+                i+++            }+            return String(out.toByteArray(), Charsets.UTF_8)+        }+    }+}
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/EphemeralTlsTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/EphemeralTlsTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/EphemeralTlsTest.ktnew file mode 100644index 0000000000..86573ab129--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/EphemeralTlsTest.kt@@ -0,0 +1,166 @@+package com.vayunmathur.cast.protocol++import java.net.InetAddress+import javax.net.ssl.SSLException+import javax.net.ssl.SSLSocket+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Tests for the session-pinned TLS the media proxy runs on.+ *+ * The certificate is assembled from hand-written DER, so the first thing to establish is that it+ * is a certificate at all: [java.security.cert.CertificateFactory] parsing it and the signature+ * verifying against its own key together catch every structural mistake, and a mistake here would+ * otherwise show up as an unexplained handshake failure on a TV.+ *+ * The second thing is that the pin is load-bearing in both directions. A trust manager that+ * accepts the right certificate but also accepts a wrong one is the failure that matters, because+ * it looks exactly like success.+ */+class EphemeralTlsTest {++    private val loopback: InetAddress = InetAddress.getLoopbackAddress()++    @Test+    fun `mints a certificate that parses and carries its own valid signature`() {+        val certificate = EphemeralTls.server(listOf(loopback)).certificate+        // Self-signed, so its own public key is the one that has to verify it. This is the check+        // that fails if any length prefix in the hand-written DER is wrong.+        certificate.verify(certificate.publicKey)+        certificate.checkValidity()+        assertEquals(3, certificate.version, "extensions require a v3 certificate")+        assertTrue(certificate.serialNumber.signum() > 0, "a negative serial number is malformed")+        assertEquals(certificate.subjectX500Principal, certificate.issuerX500Principal)+        assertTrue(certificate.subjectX500Principal.name.contains("Modern Apps cast"))+    }++    @Test+    fun `is already valid when a TV's clock is behind ours`() {+        // A TV that has been unplugged can come up hours behind. Anything in the stack that+        // checks dates would reject a certificate stamped in what it believes is the future.+        val certificate = EphemeralTls.server(listOf(loopback)).certificate+        assertTrue(+            certificate.notBefore.toInstant().isBefore(java.time.Instant.now().minusSeconds(3_600)),+            "the certificate must already be valid by an hour at least",+        )+    }++    @Test+    fun `names every address it was given so the hostname check can pass`() {+        // The TV dials an IP address. Without an iPAddress SAN the pin would accept the+        // certificate and the hostname check would then reject it, which no amount of pinning+        // fixes and which reads as an unrelated failure.+        val address = InetAddress.getByName("192.168.0.82")+        val names = assertNotNull(+            EphemeralTls.server(listOf(loopback, address)).certificate.subjectAlternativeNames,+            "a certificate with no subject alternative names cannot be used for a bare IP",+        )+        val ips = names.filter { it[0] == 7 }.map { it[1] as String }+        assertTrue(ips.contains("192.168.0.82"), "got $ips")+        assertTrue(ips.contains(loopback.hostAddress), "got $ips")+    }++    @Test+    fun `marks itself for server authentication`() {+        val usage = EphemeralTls.server(listOf(loopback)).certificate.extendedKeyUsage+        assertEquals(listOf("1.3.6.1.5.5.7.3.1"), usage)+    }++    @Test+    fun `fingerprints the DER encoding, which is what the TV is told to pin`() {+        val credentials = EphemeralTls.server(listOf(loopback))+        val expected = java.security.MessageDigest.getInstance("SHA-256")+            .digest(credentials.certificate.encoded)+        assertContentEquals(expected, credentials.fingerprint)+        assertEquals(32, credentials.fingerprint.size)+    }++    @Test+    fun `mints a different key every session`() {+        // The certificate is thrown away with the session, so two sessions sharing a key would+        // mean a fingerprint from one session still worked against the next.+        val first = EphemeralTls.server(listOf(loopback))+        val second = EphemeralTls.server(listOf(loopback))+        assertTrue(!first.fingerprint.contentEquals(second.fingerprint))+    }++    @Test+    fun `a client pinned to the fingerprint completes the handshake`() {+        val credentials = EphemeralTls.server(listOf(loopback))+        withServer(credentials) { port ->+            val socket = EphemeralTls.client(credentials.fingerprint)+                .socketFactory.createSocket(loopback, port) as SSLSocket+            socket.use {+                it.soTimeout = 5_000+                it.startHandshake()+                it.outputStream.write(41)+                it.outputStream.flush()+                assertEquals(42, it.inputStream.read(), "the connection handshook but carried nothing")+            }+        }+    }++    @Test+    fun `a client pinned to another fingerprint refuses to talk`() {+        val credentials = EphemeralTls.server(listOf(loopback))+        val otherFingerprint = EphemeralTls.server(listOf(loopback)).fingerprint+        withServer(credentials) { port ->+            val socket = EphemeralTls.client(otherFingerprint)+                .socketFactory.createSocket(loopback, port) as SSLSocket+            socket.use {+                it.soTimeout = 5_000+                assertFailsWith<SSLException> { it.startHandshake() }+            }+        }+    }++    @Test+    fun `a client trusting the platform's authorities refuses an ephemeral certificate`() {+        // Confirms the certificate is genuinely untrusted without the pin - if the default trust+        // manager accepted it, the pin would be decoration.+        val credentials = EphemeralTls.server(listOf(loopback))+        withServer(credentials) { port ->+            val socket = javax.net.ssl.SSLContext.getDefault()+                .socketFactory.createSocket(loopback, port) as SSLSocket+            socket.use {+                it.soTimeout = 5_000+                assertFailsWith<SSLException> { it.startHandshake() }+            }+        }+    }++    /**+     * Runs a one-shot echo server on the credentials, for the duration of [body].+     *+     * The server thread swallows its exceptions on purpose: the tests that assert a refusal cause+     * one here too, and the assertion belongs on the client side where the pin is.+     */+    private fun withServer(credentials: EphemeralTls.ServerCredentials, body: (Int) -> Unit) {+        val server = credentials.sslContext.serverSocketFactory.createServerSocket(0, 1, loopback)+        val thread = Thread {+            runCatching {+                server.accept().use { client ->+                    client.soTimeout = 5_000+                    val byte = client.inputStream.read()+                    if (byte != -1) {+                        client.outputStream.write(byte + 1)+                        client.outputStream.flush()+                    }+                }+            }+        }+        thread.isDaemon = true+        thread.start()+        try {+            body(server.localPort)+        } finally {+            runCatching { server.close() }+            thread.join(2_000)+        }+    }+}
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.ktnew file mode 100644index 0000000000..3a8dda8b9a--- /dev/null+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/MediaProxyTest.kt@@ -0,0 +1,314 @@+package com.vayunmathur.cast.protocol++import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.InputStream+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Tests for the media proxy's HTTP behaviour.+ *+ * The proxy replaces a re-encode with a byte serve, so the thing that has to be right is the+ * arithmetic of a byte range. A range served off by one is not a visible error at either end: the+ * TV's demuxer gets a frame it cannot parse and reports a corrupt stream, which is indistinguishable+ * from a hundred other faults. Every offset is therefore checked against the source bytes rather+ * than against a recomputed expectation.+ *+ * The refusals matter for a different reason. This is a socket open on the LAN, so a request with+ * the wrong token or no token has to be turned away without saying why, and without ever reaching+ * a resolver that would touch the user's files.+ */+class MediaProxyTest {++    private val token = "s3cr3t-token"+    private val media = ByteArray(5_000) { (it * 31 % 251).toByte() }++    // ------------------------------------------------------------------+    // Range arithmetic+    // ------------------------------------------------------------------++    @Test+    fun `serves the whole resource when nothing asks for a range`() {+        val response = exchange().get("/$token/track")+        assertEquals(200, response.status)+        assertEquals("5000", response.headers["content-length"])+        assertEquals("bytes", response.headers["accept-ranges"], "without this ExoPlayer will not scrub at all")+        assertNull(response.headers["content-range"])+        assertContentEquals(media, response.body)+    }++    @Test+    fun `serves a closed range inclusive of both ends`() {+        val response = exchange().get("/$token/track", "Range: bytes=100-199")+        assertEquals(206, response.status)+        assertEquals("bytes 100-199/5000", response.headers["content-range"])+        assertEquals("100", response.headers["content-length"], "HTTP ranges include the last byte")+        assertContentEquals(media.copyOfRange(100, 200), response.body)+    }++    @Test+    fun `serves an open range to the end of the resource`() {+        val response = exchange().get("/$token/track", "Range: bytes=4900-")+        assertEquals(206, response.status)+        assertEquals("bytes 4900-4999/5000", response.headers["content-range"])+        assertContentEquals(media.copyOfRange(4900, 5000), response.body)+    }++    @Test+    fun `serves a suffix range counted back from the end`() {+        val response = exchange().get("/$token/track", "Range: bytes=-250")+        assertEquals(206, response.status)+        assertEquals("bytes 4750-4999/5000", response.headers["content-range"])+        assertContentEquals(media.copyOfRange(4750, 5000), response.body)+    }++    @Test+    fun `clamps a range that runs past the end rather than refusing it`() {+        // Asking for more than exists is normal: a player that knows the length only+        // approximately will overshoot, and a 416 there would end playback.+        val response = exchange().get("/$token/track", "Range: bytes=4990-99999")+        assertEquals(206, response.status)+        assertEquals("bytes 4990-4999/5000", response.headers["content-range"])+        assertEquals(10, response.body.size)+    }++    @Test+    fun `serves a single byte`() {+        val response = exchange().get("/$token/track", "Range: bytes=1234-1234")+        assertEquals(206, response.status)+        assertEquals("1", response.headers["content-length"])+        assertContentEquals(byteArrayOf(media[1234]), response.body)+    }++    @Test+    fun `refuses a range that starts past the end`() {+        val response = exchange().get("/$token/track", "Range: bytes=5000-5100")+        assertEquals(416, response.status)+        assertEquals(+            "bytes */5000",+            response.headers["content-range"],+            "a 416 has to state the real length or the player cannot correct itself",+        )+    }++    @Test+    fun `ignores a multi-range request instead of answering it wrongly`() {+        // A multipart/byteranges body is code with no caller: ExoPlayer never asks for two+        // ranges. Serving the whole resource is a permitted answer; a malformed multipart+        // body would not be.+        val response = exchange().get("/$token/track", "Range: bytes=0-99, 200-299")+        assertEquals(200, response.status)+        assertEquals(5000, response.body.size)+    }++    @Test+    fun `parses range headers without needing a resource`() {+        assertEquals(RangeSpec.Satisfiable(0, 9), MediaProxyExchange.parseRange("bytes=0-9", 100))+        assertEquals(RangeSpec.Satisfiable(90, 99), MediaProxyExchange.parseRange("bytes=90-", 100))+        assertEquals(RangeSpec.Satisfiable(95, 99), MediaProxyExchange.parseRange("bytes=-5", 100))+        assertEquals(RangeSpec.Whole, MediaProxyExchange.parseRange(null, 100))+        // A unit we do not speak is not an error; the header is simply not honoured.+        assertEquals(RangeSpec.Whole, MediaProxyExchange.parseRange("items=0-9", 100))+        assertEquals(RangeSpec.Unsatisfiable, MediaProxyExchange.parseRange("bytes=100-", 100))+        assertEquals(RangeSpec.Unsatisfiable, MediaProxyExchange.parseRange("bytes=9-0", 100))+        assertEquals(RangeSpec.Unsatisfiable, MediaProxyExchange.parseRange("bytes=-0", 100))+        assertEquals(RangeSpec.Unsatisfiable, MediaProxyExchange.parseRange("bytes=abc-", 100))+        // A resource with no bytes can satisfy no range, and reporting one would have the+        // player read a body that is not there.+        assertEquals(RangeSpec.Unsatisfiable, MediaProxyExchange.parseRange("bytes=0-", 0))+    }++    // ------------------------------------------------------------------+    // Refusals+    // ------------------------------------------------------------------++    @Test+    fun `refuses a request carrying the wrong token`() {+        var asked = false+        val exchange = MediaProxyExchange(token) { asked = true; FakeResource(media) }+        val response = exchange.get("/not-the-token/track")+        assertEquals(403, response.status)+        assertTrue(!asked, "a bad token must be turned away before anything opens a file")+    }++    @Test+    fun `refuses a request with no token at all`() {+        assertEquals(403, exchange().get("/track").status)+        assertEquals(403, exchange().get("/").status)+    }++    @Test+    fun `answers an unknown resource and a bad token differently only in the log`() {+        // 403 for a bad token and 404 for a missing resource is deliberate: the token gate is+        // reached first, so a peer without the token learns nothing about what exists.+        assertEquals(403, exchange().get("/wrong/track").status)+        assertEquals(404, exchange().get("/$token/no-such-track").status)+    }++    @Test+    fun `refuses a method it does not implement`() {+        val response = exchange().request("PUT /$token/track HTTP/1.1\r\nHost: x\r\n\r\n")+        assertEquals(405, response.status)+    }++    @Test+    fun `ends the connection on a malformed request line rather than guessing`() {+        val result = exchange().serve("GARBAGE\r\n\r\n")+        assertEquals(400, assertIs<ExchangeOutcome.Rejected>(result.first.outcome).status)+        assertTrue(+            !result.first.reusable,+            "after an unparseable request the stream position is unknown, so the next read would " ++                "be nonsense",+        )+    }++    @Test+    fun `reports a peer that closed before asking for anything`() {+        val result = exchange().serve("")+        assertEquals(ExchangeOutcome.Closed, result.first.outcome)+    }++    // ------------------------------------------------------------------+    // Paths+    // ------------------------------------------------------------------++    @Test+    fun `keeps slashes inside a resource id`() {+        // A SABR segment is naturally addressed as itag and sequence number, so everything+        // after the token is the id.+        val path = MediaProxyExchange.parsePath("/tok/251/17")+        assertEquals("tok", path?.token)+        assertEquals("251/17", path?.resourceId)+    }++    @Test+    fun `drops a query string and decodes escapes`() {+        assertEquals("track 1", MediaProxyExchange.parsePath("/tok/track%201?cachebust=9")?.resourceId)+        assertNull(MediaProxyExchange.parsePath("relative/path"))+        assertNull(MediaProxyExchange.parsePath("/tok/"))+        assertNull(MediaProxyExchange.parsePath("/tok"))+    }++    // ------------------------------------------------------------------+    // Partly available resources+    // ------------------------------------------------------------------++    @Test+    fun `closes the connection when a resource yields less than its stated length`() {+        // The case a SABR segment hits: the length is known from the index while the last bytes+        // are still arriving. The response has a Content-Length by the time this is discovered,+        // so the only honest signal left is to close - a player that keeps the connection open+        // would wait for bytes that are not coming.+        val withheld = FakeResource(media, availableBytes = media.size - 1)+        val exchange = MediaProxyExchange(token) { withheld }+        val result = exchange.serve("GET /$token/track HTTP/1.1\r\nRange: bytes=4990-4999\r\n\r\n")++        val outcome = assertIs<ExchangeOutcome.Truncated>(result.first.outcome)+        assertEquals(10, outcome.expected)+        assertEquals(9, outcome.actual)+        assertTrue(!result.first.reusable, "a short body leaves the connection unusable")+    }++    @Test+    fun `serves a range that stops short of a withheld final byte in full`() {+        val withheld = FakeResource(media, availableBytes = media.size - 1)+        val exchange = MediaProxyExchange(token) { withheld }+        val response = exchange.get("/$token/track", "Range: bytes=4000-4500")+        assertEquals(206, response.status)+        assertContentEquals(media.copyOfRange(4000, 4501), response.body)+    }++    // ------------------------------------------------------------------+    // Connection reuse+    // ------------------------------------------------------------------++    @Test+    fun `serves several ranges down one connection`() {+        // Scrubbing is a burst of range requests. If each one needed a new connection the cost+        // of a seek would be a TLS handshake, which is what this path exists to avoid.+        val exchange = MediaProxyExchange(token) { FakeResource(media) }+        val input = ByteArrayInputStream(+            (+                "GET /$token/track HTTP/1.1\r\nRange: bytes=0-9\r\n\r\n" ++                    "GET /$token/track HTTP/1.1\r\nRange: bytes=10-19\r\n\r\n"+                ).toByteArray(Charsets.ISO_8859_1),+        )++        val first = ByteArrayOutputStream()+        assertTrue(exchange.serve(input, first).reusable)+        assertContentEquals(media.copyOfRange(0, 10), parse(first.toByteArray()).body)++        val second = ByteArrayOutputStream()+        exchange.serve(input, second)+        assertContentEquals(+            media.copyOfRange(10, 20),+            parse(second.toByteArray()).body,+            "the second request was misread, which means the first over-read its headers",+        )+    }++    @Test+    fun `answers a HEAD with the headers and no body`() {+        val response = exchange().request("HEAD /$token/track HTTP/1.1\r\n\r\n")+        assertEquals(200, response.status)+        assertEquals("5000", response.headers["content-length"])+        assertEquals(0, response.body.size, "a HEAD body would desynchronise the connection")+    }++    // ------------------------------------------------------------------+    // Helpers+    // ------------------------------------------------------------------++    private fun exchange() = MediaProxyExchange(token) { id ->+        if (id == "track" || id.startsWith("251/")) FakeResource(media) else null+    }++    private class FakeResource(+        private val bytes: ByteArray,+        override val contentType: String = "audio/ogg",+        /** Fewer than [bytes] to stand in for a file that is still being written. */+        private val availableBytes: Int = bytes.size,+    ) : MediaResource {+        override val length: Long get() = bytes.size.toLong()++        override fun open(offset: Long): InputStream {+            val from = offset.toInt()+            val count = (availableBytes - from).coerceAtLeast(0)+            return ByteArrayInputStream(bytes, from, count)+        }+    }++    private class Response(val status: Int, val headers: Map<String, String>, val body: ByteArray)++    private fun MediaProxyExchange.get(target: String, vararg headers: String): Response =+        request("GET $target HTTP/1.1\r\n" + headers.joinToString("") { "$it\r\n" } + "\r\n")++    private fun MediaProxyExchange.request(raw: String): Response = parse(serve(raw).second)++    private fun MediaProxyExchange.serve(raw: String): Pair<MediaProxyExchange.Result, ByteArray> {+        val output = ByteArrayOutputStream()+        val result = serve(ByteArrayInputStream(raw.toByteArray(Charsets.ISO_8859_1)), output)+        return result to output.toByteArray()+    }++    private fun parse(raw: ByteArray): Response {+        val separator = "\r\n\r\n".toByteArray(Charsets.ISO_8859_1)+        val end = (0..raw.size - separator.size).firstOrNull { at ->+            separator.indices.all { raw[at + it] == separator[it] }+        } ?: error("response has no header terminator")++        val lines = String(raw, 0, end, Charsets.ISO_8859_1).split("\r\n")+        return Response(+            status = lines[0].split(' ')[1].toInt(),+            headers = lines.drop(1).filter { it.contains(':') }.associate {+                it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim()+            },+            body = raw.copyOfRange(end + separator.size, raw.size),+        )+    }+}
cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.ktnew file mode 100644index 0000000000..416420b51e--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MediaProxyServer.kt@@ -0,0 +1,209 @@+package com.vayunmathur.cast.platform++import android.util.Log+import com.vayunmathur.cast.protocol.EphemeralTls+import com.vayunmathur.cast.protocol.ExchangeOutcome+import com.vayunmathur.cast.protocol.MediaProxyExchange+import com.vayunmathur.cast.protocol.MediaResourceResolver+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import java.net.InetAddress+import java.net.NetworkInterface+import java.net.Socket+import java.security.SecureRandom+import java.util.Base64+import java.util.concurrent.atomic.AtomicInteger+import javax.net.ssl.SSLServerSocket+import javax.net.ssl.SSLSocket++private const val TAG = "MediaProxyServer"++/**+ * How long a connection may sit idle between requests before it is reaped.+ *+ * Keep-alive is worth having - scrubbing is a burst of range requests - but a connection nobody+ * is using is a thread and a descriptor, and the TV opens a fresh one whenever it needs to.+ */+private const val IDLE_TIMEOUT_MS = 30_000++/**+ * More connections than any session needs, and few enough that a hostile peer on the LAN cannot+ * exhaust the process by opening sockets.+ *+ * A worst case is video, audio, a caption track and artwork at once, so this is generous.+ */+private const val MAX_CONNECTIONS = 16++/**+ * Serves app media to the TV over HTTPS, so the phone does not have to re-encode it.+ *+ * This is the whole reason the pixel path can go away for app content. The TV asks for byte+ * ranges of the original file and plays them with its own decoder, clock and buffer, which means+ * seeking is an offset rather than a key-frame renegotiation, pausing is the TV's business+ * entirely, and the phone neither decodes nor encodes a frame.+ *+ * The server belongs in `:cast` and not in the app being cast. `:sdk:cast` exists so that a+ * consumer owns no sockets and needs no network permission - `:music` has no `INTERNET`+ * permission at all - so the app supplies bytes through a [MediaResourceResolver] and this end+ * puts them on the wire.+ *+ * Everything that decides *what* to answer lives in `:cast:protocol`+ * ([MediaProxyExchange], [EphemeralTls]), where it can be tested without a TV. What is left here+ * is sockets, threads and lifecycle.+ */+class MediaProxyServer(+    private val token: String,+    private val resolver: MediaResourceResolver,+) {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private val exchange = MediaProxyExchange(token, resolver)+    private val connections = AtomicInteger(0)++    private var server: SSLServerSocket? = null++    /** What the TV has to be told to be able to fetch anything. */+    data class Endpoint(val port: Int, val certificateFingerprint: ByteArray) {+        override fun equals(other: Any?): Boolean = other is Endpoint &&+            port == other.port && certificateFingerprint.contentEquals(other.certificateFingerprint)++        override fun hashCode(): Int = 31 * port + certificateFingerprint.contentHashCode()+    }++    /**+     * Binds an ephemeral port and starts accepting.+     *+     * [addresses] end up as subject alternative names in the certificate, so they have to be the+     * addresses the TV will actually dial. Returns null when the port cannot be bound, which the+     * caller turns into a refused session rather than a session that silently plays nothing.+     */+    fun start(addresses: List<InetAddress> = localAddresses()): Endpoint? {+        if (server != null) return null+        return try {+            val credentials = EphemeralTls.server(addresses)+            val socket = credentials.sslContext.serverSocketFactory+                .createServerSocket(0, MAX_CONNECTIONS, InetAddress.getByName("0.0.0.0")) as SSLServerSocket+            restrictProtocols(socket.supportedProtocols) { socket.enabledProtocols = it }+            server = socket+            Log.i(TAG, "media proxy listening on ${socket.localPort} for ${addresses.joinToString { it.hostAddress ?: "?" }}")+            accept(socket)+            Endpoint(socket.localPort, credentials.fingerprint)+        } catch (e: Exception) {+            Log.w(TAG, "could not start the media proxy", e)+            stop()+            null+        }+    }++    fun stop() {+        // Closing the server socket is what unblocks the accept loop; cancelling first would+        // leave it parked in a blocking accept until a connection happened to arrive.+        runCatching { server?.close() }+        server = null+        scope.cancel()+    }++    private fun accept(socket: SSLServerSocket) {+        scope.launch {+            while (isActive) {+                val client = try {+                    socket.accept() as SSLSocket+                } catch (e: Exception) {+                    if (isActive) Log.w(TAG, "accept failed", e)+                    break+                }+                if (connections.get() >= MAX_CONNECTIONS) {+                    Log.w(TAG, "refusing a connection: already serving ${connections.get()}")+                    runCatching { client.close() }+                    continue+                }+                connections.incrementAndGet()+                scope.launch { serve(client) }+            }+        }+    }++    private fun serve(client: SSLSocket) {+        try {+            client.soTimeout = IDLE_TIMEOUT_MS+            // Nagle would hold back the tail of a response waiting for more to send, which on a+            // small range request is pure added latency.+            client.tcpNoDelay = true+            val input = client.inputStream.buffered()+            val output = client.outputStream.buffered()+            while (true) {+                val result = exchange.serve(input, output)+                report(result.outcome, client)+                if (!result.reusable) break+            }+        } catch (e: Exception) {+            // A player that has finished with a range simply closes, so this is the ordinary end+            // of a connection as often as it is a fault.+            Log.d(TAG, "connection from ${client.inetAddress?.hostAddress} ended: ${e.javaClass.simpleName}")+        } finally {+            runCatching { client.close() }+            connections.decrementAndGet()+        }+    }++    private fun report(outcome: ExchangeOutcome, client: SSLSocket) {+        val peer = client.inetAddress?.hostAddress+        when (outcome) {+            is ExchangeOutcome.Served ->+                Log.d(TAG, "served ${outcome.resourceId} ${outcome.bytes} bytes to $peer")+            is ExchangeOutcome.Rejected ->+                // Logged as a warning because on a pinned, tokenised connection there is no+                // legitimate source of a rejected request: it is either a bug at our end or a+                // peer that should not be talking to us.+                Log.w(TAG, "refused $peer with ${outcome.status}: ${outcome.detail}")+            is ExchangeOutcome.Truncated ->+                Log.w(+                    TAG,+                    "${outcome.resourceId} gave ${outcome.actual} of ${outcome.expected} bytes; " ++                        "closing so the player sees a short body rather than a stall",+                )+            ExchangeOutcome.Closed -> Unit+        }+    }++    companion object {++        /**+         * A capability token for one session.+         *+         * URL-safe because it becomes a path segment, and unpadded so it needs no escaping. 32+         * bytes rather than something shorter because the token is the only thing between a LAN+         * peer that has guessed the port and the user's media.+         */+        fun randomToken(): String {+            val bytes = ByteArray(32)+            SecureRandom().nextBytes(bytes)+            return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)+        }++        /** Every non-loopback address the TV might reach us on. */+        fun localAddresses(): List<InetAddress> =+            runCatching {+                NetworkInterface.getNetworkInterfaces().asSequence()+                    .filter { it.isUp && !it.isLoopback }+                    .flatMap { it.inetAddresses.asSequence() }+                    .filterNot { it.isLoopbackAddress || it.isLinkLocalAddress }+                    .toList()+            }.getOrDefault(emptyList())++        /**+         * TLS 1.2 at the oldest.+         *+         * Both ends are ours, so there is no legacy peer to accommodate, and the older protocols+         * are enabled by default on some platform versions.+         */+        private inline fun restrictProtocols(supported: Array<String>, apply: (Array<String>) -> Unit) {+            val wanted = supported.filter { it == "TLSv1.2" || it == "TLSv1.3" }+            if (wanted.isNotEmpty()) apply(wanted.toTypedArray())+        }+    }+}