diff --git a/gui/electron/electron-builder.yml b/gui/electron/electron-builder.yml index 43555721c..4cf816f59 100644 --- a/gui/electron/electron-builder.yml +++ b/gui/electron/electron-builder.yml @@ -51,6 +51,8 @@ linux: to: "." - from: "./resources/69-slimevr-devices.rules" to: "." + - from: "./resources/firewall" + to: "firewall" icon: "./resources/icons" deb: diff --git a/gui/electron/resources/firewall/slimevr-ufw b/gui/electron/resources/firewall/slimevr-ufw new file mode 100644 index 000000000..579d64b39 --- /dev/null +++ b/gui/electron/resources/firewall/slimevr-ufw @@ -0,0 +1,4 @@ +[SlimeVR] +title=SlimeVR Server +description=Tracker data (UDP 6969), tracker OTA firmware uploads (TCP 8266) and the SolarXR WebSocket (TCP 21110). +ports=6969/udp|8266,21110/tcp diff --git a/gui/electron/resources/firewall/slimevr.xml b/gui/electron/resources/firewall/slimevr.xml new file mode 100644 index 000000000..4508e4ba1 --- /dev/null +++ b/gui/electron/resources/firewall/slimevr.xml @@ -0,0 +1,8 @@ + + + SlimeVR + SlimeVR Server: tracker data (UDP 6969), tracker OTA firmware uploads (TCP 8266) and the SolarXR WebSocket (TCP 21110). + + + + diff --git a/gui/electron/resources/scripts/postinstall.sh b/gui/electron/resources/scripts/postinstall.sh index 48015b616..308a080ed 100644 --- a/gui/electron/resources/scripts/postinstall.sh +++ b/gui/electron/resources/scripts/postinstall.sh @@ -1,26 +1,47 @@ #!/bin/bash -SRC="/opt/SlimeVR/69-slimevr-devices.rules" -DESTDIRS=("/lib" "/usr/lib") +install_udev_rules() { + local SRC="/opt/SlimeVR/69-slimevr-devices.rules" + local DESTDIRS=("/lib" "/usr/lib") -if [[ ! -f "$SRC" ]]; then - echo "SlimeVR udev rules not found, serial console and dongles may not work" >&2 - exit 0 -fi - -echo "Configuring SlimeVR udev rules..." - -for DIR in "${DESTDIRS[@]}"; do - if [[ -d "$DIR" && ! -h "$DIR" ]]; then - echo "Copying rules to $DIR" - install -Dm644 "$SRC" "$DIR/udev/rules.d/69-slimevr-devices.rules" - - if command -v udevadm >/dev/null 2>&1; then - udevadm control --reload-rules - udevadm trigger - fi - exit 0 + if [[ ! -f "$SRC" ]]; then + echo "SlimeVR udev rules not found, serial console and dongles may not work" >&2 + return fi -done -echo "Couldn't copy SlimeVR udev rules, serial console and dongles may not work" >&2 + echo "Configuring SlimeVR udev rules..." + + for DIR in "${DESTDIRS[@]}"; do + if [[ -d "$DIR" && ! -h "$DIR" ]]; then + echo "Copying rules to $DIR" + install -Dm644 "$SRC" "$DIR/udev/rules.d/69-slimevr-devices.rules" + + if command -v udevadm >/dev/null 2>&1; then + udevadm control --reload-rules + udevadm trigger + fi + return + fi + done + + echo "Couldn't copy SlimeVR udev rules, serial console and dongles may not work" >&2 +} + +# Only defines the services, opening the ports is left to the user. +install_firewall_services() { + local SRC="/opt/SlimeVR/firewall" + + if [[ -d "/usr/lib/firewalld/services" && -f "$SRC/slimevr.xml" ]]; then + echo "Installing SlimeVR firewalld service, enable it with: firewall-cmd --permanent --add-service=slimevr && firewall-cmd --reload" + install -Dm644 "$SRC/slimevr.xml" "/usr/lib/firewalld/services/slimevr.xml" + fi + + if [[ -d "/etc/ufw/applications.d" && -f "$SRC/slimevr-ufw" ]]; then + echo "Installing SlimeVR ufw profile, enable it with: ufw allow SlimeVR" + install -Dm644 "$SRC/slimevr-ufw" "/etc/ufw/applications.d/slimevr" + fi +} + +install_udev_rules +install_firewall_services +exit 0 diff --git a/gui/electron/resources/scripts/postremove.sh b/gui/electron/resources/scripts/postremove.sh index ddd8ff38a..65c1fd517 100644 --- a/gui/electron/resources/scripts/postremove.sh +++ b/gui/electron/resources/scripts/postremove.sh @@ -1,4 +1,11 @@ #!/bin/bash + +# Upgrades run the old package remove script after the new install, keep the files then +# (deb passes "upgrade", rpm passes the remaining install count) +if [[ "$1" == "upgrade" || "$1" == "1" ]]; then + exit 0 +fi + echo "Removing SlimeVR udev rules..." rm -f "/lib/udev/rules.d/69-slimevr-devices.rules" rm -f "/usr/lib/udev/rules.d/69-slimevr-devices.rules" @@ -6,3 +13,16 @@ rm -f "/usr/lib/udev/rules.d/69-slimevr-devices.rules" if command -v udevadm >/dev/null 2>&1; then udevadm control --reload-rules fi + +# Keep a definition that is still in use, a zone or rule pointing at a missing one breaks the firewall reload +if grep -rqs 'service name="slimevr"' /etc/firewalld/zones/; then + echo "SlimeVR firewalld service still enabled, keeping /usr/lib/firewalld/services/slimevr.xml" >&2 +else + rm -f "/usr/lib/firewalld/services/slimevr.xml" +fi + +if grep -qs "SlimeVR" /etc/ufw/user.rules /etc/ufw/user6.rules; then + echo "SlimeVR ufw rule still present, keeping /etc/ufw/applications.d/slimevr" >&2 +else + rm -f "/etc/ufw/applications.d/slimevr" +fi diff --git a/server/core/resources/firewall.bat b/server/core/resources/firewall.bat index 323ecf8f7..83178a265 100644 --- a/server/core/resources/firewall.bat +++ b/server/core/resources/firewall.bat @@ -23,9 +23,8 @@ call :AddRule "SlimeVR TCP 21110 outgoing" "dir=out action=allow protocol=TCP lo rem OpenJDK Platform Binary access call :AddRule "SlimeVR OpenJDK Platform incoming" "dir=in action=allow program=""%~dp0jre\bin\java.exe"" enable=yes" call :AddRule "SlimeVR OpenJDK Platform outgoing" "dir=out action=allow program=""%~dp0jre\bin\java.exe"" enable=yes" -rem ESP8266 OTA default port -call :AddRule "SlimeVR UDP 8266 incoming" "dir=in action=allow protocol=UDP localport=8266 enable=yes" -call :AddRule "SlimeVR UDP 8266 outgoing" "dir=out action=allow protocol=UDP localport=8266 enable=yes" +rem OTA firmware upload, trackers connect back to this port +call :AddRule "SlimeVR TCP 8266 incoming" "dir=in action=allow protocol=TCP localport=8266 enable=yes" echo Done! pause diff --git a/server/core/resources/firewall_uninstall.bat b/server/core/resources/firewall_uninstall.bat index 0da7589cd..38d493dab 100644 --- a/server/core/resources/firewall_uninstall.bat +++ b/server/core/resources/firewall_uninstall.bat @@ -26,9 +26,11 @@ call :DeleteRule "SlimeVR TCP 21110 outgoing" rem OpenJDK Platform Binary access call :DeleteRule "SlimeVR OpenJDK Platform incoming" call :DeleteRule "SlimeVR OpenJDK Platform outgoing" -rem ESP8266 OTA default port +rem ESP8266 OTA port, from older installs call :DeleteRule "SlimeVR UDP 8266 incoming" call :DeleteRule "SlimeVR UDP 8266 outgoing" +rem OTA firmware upload callback port +call :DeleteRule "SlimeVR TCP 8266 incoming" echo Done! pause diff --git a/server/core/src/main/java/dev/slimevr/firmware/behaviours/ota-callback.kt b/server/core/src/main/java/dev/slimevr/firmware/behaviours/ota-callback.kt new file mode 100644 index 000000000..492703a88 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/firmware/behaviours/ota-callback.kt @@ -0,0 +1,56 @@ +package dev.slimevr.firmware.behaviours + +import dev.slimevr.firmware.FirmwareManager +import dev.slimevr.firmware.FirmwareManagerBehaviour +import dev.slimevr.firmware.OTA_CALLBACK_PORT +import dev.slimevr.firmware.OtaConnection +import dev.slimevr.firmware.isAwaitingOtaCallback +import dev.slimevr.logging.AppLogger +import dev.slimevr.util.stripIpAddressPort +import io.ktor.network.selector.SelectorManager +import io.ktor.network.sockets.InetSocketAddress +import io.ktor.network.sockets.toJavaAddress +import io.ktor.network.sockets.aSocket +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +/** + * Listens on a fixed TCP port for trackers connecting back during OTA, so a single firewall + * rule covers it. Sockets are routed to the job by remote IP, so parallel updates share the port. + */ +class OtaCallbackBehaviour( + private val port: Int = OTA_CALLBACK_PORT, +) : FirmwareManagerBehaviour { + override fun observe(receiver: FirmwareManager) { + receiver.context.scope.launch(Dispatchers.IO) { listen(receiver) } + } + + private suspend fun listen(manager: FirmwareManager) { + SelectorManager(Dispatchers.IO).use { selectorManager -> + val serverSocket = try { + aSocket(selectorManager).tcp().bind(InetSocketAddress("0.0.0.0", port)) { reuseAddress = true } + } catch (e: Exception) { + AppLogger.firmware.error(e, "Failed to bind the OTA port $port") + return + } + serverSocket.use { + while (currentCoroutineContext().isActive) { + val socket = serverSocket.accept() + // Same as the UDP address resolvers, hostString avoids a reverse DNS lookup + val ip = (socket.remoteAddress.toJavaAddress() as? java.net.InetSocketAddress)?.hostString + val waiting = manager.context.state.value.jobs.values.any { job -> + isAwaitingOtaCallback(job) && stripIpAddressPort(job.portLocation) == ip + } + if (ip != null && waiting && manager.otaConnections.subscriptionCount.value > 0) { + manager.otaConnections.emit(OtaConnection(ip, socket)) + } else { + AppLogger.firmware.warn("Rejected unexpected OTA connection from $ip") + socket.close() + } + } + } + } + } +} diff --git a/server/core/src/main/java/dev/slimevr/firmware/module.kt b/server/core/src/main/java/dev/slimevr/firmware/module.kt index 334c3faa9..fcef94d1b 100644 --- a/server/core/src/main/java/dev/slimevr/firmware/module.kt +++ b/server/core/src/main/java/dev/slimevr/firmware/module.kt @@ -7,11 +7,13 @@ import dev.slimevr.context.Behaviour import dev.slimevr.context.Context import dev.slimevr.context.debug.DiffStyle import dev.slimevr.context.debug.LoggingMiddleware +import dev.slimevr.firmware.behaviours.OtaCallbackBehaviour import dev.slimevr.logging.AppLogger import dev.slimevr.serial.SerialServer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.launch import solarxr_protocol.rpc.FirmwareDeviceIdTable import solarxr_protocol.rpc.FirmwarePart @@ -54,6 +56,8 @@ class FirmwareManager( private val runningJobs = mutableMapOf() + val otaConnections = MutableSharedFlow() + suspend fun flash( portLocation: String, parts: List, @@ -109,6 +113,7 @@ class FirmwareManager( deviceId = (firmwareDeviceId as? FirmwareDeviceIdTable)?.id ?: error("device id should exist"), part = part, server = server, + otaConnections = otaConnections, onStatus = { status, progress -> AppLogger.firmware.debug("OTA status changed to $status, progress=$progress") context.dispatch( @@ -139,6 +144,7 @@ class FirmwareManager( initialState = FirmwareManagerState(jobs = mapOf()), scope = scope, reducer = ::reduce, + behaviours = listOf(OtaCallbackBehaviour()), debugMiddleware = LoggingMiddleware( diffStyle = DiffStyle.INLINE, logNoOps = true, diff --git a/server/core/src/main/java/dev/slimevr/firmware/ota.kt b/server/core/src/main/java/dev/slimevr/firmware/ota.kt index 2e7b6aa07..cd222e157 100644 --- a/server/core/src/main/java/dev/slimevr/firmware/ota.kt +++ b/server/core/src/main/java/dev/slimevr/firmware/ota.kt @@ -7,11 +7,10 @@ import io.ktor.network.selector.SelectorManager import io.ktor.network.sockets.BoundDatagramSocket import io.ktor.network.sockets.Datagram import io.ktor.network.sockets.InetSocketAddress -import io.ktor.network.sockets.ServerSocket +import io.ktor.network.sockets.Socket import io.ktor.network.sockets.aSocket import io.ktor.network.sockets.openReadChannel import io.ktor.network.sockets.openWriteChannel -import io.ktor.network.sockets.port import io.ktor.utils.io.ByteReadChannel import io.ktor.utils.io.ByteWriteChannel import io.ktor.utils.io.core.buildPacket @@ -20,10 +19,17 @@ import io.ktor.utils.io.core.writeFully import io.ktor.utils.io.discardExact import io.ktor.utils.io.readRemaining import io.ktor.utils.io.writeFully +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import kotlinx.io.readByteArray +import solarxr_protocol.rpc.FirmwareDeviceIdTable import solarxr_protocol.rpc.FirmwarePart import solarxr_protocol.rpc.FirmwareUpdateStatus import java.security.MessageDigest @@ -31,6 +37,7 @@ import java.util.UUID import kotlin.math.min private const val OTA_PORT = 8266 +const val OTA_CALLBACK_PORT = 8266 private const val OTA_PASSWORD = "SlimeVR-OTA" private const val OTA_CHUNK_SIZE = 2048 @@ -38,6 +45,11 @@ private fun bytesToMd5(bytes: ByteArray): String = MessageDigest.getInstance("MD private suspend fun sendDatagram(socket: BoundDatagramSocket, message: String, target: InetSocketAddress) = socket.send(Datagram(buildPacket { writeFully(message.toByteArray()) }, target)) +data class OtaConnection(val ip: String, val socket: Socket) + +/** An OTA job whose device has been invited and has not connected back yet. */ +fun isAwaitingOtaCallback(job: FirmwareJobStatus) = job.firmwareDeviceId is FirmwareDeviceIdTable && job.status == FirmwareUpdateStatus.AUTHENTICATING + /** * Sends the OTA invitation over UDP and performs the optional AUTH challenge-response. * Returns true if authentication succeeded (or was not required). @@ -45,11 +57,12 @@ private suspend fun sendDatagram(socket: BoundDatagramSocket, message: String, t private suspend fun otaAuthenticate( selectorManager: SelectorManager, deviceIp: String, + devicePort: Int, localPort: Int, firmware: ByteArray, ): Boolean { val fileMd5 = bytesToMd5(firmware) - val target = InetSocketAddress(stripIpAddressPort(deviceIp), OTA_PORT) + val target = InetSocketAddress(stripIpAddressPort(deviceIp), devicePort) aSocket(selectorManager).udp().bind(InetSocketAddress("0.0.0.0", 0)).use { socket -> sendDatagram(socket, "0 $localPort ${firmware.size} $fileMd5\n", target) @@ -73,23 +86,55 @@ private suspend fun otaAuthenticate( } /** - * Accepts a TCP connection from the device and streams the firmware in chunks. - * Returns true if the device confirmed a successful flash with "OK". + * Invites the device to fetch [firmware] and streams it over the connection it opens back + * to the shared listener. The job must already be in AUTHENTICATING so the connection is routed to it. */ -private suspend fun otaUpload( - tcpServer: ServerSocket, +internal suspend fun otaTransfer( + deviceIp: String, firmware: ByteArray, - onProgress: suspend (Int) -> Unit, -): Boolean { - val socket = withTimeout(30_000) { tcpServer.accept() } - return socket.use { - uploadFirmware( - output = socket.openWriteChannel(autoFlush = true), - input = socket.openReadChannel(), - firmware = firmware, - onProgress = onProgress, - ) + otaConnections: SharedFlow, + onStatus: suspend (FirmwareUpdateStatus, Int) -> Unit, + callbackPort: Int = OTA_CALLBACK_PORT, + devicePort: Int = OTA_PORT, +): Boolean = coroutineScope { + val ip = stripIpAddressPort(deviceIp) + + val connection = async(start = CoroutineStart.UNDISPATCHED) { + otaConnections.first { it.ip == ip }.socket } + + val authenticated = SelectorManager(Dispatchers.IO).use { selectorManager -> + try { + otaAuthenticate(selectorManager, deviceIp, devicePort, callbackPort, firmware) + } catch (_: TimeoutCancellationException) { + false + } + } + if (!authenticated) { + connection.cancel() + onStatus(FirmwareUpdateStatus.ERROR_AUTHENTICATION_FAILED, 0) + return@coroutineScope false + } + + val uploaded = runCatching { + withTimeout(30_000) { connection.await() }.use { socket -> + uploadFirmware( + output = socket.openWriteChannel(autoFlush = true), + input = socket.openReadChannel(), + firmware = firmware, + onProgress = { progress -> onStatus(FirmwareUpdateStatus.UPLOADING, progress) }, + ) + } + } + if (uploaded.isFailure) { + connection.cancel() + uploaded.exceptionOrNull()?.let { e -> + AppLogger.firmware.error(e, "OTA firmware upload failed") + } + onStatus(FirmwareUpdateStatus.ERROR_UPLOAD_FAILED, 0) + return@coroutineScope false + } + true } internal suspend fun uploadFirmware( @@ -119,6 +164,7 @@ suspend fun doOtaFlash( deviceId: UShort, part: FirmwarePart, server: VRServer, + otaConnections: SharedFlow, onStatus: suspend (FirmwareUpdateStatus, Int) -> Unit, ) { onStatus(FirmwareUpdateStatus.DOWNLOADING, 0) @@ -136,31 +182,7 @@ suspend fun doOtaFlash( onStatus(FirmwareUpdateStatus.AUTHENTICATING, 0) - SelectorManager(Dispatchers.IO).use { selectorManager -> - // Bind TCP server first so we know which port to advertise in the invitation - aSocket(selectorManager).tcp().bind(port = 0).use { tcpServer -> - val localPort = tcpServer.port - - if (!otaAuthenticate(selectorManager, deviceIp, localPort, firmware)) { - onStatus(FirmwareUpdateStatus.ERROR_AUTHENTICATION_FAILED, 0) - return - } - - val uploaded = runCatching { - otaUpload(tcpServer, firmware) { progress -> - onStatus(FirmwareUpdateStatus.UPLOADING, progress) - } - } - - if (uploaded.isFailure) { - uploaded.exceptionOrNull()?.let { e -> - AppLogger.firmware.error(e, "OTA firmware upload failed") - } - onStatus(FirmwareUpdateStatus.ERROR_UPLOAD_FAILED, 0) - return - } - } - } + if (!otaTransfer(deviceIp, firmware, otaConnections, onStatus)) return onStatus(FirmwareUpdateStatus.REBOOTING, 0) diff --git a/server/core/src/test/java/dev/slimevr/firmware/OtaUploadTest.kt b/server/core/src/test/java/dev/slimevr/firmware/OtaUploadTest.kt index b8718cfa7..37ad97e8d 100644 --- a/server/core/src/test/java/dev/slimevr/firmware/OtaUploadTest.kt +++ b/server/core/src/test/java/dev/slimevr/firmware/OtaUploadTest.kt @@ -3,23 +3,51 @@ package dev.slimevr.firmware import dev.slimevr.VRServer import dev.slimevr.VRServerActions import dev.slimevr.buildTestAppContext +import dev.slimevr.buildTestDevicesConfig +import dev.slimevr.buildTestSerial import dev.slimevr.buildTestVrServerStub +import dev.slimevr.context.Context import dev.slimevr.device.Device import dev.slimevr.device.DeviceActions +import dev.slimevr.firmware.behaviours.OtaCallbackBehaviour import io.ktor.utils.io.ByteChannel import io.ktor.utils.io.readRemaining import io.ktor.utils.io.writeFully +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.io.readByteArray import solarxr_protocol.datatypes.DeviceOrigin import solarxr_protocol.datatypes.TrackerStatus +import solarxr_protocol.rpc.FirmwareDeviceIdTable +import solarxr_protocol.rpc.FirmwareUpdateStatus +import java.io.ByteArrayOutputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import kotlin.math.min import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue private fun addUdpDevice( @@ -41,6 +69,96 @@ private fun addUdpDevice( return device } +private fun freeTcpPort(): Int = ServerSocket(0).use { it.localPort } + +private suspend fun buildOtaTestManager(scope: CoroutineScope, port: Int): FirmwareManager { + val context = Context.create( + initialState = FirmwareManagerState(jobs = mapOf()), + scope = scope, + reducer = ::reduce, + behaviours = listOf(OtaCallbackBehaviour(port)), + name = "FirmwareManager[test]", + ) + val manager = FirmwareManager( + context = context, + serialServer = buildTestSerial(scope).server, + devices = buildTestDevicesConfig(scope), + flasher = { _, _, _, _ -> }, + scope = scope, + ) + manager.startObserving() + awaitListening(port) + return manager +} + +private suspend fun awaitListening(port: Int) = withTimeout(5_000) { + while (runCatching { withContext(Dispatchers.IO) { Socket("127.0.0.1", port).close() } }.isFailure) { + delay(20) + } +} + +private fun otaJob(ip: String, status: FirmwareUpdateStatus, id: Int = 1) = FirmwareManagerActions.UpdateJob( + FirmwareJobStatus( + portLocation = ip, + firmwareDeviceId = FirmwareDeviceIdTable(id = id.toUShort()), + status = status, + ), +) + +private fun runOtaTest(block: suspend CoroutineScope.(scope: CoroutineScope) -> Unit) = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + withTimeout(30_000) { block(scope) } + } finally { + scope.cancel() + } +} + +private class FakeOtaDevice(val ip: String, val udp: DatagramSocket) { + val received = ByteArrayOutputStream() + var advertisedPort = -1 + val firstChunk = CompletableDeferred() + + suspend fun run(beforeFirstAck: suspend () -> Unit) = withContext(Dispatchers.IO) { + udp.use { + udp.soTimeout = 10_000 + val buffer = ByteArray(256) + val invite = DatagramPacket(buffer, buffer.size) + udp.receive(invite) + val args = String(buffer, 0, invite.length).trim().split(" ") + advertisedPort = args[1].toInt() + val size = args[2].toInt() + udp.send(DatagramPacket("OK".toByteArray(), 2, invite.socketAddress)) + + Socket().use { socket -> + socket.soTimeout = 10_000 + socket.bind(InetSocketAddress(ip, 0)) + socket.connect(InetSocketAddress("127.0.0.1", advertisedPort)) + val input = socket.getInputStream() + val output = socket.getOutputStream() + while (received.size() < size) { + val chunk = input.readNBytes(min(2048, size - received.size())) + received.write(chunk) + if (!firstChunk.isCompleted) { + firstChunk.complete(Unit) + beforeFirstAck() + } + output.write(ByteArray(4)) + output.flush() + } + output.write("OK".toByteArray()) + output.flush() + } + } + } +} + +private fun bindDeviceUdp(ip: String, port: Int): DatagramSocket? = try { + DatagramSocket(InetSocketAddress(ip, port)) +} catch (_: Exception) { + null +} + class OtaUploadTest { @Test fun `uploadFirmware writes complete payload across chunk boundaries`() = runTest { @@ -121,4 +239,85 @@ class OtaUploadTest { assertEquals(true, result) } + + @Test + fun `routes a connection to the job waiting on its IP`() = runOtaTest { scope -> + val port = freeTcpPort() + val manager = buildOtaTestManager(scope, port) + val received = scope.async(start = CoroutineStart.UNDISPATCHED) { manager.otaConnections.first() } + + manager.context.dispatch(otaJob("127.0.0.1", FirmwareUpdateStatus.AUTHENTICATING)) + + withContext(Dispatchers.IO) { Socket("127.0.0.1", port) }.use { + val connection = withTimeout(5_000) { received.await() } + assertEquals("127.0.0.1", connection.ip) + connection.socket.close() + } + } + + @Test + fun `closes a connection from an IP nobody is waiting on`() = runOtaTest { scope -> + val port = freeTcpPort() + val manager = buildOtaTestManager(scope, port) + val received = scope.async(start = CoroutineStart.UNDISPATCHED) { manager.otaConnections.first() } + + manager.context.dispatch(otaJob("10.0.0.1", FirmwareUpdateStatus.AUTHENTICATING)) + + withContext(Dispatchers.IO) { Socket("127.0.0.1", port) }.use { client -> + client.soTimeout = 5_000 + val read = withContext(Dispatchers.IO) { client.getInputStream().read() } + assertEquals(-1, read) + } + assertNull(withTimeoutOrNull(200) { received.await() }) + received.cancel() + } + + @Test + fun `two devices update in parallel over the shared port`() = runOtaTest { scope -> + val udpA = bindDeviceUdp("127.0.0.1", 0)!! + val devicePort = udpA.localPort + // Both devices need the same OTA port, on distinct loopback IPs (all of 127/8 on Linux) + val udpB = bindDeviceUdp("127.0.0.2", devicePort) + if (udpB == null) { + udpA.close() + println("Skipping: 127.0.0.2 is not bindable on this machine") + return@runOtaTest + } + val deviceA = FakeOtaDevice("127.0.0.1", udpA) + val deviceB = FakeOtaDevice("127.0.0.2", udpB) + // Sizes not aligned to the chunk size, and different per device to prove routing + val firmwareA = ByteArray(2048 * 3 + 17) { (it * 7).toByte() } + val firmwareB = ByteArray(2048 * 2 + 901) { (it * 13 + 1).toByte() } + + val callbackPort = freeTcpPort() + val manager = buildOtaTestManager(scope, callbackPort) + manager.context.dispatch(otaJob("127.0.0.1", FirmwareUpdateStatus.AUTHENTICATING, id = 1)) + manager.context.dispatch(otaJob("127.0.0.2", FirmwareUpdateStatus.AUTHENTICATING, id = 2)) + + // Neither device acks its first chunk until both have one, so the uploads must overlap + val bothStarted: suspend () -> Unit = { listOf(deviceA.firstChunk, deviceB.firstChunk).awaitAll() } + val devices = listOf( + scope.async { deviceA.run(bothStarted) }, + scope.async { deviceB.run(bothStarted) }, + ) + + fun transfer(device: FakeOtaDevice, firmware: ByteArray) = scope.async { + otaTransfer( + deviceIp = device.ip, + firmware = firmware, + otaConnections = manager.otaConnections, + onStatus = { _, _ -> }, + callbackPort = callbackPort, + devicePort = devicePort, + ) + } + val results = listOf(transfer(deviceA, firmwareA), transfer(deviceB, firmwareB)).awaitAll() + devices.awaitAll() + + assertEquals(listOf(true, true), results) + assertContentEquals(firmwareA, deviceA.received.toByteArray()) + assertContentEquals(firmwareB, deviceB.received.toByteArray()) + assertEquals(callbackPort, deviceA.advertisedPort) + assertEquals(callbackPort, deviceB.advertisedPort) + } }