Yokan / rebuild
Course 1 8624561

CastMdns.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/media/cast/CastMdns.kt

implementation134 lines
1package eu.friedcutlet.yokan.services.media.cast23internal const val CAST_MDNS_SERVICE = "_googlecast._tcp.local"4private const val TYPE_A = 15private const val TYPE_PTR = 126private const val TYPE_TXT = 167private const val TYPE_SRV = 3389/** One-question mDNS query: PTR `_googlecast._tcp.local` IN. */10internal fun castMdnsQuery(): ByteArray {11    val labels = CAST_MDNS_SERVICE.split('.').map { it.encodeToByteArray() }12    val out = ByteArray(12 + labels.sumOf { it.size + 1 } + 1 + 4)13    out[5] = 1 // QDCOUNT14    var p = 1215    for (label in labels) {16        out[p++] = label.size.toByte()17        label.copyInto(out, p)18        p += label.size19    }20    p++ // root label21    out[p + 1] = TYPE_PTR.toByte()22    out[p + 3] = 1 // class IN23    return out24}2526/**27 * Cast devices announced in an mDNS response. Host comes from the SRV target's A record, falling back to28 * [sourceHost] (the responder's address). Malformed or truncated packets yield an empty list.29 */30internal fun parseCastMdnsResponse(packet: ByteArray, sourceHost: String): List<CastDevice> = try {31    MdnsReader(packet).castDevices(sourceHost)32} catch (_: IllegalArgumentException) {33    emptyList()34}3536private class MdnsReader(private val bytes: ByteArray) {37    var pos = 03839    fun u8(): Int {40        require(pos < bytes.size) { "Truncated mDNS packet" }41        return bytes[pos++].toInt() and 0xFF42    }4344    fun u16() = (u8() shl 8) or u8()4546    fun skip(count: Int) {47        require(count in 0..bytes.size - pos) { "Truncated mDNS packet" }48        pos += count49    }5051    /** Reads a possibly compressed name (RFC 1035 §4.1.4). */52    fun name(): String {53        val labels = mutableListOf<String>()54        var cursor = pos55        var jumps = 056        var end = -157        while (true) {58            require(cursor < bytes.size) { "Truncated mDNS name" }59            val length = bytes[cursor].toInt() and 0xFF60            when {61                length == 0 -> { cursor++; break }62                (length and 0xC0) == 0xC0 -> {63                    require(cursor + 1 < bytes.size && ++jumps <= 32) { "Bad mDNS name pointer" }64                    if (end < 0) end = cursor + 265                    cursor = ((length and 0x3F) shl 8) or (bytes[cursor + 1].toInt() and 0xFF)66                }67                (length and 0xC0) != 0 -> throw IllegalArgumentException("Bad mDNS label")68                else -> {69                    require(cursor + 1 + length <= bytes.size) { "Truncated mDNS label" }70                    labels += bytes.decodeToString(cursor + 1, cursor + 1 + length)71                    cursor += 1 + length72                }73            }74        }75        pos = if (end < 0) cursor else end76        return labels.joinToString(".")77    }7879    fun castDevices(sourceHost: String): List<CastDevice> {80        skip(2) // id81        require((u16() and 0x8000) != 0) { "Not an mDNS response" }82        val questions = u16()83        val records = u16() + u16() + u16()84        repeat(questions) { name(); skip(4) }85        val instances = linkedSetOf<String>()86        val services = mutableMapOf<String, Pair<String, Int>>()87        val texts = mutableMapOf<String, Map<String, String>>()88        val addresses = mutableMapOf<String, String>()89        repeat(records) {90            val owner = name()91            val type = u16()92            skip(2) // class (with cache-flush bit)93            val ttl = (u16().toLong() shl 16) or u16().toLong()94            val length = u16()95            val end = pos + length96            require(end <= bytes.size) { "Truncated mDNS record" }97            val key = owner.lowercase()98            when (type) {99                TYPE_PTR -> if (key == CAST_MDNS_SERVICE && ttl > 0) instances += name()100                TYPE_SRV -> { skip(4); val port = u16(); services[key] = name().lowercase() to port }101                TYPE_TXT -> texts[key] = txt(end)102                TYPE_A -> if (length == 4) addresses[key] = List(4) { u8() }.joinToString(".")103            }104            require(pos <= end) { "mDNS record overruns its length" }105            pos = end106        }107        return instances.map { instance ->108            val key = instance.lowercase()109            val suffix = ".$CAST_MDNS_SERVICE"110            val label = if (instance.endsWith(suffix, ignoreCase = true)) instance.dropLast(suffix.length) else instance111            val txt = texts[key].orEmpty()112            val srv = services[key]113            CastDevice(114                id = txt["id"] ?: label,115                name = txt["fn"] ?: label,116                host = srv?.first?.let(addresses::get) ?: sourceHost,117                port = srv?.second ?: 8009,118            )119        }120    }121122    private fun txt(end: Int): Map<String, String> {123        val entries = mutableMapOf<String, String>()124        while (pos < end) {125            val length = u8()126            require(pos + length <= end) { "Truncated TXT entry" }127            val entry = bytes.decodeToString(pos, pos + length)128            pos += length129            val separator = entry.indexOf('=')130            if (separator > 0) entries[entry.substring(0, separator).lowercase()] = entry.substring(separator + 1)131        }132        return entries133    }134}135

Search chapters, reference and source filenames.