mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-06 08:42:32 -08:00
OTA fixes (not tested)
This commit is contained in:
1 parent
6942810e4b
commit
71c627f6fa
11 files changed
+406
-67
No files matched your search
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, Job>()
|
||||
|
||||
val otaConnections = MutableSharedFlow<OtaConnection>()
|
||||
|
||||
suspend fun flash(
|
||||
portLocation: String,
|
||||
parts: List<FirmwarePart>,
|
||||
@@ -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,
|
||||
|
||||
@@ -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<OtaConnection>,
|
||||
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<OtaConnection>,
|
||||
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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user