diff --git a/gui/app/public/i18n/en/translation.ftl b/gui/app/public/i18n/en/translation.ftl index a29a6cc79..80eccd54c 100644 --- a/gui/app/public/i18n/en/translation.ftl +++ b/gui/app/public/i18n/en/translation.ftl @@ -1041,9 +1041,10 @@ settings-osc-vrchat-status-output-last-frame = Last frame sent: {$elapsed} settings-osc-vrchat-status-output-no-frame = No frame sent yet. settings-osc-vrchat-status-source-manual = manual settings-osc-vrchat-status-source-auto = auto-detected -settings-osc-vrchat-status-oscquery-disabled = OSCQuery off (manual network mode) +settings-osc-vrchat-status-oscquery-disabled = OSCQuery off settings-osc-vrchat-status-oscquery-advertising = Advertising on port {$port} settings-osc-vrchat-status-oscquery-searching = No VRChat clients found yet. +settings-osc-vrchat-status-oscquery-manual = Not looking for VRChat clients, sending to the manual address instead. settings-osc-vrchat-status-oscquery-discovered-title = Discovered VRChat clients: settings-osc-vrchat-status-oscquery-switch = Switch settings-osc-vrchat-status-network-mode = Network mode diff --git a/gui/app/src/components/settings/pages/VRCOSCSettings.tsx b/gui/app/src/components/settings/pages/VRCOSCSettings.tsx index 1e170f11d..fc353c237 100644 --- a/gui/app/src/components/settings/pages/VRCOSCSettings.tsx +++ b/gui/app/src/components/settings/pages/VRCOSCSettings.tsx @@ -278,7 +278,17 @@ function StatusCard({ OSCQuery} - badge={} + badge={ + + } > {oscQueryState === VRCOSCOscQueryState.DISABLED ? ( @@ -320,6 +330,8 @@ function StatusCard({ ))} + ) : targetSource === VRCOSCTargetSource.MANUAL ? ( + ) : ( )} diff --git a/server/android/build.gradle.kts b/server/android/build.gradle.kts index d8bff2a53..334df677f 100644 --- a/server/android/build.gradle.kts +++ b/server/android/build.gradle.kts @@ -168,7 +168,6 @@ dependencies { implementation("com.github.loucass003:EspflashKotlin:v0.11.0") // mDNS for OSCQuery, resolves to the NsdManager-backed android variant - implementation("com.appstractive:dns-sd-kt:1.1.0") // Logging implementation("io.klogging:klogging:0.11.7") diff --git a/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt b/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt index 826c04d22..2c46f4d42 100644 --- a/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt +++ b/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt @@ -13,8 +13,6 @@ import androidx.core.app.NotificationChannelCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.ServiceCompat -import com.appstractive.dnssd.createNetService -import com.appstractive.dnssd.discoverServices import dev.slimevr.AppContext import dev.slimevr.FeatureFlags import dev.slimevr.Phase1Context @@ -25,6 +23,7 @@ import dev.slimevr.android.buildinfo.SENTRY_RELEASE import dev.slimevr.android.config.AndroidConfigStorage import dev.slimevr.android.hid.createAndroidHIDManager import dev.slimevr.android.ipc.createAndroidSolarXRWebsocketServer +import dev.slimevr.android.multicast.bindAndroidMulticast import dev.slimevr.android.serial.AndroidFirmwareFlasher import dev.slimevr.android.serial.createAndroidSerialServer import dev.slimevr.android.timing.createAndroidWaiter @@ -36,6 +35,7 @@ import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager import dev.slimevr.keybind.KeybindManager import dev.slimevr.logging.ServerLogSource +import dev.slimevr.mdns.createMdns import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsManager @@ -180,11 +180,13 @@ class ForegroundService : Service() { val boneRouting = BoneRoutingManager.create(scope = scope) val bvhManager = BVHManager.create(skeleton = skeleton, storage = storage, scope = scope) val vmcManager = VMCManager.create(scope = scope) + val oscQueryAddress = resolveAndroidLocalIpAddress() + val mdns = createMdns(scope = scope, address = oscQueryAddress, bind = ::bindAndroidMulticast) val vrcOscManager = VRCOSCManager.create( scope = scope, - oscQueryAddress = resolveAndroidLocalIpAddress(), - discoverServicesFlow = ::discoverServices, - serviceFactory = ::createNetService, + oscQueryAddress = oscQueryAddress, + browse = mdns.browse, + advertise = mdns.advertise, ) val stepMountingManager = StepMountingManager.create(ctx = phase1, scope = scope) val resetsManager = ResetsManager.create(ctx = phase1, skeleton = skeleton, stepMountingManager = stepMountingManager, scope = scope) diff --git a/server/android/src/main/java/dev/slimevr/android/multicast/transport.kt b/server/android/src/main/java/dev/slimevr/android/multicast/transport.kt new file mode 100644 index 000000000..5ea85ef91 --- /dev/null +++ b/server/android/src/main/java/dev/slimevr/android/multicast/transport.kt @@ -0,0 +1,48 @@ +package dev.slimevr.android.multicast + +import dev.slimevr.multicast.MulticastSocket +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.NetworkInterface +import java.net.StandardProtocolFamily +import java.net.StandardSocketOptions +import java.nio.ByteBuffer +import java.nio.channels.ClosedChannelException +import java.nio.channels.DatagramChannel + +private const val MAX_DATAGRAM_SIZE = 65_536 + +private class AndroidMulticastSocket(private val channel: DatagramChannel, private val group: InetSocketAddress) : MulticastSocket { + override suspend fun listen(onPacket: (ByteArray) -> Unit) = withContext(Dispatchers.IO) { + val buffer = ByteBuffer.allocate(MAX_DATAGRAM_SIZE) + while (true) { + buffer.clear() + try { + channel.receive(buffer) + } catch (_: ClosedChannelException) { + return@withContext + } + onPacket(buffer.array().copyOf(buffer.position())) + } + } + + override suspend fun send(payload: ByteArray) { + withContext(Dispatchers.IO) { channel.send(ByteBuffer.wrap(payload), group) } + } + + override suspend fun close() = withContext(Dispatchers.IO) { channel.close() } +} + +suspend fun bindAndroidMulticast(group: ByteArray, port: Int, interfaceAddress: String): MulticastSocket = withContext(Dispatchers.IO) { + val groupAddress = InetAddress.getByAddress(group) + val iface = requireNotNull(NetworkInterface.getByInetAddress(InetAddress.getByName(interfaceAddress))) { "No network interface for $interfaceAddress" } + val channel = DatagramChannel.open(StandardProtocolFamily.INET) + .setOption(StandardSocketOptions.SO_REUSEADDR, true) + .setOption(StandardSocketOptions.IP_MULTICAST_IF, iface) + .setOption(StandardSocketOptions.IP_MULTICAST_LOOP, true) + .bind(InetSocketAddress(port)) + channel.join(groupAddress, iface) + AndroidMulticastSocket(channel, InetSocketAddress(groupAddress, port)) +} diff --git a/server/core/build.gradle.kts b/server/core/build.gradle.kts index d856bb178..2b18488a0 100644 --- a/server/core/build.gradle.kts +++ b/server/core/build.gradle.kts @@ -38,7 +38,6 @@ kotlin { implementation("com.mayakapps.kache:kache:2.1.1") implementation("io.klogging:klogging:0.11.7") implementation("io.sentry:sentry:${providers.gradleProperty("sentryVersion").get()}") - api("com.appstractive:dns-sd-kt:1.1.0") val ktorVersion = "3.4.1" implementation("io.ktor:ktor-client-core:$ktorVersion") diff --git a/server/core/src/main/java/dev/slimevr/mdns/mdns.kt b/server/core/src/main/java/dev/slimevr/mdns/mdns.kt new file mode 100644 index 000000000..60e45b470 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/mdns/mdns.kt @@ -0,0 +1,227 @@ +package dev.slimevr.mdns + +import dev.slimevr.multicast.MulticastBind +import dev.slimevr.multicast.MulticastSocket +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.shareIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource + +private const val MDNS_PORT = 5353 +private val MDNS_GROUP = byteArrayOf(224.toByte(), 0, 0, 251.toByte()) +private val MAX_QUERY_INTERVAL = 60.seconds + +data class MdnsDiscoveredService( + val name: String, + val type: String, + val host: String, + val port: Int, + val addresses: List, + val txt: Map, +) + +/** Advertises a [type] (e.g. "_oscjson._tcp") service named [name] until cancelled, then says goodbye. */ +typealias MdnsAdvertise = suspend (type: String, name: String, port: Int, txt: Map) -> Nothing + +/** Services of [type] currently on the network, kept up to date (and queried for) while collected. */ +typealias MdnsBrowse = (type: String) -> Flow> + +interface Mdns { + val advertise: MdnsAdvertise + val browse: MdnsBrowse +} + +private typealias RecordCache = Map> + +private fun RecordCache.unexpired() = filterValues { (_, expiry) -> !expiry.hasPassedNow() } + +private val ticks = flow { + while (true) { + emit(Unit) + delay(1.seconds) + } +} + +private enum class MdnsReply { SERVICE, HOST } + +/** What to send back for [question] about [service], null when the question is not about it. */ +private fun replyFor(question: MdnsQuestion, service: MdnsService): MdnsReply? { + fun asks(vararg types: MdnsRecordType) = question.type == MdnsRecordType.ANY || question.type in types + return when { + question.name.equals(service.type, ignoreCase = true) && asks(MdnsRecordType.PTR) -> MdnsReply.SERVICE + question.name.equals(service.instance, ignoreCase = true) && asks(MdnsRecordType.SRV, MdnsRecordType.TXT) -> MdnsReply.SERVICE + question.name.equals(service.host, ignoreCase = true) && asks(MdnsRecordType.A) -> MdnsReply.HOST + else -> null + } +} + +private fun repliesTo(questions: List, services: List): List = questions + .flatMap { question -> services.mapNotNull { service -> replyFor(question, service)?.let { service to it } } } + .toSet() + .map { (service, reply) -> + when (reply) { + MdnsReply.SERVICE -> buildServiceResponse(service) + MdnsReply.HOST -> buildHostResponse(service) + } + } + +private val MdnsRecord.cacheKey: Any + get() = when (this) { + is MdnsRecord.Service -> "SRV" to name.lowercase() + is MdnsRecord.Text -> "TXT" to name.lowercase() + is MdnsRecord.Pointer, is MdnsRecord.Address -> this + } + +private fun servicesOf(records: Collection, type: String): List { + val typeName = "$type.local" + return records.filterIsInstance() + .filter { it.name.equals(typeName, ignoreCase = true) } + .mapNotNull { pointer -> + val srv = records.filterIsInstance().firstOrNull { it.name.equals(pointer.target, ignoreCase = true) } + ?: return@mapNotNull null + MdnsDiscoveredService( + name = pointer.target.dropLast(typeName.length + 1), + type = type, + host = srv.host, + port = srv.port, + addresses = records.filterIsInstance().filter { it.name.equals(srv.host, ignoreCase = true) }.map { it.address }, + txt = records.filterIsInstance().firstOrNull { it.name.equals(pointer.target, ignoreCase = true) }?.entries.orEmpty(), + ) + } + .distinctBy { it.name } + .sortedBy { it.name } +} + +/** Questions still needed to resolve [type] instances we only know by PTR, or hosts we have no address for. */ +private fun missingQuestions(records: Collection, type: String): List { + val typeName = "$type.local" + val services = records.filterIsInstance() + val pointers = records.filterIsInstance().filter { it.name.equals(typeName, ignoreCase = true) } + val unresolved = pointers + .filter { pointer -> services.none { it.name.equals(pointer.target, ignoreCase = true) } } + .map { MdnsQuestion(it.target, MdnsRecordType.SRV) } + val addressless = services + .filter { srv -> pointers.any { it.target.equals(srv.name, ignoreCase = true) } } + .filter { srv -> records.none { it is MdnsRecord.Address && it.name.equals(srv.host, ignoreCase = true) } } + .map { MdnsQuestion(it.host, MdnsRecordType.A) } + return unresolved + addressless +} + +/** + * mDNS on the interface owning [address], through one multicast socket opened with [bind] while + * anything is advertised or browsed. + * + * Responses are DNS-SD style: PTR as the answer, SRV/TXT/A as additional records. VRChat + * only reads SRV/TXT/A from the additional records and drops responses carrying + * them as answers + */ +fun createMdns(scope: CoroutineScope, address: String, bind: MulticastBind): Mdns { + val published = MutableStateFlow>(emptyList()) + val cache = MutableStateFlow(emptyMap()) + + fun onPacket(opened: MulticastSocket, packet: ByteArray) { + val (questions, records) = try { + parseQueryQuestions(packet) to parseResponseRecords(packet) + } catch (_: IndexOutOfBoundsException) { + return // malformed packet from someone else on the network + } + if (records.isNotEmpty()) { + cache.update { current -> + records.fold(current.unexpired()) { acc, (record, ttl) -> + if (ttl == Duration.ZERO) acc - record.cacheKey else acc + (record.cacheKey to (record to TimeSource.Monotonic.markNow() + ttl)) + } + } + } + val replies = repliesTo(questions, published.value) + if (replies.isNotEmpty()) scope.launch { replies.forEach { opened.send(it) } } + } + + val socket = channelFlow { + val opened = try { + bind(MDNS_GROUP, MDNS_PORT, address) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + send(Result.failure(e)) + awaitCancellation() + } + launch { opened.listen { packet -> onPacket(opened, packet) } } + try { + send(Result.success(opened)) + awaitCancellation() + } finally { + withContext(NonCancellable) { opened.close() } + cache.value = emptyMap() + } + }.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1) + + return object : Mdns { + override val advertise: MdnsAdvertise = { type, name, port, txt -> + val service = MdnsService( + type = "$type.local", + instance = "$name.$type.local", + host = "$name.local", + address = address, + port = port, + txt = txt, + ) + socket.collect { result -> + val opened = result.getOrThrow() + published.update { it + service } + try { + // Announce twice, one second apart (RFC 6762 8.3) + opened.send(buildServiceResponse(service)) + delay(1.seconds) + opened.send(buildServiceResponse(service)) + awaitCancellation() + } finally { + published.update { it - service } + withContext(NonCancellable) { opened.send(buildServiceResponse(service, ttl = Duration.ZERO)) } + } + } + } + + override val browse: MdnsBrowse = { type -> + channelFlow { + socket.collect { result -> + val opened = result.getOrThrow() + coroutineScope { + launch { + var interval = 1.seconds + while (true) { + opened.send(buildQuery("$type.local", MdnsRecordType.PTR)) + delay(interval) + interval = (interval * 2).coerceAtMost(MAX_QUERY_INTERVAL) + } + } + val asked = mutableSetOf() + combine(cache, ticks) { entries, _ -> entries.unexpired().values.map { (record, _) -> record } } + .distinctUntilChanged() + .collect { records -> + missingQuestions(records, type) + .filter { asked.add(it) } + .forEach { opened.send(buildQuery(it.name, requireNotNull(it.type))) } + send(servicesOf(records, type)) + } + } + } + }.distinctUntilChanged() + } + } +} diff --git a/server/core/src/main/java/dev/slimevr/mdns/packets.kt b/server/core/src/main/java/dev/slimevr/mdns/packets.kt new file mode 100644 index 000000000..756a85fa7 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/mdns/packets.kt @@ -0,0 +1,194 @@ +package dev.slimevr.mdns + +import kotlinx.io.Buffer +import kotlinx.io.readByteArray +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +private const val CLASS_IN = 1 + +private val SERVICE_TTL = 75.minutes +private val HOST_TTL = 2.minutes + +internal enum class MdnsRecordType(val code: Int) { + A(1), + PTR(12), + TXT(16), + SRV(33), + ANY(255), + ; + + companion object { + fun fromCode(code: Int) = entries.firstOrNull { it.code == code } + } +} + +/** One of our published services, with fully qualified names ("…local"). */ +internal data class MdnsService( + val type: String, + val instance: String, + val host: String, + val address: String, + val port: Int, + val txt: Map, +) + +/** [type] is null for record types we never answer. */ +internal data class MdnsQuestion(val name: String, val type: MdnsRecordType?) + +/** The records we read from other responders; any other type is skipped. */ +internal sealed interface MdnsRecord { + val name: String + + data class Pointer(override val name: String, val target: String) : MdnsRecord + data class Service(override val name: String, val port: Int, val host: String) : MdnsRecord + data class Text(override val name: String, val entries: Map) : MdnsRecord + data class Address(override val name: String, val address: String) : MdnsRecord +} + +/** A TTL of zero is a goodbye: the record must be forgotten. */ +internal data class ReceivedRecord(val record: MdnsRecord, val ttl: Duration) + +internal fun buildServiceResponse(service: MdnsService, ttl: Duration = SERVICE_TTL): ByteArray = buildPacket(flags = 0x8400, answers = 1, additional = 3) { + writeRecord(service.type, MdnsRecordType.PTR, ttl, encodeName(service.instance)) + writeRecord(service.instance, MdnsRecordType.TXT, ttl, encodeTxt(service.txt)) + writeRecord(service.instance, MdnsRecordType.SRV, ttl, encodeSrv(service.port, service.host)) + writeRecord(service.host, MdnsRecordType.A, if (ttl == Duration.ZERO) Duration.ZERO else HOST_TTL, encodeIpv4(service.address)) +} + +internal fun buildHostResponse(service: MdnsService): ByteArray = buildPacket(flags = 0x8400, answers = 1) { + writeRecord(service.host, MdnsRecordType.A, HOST_TTL, encodeIpv4(service.address)) +} + +internal fun buildQuery(name: String, type: MdnsRecordType): ByteArray = buildPacket(flags = 0, questions = 1) { + write(encodeName(name)) + writeShort(type.code.toShort()) + writeShort(CLASS_IN.toShort()) +} + +private fun buildPacket(flags: Int, questions: Int = 0, answers: Int = 0, additional: Int = 0, body: Buffer.() -> Unit): ByteArray = Buffer().apply { + writeShort(0) // id + writeShort(flags.toShort()) + writeShort(questions.toShort()) + writeShort(answers.toShort()) + writeShort(0) // authority + writeShort(additional.toShort()) + body() +}.readByteArray() + +private fun Buffer.writeRecord(name: String, type: MdnsRecordType, ttl: Duration, data: ByteArray) { + write(encodeName(name)) + writeShort(type.code.toShort()) + writeShort(CLASS_IN.toShort()) + writeInt(ttl.inWholeSeconds.toInt()) + writeShort(data.size.toShort()) + write(data) +} + +private fun encodeName(name: String): ByteArray = Buffer().apply { + name.split('.').filter { it.isNotEmpty() }.forEach { label -> + val bytes = label.encodeToByteArray() + writeByte(bytes.size.toByte()) + write(bytes) + } + writeByte(0) +}.readByteArray() + +private fun encodeTxt(txt: Map): ByteArray = Buffer().apply { + txt.forEach { (key, value) -> + val bytes = "$key=$value".encodeToByteArray() + writeByte(bytes.size.toByte()) + write(bytes) + } +}.readByteArray() + +private fun encodeSrv(port: Int, host: String): ByteArray = Buffer().apply { + writeShort(0) // priority + writeShort(0) // weight + writeShort(port.toShort()) + write(encodeName(host)) +}.readByteArray() + +private fun encodeIpv4(address: String): ByteArray { + val octets = address.split('.').map { it.toInt() } + require(octets.size == 4 && octets.all { it in 0..255 }) { "Not an IPv4 address: $address" } + return ByteArray(4) { octets[it].toByte() } +} + +private fun ByteArray.isResponse() = u16(2) and 0x8000 != 0 + +internal fun parseQueryQuestions(packet: ByteArray): List { + if (packet.size < 12 || packet.isResponse()) return emptyList() + var offset = 12 + return List(packet.u16(4)) { + val (name, end) = readName(packet, offset) + offset = end + 4 // type + class + MdnsQuestion(name, MdnsRecordType.fromCode(packet.u16(end))) + } +} + +internal fun parseResponseRecords(packet: ByteArray): List { + if (packet.size < 12 || !packet.isResponse()) return emptyList() + var offset = 12 + repeat(packet.u16(4)) { offset = readName(packet, offset).second + 4 } + val count = packet.u16(6) + packet.u16(8) + packet.u16(10) + return List(count) { + val (name, end) = readName(packet, offset) + val type = MdnsRecordType.fromCode(packet.u16(end)) + val ttl = ((packet.u16(end + 4).toLong() shl 16) or packet.u16(end + 6).toLong()).seconds + val length = packet.u16(end + 8) + val data = end + 10 + offset = data + length + if (offset > packet.size) throw IndexOutOfBoundsException("mDNS record past end of packet") + val record = when (type) { + MdnsRecordType.PTR -> MdnsRecord.Pointer(name, readName(packet, data).first) + MdnsRecordType.SRV -> MdnsRecord.Service(name, port = packet.u16(data + 4), host = readName(packet, data + 6).first) + MdnsRecordType.TXT -> MdnsRecord.Text(name, decodeTxt(packet.copyOfRange(data, offset))) + MdnsRecordType.A -> if (length == 4) MdnsRecord.Address(name, (0..3).joinToString(".") { (packet[data + it].toInt() and 0xFF).toString() }) else null + else -> null + } + record?.let { ReceivedRecord(it, ttl) } + }.filterNotNull() +} + +private fun decodeTxt(data: ByteArray): Map { + val entries = mutableMapOf() + var offset = 0 + while (offset < data.size) { + val length = data[offset].toInt() and 0xFF + val entry = data.copyOfRange(offset + 1, offset + 1 + length).decodeToString() + if (entry.isNotEmpty()) entries[entry.substringBefore('=')] = entry.substringAfter('=', "") + offset += 1 + length + } + return entries +} + +private fun readName(packet: ByteArray, start: Int): Pair { + val labels = mutableListOf() + var offset = start + var end = -1 + var jumps = 0 + while (true) { + val length = packet[offset].toInt() and 0xFF + when { + length == 0 -> { + if (end < 0) end = offset + 1 + return labels.joinToString(".") to end + } + + length and 0xC0 == 0xC0 -> { + if (end < 0) end = offset + 2 + if (++jumps > 16) throw IndexOutOfBoundsException("mDNS name pointer loop") + offset = ((length and 0x3F) shl 8) or (packet[offset + 1].toInt() and 0xFF) + } + + else -> { + labels += packet.copyOfRange(offset + 1, offset + 1 + length).decodeToString() + offset += 1 + length + } + } + } +} + +private fun ByteArray.u16(offset: Int) = ((this[offset].toInt() and 0xFF) shl 8) or (this[offset + 1].toInt() and 0xFF) diff --git a/server/core/src/main/java/dev/slimevr/multicast/transport.kt b/server/core/src/main/java/dev/slimevr/multicast/transport.kt new file mode 100644 index 000000000..10998d016 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/multicast/transport.kt @@ -0,0 +1,17 @@ +package dev.slimevr.multicast + +interface MulticastSocket { + /** Calls [onPacket] for every datagram received on the group, until the socket closes. */ + suspend fun listen(onPacket: (ByteArray) -> Unit) + + /** Sends [payload] to the group. */ + suspend fun send(payload: ByteArray) + + suspend fun close() +} + +/** + * Opens an IPv4 socket on [port], shared with other processes bound to it, joined to the [group] + * multicast address on the interface owning [interfaceAddress]. Provided by each platform. + */ +typealias MulticastBind = suspend (group: ByteArray, port: Int, interfaceAddress: String) -> MulticastSocket diff --git a/server/core/src/main/java/dev/slimevr/oscquery/client.kt b/server/core/src/main/java/dev/slimevr/oscquery/client.kt new file mode 100644 index 000000000..fc157dc9b --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/oscquery/client.kt @@ -0,0 +1,27 @@ +package dev.slimevr.oscquery + +import io.ktor.client.HttpClient +import io.ktor.client.engine.cio.CIO +import io.ktor.client.plugins.HttpTimeout +import io.ktor.client.request.get +import io.ktor.client.statement.bodyAsText +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +private val oscQueryHttpClient = HttpClient(CIO) { + install(HttpTimeout) { + connectTimeoutMillis = 2_000 + requestTimeoutMillis = 5_000 + } +} + +/** + * OSC port of the OSCQuery host at [address]:[port], read from its HOST_INFO. Only OSC_PORT is read: + * the rest varies between implementations (e.g. extension names we don't model). + */ +suspend fun fetchOscQueryOscPort(address: String, port: Int): Int { + val host = if (':' in address) "[$address]" else address + val hostInfo = oscQueryJson.parseToJsonElement(oscQueryHttpClient.get("http://$host:$port/?HOST_INFO").bodyAsText()) + return hostInfo.jsonObject.getValue("OSC_PORT").jsonPrimitive.int +} diff --git a/server/core/src/main/java/dev/slimevr/oscquery/discovery.kt b/server/core/src/main/java/dev/slimevr/oscquery/discovery.kt deleted file mode 100644 index aed28982f..000000000 --- a/server/core/src/main/java/dev/slimevr/oscquery/discovery.kt +++ /dev/null @@ -1,76 +0,0 @@ -package dev.slimevr.oscquery - -import com.appstractive.dnssd.DiscoveryEvent -import dev.slimevr.logging.AppLogger -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.cancelAndJoin -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp" - -class OscQueryDiscovery( - private val discoverServicesFlow: (String) -> Flow, - private val serviceType: String = OSC_JSON_SERVICE_TYPE, - private val serviceFilter: (String) -> Boolean = { true }, -) { - private val mutableServices = MutableStateFlow>(emptyList()) - val services: StateFlow> = mutableServices.asStateFlow() - - private var job: Job? = null - - fun start(scope: CoroutineScope) { - if (job != null) return - job = scope.launch { - discoverServicesFlow(serviceType).collect { event -> - when (event) { - is DiscoveryEvent.Discovered -> { - if (!serviceFilter(event.service.name)) return@collect - event.resolve() - } - - is DiscoveryEvent.Resolved -> onResolved(event) - - is DiscoveryEvent.Removed -> onRemoved(event.service.name) - } - } - } - } - - suspend fun close() { - job?.cancelAndJoin() - job = null - mutableServices.value = emptyList() - } - - private fun onRemoved(name: String) { - if (!serviceFilter(name)) return - mutableServices.value = mutableServices.value.filterNot { entry -> entry.name == name } - } - - private suspend fun onResolved(event: DiscoveryEvent.Resolved) { - val service = event.service - val name = service.name - if (!serviceFilter(name)) return - - val resolved = OscQueryService( - name = name, - addresses = service.addresses, - host = service.host, - type = service.type, - port = service.port, - txt = service.txt.mapValues { (_, value) -> value?.decodeToString().orEmpty() }, - ) - AppLogger.oscQuery.info( - "OSCQuery discovered service: name=$name address=${service.addresses.firstOrNull().orEmpty()} port=${service.port}", - ) - mutableServices.value = mutableServices.value - .filterNot { existing -> existing.name == name } - .plus(resolved) - .sortedBy { entry -> entry.name } - } -} diff --git a/server/core/src/main/java/dev/slimevr/oscquery/model.kt b/server/core/src/main/java/dev/slimevr/oscquery/model.kt index c17989da5..a72cedc6e 100644 --- a/server/core/src/main/java/dev/slimevr/oscquery/model.kt +++ b/server/core/src/main/java/dev/slimevr/oscquery/model.kt @@ -84,12 +84,3 @@ data class OscQueryNode( return fullPath.substring(0, parentEnd).ifEmpty { "/" } } } - -data class OscQueryService( - val name: String, - val addresses: List, - val host: String, - val type: String, - val port: Int, - val txt: Map, -) diff --git a/server/core/src/main/java/dev/slimevr/oscquery/server.kt b/server/core/src/main/java/dev/slimevr/oscquery/server.kt index 96799b657..d76bdc06e 100644 --- a/server/core/src/main/java/dev/slimevr/oscquery/server.kt +++ b/server/core/src/main/java/dev/slimevr/oscquery/server.kt @@ -1,35 +1,32 @@ package dev.slimevr.oscquery -import com.appstractive.dnssd.NetService +import dev.slimevr.mdns.MdnsAdvertise import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.NonCancellable -import kotlinx.coroutines.withContext +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch +import kotlin.random.Random private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp" private const val OSC_UDP_SERVICE_TYPE = "_osc._udp" -typealias OscQueryServiceFactory = ( - type: String, - name: String, - port: Int, - priority: Int, - weight: Int, - addresses: List?, - txt: Map, -) -> NetService - class OscQueryServer( private val name: String, private val address: String, - private var oscPort: UShort, - private val serviceFactory: OscQueryServiceFactory, + oscPort: UShort, + private val advertise: MdnsAdvertise, private val tree: OscQueryTree = OscQueryTree(), private val transport: OscQueryTransport = OscQueryTransport.UDP, ) { private val httpServer = OscQueryHttpServer(hostInfo = ::buildHostInfo, tree = tree) - private var oscQueryService: NetService? = null - private var oscService: NetService? = null - private var started = false + private val oscPort = MutableStateFlow(oscPort) + + // mDNS instance names must be unique on the network and we don't probe for conflicts + // the odds are very low 1 in 16.7 million, if it happens the user can restart the server + // TODO: actually check for conflicts someday + private val instanceName = "$name-${Random.nextInt(0x1000000).toString(16).uppercase().padStart(6, '0')}" val oscQueryPort: UShort get() = httpServer.port @@ -39,65 +36,38 @@ class OscQueryServer( fun removeNode(path: String): Boolean = tree.remove(path) suspend fun start(scope: CoroutineScope) { - if (started) return - val httpPort = httpServer.start(scope) - oscQueryService = createOscQueryService(httpPort).also { it.register() } - oscService = createOscService(oscPort).also { it.register() } - started = true + httpServer.start(scope) } - suspend fun updateOscPort(port: UShort) { - if (oscPort == port) return - oscPort = port - if (!started) return - withContext(NonCancellable) { - oscService?.unregister() - oscService = createOscService(port).also { it.register() } + suspend fun advertise(): Nothing { + oscPort.collectLatest { port -> + coroutineScope { + launch { + advertise( + OSC_JSON_SERVICE_TYPE, + instanceName, + oscQueryPort.toInt(), + mapOf("txtvers" to "1", "osc_transport" to transport.name.lowercase(), "osc_port" to port.toString()), + ) + } + advertise(OSC_UDP_SERVICE_TYPE, instanceName, port.toInt(), mapOf("txtvers" to "1", "oscquery_port" to oscQueryPort.toString())) + } } + awaitCancellation() } - suspend fun close() { - withContext(NonCancellable) { - oscService?.unregister() - oscService = null - oscQueryService?.unregister() - oscQueryService = null - } + fun updateOscPort(port: UShort) { + oscPort.value = port + } + + fun close() { httpServer.close() - started = false } - private fun createOscQueryService(httpPort: UShort) = createService( - type = OSC_JSON_SERVICE_TYPE, - name = "$name-$httpPort", - port = httpPort.toInt(), - txt = mapOf( - "txtvers" to "1", - "osc_transport" to transport.name.lowercase(), - "osc_port" to oscPort.toString(), - ), - ) - - private fun createOscService(port: UShort) = createService( - type = OSC_UDP_SERVICE_TYPE, - name = "$name-$oscQueryPort", - port = port.toInt(), - txt = mapOf( - "txtvers" to "1", - "oscquery_port" to oscQueryPort.toString(), - ), - ) - - // Pin the advertised address to our resolved local IP. Otherwise dns-sd-kt - // falls back to `getLocalAddresses().firstOrNull()` which iterates every NIC - // and may pick a virtual / wrong-subnet adapter, making the service - // unreachable from headsets on the actual LAN. - private fun createService(type: String, name: String, port: Int, txt: Map): NetService = serviceFactory(type, name, port, 0, 1, listOf(address), txt) - private fun buildHostInfo() = OscQueryHostInfo( name = name, oscIp = address, - oscPort = oscPort, + oscPort = oscPort.value, oscTransport = transport, ) } diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/module.kt b/server/core/src/main/java/dev/slimevr/vrcosc/module.kt index 9b67a0a3b..31cf192cf 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/module.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/module.kt @@ -1,14 +1,13 @@ package dev.slimevr.vrcosc -import com.appstractive.dnssd.DiscoveryEvent import dev.slimevr.AppContextProvider import dev.slimevr.EventDispatcher import dev.slimevr.context.Behaviour import dev.slimevr.context.Context -import dev.slimevr.oscquery.OscQueryServiceFactory +import dev.slimevr.mdns.MdnsAdvertise +import dev.slimevr.mdns.MdnsBrowse import io.github.axisangles.ktmath.Quaternion import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import solarxr_protocol.rpc.VRCOSCInputState import solarxr_protocol.rpc.VRCOSCOscQueryState @@ -100,8 +99,8 @@ typealias VRCOSCBehaviour = Behaviour class VRCOSCManager( val context: VRCOSCContext, val oscQueryAddress: String, - private val discoverServicesFlow: (String) -> Flow, - private val serviceFactory: OscQueryServiceFactory, + private val browse: MdnsBrowse, + private val advertise: MdnsAdvertise, ) { val events: EventDispatcher = EventDispatcher("VRCOSC", context.scope, capacity = 32) @@ -113,8 +112,8 @@ class VRCOSCManager( VRCOSCOscQueryBehaviour( settings, localIp = oscQueryAddress, - discoverServicesFlow = discoverServicesFlow, - serviceFactory = serviceFactory, + browse = browse, + advertise = advertise, ), VRCOSCTrackingDataBehaviour(settings), ) @@ -133,8 +132,8 @@ class VRCOSCManager( fun create( scope: CoroutineScope, oscQueryAddress: String, - discoverServicesFlow: (String) -> Flow, - serviceFactory: OscQueryServiceFactory, + browse: MdnsBrowse, + advertise: MdnsAdvertise, ): VRCOSCManager { val context = Context.create( initialState = VRCOSCState(), @@ -143,7 +142,7 @@ class VRCOSCManager( behaviours = emptyList(), name = "VRCOSC", ) - return VRCOSCManager(context, oscQueryAddress, discoverServicesFlow, serviceFactory) + return VRCOSCManager(context, oscQueryAddress, browse, advertise) } } } diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/oscquery.kt b/server/core/src/main/java/dev/slimevr/vrcosc/oscquery.kt index aeb0eda05..080ee3d1a 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/oscquery.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/oscquery.kt @@ -1,39 +1,43 @@ package dev.slimevr.vrcosc -import com.appstractive.dnssd.DiscoveryEvent import dev.slimevr.config.DEFAULT_VRC_OSC_PORT_OUT import dev.slimevr.config.Settings import dev.slimevr.logging.AppLogger +import dev.slimevr.mdns.MdnsAdvertise +import dev.slimevr.mdns.MdnsBrowse import dev.slimevr.oscquery.OscQueryAccess -import dev.slimevr.oscquery.OscQueryDiscovery import dev.slimevr.oscquery.OscQueryNode import dev.slimevr.oscquery.OscQueryServer -import dev.slimevr.oscquery.OscQueryServiceFactory +import dev.slimevr.oscquery.fetchOscQueryOscPort import dev.slimevr.util.formatExceptionMessage +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import solarxr_protocol.rpc.VRCOSCOscQueryState private const val VRCHAT_SERVICE_PREFIX = "VRChat-Client" +private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp" class VRCOSCOscQueryBehaviour( private val settings: Settings, private val localIp: String, - private val discoverServicesFlow: (String) -> Flow, - private val serviceFactory: OscQueryServiceFactory, + private val browse: MdnsBrowse, + private val advertise: MdnsAdvertise, ) : VRCOSCBehaviour { private class OscQueryRuntime( val localIp: String, ) { var server: OscQueryServer? = null - var discovery: OscQueryDiscovery? = null + var advertiseJob: Job? = null var discoveryJob: Job? = null } @@ -52,21 +56,41 @@ class VRCOSCOscQueryBehaviour( ::Pair, ) .onEach { (settings, portIn) -> - if (!settings.first || settings.second || portIn == null) { + val (enabled, useManualNetwork) = settings + if (!enabled || portIn == null) { stopOscQuery(receiver, runtime) return@onEach } syncOscQueryServer(receiver, runtime, portIn) - startDiscovery(receiver, runtime) + if (useManualNetwork) { + stopDiscovery(receiver, runtime) + } else { + startDiscovery(receiver, runtime) + } }.launchIn(receiver.context.scope) } - private suspend fun stopOscQuery(receiver: VRCOSCManager, runtime: OscQueryRuntime) { - runtime.discoveryJob?.cancel() + private suspend fun stopDiscovery(receiver: VRCOSCManager, runtime: OscQueryRuntime) { + runtime.discoveryJob?.cancelAndJoin() runtime.discoveryJob = null - runtime.discovery?.close() - runtime.discovery = null + val server = runtime.server ?: return + receiver.context.dispatchAll( + listOf( + VRCOSCActions.SetDiscoveredTargets(emptyList()), + VRCOSCActions.SetOscQuery( + state = VRCOSCOscQueryState.SEARCHING, + advertisedPort = server.oscQueryPort.toInt(), + ), + ), + ) + } + + private suspend fun stopOscQuery(receiver: VRCOSCManager, runtime: OscQueryRuntime) { + runtime.discoveryJob?.cancelAndJoin() + runtime.discoveryJob = null + runtime.advertiseJob?.cancelAndJoin() + runtime.advertiseJob = null try { runtime.server?.close() } catch (e: Exception) { @@ -90,13 +114,27 @@ class VRCOSCOscQueryBehaviour( name = "SlimeVR-Server", address = runtime.localIp, oscPort = portIn.toUShort(), - serviceFactory = serviceFactory, + advertise = advertise, ) arrayOf(HEAD_POSE_SUBPATH, LEFT_WRIST_POSE_SUBPATH, RIGHT_WRIST_POSE_SUBPATH).forEach { newServer.addNode(OscQueryNode("$TRACKING_VRSYSTEM_PATH$it", type = "ffffff", access = OscQueryAccess.WRITE)) } withContext(Dispatchers.IO) { newServer.start(receiver.context.scope) } runtime.server = newServer + runtime.advertiseJob = receiver.context.scope.launch { + try { + newServer.advertise() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + dispatchOscQueryError( + receiver = receiver, + message = "Failed to advertise VRChat OSCQuery", + throwable = e, + advertisedPort = newServer.oscQueryPort.toInt(), + ) + } + } AppLogger.vrc.info("VRChat OSCQuery started on http://${runtime.localIp}:${newServer.oscQueryPort}") receiver.context.dispatch( VRCOSCActions.SetOscQuery( @@ -115,66 +153,54 @@ class VRCOSCOscQueryBehaviour( return } - try { - existing.updateOscPort(portIn.toUShort()) - } catch (e: Exception) { - dispatchOscQueryError( - receiver = receiver, - message = "Failed to update VRChat OSCQuery port", - throwable = e, - advertisedPort = existing.oscQueryPort.toInt(), - ) - } + existing.updateOscPort(portIn.toUShort()) } - private suspend fun startDiscovery(receiver: VRCOSCManager, runtime: OscQueryRuntime) { - if (runtime.discovery != null) return + private fun startDiscovery(receiver: VRCOSCManager, runtime: OscQueryRuntime) { + if (runtime.discoveryJob != null) return - val discovery = OscQueryDiscovery( - discoverServicesFlow = discoverServicesFlow, - serviceFilter = { serviceName -> serviceName.startsWith(VRCHAT_SERVICE_PREFIX) }, - ) - runtime.discovery = discovery - - try { - discovery.start(receiver.context.scope) - } catch (e: Exception) { - discovery.close() - runtime.discovery = null - dispatchOscQueryError( - receiver = receiver, - message = "Failed to start VRChat OSCQuery discovery", - throwable = e, - advertisedPort = runtime.server?.oscQueryPort?.toInt(), - ) - return - } - - runtime.discoveryJob = discovery.services + runtime.discoveryJob = browse(OSC_JSON_SERVICE_TYPE) + .map { services -> services.filter { it.name.startsWith(VRCHAT_SERVICE_PREFIX) && it.addresses.isNotEmpty() } } + .distinctUntilChanged() .onEach { services -> - val targets = services.mapNotNull { service -> - val address = service.addresses.firstOrNull().orEmpty().ifEmpty { service.host } - if (address.isBlank()) { - null - } else { - VRCOSCDiscoveredTargetInfo( - name = service.name, - address = address, - portOut = DEFAULT_VRC_OSC_PORT_OUT, // TODO should read VRChat's /?HOST_INFO - ) + AppLogger.oscQuery.info("Discovered VRChat clients: ${services.map { "${it.name} ${it.addresses}:${it.port}" }}") + val targets = services.map { service -> + val address = service.addresses.first() + val portOut = try { + fetchOscQueryOscPort(address, service.port).also { port -> + AppLogger.oscQuery.info("HOST_INFO of ${service.name} at $address:${service.port}: OSC port $port") + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + AppLogger.oscQuery.warn(e, "Could not read HOST_INFO of ${service.name} at $address:${service.port}, assuming OSC port $DEFAULT_VRC_OSC_PORT_OUT") + DEFAULT_VRC_OSC_PORT_OUT } + VRCOSCDiscoveredTargetInfo( + name = service.name, + address = address, + portOut = portOut, + ) } - val advertisedPort = runtime.server?.oscQueryPort?.toInt() receiver.context.dispatchAll( listOf( VRCOSCActions.SetDiscoveredTargets(targets), VRCOSCActions.SetOscQuery( state = if (targets.isEmpty()) VRCOSCOscQueryState.SEARCHING else VRCOSCOscQueryState.FOUND, - advertisedPort = advertisedPort, + advertisedPort = runtime.server?.oscQueryPort?.toInt(), ), ), ) - }.launchIn(receiver.context.scope) + } + .catch { e -> + dispatchOscQueryError( + receiver = receiver, + message = "VRChat OSCQuery discovery failed", + throwable = e, + advertisedPort = runtime.server?.oscQueryPort?.toInt(), + ) + } + .launchIn(receiver.context.scope) } private suspend fun dispatchOscQueryError( diff --git a/server/core/src/test/java/dev/slimevr/mdns/MdnsTest.kt b/server/core/src/test/java/dev/slimevr/mdns/MdnsTest.kt new file mode 100644 index 000000000..15cd764f1 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/mdns/MdnsTest.kt @@ -0,0 +1,140 @@ +package dev.slimevr.mdns + +import dev.slimevr.multicast.MulticastSocket +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes + +class MdnsTest { + private val vrchat = MdnsService( + type = "_oscjson._tcp.local", + instance = "VRChat-Client-103C3C._oscjson._tcp.local", + host = "VRChat-Client-103C3C.oscjson.local", + address = "192.168.1.242", + port = 46463, + txt = mapOf("txtvers" to "1"), + ) + + // VRChat drops responses that carry SRV/TXT/A as answers instead of additional records + @Test + fun serviceResponseHasPtrAnswerAndSrvTxtAInAdditionalRecords() { + val packet = buildServiceResponse(vrchat) + + assertEquals(1, packet.u16(6)) // answers + assertEquals(3, packet.u16(10)) // additional + assertEquals( + listOf( + ReceivedRecord(MdnsRecord.Pointer(vrchat.type, vrchat.instance), 75.minutes), + ReceivedRecord(MdnsRecord.Text(vrchat.instance, vrchat.txt), 75.minutes), + ReceivedRecord(MdnsRecord.Service(vrchat.instance, vrchat.port, vrchat.host), 75.minutes), + ReceivedRecord(MdnsRecord.Address(vrchat.host, vrchat.address), 2.minutes), + ), + parseResponseRecords(packet), + ) + } + + @Test + fun parsesCompressedNamesAndSkipsUnknownRecordTypes() { + // Question "_osc._udp" + pointer to "local" in the first question's name + val query = header(flags = 0, questions = 2) + + encode("_oscjson._tcp.local") + u16(12) + u16(1) + + encode("_osc._udp", terminated = false) + u16(0xC000 or (12 + 1 + 8 + 1 + 4)) + u16(255) + u16(0x8001) + assertEquals( + listOf(MdnsQuestion("_oscjson._tcp.local", MdnsRecordType.PTR), MdnsQuestion("_osc._udp.local", MdnsRecordType.ANY)), + parseQueryQuestions(query), + ) + + // AAAA (type 28) is not read, the A record after it is + val response = header(flags = 0x8400, answers = 2) + + encode("host.local") + u16(28) + u16(1) + u16(0) + u16(120) + u16(16) + ByteArray(16) + + encode("host.local") + u16(1) + u16(1) + u16(0) + u16(120) + u16(4) + byteArrayOf(10, 0, 0, 1) + assertEquals(listOf(ReceivedRecord(MdnsRecord.Address("host.local", "10.0.0.1"), 2.minutes)), parseResponseRecords(response)) + } + + @Test + fun advertisingAnnouncesTwiceThenSaysGoodbyeAndClosesTheSocket() = runTest { + val sockets = mutableListOf() + val mdns = createMdns(backgroundScope, "192.168.1.10") { _, _, _ -> FakeSocket().also(sockets::add) } + + val advertising = launch { mdns.advertise("_oscjson._tcp", "SlimeVR-Server-ABC123", 1234, mapOf("txtvers" to "1")) } + advanceTimeBy(1_500) + assertEquals(2, sockets.single().sent.size) + + advertising.cancelAndJoin() + runCurrent() + assertTrue(parseResponseRecords(sockets.single().sent.last()).all { it.ttl == Duration.ZERO }) + assertTrue(sockets.single().closed) + } + + @Test + fun browsingSharesTheSocketAndFindsAnsweringServices() = runTest { + val sockets = mutableListOf() + val mdns = createMdns(backgroundScope, "192.168.1.10") { _, _, _ -> FakeSocket().also(sockets::add) } + + val advertising = launch { mdns.advertise("_osc._udp", "SlimeVR-Server-ABC123", 9001, emptyMap()) } + val found = async { mdns.browse("_oscjson._tcp").first { it.isNotEmpty() } } + runCurrent() + val socket = sockets.single() + assertTrue(socket.sent.any { parseQueryQuestions(it) == listOf(MdnsQuestion("_oscjson._tcp.local", MdnsRecordType.PTR)) }) + + socket.incoming.send(buildServiceResponse(vrchat)) + assertEquals( + listOf(MdnsDiscoveredService("VRChat-Client-103C3C", "_oscjson._tcp", vrchat.host, vrchat.port, listOf(vrchat.address), vrchat.txt)), + found.await(), + ) + + runCurrent() + assertFalse(socket.closed) + advertising.cancelAndJoin() + runCurrent() + assertTrue(socket.closed) + } + + @Test + fun bindFailureReachesTheCaller() = runTest { + val mdns = createMdns(backgroundScope, "192.168.1.10") { _, _, _ -> error("no interface") } + + assertEquals("no interface", runCatching { mdns.browse("_oscjson._tcp").first() }.exceptionOrNull()?.message) + } + + private fun header(flags: Int, questions: Int = 0, answers: Int = 0) = u16(0) + u16(flags) + u16(questions) + u16(answers) + u16(0) + u16(0) + + private fun encode(name: String, terminated: Boolean = true): ByteArray = name.split('.').fold(byteArrayOf()) { acc, label -> + acc + byteArrayOf(label.length.toByte()) + label.encodeToByteArray() + } + if (terminated) byteArrayOf(0) else byteArrayOf() + + private fun u16(value: Int) = byteArrayOf((value shr 8).toByte(), value.toByte()) + + private fun ByteArray.u16(offset: Int) = ((this[offset].toInt() and 0xFF) shl 8) or (this[offset + 1].toInt() and 0xFF) +} + +private class FakeSocket : MulticastSocket { + val sent = mutableListOf() + val incoming = Channel(Channel.UNLIMITED) + var closed = false + + override suspend fun listen(onPacket: (ByteArray) -> Unit) { + for (packet in incoming) onPacket(packet) + } + + override suspend fun send(payload: ByteArray) { + check(!closed) { "send on closed socket" } + sent += payload + } + + override suspend fun close() { + closed = true + incoming.close() + } +} diff --git a/server/core/src/test/java/dev/slimevr/oscquery/OscQueryServerTest.kt b/server/core/src/test/java/dev/slimevr/oscquery/OscQueryServerTest.kt index 11ded211e..12acf7a4d 100644 --- a/server/core/src/test/java/dev/slimevr/oscquery/OscQueryServerTest.kt +++ b/server/core/src/test/java/dev/slimevr/oscquery/OscQueryServerTest.kt @@ -1,10 +1,15 @@ package dev.slimevr.oscquery -import com.appstractive.dnssd.NetService import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive @@ -17,26 +22,34 @@ class OscQueryServerTest { private val json = Json { ignoreUnknownKeys = true } @Test - fun httpRoutesAndServiceLifecycleAreWired() = runBlocking { - val createdServices = mutableListOf() + fun httpRoutesAndAdvertisementsAreWired() = runBlocking { + val advertised = MutableStateFlow>(emptyList()) val server = OscQueryServer( name = "SlimeVR", address = "127.0.0.1", oscPort = 9000u, - serviceFactory = { type, name, port, _, _, _, txt -> - FakeNetService(type = type, name = name, port = port, txt = txt).also(createdServices::add) + advertise = { type, name, port, txt -> + val ad = Advertised(type, name, port, txt) + advertised.update { it + ad } + try { + awaitCancellation() + } finally { + advertised.update { it - ad } + } }, ) server.addNode(OscQueryNode(fullPath = "/tracking/vrsystem")) + server.start(this) + val advertising = launch { server.advertise() } try { - server.start(this) - assertTrue(server.oscQueryPort > 0u) - assertEquals(2, createdServices.size) - assertEquals("_oscjson._tcp", createdServices[0].type) - assertEquals("_osc._udp", createdServices[1].type) - assertTrue(createdServices.all { it.isRegistered.value }) + val initial = withTimeout(5_000) { advertised.first { it.size == 2 } } + val oscJson = initial.single { it.type == "_oscjson._tcp" } + assertEquals(server.oscQueryPort.toInt(), oscJson.port) + assertEquals("9000", oscJson.txt["osc_port"]) + assertEquals(9000, initial.single { it.type == "_osc._udp" }.port) + assertEquals(1, initial.map { it.name }.distinct().size) // both services share the instance name val hostInfo = json.parseToJsonElement(readUrl("http://127.0.0.1:${server.oscQueryPort}/?HOST_INFO")).jsonObject assertEquals("SlimeVR", hostInfo["NAME"]?.jsonPrimitive?.content) @@ -49,17 +62,20 @@ class OscQueryServerTest { val node = json.parseToJsonElement(readUrl("http://127.0.0.1:${server.oscQueryPort}/tracking/vrsystem")).jsonObject assertEquals("/tracking/vrsystem", node["FULL_PATH"]?.jsonPrimitive?.content) - val notFound = readStatus("http://127.0.0.1:${server.oscQueryPort}/missing") - assertEquals(404, notFound) + assertEquals(404, readStatus("http://127.0.0.1:${server.oscQueryPort}/missing")) + // A new OSC port is re-advertised in both records server.updateOscPort(9100u) - assertEquals(3, createdServices.size) - assertEquals(createdServices[1].unregisterCount, 1) - assertEquals(9100, createdServices[2].port) - assertTrue(createdServices[2].isRegistered.value) + val updated = withTimeout(5_000) { + advertised.first { ads -> ads.size == 2 && ads.any { it.type == "_osc._udp" && it.port == 9100 } } + } + assertEquals("9100", updated.single { it.type == "_oscjson._tcp" }.txt["osc_port"]) + + advertising.cancelAndJoin() + assertEquals(emptyList(), advertised.value) } finally { + advertising.cancel() server.close() - assertTrue(createdServices.all { it.unregistered.value }) } } } @@ -80,26 +96,9 @@ private suspend fun readStatus(url: String): Int { } } -private class FakeNetService( - override val name: String, - override val domain: String = "", - override val type: String, - override val port: Int, - private val txt: Map, -) : NetService { - override val isRegistered = MutableStateFlow(false) - val unregistered = MutableStateFlow(false) - var registerCount = 0 - var unregisterCount = 0 - - override suspend fun register(timeoutInMs: Long) { - registerCount++ - isRegistered.value = true - } - - override suspend fun unregister() { - unregisterCount++ - unregistered.value = true - isRegistered.value = false - } -} +private data class Advertised( + val type: String, + val name: String, + val port: Int, + val txt: Map, +) diff --git a/server/desktop/build.gradle.kts b/server/desktop/build.gradle.kts index 4cba99f2d..bdb3fd858 100644 --- a/server/desktop/build.gradle.kts +++ b/server/desktop/build.gradle.kts @@ -81,7 +81,6 @@ dependencies { implementation("org.hid4java:hid4java:0.8.0") // mDNS for OSCQuery, resolves to the JmDNS-backed jvm variant - implementation("com.appstractive:dns-sd-kt:1.1.0") implementation("io.klogging:klogging:0.11.7") // SLF4J provider, so what ktor and the discovery libraries log reaches our sinks diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt index b9d196f08..53f594512 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -2,8 +2,6 @@ package dev.slimevr.desktop -import com.appstractive.dnssd.createNetService -import com.appstractive.dnssd.discoverServices import dev.slimevr.AppContext import dev.slimevr.CURRENT_PLATFORM import dev.slimevr.FeatureFlags @@ -21,6 +19,7 @@ import dev.slimevr.desktop.ipc.createIpcServers import dev.slimevr.desktop.ipc.createSolarXRWebsocketServer import dev.slimevr.desktop.keybind.createDesktopKeybindManager import dev.slimevr.desktop.keybind.isGnome +import dev.slimevr.desktop.multicast.bindDesktopMulticast import dev.slimevr.desktop.networkprofile.setupDesktopNetworkProfileChecker import dev.slimevr.desktop.serial.DesktopFirmwareFlasher import dev.slimevr.desktop.serial.createDesktopSerialServer @@ -33,6 +32,7 @@ import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager import dev.slimevr.keybind.KeybindManager import dev.slimevr.logging.AppLogger +import dev.slimevr.mdns.createMdns import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsManager @@ -165,11 +165,13 @@ fun main(args: Array) = runBlocking(appCoroutineExceptionHandler + val boneRouting = BoneRoutingManager.create(scope = this) val bvhManager = BVHManager.create(skeleton = skeleton, storage = storage, scope = this) val vmcManager = VMCManager.create(scope = this) + val oscQueryAddress = resolveDesktopLocalIpAddress() + val mdns = createMdns(scope = this, address = oscQueryAddress, bind = ::bindDesktopMulticast) val vrcOscManager = VRCOSCManager.create( scope = this, - oscQueryAddress = resolveDesktopLocalIpAddress(), - discoverServicesFlow = ::discoverServices, - serviceFactory = ::createNetService, + oscQueryAddress = oscQueryAddress, + browse = mdns.browse, + advertise = mdns.advertise, ) val stepMountingManager = StepMountingManager.create(ctx = phase1, scope = this) val resetsManager = ResetsManager.create(ctx = phase1, skeleton = skeleton, stepMountingManager = stepMountingManager, scope = this) diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/multicast/transport.kt b/server/desktop/src/main/java/dev/slimevr/desktop/multicast/transport.kt new file mode 100644 index 000000000..b00cd59df --- /dev/null +++ b/server/desktop/src/main/java/dev/slimevr/desktop/multicast/transport.kt @@ -0,0 +1,48 @@ +package dev.slimevr.desktop.multicast + +import dev.slimevr.multicast.MulticastSocket +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.NetworkInterface +import java.net.StandardProtocolFamily +import java.net.StandardSocketOptions +import java.nio.ByteBuffer +import java.nio.channels.ClosedChannelException +import java.nio.channels.DatagramChannel + +private const val MAX_DATAGRAM_SIZE = 65_536 + +private class DesktopMulticastSocket(private val channel: DatagramChannel, private val group: InetSocketAddress) : MulticastSocket { + override suspend fun listen(onPacket: (ByteArray) -> Unit) = withContext(Dispatchers.IO) { + val buffer = ByteBuffer.allocate(MAX_DATAGRAM_SIZE) + while (true) { + buffer.clear() + try { + channel.receive(buffer) + } catch (_: ClosedChannelException) { + return@withContext + } + onPacket(buffer.array().copyOf(buffer.position())) + } + } + + override suspend fun send(payload: ByteArray) { + withContext(Dispatchers.IO) { channel.send(ByteBuffer.wrap(payload), group) } + } + + override suspend fun close() = withContext(Dispatchers.IO) { channel.close() } +} + +suspend fun bindDesktopMulticast(group: ByteArray, port: Int, interfaceAddress: String): MulticastSocket = withContext(Dispatchers.IO) { + val groupAddress = InetAddress.getByAddress(group) + val iface = requireNotNull(NetworkInterface.getByInetAddress(InetAddress.getByName(interfaceAddress))) { "No network interface for $interfaceAddress" } + val channel = DatagramChannel.open(StandardProtocolFamily.INET) + .setOption(StandardSocketOptions.SO_REUSEADDR, true) + .setOption(StandardSocketOptions.IP_MULTICAST_IF, iface) + .setOption(StandardSocketOptions.IP_MULTICAST_LOOP, true) + .bind(InetSocketAddress(port)) + channel.join(groupAddress, iface) + DesktopMulticastSocket(channel, InetSocketAddress(groupAddress, port)) +}