added JoinResponsePacket.kt + Builders + ext

added game protocol compression
This commit is contained in:
fiereu committed 2025-09-04 18:30:17 +02:00
1 parent f5e18d8540
commit 88e888dfc9
16 files changed
+272 -16

No files matched your search

@@ -4,6 +4,9 @@ import de.fiereu.openmmo.protocols.Protocol
import de.fiereu.openmmo.protocols.game.packets.JoinGamePacket
import de.fiereu.openmmo.protocols.game.packets.JoinPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.JoinPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.JoinResponsePacket
import de.fiereu.openmmo.protocols.game.packets.JoinResponsePacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.JoinResponsePacketSerializer
import de.fiereu.openmmo.protocols.incomingPacket
import de.fiereu.openmmo.protocols.outgoingPacket
@@ -14,16 +17,20 @@ import de.fiereu.openmmo.protocols.outgoingPacket
abstract class GameProtocol : Protocol() {
override val async: Boolean
get() = true
override val compressed: Boolean
get() = true
}
class GameServerProtocol : GameProtocol() {
init {
incomingPacket(0x01u, JoinPacketDeserializer())
outgoingPacket(0x01u, JoinResponsePacketSerializer(), JoinResponsePacket::class)
}
}
class GameClientProtocol : GameProtocol() {
init {
outgoingPacket(0x01u, JoinPacketSerializer(), JoinGamePacket::class)
incomingPacket(0x01u, JoinResponsePacketDeserializer())
}
}
@@ -0,0 +1,92 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import de.fiereu.openmmo.protocols.readUtf16LE
import de.fiereu.openmmo.protocols.writeUtf16LE
import io.netty.buffer.ByteBuf
import java.time.LocalDate
import java.time.ZoneId
/*
* Some info to the packet:
* The packet is sent in response to a JoinGamePacket BUT
* seems to also be sent as some kind of time sync packet
*/
data class JoinResponsePacket(
val canJoin: Boolean,
val stats: GameStats? = null
// we dont need TimeInfo here since it can be calculated on the fly
) {
data class GameStats(
val playtime: Int,
val rewardPoints: Int,
val balance: Int
)
}
class JoinResponsePacketSerializer : PacketSerializer<JoinResponsePacket> {
override fun serialize(packet: JoinResponsePacket, buffer: ByteBuf) {
buffer.writeBoolean(packet.canJoin)
if (!packet.canJoin) return // no further data is sent
// the following fields are not used by the client, so we send empty/default values
buffer.writeUtf16LE("")
buffer.writeByte(0)
requireNotNull(packet.stats) { "Stats must be provided if canJoin is true" }
buffer.writeIntLE(packet.stats.playtime) // Playtime
buffer.writeIntLE(packet.stats.rewardPoints) // Reward Points
buffer.writeIntLE(packet.stats.balance) // Balance (pokeyen obvsly)
// start of current day in epoch seconds
// used to calculate the current hour
buffer.writeIntLE(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toEpochSecond().toInt())
// Used to calculate server time / desync
buffer.writeIntLE(((System.currentTimeMillis() / 1000).toInt()))
}
}
class JoinResponsePacketDeserializer : PacketDeserializer<JoinResponsePacketDeserializer.JoinResponsePacket> {
data class JoinResponsePacket(
val canJoin: Boolean,
val stats: GameStats? = null,
val time: TimeInfo? = null
) {
data class GameStats(
val playtime: Int,
val rewardPoints: Int,
val balance: Int
)
data class TimeInfo(
val serverDayStartSecond: Int,
val serverCurrentSecond: Int
)
}
override fun deserialize(buffer: ByteBuf): JoinResponsePacket {
if (!buffer.readBoolean()) {
return JoinResponsePacket(false, null)
}
// unused
buffer.readUtf16LE()
buffer.readByte()
val playtime = buffer.readUnsignedIntLE().toInt()
val rewardPoints = buffer.readUnsignedIntLE().toInt()
val balance = buffer.readUnsignedIntLE().toInt()
val serverDayStartSecond = buffer.readUnsignedIntLE().toInt()
val serverCurrentSecond = buffer.readUnsignedIntLE().toInt()
return JoinResponsePacket(
true,
JoinResponsePacket.GameStats(playtime, rewardPoints, balance),
JoinResponsePacket.TimeInfo(serverDayStartSecond, serverCurrentSecond)
)
}
}
@@ -0,0 +1,48 @@
package de.fiereu.openmmo.protocols.game.packets.builders
import de.fiereu.openmmo.protocols.game.packets.JoinResponsePacket
class JoinResponsePacketBuilder(
private val canJoin: Boolean
) {
private var playtime: Int = 0
private var rewardPoints: Int = 0
private var balance: Int = 0
companion object {
fun reject(): JoinResponsePacket {
return JoinResponsePacket(false)
}
fun accept(): JoinResponsePacketBuilder {
return JoinResponsePacketBuilder(true)
}
}
fun withPlaytime(playtime: Int): JoinResponsePacketBuilder {
this.playtime = playtime
return this
}
fun withRewardPoints(rewardPoints: Int): JoinResponsePacketBuilder {
this.rewardPoints = rewardPoints
return this
}
fun withBalance(balance: Int): JoinResponsePacketBuilder {
this.balance = balance
return this
}
fun build(): JoinResponsePacket {
require(canJoin) { "Cannot build a JoinResponsePacket with canJoin=false. Use JoinResponsePacketBuilder.reject() instead." }
return JoinResponsePacket(
canJoin = true,
stats = JoinResponsePacket.GameStats(
playtime = playtime,
rewardPoints = rewardPoints,
balance = balance
)
)
}
}
@@ -50,6 +50,8 @@ import de.fiereu.openmmo.protocols.tls.packets.ToSPacketSerializer
abstract class LoginProtocol() : Protocol() {
override val async: Boolean
get() = true
override val compressed: Boolean
get() = false
}
class LoginServerProtocol() : LoginProtocol() {
@@ -24,6 +24,8 @@ import java.security.interfaces.ECPublicKey
abstract class TlsProtocol() : Protocol() {
override val async: Boolean
get() = false
override val compressed: Boolean
get() = false
}
class TlsServerProtocol(serverKeyPair: Pair<ECPrivateKey, ECPublicKey>) : TlsProtocol() {
@@ -48,6 +48,7 @@ abstract class Protocol {
private val dataClassToOpcode: MutableMap<KClass<*>, Opcode> = mutableMapOf()
abstract val async: Boolean
abstract val compressed: Boolean
fun getOpcode(dataClass: KClass<*>): Opcode? = dataClassToOpcode[dataClass]
@@ -22,7 +22,7 @@ fun main() {
.withTlsConfig(tlsConfig)
.withPublicKey(KeyLoader.loadPemECPublicKey(resource("game.public.pem")))
.withPrivateKey(KeyLoader.loadPemECPrivateKey(resource("game.private.pem")))
.withChannelHandlerProvider { GameProtocolHandler(GameServerProtocol(), coroutineScope) }
.withChannelHandlerProvider { GameProtocolHandler(GameServerProtocol(), serverConfig, coroutineScope) }
.build()
server.start()
}
@@ -2,6 +2,9 @@ package de.fiereu.openmmo.server.game.protocol.game
import de.fiereu.openmmo.protocols.Protocol
import de.fiereu.openmmo.protocols.game.packets.JoinGamePacket
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.game.protocol.game.ext.accept
import de.fiereu.openmmo.server.game.protocol.game.ext.buildAndRespond
import de.fiereu.openmmo.server.netty.handlers.ProtocolHandler
import de.fiereu.openmmo.server.protocol.PacketEvent
import io.github.oshai.kotlinlogging.KotlinLogging
@@ -12,9 +15,10 @@ import kotlinx.coroutines.launch
private val log = KotlinLogging.logger {}
class GameProtocolHandler(
protocol: Protocol,
private val coroutineScope: CoroutineScope,
) : ProtocolHandler(protocol) {
protocol: Protocol,
serverConfig: ServerConfig,
private val coroutineScope: CoroutineScope,
) : ProtocolHandler(protocol, serverConfig) {
override fun onActive(ctx: ChannelHandlerContext) {
log.info { "Client ${ctx.channel().remoteAddress()} connected to game server." }
@@ -35,6 +39,12 @@ class GameProtocolHandler(
log.debug {
"This is what the Game knows about you:\n${event.packet.clientInfo.values.joinToString("\n")}"
}
// TODO handle player joining the game
// TODO handle player joining the game e.g. authentication
event.accept()
.withPlaytime(1337)
.withRewardPoints(420)
.withBalance(187)
.buildAndRespond(event)
}
}
@@ -0,0 +1,16 @@
package de.fiereu.openmmo.server.game.protocol.game.ext
import de.fiereu.openmmo.protocols.game.packets.JoinGamePacket
import de.fiereu.openmmo.protocols.game.packets.builders.JoinResponsePacketBuilder
import de.fiereu.openmmo.server.protocol.PacketEvent
import de.fiereu.openmmo.server.protocol.respond
fun PacketEvent<JoinGamePacket>.reject() {
this.respond(JoinResponsePacketBuilder.reject())
}
fun PacketEvent<JoinGamePacket>.accept() = JoinResponsePacketBuilder.accept()
fun JoinResponsePacketBuilder.buildAndRespond(event: PacketEvent<JoinGamePacket>) {
event.respond(this.build())
}
@@ -23,7 +23,7 @@ fun main() {
.withPublicKey(KeyLoader.loadPemECPublicKey(resource("game.public.pem")))
.withPrivateKey(KeyLoader.loadPemECPrivateKey(resource("game.private.pem")))
.withChannelHandlerProvider {
LoginProtocolHandler(LoginServerProtocol(), coroutineScope)
LoginProtocolHandler(LoginServerProtocol(), serverConfig, coroutineScope)
}
.build()
server.start()
@@ -10,6 +10,7 @@ import de.fiereu.openmmo.protocols.tls.packets.GameServerNode
import de.fiereu.openmmo.protocols.tls.packets.JoinGameServerPacket
import de.fiereu.openmmo.protocols.tls.packets.LoginRequestPacket
import de.fiereu.openmmo.protocols.tls.packets.RequestGameServerListPacket
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.login.protocol.login.ext.respondForAuthedUser
import de.fiereu.openmmo.server.login.protocol.login.ext.respondTo
import de.fiereu.openmmo.server.login.protocol.login.ext.respondWithServers
@@ -25,8 +26,9 @@ private val log = KotlinLogging.logger {}
class LoginProtocolHandler(
protocol: Protocol,
serverConfig: ServerConfig,
private val coroutineScope: CoroutineScope,
) : ProtocolHandler(protocol) {
) : ProtocolHandler(protocol, serverConfig) {
override fun onActive(ctx: ChannelHandlerContext) {
log.info { "Client ${ctx.channel().remoteAddress()} swapped to login protocol." }
@@ -0,0 +1,55 @@
package de.fiereu.openmmo.server.netty
import de.fiereu.openmmo.server.config.ServerConfig
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToMessageEncoder
import java.util.zip.Deflater
class Compressor(
serverConfig: ServerConfig,
) {
private val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true)
/**
* At which packet size we need to compress the packet.
*/
private val threshold: Int = (serverConfig.sendBufferSize * 0.9).toInt()
fun compress(
msg: ByteBuf
) : ByteBuf {
val dataLength = msg.readableBytes()
if (dataLength < threshold) {
val outputBuffer = Unpooled
.buffer(dataLength + 1)
.writeBoolean(false)
.writeBytes(msg)
return outputBuffer
}
// Maybe use pre-allocated buffer?
val inputBuffer = Unpooled.copiedBuffer(msg)
.writeShortLE(0xFFFF)
deflater.setInput(
inputBuffer.array(),
inputBuffer.arrayOffset() + inputBuffer.readerIndex(),
inputBuffer.readableBytes()
)
val outputBuffer = Unpooled
.buffer(dataLength + 1)
.writeBoolean(true)
val buffer = ByteArray(Short.MAX_VALUE.toInt())
do {
val read = deflater.deflate(buffer)
if (read == 0) break
outputBuffer.writeBytes(buffer, 0, read)
} while (true)
return outputBuffer
}
}
@@ -52,7 +52,7 @@ class DefaultChannelHandlerProvider(
pipeline.addLast("tls-encryption", TlsEncryptionHandler(tlsContext))
pipeline.addLast("protocol-logger", LoggingHandler("protocol-logger", LogLevel.TRACE))
pipeline.addLast("protocol", TlsProtocolHandler(tlsProtocol, tlsConfig, this))
pipeline.addLast("protocol", TlsProtocolHandler(tlsProtocol, serverConfig, tlsConfig, this))
}
/**
@@ -3,9 +3,12 @@ package de.fiereu.openmmo.server.netty.handlers
import de.fiereu.openmmo.protocols.PacketDirection
import de.fiereu.openmmo.protocols.Protocol
import de.fiereu.openmmo.protocols.getDeserializer
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.netty.Compressor
import de.fiereu.openmmo.server.protocol.PacketEvent
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelDuplexHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPromise
@@ -13,9 +16,12 @@ import io.netty.channel.ChannelPromise
private val log = KotlinLogging.logger {}
abstract class ProtocolHandler(
private val protocol: Protocol
val protocol: Protocol,
serverConfig: ServerConfig
) : ChannelDuplexHandler() {
private val compressor = Compressor(serverConfig)
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
if (msg !is ByteBuf) {
log.warn { "Received non-ByteBuf message: ${msg::class.simpleName}" }
@@ -38,11 +44,11 @@ abstract class ProtocolHandler(
val packetData = deserializer.deserialize(msg)
/*
We cant call the onPacketReceived function asynchronously directly here,
because the TLS protocol expects a synchronous flow. Meaning that the client already sends the next packet
after the ClientReady packet, so if we would process the ClientReady packet asynchronously,
the next packet would be processed before the ClientReady packet is fully processed.
-> It would be processed by the TLS protocol before and not by the next protocol (e.g. login protocol).
* We cant call the onPacketReceived function asynchronously directly here,
* because the TLS protocol expects a synchronous flow. Meaning that the client already sends the next packet
* after the ClientReady packet, so if we would process the ClientReady packet asynchronously,
* the next packet would be processed before the ClientReady packet is fully processed.
* -> It would be processed by the TLS protocol before and not by the next protocol (e.g. login protocol).
*/
onPacketReceived(PacketEvent(ctx, packetData))
} catch (e: Exception) {
@@ -71,7 +77,20 @@ abstract class ProtocolHandler(
val buffer = ctx.alloc().buffer()
buffer.writeByte(opcode.value.toInt())
serializer.serializeObject(msg, buffer)
/*
* If the protocol requires compression (e.g. Game protocol),
* we need to compress the serialized packet before adding the opcode.
*/
if (!protocol.compressed) {
serializer.serializeObject(msg, buffer)
} else {
val uncompressedBuffer = Unpooled.buffer()
serializer.serializeObject(msg, uncompressedBuffer)
buffer.writeBytes(
compressor.compress(uncompressedBuffer)
)
}
ctx.write(buffer, promise)
} catch (e: Exception) {
@@ -4,6 +4,7 @@ import de.fiereu.openmmo.protocols.Protocol
import de.fiereu.openmmo.protocols.tls.packets.ClientHelloPacket
import de.fiereu.openmmo.protocols.tls.packets.ClientReadyPacket
import de.fiereu.openmmo.protocols.tls.packets.ServerHelloPacket
import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.config.TlsConfig
import de.fiereu.openmmo.server.netty.DefaultChannelHandlerProvider
import de.fiereu.openmmo.server.netty.handlers.ProtocolHandler
@@ -23,9 +24,10 @@ private val log = KotlinLogging.logger {}
class TlsProtocolHandler(
protocol: Protocol,
serverConfig: ServerConfig,
private val tlsConfig: TlsConfig,
private val channelHandlerProvider: DefaultChannelHandlerProvider
) : ProtocolHandler(protocol) {
) : ProtocolHandler(protocol, serverConfig) {
private val packetBuffer: MutableList<ByteBuf> = mutableListOf()
private val connectionKeyPair: Pair<ECPublicKey, ECPrivateKey>