Better handling of network switching. Better handling of exceptions with mdns

This commit is contained in:
loucass003 committed 2026-10-27 19:15:33 +01:00
1 parent e52e2f8bc0
commit 4bef38a4fd
15 files changed
+265 -67

No files matched your search

@@ -29,6 +29,7 @@ object AppLogger {
val bvh = logger("BVH")
val vmc = logger("VMC")
val oscQuery = logger("OSCQuery")
val mdns = logger("mDNS")
val install = logger("Install")
val resets = logger("Resets")
val keybind = logger("Keybind")
@@ -1,9 +1,11 @@
package dev.slimevr.mdns
import dev.slimevr.logging.AppLogger
import dev.slimevr.multicast.MulticastBind
import dev.slimevr.multicast.MulticastSocket
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
@@ -12,10 +14,13 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.retryWhen
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.transformLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -26,6 +31,7 @@ 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
private val REBIND_DELAY = 5.seconds
data class MdnsDiscoveredService(
val name: String,
@@ -60,6 +66,18 @@ private val ticks = flow {
private enum class MdnsReply { SERVICE, HOST }
private class MdnsSocket(private val socket: MulticastSocket, val address: String) {
suspend fun send(packet: ByteArray) {
try {
socket.send(packet)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
AppLogger.mdns.warn(e, "mDNS send failed on $address")
}
}
}
/** 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
@@ -124,18 +142,20 @@ private fun missingQuestions(records: Collection<MdnsRecord>, type: String): Lis
}
/**
* mDNS on the interface owning [address], through one multicast socket opened with [bind] while
* anything is advertised or browsed.
* mDNS on the interface owning the latest [localAddress], through one multicast socket opened with
* [bind] while anything is advertised or browsed. The socket is bound again whenever the address
* changes, and after [REBIND_DELAY] when binding or listening fails.
*
* 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 {
@OptIn(ExperimentalCoroutinesApi::class)
fun createMdns(scope: CoroutineScope, localAddress: Flow<String>, bind: MulticastBind): Mdns {
val published = MutableStateFlow<List<MdnsService>>(emptyList())
val cache = MutableStateFlow<RecordCache>(emptyMap())
fun onPacket(opened: MulticastSocket, packet: ByteArray) {
fun onPacket(opened: MdnsSocket, packet: ByteArray) {
val (questions, records) = try {
parseQueryQuestions(packet) to parseResponseRecords(packet)
} catch (_: IndexOutOfBoundsException) {
@@ -152,37 +172,42 @@ fun createMdns(scope: CoroutineScope, address: String, bind: MulticastBind): Mdn
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) } }
val socket = localAddress.distinctUntilChanged().transformLatest { address ->
val bound = bind(MDNS_GROUP, MDNS_PORT, address)
val opened = MdnsSocket(bound, address)
try {
send(Result.success(opened))
awaitCancellation()
coroutineScope {
launch { bound.listen { packet -> onPacket(opened, packet) } }
try {
emit(opened)
awaitCancellation()
} finally {
withContext(NonCancellable) {
published.value.forEach { opened.send(buildServiceResponse(it, ttl = Duration.ZERO)) }
bound.close()
}
}
}
} finally {
withContext(NonCancellable) { opened.close() }
cache.value = emptyMap()
}
}.retryWhen { cause, _ ->
AppLogger.mdns.warn(cause, "mDNS socket failed, binding again in $REBIND_DELAY")
delay(REBIND_DELAY)
true
}.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()
socket.collectLatest { opened ->
val service = MdnsService(
type = "$type.local",
instance = "$name.$type.local",
host = "$name.local",
address = opened.address,
port = port,
txt = txt,
)
published.update { it + service }
try {
// Announce twice, one second apart (RFC 6762 8.3)
@@ -191,16 +216,16 @@ fun createMdns(scope: CoroutineScope, address: String, bind: MulticastBind): Mdn
opened.send(buildServiceResponse(service))
awaitCancellation()
} finally {
published.update { it - service }
withContext(NonCancellable) { opened.send(buildServiceResponse(service, ttl = Duration.ZERO)) }
published.update { it - service }
}
}
awaitCancellation()
}
override val browse: MdnsBrowse = { type ->
channelFlow {
socket.collect { result ->
val opened = result.getOrThrow()
socket.collectLatest { opened ->
coroutineScope {
launch {
var interval = 1.seconds
@@ -23,13 +23,22 @@ class OscSender(private val address: String, private val port: Int) {
suspend fun send(message: OscMessage) {
val buf = Buffer()
writeMessage(buf, message)
socket().send(Datagram(buf, InetSocketAddress(address, port)))
send(buf)
}
suspend fun send(bundle: OscBundle) {
val buf = Buffer()
writeBundle(buf, bundle)
socket().send(Datagram(buf, InetSocketAddress(address, port)))
send(buf)
}
private suspend fun send(buf: Buffer) {
try {
socket().send(Datagram(buf, InetSocketAddress(address, port)))
} catch (e: Exception) {
close()
throw e
}
}
fun close() {
@@ -5,16 +5,17 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
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"
class OscQueryServer(
private val name: String,
private val address: String,
private val localAddress: StateFlow<String>,
oscPort: UShort,
private val advertise: MdnsAdvertise,
private val tree: OscQueryTree = OscQueryTree(),
@@ -23,11 +24,6 @@ class OscQueryServer(
private val httpServer = OscQueryHttpServer(hostInfo = ::buildHostInfo, tree = tree)
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
@@ -40,7 +36,8 @@ class OscQueryServer(
}
suspend fun advertise(): Nothing {
oscPort.collectLatest { port ->
combine(localAddress, oscPort, ::Pair).collectLatest { (address, port) ->
val instanceName = instanceName(name, address, port)
coroutineScope {
launch {
advertise(
@@ -66,8 +63,13 @@ class OscQueryServer(
private fun buildHostInfo() = OscQueryHostInfo(
name = name,
oscIp = address,
oscIp = localAddress.value,
oscPort = oscPort.value,
oscTransport = transport,
)
}
internal fun instanceName(name: String, address: String, oscPort: UShort): String {
val suffix = ("$address:$oscPort".hashCode().toUInt() % 0x1000000u).toString(16).uppercase().padStart(6, '0')
return "$name-$suffix"
}
@@ -5,7 +5,9 @@ import dev.slimevr.EventDispatcher
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.device.Device
import dev.slimevr.logging.AppLogger
import dev.slimevr.tracker.Tracker
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
@@ -64,7 +66,13 @@ class UDPConnection(
scope.launch {
val buf = Buffer()
writePacket(buf, packet)
socket.send(peer, buf.readByteArray())
try {
socket.send(peer, buf.readByteArray())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
AppLogger.udp.warn(e, "Failed to send ${packet::class.simpleName}")
}
}
}
@@ -124,8 +124,8 @@ class VRCOSCInputBehaviour(
}
val bindPort = if (useManualNetwork) configPortIn else 0
val newReceiver = try {
OscReceiver(bindPort)
val (newReceiver, portIn) = try {
bindReceiver(bindPort)
} catch (e: Exception) {
dispatchInputError(
receiver = receiver,
@@ -135,7 +135,6 @@ class VRCOSCInputBehaviour(
)
return@onEach
}
val portIn = newReceiver.getSocketPort()
oscReceiver = newReceiver
receiver.context.dispatch(
VRCOSCActions.SetInput(state = VRCOSCInputState.LISTENING, port = portIn),
@@ -159,6 +158,16 @@ class VRCOSCInputBehaviour(
}.launchIn(receiver.context.scope)
}
private suspend fun bindReceiver(port: Int): Pair<OscReceiver, Int> {
val oscReceiver = OscReceiver(port)
try {
return oscReceiver to oscReceiver.getSocketPort()
} catch (e: Exception) {
oscReceiver.close()
throw e
}
}
private suspend fun dispatchInputError(
receiver: VRCOSCManager,
port: Int?,
@@ -8,6 +8,7 @@ import dev.slimevr.mdns.MdnsAdvertise
import dev.slimevr.mdns.MdnsBrowse
import io.github.axisangles.ktmath.Quaternion
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import solarxr_protocol.rpc.VRCOSCInputState
import solarxr_protocol.rpc.VRCOSCOscQueryState
@@ -98,7 +99,7 @@ typealias VRCOSCBehaviour = Behaviour<VRCOSCManager>
class VRCOSCManager(
val context: VRCOSCContext,
val oscQueryAddress: String,
private val oscQueryAddress: StateFlow<String>,
private val browse: MdnsBrowse,
private val advertise: MdnsAdvertise,
) {
@@ -131,7 +132,7 @@ class VRCOSCManager(
companion object {
fun create(
scope: CoroutineScope,
oscQueryAddress: String,
oscQueryAddress: StateFlow<String>,
browse: MdnsBrowse,
advertise: MdnsAdvertise,
): VRCOSCManager {
@@ -15,6 +15,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
@@ -29,20 +30,18 @@ private const val OSC_JSON_SERVICE_TYPE = "_oscjson._tcp"
class VRCOSCOscQueryBehaviour(
private val settings: Settings,
private val localIp: String,
private val localIp: StateFlow<String>,
private val browse: MdnsBrowse,
private val advertise: MdnsAdvertise,
) : VRCOSCBehaviour {
private class OscQueryRuntime(
val localIp: String,
) {
private class OscQueryRuntime {
var server: OscQueryServer? = null
var advertiseJob: Job? = null
var discoveryJob: Job? = null
}
override fun observe(receiver: VRCOSCManager) {
val runtime = OscQueryRuntime(localIp)
val runtime = OscQueryRuntime()
val settingsFlow = settings.context.state
.map { Pair(it.data.vrcOscConfig.enabled, it.data.vrcOscConfig.useManualNetwork) }
@@ -112,7 +111,7 @@ class VRCOSCOscQueryBehaviour(
try {
val newServer = OscQueryServer(
name = "SlimeVR-Server",
address = runtime.localIp,
localAddress = localIp,
oscPort = portIn.toUShort(),
advertise = advertise,
)
@@ -135,7 +134,7 @@ class VRCOSCOscQueryBehaviour(
)
}
}
AppLogger.vrc.info("VRChat OSCQuery started on http://${runtime.localIp}:${newServer.oscQueryPort}")
AppLogger.vrc.info("VRChat OSCQuery started on http://${localIp.value}:${newServer.oscQueryPort}")
receiver.context.dispatch(
VRCOSCActions.SetOscQuery(
state = VRCOSCOscQueryState.SEARCHING,