Yokan / rebuild
Course 1 8624561

CastController.jvmCommon.kt

composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastController.jvmCommon.kt

implementation124 lines
1package eu.friedcutlet.yokan.services.media.cast23import java.io.EOFException4import java.net.DatagramPacket5import java.net.InetAddress6import java.net.InetSocketAddress7import java.net.MulticastSocket8import java.net.SocketTimeoutException9import java.security.cert.X509Certificate10import javax.net.ssl.SSLContext11import javax.net.ssl.SSLSocket12import javax.net.ssl.TrustManager13import javax.net.ssl.X509TrustManager14import kotlin.time.Duration.Companion.seconds15import kotlin.time.TimeMark16import kotlin.time.TimeSource17import kotlinx.coroutines.CoroutineScope18import kotlinx.coroutines.Dispatchers19import kotlinx.coroutines.currentCoroutineContext20import kotlinx.coroutines.ensureActive21import kotlinx.coroutines.flow.Flow22import kotlinx.coroutines.flow.distinctUntilChanged23import kotlinx.coroutines.flow.flow24import kotlinx.coroutines.flow.flowOn25import kotlinx.coroutines.withContext2627actual fun createCastController(scope: CoroutineScope): CastController =28    NetworkCastController(scope, ::discoverCastDevices, ::openCastSocket)2930/** Holds whatever the platform needs to receive multicast while discovering; returns the release action. */31internal expect fun holdCastMulticastLock(): () -> Unit3233private val MDNS_GROUP: InetAddress = InetAddress.getByName("224.0.0.251")34private const val MDNS_PORT = 535335private val QUERY_INTERVAL = 3.seconds36private val DEVICE_EXPIRY = 30.seconds3738/**39 * Re-sends the `_googlecast._tcp` PTR query every 3s from an ephemeral port, so responders answer by unicast40 * (RFC 6762 §6.7 legacy queries) and port 5353 never has to be shared with the OS responder.41 * Devices not heard from for 30s are dropped.42 */43internal fun discoverCastDevices(): Flow<List<CastDevice>> = flow {44    val release = holdCastMulticastLock()45    try {46        MulticastSocket().use { socket ->47            socket.timeToLive = 25548            socket.soTimeout = 100049            val query = castMdnsQuery()50            val buffer = ByteArray(9000)51            val packet = DatagramPacket(buffer, buffer.size)52            val seen = linkedMapOf<String, Pair<CastDevice, TimeMark>>()53            var lastQuery: TimeMark? = null54            while (true) {55                currentCoroutineContext().ensureActive()56                if (lastQuery == null || lastQuery.elapsedNow() >= QUERY_INTERVAL) {57                    socket.send(DatagramPacket(query, query.size, MDNS_GROUP, MDNS_PORT))58                    lastQuery = TimeSource.Monotonic.markNow()59                }60                try {61                    packet.setLength(buffer.size)62                    socket.receive(packet)63                    val now = TimeSource.Monotonic.markNow()64                    parseCastMdnsResponse(buffer.copyOf(packet.length), packet.address.hostAddress.orEmpty())65                        .forEach { seen[it.id] = it to now }66                } catch (_: SocketTimeoutException) {67                    // Wake up to re-query, expire devices and observe cancellation.68                }69                seen.values.removeAll { it.second.elapsedNow() > DEVICE_EXPIRY }70                emit(seen.values.map { it.first }.sortedBy { it.name.lowercase() })71            }72        }73    } finally {74        release()75    }76}.flowOn(Dispatchers.IO).distinctUntilChanged()7778private class SocketCastTransport(private val socket: SSLSocket) : CastTransport {79    private val input = socket.inputStream80    private val output = socket.outputStream81    private val buffer = ByteArray(16 * 1024)8283    override suspend fun write(frame: ByteArray) = withContext(Dispatchers.IO) {84        output.write(frame)85        output.flush()86    }8788    // Blocking read; close() unblocks it with a SocketException.89    override suspend fun read(): ByteArray = withContext(Dispatchers.IO) {90        val count = input.read(buffer)91        if (count < 0) throw EOFException("Cast device closed the connection")92        buffer.copyOf(count)93    }9495    override fun close() = socket.close()96}9798private suspend fun openCastSocket(device: CastDevice): CastTransport = withContext(Dispatchers.IO) {99    val context = SSLContext.getInstance("TLS").apply { init(null, arrayOf<TrustManager>(AcceptReceiverCertificate), null) }100    // A plain SSLSocket performs no hostname verification (no endpoint identification algorithm is set),101    // which is required: receivers are addressed by LAN IP, not by a name on their certificate.102    val socket = context.socketFactory.createSocket() as SSLSocket103    try {104        socket.connect(InetSocketAddress(device.host, device.port), CAST_CONNECT_TIMEOUT_MS.toInt())105        socket.soTimeout = CAST_CONNECT_TIMEOUT_MS.toInt()106        socket.startHandshake()107        socket.soTimeout = 0108        SocketCastTransport(socket)109    } catch (e: Throwable) {110        socket.close()111        throw e112    }113}114115/**116 * Chromecast receivers present a self-signed per-device TLS certificate (authenticity is proven separately by117 * Google's device-auth challenge, which this client does not implement), so platform trust stores always reject118 * it. Installed only on the Cast socket's own SSLContext; no other connection is affected.119 */120private object AcceptReceiverCertificate : X509TrustManager {121    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit122    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit123    override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()124}125

Search chapters, reference and source filenames.