diff --git a/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/GameProtocol.kt b/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/GameProtocol.kt index 49caea0..427b5fa 100644 --- a/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/GameProtocol.kt +++ b/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/GameProtocol.kt @@ -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()) } } diff --git a/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/packets/JoinResponsePacket.kt b/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/packets/JoinResponsePacket.kt new file mode 100644 index 0000000..7a8277e --- /dev/null +++ b/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/packets/JoinResponsePacket.kt @@ -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 { + 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 { + 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) + ) + } +} \ No newline at end of file diff --git a/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/packets/builders/JoinResponsePacketBuilder.kt b/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/packets/builders/JoinResponsePacketBuilder.kt new file mode 100644 index 0000000..b86110c --- /dev/null +++ b/protocol.game/src/main/kotlin/de/fiereu/openmmo/protocols/game/packets/builders/JoinResponsePacketBuilder.kt @@ -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 + ) + ) + } +} \ No newline at end of file diff --git a/protocol.login/src/main/kotlin/de/fiereu/openmmo/protocols/tls/LoginProtocol.kt b/protocol.login/src/main/kotlin/de/fiereu/openmmo/protocols/tls/LoginProtocol.kt index 57fcab3..2c4556b 100644 --- a/protocol.login/src/main/kotlin/de/fiereu/openmmo/protocols/tls/LoginProtocol.kt +++ b/protocol.login/src/main/kotlin/de/fiereu/openmmo/protocols/tls/LoginProtocol.kt @@ -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() { diff --git a/protocol.tls/src/main/kotlin/de/fiereu/openmmo/protocols/tls/TlsProtocol.kt b/protocol.tls/src/main/kotlin/de/fiereu/openmmo/protocols/tls/TlsProtocol.kt index 55db2e1..70d2112 100644 --- a/protocol.tls/src/main/kotlin/de/fiereu/openmmo/protocols/tls/TlsProtocol.kt +++ b/protocol.tls/src/main/kotlin/de/fiereu/openmmo/protocols/tls/TlsProtocol.kt @@ -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) : TlsProtocol() { diff --git a/protocol/src/main/kotlin/de/fiereu/openmmo/protocols/Protocol.kt b/protocol/src/main/kotlin/de/fiereu/openmmo/protocols/Protocol.kt index 730092f..78301ac 100644 --- a/protocol/src/main/kotlin/de/fiereu/openmmo/protocols/Protocol.kt +++ b/protocol/src/main/kotlin/de/fiereu/openmmo/protocols/Protocol.kt @@ -48,6 +48,7 @@ abstract class Protocol { private val dataClassToOpcode: MutableMap, Opcode> = mutableMapOf() abstract val async: Boolean + abstract val compressed: Boolean fun getOpcode(dataClass: KClass<*>): Opcode? = dataClassToOpcode[dataClass] diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/GameServer.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/GameServer.kt index 35f77e8..29f4692 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/GameServer.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/GameServer.kt @@ -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() } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/protocol/game/GameProtocolHandler.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/protocol/game/GameProtocolHandler.kt index 9f30cec..cca1f03 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/protocol/game/GameProtocolHandler.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/protocol/game/GameProtocolHandler.kt @@ -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) } } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/protocol/game/ext/JoinGameResponsePacketExtension.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/protocol/game/ext/JoinGameResponsePacketExtension.kt new file mode 100644 index 0000000..3fa2ea1 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/protocol/game/ext/JoinGameResponsePacketExtension.kt @@ -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.reject() { + this.respond(JoinResponsePacketBuilder.reject()) +} + +fun PacketEvent.accept() = JoinResponsePacketBuilder.accept() + +fun JoinResponsePacketBuilder.buildAndRespond(event: PacketEvent) { + event.respond(this.build()) +} \ No newline at end of file diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/LoginServer.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/LoginServer.kt index 6f7fc1e..6da0866 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/LoginServer.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/LoginServer.kt @@ -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() diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/LoginProtocolHandler.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/LoginProtocolHandler.kt index c51593b..324df45 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/LoginProtocolHandler.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/LoginProtocolHandler.kt @@ -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." } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/ext/JoinGameServerPacket.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/ext/JoinGameServerPacketExtension.kt similarity index 100% rename from server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/ext/JoinGameServerPacket.kt rename to server.login/src/main/kotlin/de/fiereu/openmmo/server/login/protocol/login/ext/JoinGameServerPacketExtension.kt diff --git a/server/src/main/kotlin/de/fiereu/openmmo/server/netty/Compressor.kt b/server/src/main/kotlin/de/fiereu/openmmo/server/netty/Compressor.kt new file mode 100644 index 0000000..4b74315 --- /dev/null +++ b/server/src/main/kotlin/de/fiereu/openmmo/server/netty/Compressor.kt @@ -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 + } +} \ No newline at end of file diff --git a/server/src/main/kotlin/de/fiereu/openmmo/server/netty/DefaultChannelHandlerProvider.kt b/server/src/main/kotlin/de/fiereu/openmmo/server/netty/DefaultChannelHandlerProvider.kt index 4fecaa8..fd8d56d 100644 --- a/server/src/main/kotlin/de/fiereu/openmmo/server/netty/DefaultChannelHandlerProvider.kt +++ b/server/src/main/kotlin/de/fiereu/openmmo/server/netty/DefaultChannelHandlerProvider.kt @@ -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)) } /** diff --git a/server/src/main/kotlin/de/fiereu/openmmo/server/netty/handlers/ProtocolHandler.kt b/server/src/main/kotlin/de/fiereu/openmmo/server/netty/handlers/ProtocolHandler.kt index ddd2148..8282fb3 100644 --- a/server/src/main/kotlin/de/fiereu/openmmo/server/netty/handlers/ProtocolHandler.kt +++ b/server/src/main/kotlin/de/fiereu/openmmo/server/netty/handlers/ProtocolHandler.kt @@ -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) { diff --git a/server/src/main/kotlin/de/fiereu/openmmo/server/protocol/tls/TlsProtocolHandler.kt b/server/src/main/kotlin/de/fiereu/openmmo/server/protocol/tls/TlsProtocolHandler.kt index d25913c..1861e5d 100644 --- a/server/src/main/kotlin/de/fiereu/openmmo/server/protocol/tls/TlsProtocolHandler.kt +++ b/server/src/main/kotlin/de/fiereu/openmmo/server/protocol/tls/TlsProtocolHandler.kt @@ -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 = mutableListOf() private val connectionKeyPair: Pair