From 4bef38a4fde9207ea61d514a1cccf0bbae2e8c91 Mon Sep 17 00:00:00 2001 From: loucass003 Date: Tue, 27 Oct 2026 19:15:33 +0100 Subject: [PATCH] Better handling of network switching. Better handling of exceptions with mdns --- .../dev/slimevr/android/ForegroundService.kt | 7 +- .../dev/slimevr/android/vrchat/oscquery.kt | 38 +++++++++ .../main/java/dev/slimevr/logging/logger.kt | 1 + .../src/main/java/dev/slimevr/mdns/mdns.kt | 85 ++++++++++++------- .../main/java/dev/slimevr/osc/transport.kt | 13 ++- .../main/java/dev/slimevr/oscquery/server.kt | 20 +++-- .../main/java/dev/slimevr/udp/connection.kt | 10 ++- .../src/main/java/dev/slimevr/vrcosc/input.kt | 15 +++- .../main/java/dev/slimevr/vrcosc/module.kt | 5 +- .../main/java/dev/slimevr/vrcosc/oscquery.kt | 13 ++- .../test/java/dev/slimevr/mdns/MdnsTest.kt | 42 +++++++-- .../slimevr/oscquery/OscQueryServerTest.kt | 12 ++- .../src/main/java/dev/slimevr/desktop/Main.kt | 7 +- .../desktop/networkprofile/network-profile.kt | 8 ++ .../dev/slimevr/desktop/vrchat/oscquery.kt | 56 ++++++++++++ 15 files changed, 265 insertions(+), 67 deletions(-) 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 2c46f4d42..7d641af62 100644 --- a/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt +++ b/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt @@ -28,6 +28,7 @@ import dev.slimevr.android.serial.AndroidFirmwareFlasher import dev.slimevr.android.serial.createAndroidSerialServer import dev.slimevr.android.timing.createAndroidWaiter import dev.slimevr.android.udp.bindAndroidUdp +import dev.slimevr.android.vrchat.observeAndroidLocalIpAddress import dev.slimevr.android.vrchat.resolveAndroidLocalIpAddress import dev.slimevr.bvh.BVHManager import dev.slimevr.config.AppConfig @@ -180,11 +181,11 @@ 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 localIpAddress = observeAndroidLocalIpAddress(context = this@ForegroundService, scope = scope) + val mdns = createMdns(scope = scope, localAddress = localIpAddress, bind = ::bindAndroidMulticast) val vrcOscManager = VRCOSCManager.create( scope = scope, - oscQueryAddress = oscQueryAddress, + oscQueryAddress = localIpAddress, browse = mdns.browse, advertise = mdns.advertise, ) diff --git a/server/android/src/main/java/dev/slimevr/android/vrchat/oscquery.kt b/server/android/src/main/java/dev/slimevr/android/vrchat/oscquery.kt index 71d5b9a60..1ff1c9cfc 100644 --- a/server/android/src/main/java/dev/slimevr/android/vrchat/oscquery.kt +++ b/server/android/src/main/java/dev/slimevr/android/vrchat/oscquery.kt @@ -1,5 +1,19 @@ package dev.slimevr.android.vrchat +import android.content.Context +import android.net.ConnectivityManager +import android.net.LinkProperties +import android.net.Network +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.awaitClose +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.conflate +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn import java.net.InetAddress import java.net.NetworkInterface import java.util.Collections @@ -18,3 +32,27 @@ fun resolveAndroidLocalIpAddress(): String = try { } catch (_: Exception) { InetAddress.getLoopbackAddress().hostAddress } + +/** [resolveAndroidLocalIpAddress], resolved again whenever the default network or its addresses change. */ +fun observeAndroidLocalIpAddress(context: Context, scope: CoroutineScope): StateFlow = callbackFlow { + val connectivity = context.getSystemService(ConnectivityManager::class.java) + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + trySend(Unit) + } + + override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) { + trySend(Unit) + } + + override fun onLost(network: Network) { + trySend(Unit) + } + } + connectivity.registerDefaultNetworkCallback(callback) + awaitClose { connectivity.unregisterNetworkCallback(callback) } +} + .conflate() + .map { resolveAndroidLocalIpAddress() } + .flowOn(Dispatchers.IO) + .stateIn(scope, SharingStarted.Eagerly, resolveAndroidLocalIpAddress()) diff --git a/server/core/src/main/java/dev/slimevr/logging/logger.kt b/server/core/src/main/java/dev/slimevr/logging/logger.kt index 5a1c92423..2022ff21a 100644 --- a/server/core/src/main/java/dev/slimevr/logging/logger.kt +++ b/server/core/src/main/java/dev/slimevr/logging/logger.kt @@ -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") diff --git a/server/core/src/main/java/dev/slimevr/mdns/mdns.kt b/server/core/src/main/java/dev/slimevr/mdns/mdns.kt index 60e45b470..fdab90b57 100644 --- a/server/core/src/main/java/dev/slimevr/mdns/mdns.kt +++ b/server/core/src/main/java/dev/slimevr/mdns/mdns.kt @@ -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, 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, bind: MulticastBind): Mdns { val published = MutableStateFlow>(emptyList()) val cache = MutableStateFlow(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 diff --git a/server/core/src/main/java/dev/slimevr/osc/transport.kt b/server/core/src/main/java/dev/slimevr/osc/transport.kt index 6a1e80553..bf3a23620 100644 --- a/server/core/src/main/java/dev/slimevr/osc/transport.kt +++ b/server/core/src/main/java/dev/slimevr/osc/transport.kt @@ -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() { 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 d76bdc06e..36da95188 100644 --- a/server/core/src/main/java/dev/slimevr/oscquery/server.kt +++ b/server/core/src/main/java/dev/slimevr/oscquery/server.kt @@ -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, 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" +} diff --git a/server/core/src/main/java/dev/slimevr/udp/connection.kt b/server/core/src/main/java/dev/slimevr/udp/connection.kt index dc7222aa3..36274fb44 100644 --- a/server/core/src/main/java/dev/slimevr/udp/connection.kt +++ b/server/core/src/main/java/dev/slimevr/udp/connection.kt @@ -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}") + } } } diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/input.kt b/server/core/src/main/java/dev/slimevr/vrcosc/input.kt index 2d2903ed3..c2cdca8dc 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/input.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/input.kt @@ -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 { + 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?, 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 31cf192cf..610018465 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/module.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/module.kt @@ -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 class VRCOSCManager( val context: VRCOSCContext, - val oscQueryAddress: String, + private val oscQueryAddress: StateFlow, private val browse: MdnsBrowse, private val advertise: MdnsAdvertise, ) { @@ -131,7 +132,7 @@ class VRCOSCManager( companion object { fun create( scope: CoroutineScope, - oscQueryAddress: String, + oscQueryAddress: StateFlow, browse: MdnsBrowse, advertise: MdnsAdvertise, ): VRCOSCManager { 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 080ee3d1a..5cf0d8bf7 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/oscquery.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/oscquery.kt @@ -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, 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, diff --git a/server/core/src/test/java/dev/slimevr/mdns/MdnsTest.kt b/server/core/src/test/java/dev/slimevr/mdns/MdnsTest.kt index 15cd764f1..054e8a290 100644 --- a/server/core/src/test/java/dev/slimevr/mdns/MdnsTest.kt +++ b/server/core/src/test/java/dev/slimevr/mdns/MdnsTest.kt @@ -1,14 +1,17 @@ package dev.slimevr.mdns import dev.slimevr.multicast.MulticastSocket +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.MutableStateFlow 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 kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -65,7 +68,7 @@ class MdnsTest { @Test fun advertisingAnnouncesTwiceThenSaysGoodbyeAndClosesTheSocket() = runTest { val sockets = mutableListOf() - val mdns = createMdns(backgroundScope, "192.168.1.10") { _, _, _ -> FakeSocket().also(sockets::add) } + val mdns = createMdns(backgroundScope, MutableStateFlow("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) @@ -80,7 +83,7 @@ class MdnsTest { @Test fun browsingSharesTheSocketAndFindsAnsweringServices() = runTest { val sockets = mutableListOf() - val mdns = createMdns(backgroundScope, "192.168.1.10") { _, _, _ -> FakeSocket().also(sockets::add) } + val mdns = createMdns(backgroundScope, MutableStateFlow("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() } } @@ -102,10 +105,37 @@ class MdnsTest { } @Test - fun bindFailureReachesTheCaller() = runTest { - val mdns = createMdns(backgroundScope, "192.168.1.10") { _, _, _ -> error("no interface") } + fun bindFailureIsRetried() = runTest { + var attempts = 0 + val mdns = createMdns(backgroundScope, MutableStateFlow("192.168.1.10")) { _, _, _ -> + if (attempts++ == 0) error("no interface") + FakeSocket() + } - assertEquals("no interface", runCatching { mdns.browse("_oscjson._tcp").first() }.exceptionOrNull()?.message) + val browsing = launch { mdns.browse("_oscjson._tcp").collect {} } + advanceTimeBy(6_000) + assertEquals(2, attempts) + browsing.cancelAndJoin() + } + + @Test + fun addressChangeRebindsAndReannouncesOnTheNewAddress() = runTest { + val address = MutableStateFlow("192.168.1.10") + val sockets = mutableListOf>() + val mdns = createMdns(backgroundScope, address) { _, _, bound -> FakeSocket().also { sockets += bound to it } } + + val advertising = launch { mdns.advertise("_oscjson._tcp", "SlimeVR-Server-ABC123", 1234, emptyMap()) } + advanceTimeBy(1_500) + address.value = "192.168.1.20" + advanceTimeBy(1_500) + + val (firstAddress, first) = sockets.first() + val (secondAddress, second) = sockets.last() + assertEquals(listOf("192.168.1.10", "192.168.1.20"), listOf(firstAddress, secondAddress)) + assertTrue(first.closed) + val announced = parseResponseRecords(second.sent.first()).map { it.record } + assertTrue(MdnsRecord.Address("SlimeVR-Server-ABC123.local", "192.168.1.20") in announced) + advertising.cancelAndJoin() } private fun header(flags: Int, questions: Int = 0, answers: Int = 0) = u16(0) + u16(flags) + u16(questions) + u16(answers) + u16(0) + u16(0) @@ -124,7 +154,7 @@ private class FakeSocket : MulticastSocket { val incoming = Channel(Channel.UNLIMITED) var closed = false - override suspend fun listen(onPacket: (ByteArray) -> Unit) { + override suspend fun listen(onPacket: (ByteArray) -> Unit) = withContext(NonCancellable) { for (packet in incoming) onPacket(packet) } 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 12acf7a4d..54ec2ee13 100644 --- a/server/core/src/test/java/dev/slimevr/oscquery/OscQueryServerTest.kt +++ b/server/core/src/test/java/dev/slimevr/oscquery/OscQueryServerTest.kt @@ -16,17 +16,27 @@ import kotlinx.serialization.json.jsonPrimitive import java.net.URI import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNotEquals import kotlin.test.assertTrue class OscQueryServerTest { private val json = Json { ignoreUnknownKeys = true } + @Test + fun instanceNameIsStableForAnEndpointAndChangesWithIt() { + val name = instanceName("SlimeVR-Server", "192.168.1.10", 9001u) + assertEquals(name, instanceName("SlimeVR-Server", "192.168.1.10", 9001u)) + assertTrue(name.matches(Regex("SlimeVR-Server-[0-9A-F]{6}"))) + assertNotEquals(name, instanceName("SlimeVR-Server", "192.168.1.10", 9002u)) + assertNotEquals(name, instanceName("SlimeVR-Server", "192.168.1.11", 9001u)) + } + @Test fun httpRoutesAndAdvertisementsAreWired() = runBlocking { val advertised = MutableStateFlow>(emptyList()) val server = OscQueryServer( name = "SlimeVR", - address = "127.0.0.1", + localAddress = MutableStateFlow("127.0.0.1"), oscPort = 9000u, advertise = { type, name, port, txt -> val ad = Advertised(type, name, port, txt) 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 53f594512..1394fcddf 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -27,6 +27,7 @@ import dev.slimevr.desktop.timing.createDesktopWaiter import dev.slimevr.desktop.trackingchecklist.SteamVRCheckBehaviour import dev.slimevr.desktop.udp.bindDesktopUdp import dev.slimevr.desktop.vrchat.createDesktopVRCConfigManager +import dev.slimevr.desktop.vrchat.observeDesktopLocalIpAddress import dev.slimevr.desktop.vrchat.resolveDesktopLocalIpAddress import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager @@ -165,11 +166,11 @@ 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 localIpAddress = observeDesktopLocalIpAddress(scope = this) + val mdns = createMdns(scope = this, localAddress = localIpAddress, bind = ::bindDesktopMulticast) val vrcOscManager = VRCOSCManager.create( scope = this, - oscQueryAddress = oscQueryAddress, + oscQueryAddress = localIpAddress, browse = mdns.browse, advertise = mdns.advertise, ) diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/networkprofile/network-profile.kt b/server/desktop/src/main/java/dev/slimevr/desktop/networkprofile/network-profile.kt index 578b9f828..545f55eb5 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/networkprofile/network-profile.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/networkprofile/network-profile.kt @@ -37,6 +37,14 @@ interface Iphlpapi : Library { notificationHandle: PointerByReference, ): Int + fun NotifyUnicastIpAddressChange( + family: Int, + callback: Callback, + context: Pointer?, + initialNotification: Int, + notificationHandle: PointerByReference, + ): Int + fun CancelMibChangeNotify2(handle: Pointer): Int companion object { diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/vrchat/oscquery.kt b/server/desktop/src/main/java/dev/slimevr/desktop/vrchat/oscquery.kt index 7ad272be2..e91588753 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/vrchat/oscquery.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/vrchat/oscquery.kt @@ -1,8 +1,31 @@ package dev.slimevr.desktop.vrchat +import com.sun.jna.Callback +import com.sun.jna.Pointer +import com.sun.jna.ptr.PointerByReference +import dev.slimevr.CURRENT_PLATFORM +import dev.slimevr.Platform +import dev.slimevr.desktop.networkprofile.Iphlpapi +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.awaitClose +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.conflate +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import java.lang.ref.Reference import java.net.InetAddress import java.net.NetworkInterface import java.util.Collections +import kotlin.time.Duration.Companion.seconds + +private val RESOLVE_INTERVAL = 5.seconds fun resolveDesktopLocalIpAddress(): String = try { val candidates = Collections.list(NetworkInterface.getNetworkInterfaces()) @@ -18,3 +41,36 @@ fun resolveDesktopLocalIpAddress(): String = try { } catch (_: Exception) { InetAddress.getLoopbackAddress().hostAddress } + +/** [resolveDesktopLocalIpAddress], resolved again whenever the machine's addresses may have changed. */ +fun observeDesktopLocalIpAddress(scope: CoroutineScope): StateFlow = addressChanges() + .map { resolveDesktopLocalIpAddress() } + .flowOn(Dispatchers.IO) + .stateIn(scope, SharingStarted.Eagerly, resolveDesktopLocalIpAddress()) + +// The JVM has no address change notification, so outside Windows we resolve again on a timer +private fun addressChanges(): Flow = if (CURRENT_PLATFORM == Platform.WINDOWS) { + windowsAddressChanges() +} else { + flow { + while (true) { + delay(RESOLVE_INTERVAL) + emit(Unit) + } + } +} + +private class AddressChangeCallback(private val onChange: () -> Unit) : Callback { + @Suppress("UNUSED") + fun callback(context: Pointer?, row: Pointer?, notificationType: Int) = onChange() +} + +private fun windowsAddressChanges(): Flow = callbackFlow { + val callback = AddressChangeCallback { trySend(Unit) } + val handle = PointerByReference() + Iphlpapi.INSTANCE.NotifyUnicastIpAddressChange(0, callback, null, 0, handle) + awaitClose { + handle.value?.let { Iphlpapi.INSTANCE.CancelMibChangeNotify2(it) } + Reference.reachabilityFence(callback) + } +}.conflate()