Merge pull request #1 from openmmo-org/refactor/bytecodec-migration

refactor: migrate network module to bytecodec
This commit is contained in:
Fiereu authored and GitHub committed 2026-05-30 12:35:54 +02:00
commit fc3645592f
350 files changed
+8687 -62678

No files matched your search

View File
Whitespace-only changes.
+1
View File
@@ -9,5 +9,6 @@ kotlin {
dependencies { dependencies {
implementation(libs.kotlinGradlePlugin) implementation(libs.kotlinGradlePlugin)
implementation(libs.spotlessGradlePlugin) implementation(libs.spotlessGradlePlugin)
implementation(libs.sonarlintGradlePlugin)
implementation(libs.junit5) implementation(libs.junit5)
} }
+1
View File
@@ -2,6 +2,7 @@ dependencyResolutionManagement {
@Suppress("UnstableApiUsage") @Suppress("UnstableApiUsage")
repositories { repositories {
mavenCentral() mavenCentral()
gradlePluginPortal()
} }
versionCatalogs { versionCatalogs {
+6
View File
@@ -61,3 +61,9 @@ tasks.register("copyKeys") {
description = "Copies all keys from \":keys\" to the current projects resources directory" description = "Copies all keys from \":keys\" to the current projects resources directory"
dependsOn("copyKeysChat", "copyKeysGame") dependsOn("copyKeysChat", "copyKeysGame")
} }
val keyCopyTasks =
listOf("copyPublicKeyChat", "copyPrivateKeyChat", "copyPublicKeyGame", "copyPrivateKeyGame")
tasks.matching { it.name.startsWith("spotless") || it.name.startsWith("sonarlint") }
.configureEach { mustRunAfter(keyCopyTasks) }
@@ -0,0 +1,11 @@
package buildsrc.convention
plugins { id("name.remal.sonarlint") }
sonarLint {
languages { include("kotlin", "java") }
rules {
disable("kotlin:S1186")
disable("kotlin:S3776")
}
}
+2 -2
View File
@@ -11,13 +11,13 @@ spotless {
lineEndings = LineEnding.UNIX lineEndings = LineEnding.UNIX
kotlinGradle { kotlinGradle {
target("**/*.gradle.kts") target("**/*.gradle.kts")
ktfmt() ktfmt("0.54")
trimTrailingWhitespace() trimTrailingWhitespace()
endWithNewline() endWithNewline()
} }
kotlin { kotlin {
target("**/src/**/*.kt") target("**/src/**/*.kt")
ktfmt() ktfmt("0.54")
trimTrailingWhitespace() trimTrailingWhitespace()
endWithNewline() endWithNewline()
} }
+7
View File
@@ -0,0 +1,7 @@
plugins {
id("buildsrc.convention.kotlin-jvm")
id("buildsrc.convention.spotless")
id("buildsrc.convention.sonarlint")
}
dependencies { testImplementation(libs.bundles.kotest) }
@@ -0,0 +1,328 @@
package de.fiereu.bytecodec
object Bool : Codec<Boolean> {
override fun read(buf: ReadBuffer): Boolean = buf.readByte() != 0.toByte()
override fun write(buf: WriteBuffer, value: Boolean) {
buf.writeByte(if (value) 1 else 0)
}
}
object S8 : Codec<Byte> {
override fun read(buf: ReadBuffer): Byte = buf.readByte()
override fun write(buf: WriteBuffer, value: Byte) {
buf.writeByte(value)
}
}
object U8 : Codec<Int> {
override fun read(buf: ReadBuffer): Int = buf.readByte().toInt() and 0xFF
override fun write(buf: WriteBuffer, value: Int) {
require(value in 0..0xFF) { "U8 out of range: $value" }
buf.writeByte(value.toByte())
}
}
object S16LE : Codec<Short> {
override fun read(buf: ReadBuffer): Short {
val b0 = buf.readByte().toInt() and 0xFF
val b1 = buf.readByte().toInt() and 0xFF
return ((b1 shl 8) or b0).toShort()
}
override fun write(buf: WriteBuffer, value: Short) {
val v = value.toInt()
buf.writeByte((v and 0xFF).toByte())
buf.writeByte(((v ushr 8) and 0xFF).toByte())
}
}
object S16BE : Codec<Short> {
override fun read(buf: ReadBuffer): Short {
val b0 = buf.readByte().toInt() and 0xFF
val b1 = buf.readByte().toInt() and 0xFF
return ((b0 shl 8) or b1).toShort()
}
override fun write(buf: WriteBuffer, value: Short) {
val v = value.toInt()
buf.writeByte(((v ushr 8) and 0xFF).toByte())
buf.writeByte((v and 0xFF).toByte())
}
}
object U16LE : Codec<Int> {
override fun read(buf: ReadBuffer): Int {
val b0 = buf.readByte().toInt() and 0xFF
val b1 = buf.readByte().toInt() and 0xFF
return (b1 shl 8) or b0
}
override fun write(buf: WriteBuffer, value: Int) {
require(value in 0..0xFFFF) { "U16 out of range: $value" }
buf.writeByte((value and 0xFF).toByte())
buf.writeByte(((value ushr 8) and 0xFF).toByte())
}
}
object U16BE : Codec<Int> {
override fun read(buf: ReadBuffer): Int {
val b0 = buf.readByte().toInt() and 0xFF
val b1 = buf.readByte().toInt() and 0xFF
return (b0 shl 8) or b1
}
override fun write(buf: WriteBuffer, value: Int) {
require(value in 0..0xFFFF) { "U16 out of range: $value" }
buf.writeByte(((value ushr 8) and 0xFF).toByte())
buf.writeByte((value and 0xFF).toByte())
}
}
object S32LE : Codec<Int> {
override fun read(buf: ReadBuffer): Int {
val b0 = buf.readByte().toInt() and 0xFF
val b1 = buf.readByte().toInt() and 0xFF
val b2 = buf.readByte().toInt() and 0xFF
val b3 = buf.readByte().toInt() and 0xFF
return (b3 shl 24) or (b2 shl 16) or (b1 shl 8) or b0
}
override fun write(buf: WriteBuffer, value: Int) {
buf.writeByte((value and 0xFF).toByte())
buf.writeByte(((value ushr 8) and 0xFF).toByte())
buf.writeByte(((value ushr 16) and 0xFF).toByte())
buf.writeByte(((value ushr 24) and 0xFF).toByte())
}
}
object S32BE : Codec<Int> {
override fun read(buf: ReadBuffer): Int {
val b0 = buf.readByte().toInt() and 0xFF
val b1 = buf.readByte().toInt() and 0xFF
val b2 = buf.readByte().toInt() and 0xFF
val b3 = buf.readByte().toInt() and 0xFF
return (b0 shl 24) or (b1 shl 16) or (b2 shl 8) or b3
}
override fun write(buf: WriteBuffer, value: Int) {
buf.writeByte(((value ushr 24) and 0xFF).toByte())
buf.writeByte(((value ushr 16) and 0xFF).toByte())
buf.writeByte(((value ushr 8) and 0xFF).toByte())
buf.writeByte((value and 0xFF).toByte())
}
}
object U32LE : Codec<Long> {
override fun read(buf: ReadBuffer): Long {
val b0 = buf.readByte().toLong() and 0xFF
val b1 = buf.readByte().toLong() and 0xFF
val b2 = buf.readByte().toLong() and 0xFF
val b3 = buf.readByte().toLong() and 0xFF
return (b3 shl 24) or (b2 shl 16) or (b1 shl 8) or b0
}
override fun write(buf: WriteBuffer, value: Long) {
require(value in 0L..0xFFFFFFFFL) { "U32 out of range: $value" }
buf.writeByte((value and 0xFF).toByte())
buf.writeByte(((value ushr 8) and 0xFF).toByte())
buf.writeByte(((value ushr 16) and 0xFF).toByte())
buf.writeByte(((value ushr 24) and 0xFF).toByte())
}
}
object U32BE : Codec<Long> {
override fun read(buf: ReadBuffer): Long {
val b0 = buf.readByte().toLong() and 0xFF
val b1 = buf.readByte().toLong() and 0xFF
val b2 = buf.readByte().toLong() and 0xFF
val b3 = buf.readByte().toLong() and 0xFF
return (b0 shl 24) or (b1 shl 16) or (b2 shl 8) or b3
}
override fun write(buf: WriteBuffer, value: Long) {
require(value in 0L..0xFFFFFFFFL) { "U32 out of range: $value" }
buf.writeByte(((value ushr 24) and 0xFF).toByte())
buf.writeByte(((value ushr 16) and 0xFF).toByte())
buf.writeByte(((value ushr 8) and 0xFF).toByte())
buf.writeByte((value and 0xFF).toByte())
}
}
object S64LE : Codec<Long> {
override fun read(buf: ReadBuffer): Long {
var result = 0L
var shift = 0
repeat(8) {
result = result or ((buf.readByte().toLong() and 0xFF) shl shift)
shift += 8
}
return result
}
override fun write(buf: WriteBuffer, value: Long) {
var v = value
repeat(8) {
buf.writeByte((v and 0xFF).toByte())
v = v ushr 8
}
}
}
object S64BE : Codec<Long> {
override fun read(buf: ReadBuffer): Long {
var result = 0L
repeat(8) { result = (result shl 8) or (buf.readByte().toLong() and 0xFF) }
return result
}
override fun write(buf: WriteBuffer, value: Long) {
var shift = 56
repeat(8) {
buf.writeByte(((value ushr shift) and 0xFF).toByte())
shift -= 8
}
}
}
object F32LE : Codec<Float> {
override fun read(buf: ReadBuffer): Float = Float.fromBits(S32LE.read(buf))
override fun write(buf: WriteBuffer, value: Float) {
S32LE.write(buf, value.toRawBits())
}
}
object F32BE : Codec<Float> {
override fun read(buf: ReadBuffer): Float = Float.fromBits(S32BE.read(buf))
override fun write(buf: WriteBuffer, value: Float) {
S32BE.write(buf, value.toRawBits())
}
}
object F64LE : Codec<Double> {
override fun read(buf: ReadBuffer): Double = Double.fromBits(S64LE.read(buf))
override fun write(buf: WriteBuffer, value: Double) {
S64LE.write(buf, value.toRawBits())
}
}
object F64BE : Codec<Double> {
override fun read(buf: ReadBuffer): Double = Double.fromBits(S64BE.read(buf))
override fun write(buf: WriteBuffer, value: Double) {
S64BE.write(buf, value.toRawBits())
}
}
fun fixedBytes(n: Int): Codec<ByteArray> {
require(n >= 0) { "fixedBytes negative size: $n" }
return object : Codec<ByteArray> {
override fun read(buf: ReadBuffer): ByteArray {
val arr = ByteArray(n)
if (n > 0) buf.readBytes(arr)
return arr
}
override fun write(buf: WriteBuffer, value: ByteArray) {
if (value.size != n) {
throw MalformedPacketException("fixedBytes($n) got ${value.size}")
}
if (n > 0) buf.writeBytes(value)
}
}
}
fun unknownBytes(n: Int): Codec<ByteArray> = fixedBytes(n)
fun reserved(byte: Int, strict: Boolean = false): Codec<Unit> {
val literal = (byte and 0xFF).toByte()
return object : Codec<Unit> {
override fun read(buf: ReadBuffer) {
val read = buf.readByte()
if (strict && read != literal) {
throw ReservedByteMismatchException(byte and 0xFF, read.toInt() and 0xFF)
}
}
override fun write(buf: WriteBuffer, value: Unit) {
buf.writeByte(literal)
}
}
}
fun padding(n: Int, fill: Byte = 0): Codec<Unit> {
require(n >= 0) { "padding negative size: $n" }
return object : Codec<Unit> {
override fun read(buf: ReadBuffer) {
if (n > 0) buf.skip(n)
}
override fun write(buf: WriteBuffer, value: Unit) {
repeat(n) { buf.writeByte(fill) }
}
}
}
fun skip(n: Int): Codec<Unit> = padding(n)
object Utf16LeNullTerminated : Codec<String> {
override fun read(buf: ReadBuffer): String {
val out = java.io.ByteArrayOutputStream()
while (true) {
val lo = buf.readByte()
val hi = buf.readByte()
if (lo == 0.toByte() && hi == 0.toByte()) break
out.write(lo.toInt() and 0xFF)
out.write(hi.toInt() and 0xFF)
}
return String(out.toByteArray(), Charsets.UTF_16LE)
}
override fun write(buf: WriteBuffer, value: String) {
buf.writeBytes(value.toByteArray(Charsets.UTF_16LE))
buf.writeByte(0)
buf.writeByte(0)
}
}
object Utf16BeNullTerminated : Codec<String> {
override fun read(buf: ReadBuffer): String {
val out = java.io.ByteArrayOutputStream()
while (true) {
val hi = buf.readByte()
val lo = buf.readByte()
if (hi == 0.toByte() && lo == 0.toByte()) break
out.write(hi.toInt() and 0xFF)
out.write(lo.toInt() and 0xFF)
}
return String(out.toByteArray(), Charsets.UTF_16BE)
}
override fun write(buf: WriteBuffer, value: String) {
buf.writeBytes(value.toByteArray(Charsets.UTF_16BE))
buf.writeByte(0)
buf.writeByte(0)
}
}
object AsciiNullTerminated : Codec<String> {
override fun read(buf: ReadBuffer): String {
val out = java.io.ByteArrayOutputStream()
while (true) {
val b = buf.readByte()
if (b == 0.toByte()) break
out.write(b.toInt() and 0xFF)
}
return String(out.toByteArray(), Charsets.US_ASCII)
}
override fun write(buf: WriteBuffer, value: String) {
buf.writeBytes(value.toByteArray(Charsets.US_ASCII))
buf.writeByte(0)
}
}
@@ -0,0 +1,19 @@
package de.fiereu.bytecodec
interface ReadBuffer {
fun readByte(): Byte
fun readBytes(dst: ByteArray, offset: Int = 0, length: Int = dst.size - offset)
fun skip(n: Int)
fun remaining(): Int
}
interface WriteBuffer {
fun writeByte(value: Byte)
fun writeBytes(src: ByteArray, offset: Int = 0, length: Int = src.size - offset)
}
interface Buffer : ReadBuffer, WriteBuffer
@@ -0,0 +1,88 @@
package de.fiereu.bytecodec
import java.nio.ByteBuffer
class ByteArrayReadBuffer(
private val array: ByteArray,
private val offset: Int = 0,
private val length: Int = array.size - offset,
) : ReadBuffer {
init {
require(offset >= 0) { "offset < 0" }
require(length >= 0) { "length < 0" }
require(offset + length <= array.size) { "offset + length > array.size" }
}
private var pos = 0
override fun readByte(): Byte {
if (pos >= length) throw IndexOutOfBoundsException("read past end")
return array[offset + pos++]
}
override fun readBytes(dst: ByteArray, offset: Int, length: Int) {
if (this.pos + length > this.length) throw IndexOutOfBoundsException("read past end")
System.arraycopy(array, this.offset + pos, dst, offset, length)
pos += length
}
override fun skip(n: Int) {
if (n < 0) throw IndexOutOfBoundsException("negative skip")
if (pos + n > length) throw IndexOutOfBoundsException("skip past end")
pos += n
}
override fun remaining(): Int = length - pos
}
class GrowableWriteBuffer(initialCapacity: Int = 256) : WriteBuffer {
private var buf: ByteArray = ByteArray(initialCapacity.coerceAtLeast(16))
private var pos: Int = 0
fun size(): Int = pos
fun toByteArray(): ByteArray = buf.copyOf(pos)
private fun ensure(extra: Int) {
val needed = pos + extra
if (needed <= buf.size) return
var newSize = buf.size
while (newSize < needed) newSize *= 2
buf = buf.copyOf(newSize)
}
override fun writeByte(value: Byte) {
ensure(1)
buf[pos++] = value
}
override fun writeBytes(src: ByteArray, offset: Int, length: Int) {
ensure(length)
System.arraycopy(src, offset, buf, pos, length)
pos += length
}
}
class NioReadBuffer(private val nio: ByteBuffer) : ReadBuffer {
override fun readByte(): Byte = nio.get()
override fun readBytes(dst: ByteArray, offset: Int, length: Int) {
nio[dst, offset, length]
}
override fun skip(n: Int) {
nio.position(nio.position() + n)
}
override fun remaining(): Int = nio.remaining()
}
class NioWriteBuffer(private val nio: ByteBuffer) : WriteBuffer {
override fun writeByte(value: Byte) {
nio.put(value)
}
override fun writeBytes(src: ByteArray, offset: Int, length: Int) {
nio.put(src, offset, length)
}
}
@@ -0,0 +1,7 @@
package de.fiereu.bytecodec
interface Codec<T> {
fun read(buf: ReadBuffer): T
fun write(buf: WriteBuffer, value: T)
}
@@ -0,0 +1,264 @@
package de.fiereu.bytecodec
import java.nio.charset.Charset
fun <T, R> Codec<T>.imap(decode: (T) -> R, encode: (R) -> T): Codec<R> {
val inner = this
return object : Codec<R> {
override fun read(buf: ReadBuffer): R = decode(inner.read(buf))
override fun write(buf: WriteBuffer, value: R) {
inner.write(buf, encode(value))
}
}
}
fun <T, R> Codec<T>.imapCatching(
decode: (T) -> R,
encode: (R) -> T,
onError: (T, Throwable) -> String = { v, _ -> "Cannot decode $v" },
): Codec<R> {
val inner = this
return object : Codec<R> {
override fun read(buf: ReadBuffer): R {
val raw = inner.read(buf)
return try {
decode(raw)
} catch (e: CodecException) {
throw e
} catch (e: Throwable) {
throw MalformedPacketException(onError(raw, e), e)
}
}
override fun write(buf: WriteBuffer, value: R) {
inner.write(buf, encode(value))
}
}
}
fun <T> Codec<T>.listPrefixed(prefix: Codec<Int>): Codec<List<T>> {
val inner = this
return object : Codec<List<T>> {
override fun read(buf: ReadBuffer): List<T> {
val n = prefix.read(buf)
if (n < 0) throw MalformedPacketException("negative list length: $n")
val list = ArrayList<T>(n.coerceAtMost(1024))
repeat(n) { list.add(inner.read(buf)) }
return list
}
override fun write(buf: WriteBuffer, value: List<T>) {
prefix.write(buf, value.size)
for (item in value) inner.write(buf, item)
}
}
}
fun <T> Codec<T>.repeat(count: Int): Codec<List<T>> {
require(count >= 0) { "repeat negative count: $count" }
val inner = this
return object : Codec<List<T>> {
override fun read(buf: ReadBuffer): List<T> = List(count) { inner.read(buf) }
override fun write(buf: WriteBuffer, value: List<T>) {
if (value.size != count) {
throw MalformedPacketException("repeat($count) got ${value.size}")
}
for (item in value) inner.write(buf, item)
}
}
}
fun bytesPrefixed(prefix: Codec<Int>): Codec<ByteArray> =
object : Codec<ByteArray> {
override fun read(buf: ReadBuffer): ByteArray {
val n = prefix.read(buf)
if (n < 0) throw MalformedPacketException("negative byte length: $n")
val arr = ByteArray(n)
if (n > 0) buf.readBytes(arr)
return arr
}
override fun write(buf: WriteBuffer, value: ByteArray) {
prefix.write(buf, value.size)
if (value.isNotEmpty()) buf.writeBytes(value)
}
}
fun stringPrefixed(prefix: Codec<Int>, charset: Charset): Codec<String> =
object : Codec<String> {
override fun read(buf: ReadBuffer): String {
val n = prefix.read(buf)
if (n < 0) throw MalformedPacketException("negative string length: $n")
val arr = ByteArray(n)
if (n > 0) buf.readBytes(arr)
return String(arr, charset)
}
override fun write(buf: WriteBuffer, value: String) {
val arr = value.toByteArray(charset)
prefix.write(buf, arr.size)
if (arr.isNotEmpty()) buf.writeBytes(arr)
}
}
inline fun <reified E : Enum<E>> enumByOrdinalByte(): Codec<E> {
val values = enumValues<E>()
val name = E::class.simpleName ?: "enum"
return U8.imapCatching(
decode = { ord ->
if (ord !in values.indices) {
throw MalformedPacketException("ordinal $ord out of range for $name")
}
values[ord]
},
encode = { it.ordinal },
)
}
inline fun <reified E : Enum<E>> enumByOrdinalU16LE(): Codec<E> {
val values = enumValues<E>()
val name = E::class.simpleName ?: "enum"
return U16LE.imapCatching(
decode = { ord ->
if (ord !in values.indices) {
throw MalformedPacketException("ordinal $ord out of range for $name")
}
values[ord]
},
encode = { it.ordinal },
)
}
fun <E : Enum<E>> enumBy(
prefix: Codec<Int>,
lookup: (Int) -> E,
keyOf: (E) -> Int,
): Codec<E> =
object : Codec<E> {
override fun read(buf: ReadBuffer): E {
val key = prefix.read(buf)
return try {
lookup(key)
} catch (e: CodecException) {
throw e
} catch (e: Throwable) {
throw MalformedPacketException("no enum value for key $key", e)
}
}
override fun write(buf: WriteBuffer, value: E) {
prefix.write(buf, keyOf(value))
}
}
fun <T : Any> choose(
tag: Codec<Int>,
identify: (T) -> Int,
vararg branches: Pair<Int, Codec<out T>>,
): Codec<T> {
val byTag: Map<Int, Codec<out T>> = branches.toMap()
require(byTag.size == branches.size) { "duplicate branch tags in choose" }
return object : Codec<T> {
override fun read(buf: ReadBuffer): T {
val t = tag.read(buf)
val branch = byTag[t] ?: throw UnknownTagException(t)
return branch.read(buf)
}
override fun write(buf: WriteBuffer, value: T) {
val t = identify(value)
val branch =
byTag[t]
?: throw MalformedPacketException("identify returned unknown tag 0x${t.toString(16)}")
tag.write(buf, t)
@Suppress("UNCHECKED_CAST") (branch as Codec<T>).write(buf, value)
}
}
}
fun <T : Any> Codec<T>.optional(flag: Codec<Boolean> = Bool): Codec<T?> {
val inner = this
return object : Codec<T?> {
override fun read(buf: ReadBuffer): T? {
val present = flag.read(buf)
return if (present) inner.read(buf) else null
}
override fun write(buf: WriteBuffer, value: T?) {
flag.write(buf, value != null)
if (value != null) inner.write(buf, value)
}
}
}
fun <A, B> Codec<A>.then(other: Codec<B>): Codec<Pair<A, B>> {
val first = this
return object : Codec<Pair<A, B>> {
override fun read(buf: ReadBuffer): Pair<A, B> = first.read(buf) to other.read(buf)
override fun write(buf: WriteBuffer, value: Pair<A, B>) {
first.write(buf, value.first)
other.write(buf, value.second)
}
}
}
fun interface BitsBuilder {
fun bit(index: Int, name: String)
}
class BitSet32
internal constructor(
internal val raw: Int,
internal val byName: Map<String, Int>,
) {
operator fun get(index: Int): Boolean {
require(index in 0..31) { "bit index out of range: $index" }
return (raw ushr index) and 1 != 0
}
operator fun get(name: String): Boolean {
val i = byName[name] ?: error("unknown bit name: $name")
return get(i)
}
fun toRaw(): Int = raw
override fun equals(other: Any?): Boolean = other is BitSet32 && other.raw == raw
override fun hashCode(): Int = raw
}
class BitsCodec
internal constructor(
private val backing: Codec<Int>,
private val byName: Map<String, Int>,
) : Codec<BitSet32> {
override fun read(buf: ReadBuffer): BitSet32 = BitSet32(backing.read(buf), byName)
override fun write(buf: WriteBuffer, value: BitSet32) {
backing.write(buf, value.raw)
}
fun of(vararg bits: Pair<String, Boolean>): BitSet32 {
var raw = 0
for ((name, set) in bits) {
val i = byName[name] ?: error("unknown bit name: $name")
if (set) raw = raw or (1 shl i)
}
return BitSet32(raw, byName)
}
}
fun bitsLE(backing: Codec<Int>, builder: BitsBuilder.() -> Unit): BitsCodec {
val map = LinkedHashMap<String, Int>()
val b = BitsBuilder { index, name ->
require(index in 0..31) { "bit index out of range: $index" }
require(name !in map) { "duplicate bit name: $name" }
map[name] = index
}
b.builder()
return BitsCodec(backing, map)
}
@@ -0,0 +1,14 @@
package de.fiereu.bytecodec
open class CodecException(message: String, cause: Throwable? = null) :
RuntimeException(message, cause)
class MalformedPacketException(message: String, cause: Throwable? = null) :
CodecException(message, cause)
class UnknownTagException(val tag: Int) : CodecException("No branch for tag 0x${tag.toString(16)}")
class ReservedByteMismatchException(val expected: Int, val actual: Int) :
CodecException(
"Expected reserved 0x${expected.toString(16)}, got 0x${actual.toString(16)}",
)
@@ -0,0 +1,56 @@
package de.fiereu.bytecodec
interface CodecScope<P> {
fun <T> field(codec: Codec<T>, get: (P) -> T): T
fun structural(codec: Codec<Unit>)
}
internal class ReadingScope<P>(private val buf: ReadBuffer) : CodecScope<P> {
override fun <T> field(codec: Codec<T>, get: (P) -> T): T = codec.read(buf)
override fun structural(codec: Codec<Unit>) {
codec.read(buf)
}
}
internal class WritingScope<P>(
private val buf: WriteBuffer,
private val value: P,
) : CodecScope<P> {
override fun <T> field(codec: Codec<T>, get: (P) -> T): T {
val v = get(value)
codec.write(buf, v)
return v
}
override fun structural(codec: Codec<Unit>) {
codec.write(buf, Unit)
}
}
abstract class PacketCodec<P> : Codec<P> {
protected abstract fun CodecScope<P>.body(): P
final override fun read(buf: ReadBuffer): P {
val scope = ReadingScope<P>(buf)
return with(scope) { body() }
}
final override fun write(buf: WriteBuffer, value: P) {
val scope = WritingScope(buf, value)
with(scope) { body() }
}
}
fun CodecScope<*>.reserved(byte: Int = 0, strict: Boolean = false) {
structural(de.fiereu.bytecodec.reserved(byte = byte, strict = strict))
}
fun CodecScope<*>.padding(n: Int, fill: Byte = 0) {
structural(de.fiereu.bytecodec.padding(n = n, fill = fill))
}
fun CodecScope<*>.skip(n: Int) {
structural(de.fiereu.bytecodec.skip(n = n))
}
@@ -0,0 +1,47 @@
package de.fiereu.bytecodec.test
import de.fiereu.bytecodec.ByteArrayReadBuffer
import de.fiereu.bytecodec.Codec
import de.fiereu.bytecodec.GrowableWriteBuffer
private fun contentEqual(a: Any?, b: Any?): Boolean =
when {
a is ByteArray && b is ByteArray -> a.contentEquals(b)
a is Array<*> && b is Array<*> -> a.contentDeepEquals(b)
else -> a == b
}
fun <T> Codec<T>.encodeToBytes(value: T): ByteArray {
val buf = GrowableWriteBuffer()
write(buf, value)
return buf.toByteArray()
}
fun <T> Codec<T>.decodeBytes(bytes: ByteArray): T {
val buf = ByteArrayReadBuffer(bytes)
val value = read(buf)
check(buf.remaining() == 0) { "decode left ${buf.remaining()} bytes unread" }
return value
}
fun <T> Codec<T>.assertValueRoundtrip(value: T) {
val bytes = encodeToBytes(value)
val decoded = decodeBytes(bytes)
if (!contentEqual(decoded, value)) {
throw AssertionError(
"value roundtrip mismatch: original=$value decoded=$decoded bytes=${bytes.toHex()}",
)
}
}
fun <T> Codec<T>.assertBytesRoundtrip(bytes: ByteArray) {
val value = decodeBytes(bytes)
val reencoded = encodeToBytes(value)
if (!reencoded.contentEquals(bytes)) {
throw AssertionError(
"bytes roundtrip mismatch: original=${bytes.toHex()} reencoded=${reencoded.toHex()} value=$value",
)
}
}
private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it.toInt() and 0xFF) }
@@ -0,0 +1,140 @@
package de.fiereu.bytecodec
import de.fiereu.bytecodec.test.assertBytesRoundtrip
import de.fiereu.bytecodec.test.assertValueRoundtrip
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class AtomsTest :
FunSpec({
test("Bool roundtrips") {
Bool.assertValueRoundtrip(true)
Bool.assertValueRoundtrip(false)
Bool.encodeToBytes(true) shouldBe byteArrayOf(0x01)
Bool.encodeToBytes(false) shouldBe byteArrayOf(0x00)
Bool.decodeBytes(byteArrayOf(0x05)) shouldBe true
}
test("U8 wire format") {
U8.encodeToBytes(0) shouldBe byteArrayOf(0x00)
U8.encodeToBytes(255) shouldBe byteArrayOf(0xFF.toByte())
U8.decodeBytes(byteArrayOf(0xFF.toByte())) shouldBe 255
shouldThrow<IllegalArgumentException> { U8.encodeToBytes(256) }
}
test("S8 wire format") {
S8.assertValueRoundtrip(0)
S8.assertValueRoundtrip(-1)
S8.assertValueRoundtrip(127)
S8.assertValueRoundtrip(-128)
}
test("U16LE wire format") {
U16LE.encodeToBytes(0x1234) shouldBe byteArrayOf(0x34, 0x12)
U16LE.decodeBytes(byteArrayOf(0x34, 0x12)) shouldBe 0x1234
}
test("U16BE wire format") {
U16BE.encodeToBytes(0x1234) shouldBe byteArrayOf(0x12, 0x34)
U16BE.decodeBytes(byteArrayOf(0x12, 0x34)) shouldBe 0x1234
}
test("S16LE signed") {
S16LE.assertValueRoundtrip((-1).toShort())
S16LE.assertValueRoundtrip(Short.MIN_VALUE)
S16LE.assertValueRoundtrip(Short.MAX_VALUE)
}
test("S32LE wire format") {
S32LE.encodeToBytes(0x11223344) shouldBe byteArrayOf(0x44, 0x33, 0x22, 0x11)
S32LE.decodeBytes(byteArrayOf(0x44, 0x33, 0x22, 0x11)) shouldBe 0x11223344
S32LE.assertValueRoundtrip(Int.MIN_VALUE)
S32LE.assertValueRoundtrip(Int.MAX_VALUE)
}
test("S32BE wire format") {
S32BE.encodeToBytes(0x11223344) shouldBe byteArrayOf(0x11, 0x22, 0x33, 0x44)
S32BE.assertValueRoundtrip(Int.MIN_VALUE)
}
test("U32LE roundtrip across full range") {
U32LE.assertValueRoundtrip(0L)
U32LE.assertValueRoundtrip(0xFFFFFFFFL)
U32LE.encodeToBytes(0xFFFFFFFFL) shouldBe
byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte())
}
test("U32BE roundtrip") {
U32BE.encodeToBytes(0x11223344L) shouldBe byteArrayOf(0x11, 0x22, 0x33, 0x44)
}
test("S64LE wire format") {
S64LE.encodeToBytes(0x0102030405060708L) shouldBe
byteArrayOf(0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01)
S64LE.assertValueRoundtrip(Long.MIN_VALUE)
S64LE.assertValueRoundtrip(Long.MAX_VALUE)
}
test("S64BE wire format") {
S64BE.encodeToBytes(0x0102030405060708L) shouldBe
byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08)
}
test("F32 / F64 roundtrip") {
F32LE.assertValueRoundtrip(3.14f)
F32BE.assertValueRoundtrip(-0.0f)
F64LE.assertValueRoundtrip(2.718281828)
F64BE.assertValueRoundtrip(Double.NEGATIVE_INFINITY)
}
test("fixedBytes preserves payload") {
val codec = fixedBytes(4)
val payload = byteArrayOf(0x01, 0x02, 0x03, 0x04)
codec.assertBytesRoundtrip(payload)
shouldThrow<MalformedPacketException> { codec.encodeToBytes(byteArrayOf(0, 0, 0)) }
}
test("unknownBytes is lossless") {
val codec = unknownBytes(3)
codec.assertBytesRoundtrip(byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte()))
}
test("reserved strict checks value") {
val codec = reserved(0xAB, strict = true)
codec.decodeBytes(byteArrayOf(0xAB.toByte())) shouldBe Unit
shouldThrow<ReservedByteMismatchException> { codec.decodeBytes(byteArrayOf(0x01)) }
}
test("reserved non-strict accepts anything on read but writes literal") {
val codec = reserved(0x00)
codec.decodeBytes(byteArrayOf(0xFF.toByte())) shouldBe Unit
codec.encodeToBytes(Unit) shouldBe byteArrayOf(0x00)
}
test("padding writes fill bytes") {
val codec = padding(3, fill = 0xAA.toByte())
codec.encodeToBytes(Unit) shouldBe byteArrayOf(0xAA.toByte(), 0xAA.toByte(), 0xAA.toByte())
}
test("Utf16LeNullTerminated roundtrip") {
Utf16LeNullTerminated.assertValueRoundtrip("hello")
Utf16LeNullTerminated.assertValueRoundtrip("")
Utf16LeNullTerminated.assertValueRoundtrip("naïve résumé")
Utf16LeNullTerminated.encodeToBytes("ab") shouldBe
byteArrayOf(0x61, 0x00, 0x62, 0x00, 0x00, 0x00)
}
test("Utf16BeNullTerminated roundtrip") {
Utf16BeNullTerminated.assertValueRoundtrip("hello")
Utf16BeNullTerminated.encodeToBytes("ab") shouldBe
byteArrayOf(0x00, 0x61, 0x00, 0x62, 0x00, 0x00)
}
test("AsciiNullTerminated roundtrip") {
AsciiNullTerminated.assertValueRoundtrip("hello")
AsciiNullTerminated.encodeToBytes("ab") shouldBe byteArrayOf(0x61, 0x62, 0x00)
}
})
@@ -0,0 +1,50 @@
package de.fiereu.bytecodec
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.nio.ByteBuffer
class BuffersTest :
FunSpec({
test("ByteArrayReadBuffer sequential read") {
val buf = ByteArrayReadBuffer(byteArrayOf(1, 2, 3, 4))
buf.readByte() shouldBe 1
buf.remaining() shouldBe 3
val dst = ByteArray(2)
buf.readBytes(dst)
dst shouldBe byteArrayOf(2, 3)
buf.skip(1)
buf.remaining() shouldBe 0
shouldThrow<IndexOutOfBoundsException> { buf.readByte() }
}
test("ByteArrayReadBuffer respects offset and length") {
val buf = ByteArrayReadBuffer(byteArrayOf(9, 1, 2, 3, 9), offset = 1, length = 3)
buf.remaining() shouldBe 3
val arr = ByteArray(3)
buf.readBytes(arr)
arr shouldBe byteArrayOf(1, 2, 3)
}
test("GrowableWriteBuffer grows on demand") {
val buf = GrowableWriteBuffer(initialCapacity = 2)
repeat(10) { buf.writeByte(it.toByte()) }
buf.size() shouldBe 10
buf.toByteArray() shouldBe byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
}
test("NioReadBuffer / NioWriteBuffer interoperate") {
val nio = ByteBuffer.allocate(8)
val write = NioWriteBuffer(nio)
write.writeByte(0x11)
write.writeBytes(byteArrayOf(0x22, 0x33))
nio.flip()
val read = NioReadBuffer(nio)
read.readByte() shouldBe 0x11
val arr = ByteArray(2)
read.readBytes(arr)
arr shouldBe byteArrayOf(0x22, 0x33)
read.remaining() shouldBe 0
}
})
@@ -0,0 +1,134 @@
package de.fiereu.bytecodec
import de.fiereu.bytecodec.test.assertBytesRoundtrip
import de.fiereu.bytecodec.test.assertValueRoundtrip
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private enum class Color {
RED,
GREEN,
BLUE
}
class CombinatorsTest :
FunSpec({
test("imap lifts an atom") {
val codec = U8.imap(decode = { it + 1 }, encode = { it - 1 })
codec.encodeToBytes(10) shouldBe byteArrayOf(0x09)
codec.decodeBytes(byteArrayOf(0x09)) shouldBe 10
}
test("imapCatching wraps non-CodecException") {
val codec =
U8.imapCatching(
decode = { error("boom") },
encode = { _: Int -> 0 },
)
shouldThrow<MalformedPacketException> { codec.decodeBytes(byteArrayOf(0x00)) }
}
test("listPrefixed with U8 prefix") {
val codec = U16LE.listPrefixed(U8)
codec.assertValueRoundtrip(listOf(1, 2, 3))
codec.encodeToBytes(emptyList()) shouldBe byteArrayOf(0x00)
codec.encodeToBytes(listOf(0x1234, 0x5678)) shouldBe
byteArrayOf(0x02, 0x34, 0x12, 0x78, 0x56)
}
test("repeat is fixed-count") {
val codec = U8.repeat(3)
codec.assertBytesRoundtrip(byteArrayOf(1, 2, 3))
shouldThrow<MalformedPacketException> { codec.encodeToBytes(listOf(1, 2)) }
}
test("bytesPrefixed") {
val codec = bytesPrefixed(U8)
codec.assertBytesRoundtrip(byteArrayOf(0x03, 0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte()))
}
test("stringPrefixed UTF-8") {
val codec = stringPrefixed(U8, Charsets.UTF_8)
codec.assertValueRoundtrip("hello")
val bytes = "héllo".toByteArray(Charsets.UTF_8)
codec.encodeToBytes("héllo")[0].toInt() shouldBe bytes.size
}
test("enumByOrdinalByte") {
val codec = enumByOrdinalByte<Color>()
codec.assertValueRoundtrip(Color.RED)
codec.assertValueRoundtrip(Color.BLUE)
codec.encodeToBytes(Color.BLUE) shouldBe byteArrayOf(0x02)
shouldThrow<MalformedPacketException> { codec.decodeBytes(byteArrayOf(0x05)) }
}
test("enumBy with custom mapping") {
val keys = mapOf(Color.RED to 10, Color.GREEN to 20, Color.BLUE to 30)
val reverse = keys.entries.associate { (k, v) -> v to k }
val codec =
enumBy<Color>(
prefix = U8,
lookup = { reverse[it] ?: throw MalformedPacketException("bad key $it") },
keyOf = { keys.getValue(it) },
)
codec.encodeToBytes(Color.GREEN) shouldBe byteArrayOf(20)
codec.decodeBytes(byteArrayOf(30)) shouldBe Color.BLUE
}
test("choose dispatches on tag") {
val u8List = U8.listPrefixed(U8)
val codec: Codec<Any> =
choose(
tag = U8,
identify = { v ->
when (v) {
is Int -> 0x01
is String -> 0x02
else -> error("unhandled $v")
}
},
0x01 to U16LE as Codec<out Any>,
0x02 to AsciiNullTerminated as Codec<out Any>,
)
codec.encodeToBytes(0x1234) shouldBe byteArrayOf(0x01, 0x34, 0x12)
codec.encodeToBytes("ok") shouldBe byteArrayOf(0x02, 0x6F, 0x6B, 0x00)
shouldThrow<UnknownTagException> { codec.decodeBytes(byteArrayOf(0xFE.toByte())) }
u8List.encodeToBytes(emptyList()).size shouldBe 1
}
test("optional with explicit flag") {
val codec = U16LE.optional()
codec.assertValueRoundtrip(null)
codec.assertValueRoundtrip(0x1234)
codec.encodeToBytes(null) shouldBe byteArrayOf(0x00)
codec.encodeToBytes(0x1234) shouldBe byteArrayOf(0x01, 0x34, 0x12)
}
test("then pairs two codecs") {
val codec = U8.then(U16LE)
codec.assertValueRoundtrip(5 to 0x1234)
codec.encodeToBytes(5 to 0x1234) shouldBe byteArrayOf(0x05, 0x34, 0x12)
}
test("bitsLE roundtrip") {
val codec =
bitsLE(U8) {
bit(0, "a")
bit(3, "b")
bit(7, "c")
}
val set = codec.of("a" to true, "b" to false, "c" to true)
set["a"] shouldBe true
set["b"] shouldBe false
set["c"] shouldBe true
set[0] shouldBe true
val bytes = codec.encodeToBytes(set)
bytes shouldBe byteArrayOf(0b10000001.toByte())
val decoded = codec.decodeBytes(bytes)
decoded["a"] shouldBe true
decoded["c"] shouldBe true
}
})
@@ -0,0 +1,109 @@
package de.fiereu.bytecodec
import de.fiereu.bytecodec.test.assertBytesRoundtrip
import de.fiereu.bytecodec.test.assertValueRoundtrip
import de.fiereu.bytecodec.test.encodeToBytes
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private data class GameServer(
val id: Int,
val name: String,
val currentPlayers: Int,
val maxPlayers: Int,
val joinable: Boolean,
)
private object GameServerCodec : PacketCodec<GameServer>() {
override fun CodecScope<GameServer>.body() =
GameServer(
id = field(U8, GameServer::id),
name = field(Utf16LeNullTerminated, GameServer::name),
currentPlayers = field(U16LE, GameServer::currentPlayers),
maxPlayers = field(U16LE, GameServer::maxPlayers),
joinable = field(Bool, GameServer::joinable),
)
}
private data class LoadEntityPacket(
val entityId: Long,
val name: String,
val gateA: ByteArray?,
val gateB: Int?,
) {
override fun equals(other: Any?): Boolean =
other is LoadEntityPacket &&
entityId == other.entityId &&
name == other.name &&
(gateA?.contentEquals(other.gateA) ?: (other.gateA == null)) &&
gateB == other.gateB
override fun hashCode(): Int = entityId.hashCode()
}
private object LoadEntityCodec : PacketCodec<LoadEntityPacket>() {
override fun CodecScope<LoadEntityPacket>.body(): LoadEntityPacket {
val entityId = field(S64BE, LoadEntityPacket::entityId)
reserved(0)
val name = field(Utf16LeNullTerminated, LoadEntityPacket::name)
val flags =
field(U16LE) {
var f = 0
if (it.gateA != null) f = f or 0x01
if (it.gateB != null) f = f or 0x02
f
}
val gateA = if (flags and 0x01 != 0) field(unknownBytes(2)) { it.gateA!! } else null
val gateB = if (flags and 0x02 != 0) field(U32LE) { it.gateB!!.toLong() }.toInt() else null
return LoadEntityPacket(entityId, name, gateA, gateB)
}
}
class PacketCodecTest :
FunSpec({
test("simple PacketCodec roundtrip") {
val pkt =
GameServer(
id = 1, name = "alpha", currentPlayers = 10, maxPlayers = 100, joinable = true)
GameServerCodec.assertValueRoundtrip(pkt)
}
test("byte-level layout of GameServer") {
val bytes = GameServerCodec.encodeToBytes(GameServer(7, "ab", 3, 9, false))
bytes shouldBe
byteArrayOf(
0x07,
0x61,
0x00,
0x62,
0x00,
0x00,
0x00,
0x03,
0x00,
0x09,
0x00,
0x00,
)
}
test("complex packet with reserved, flags, optional sections") {
LoadEntityCodec.assertValueRoundtrip(
LoadEntityPacket(42L, "world", gateA = null, gateB = null),
)
LoadEntityCodec.assertValueRoundtrip(
LoadEntityPacket(
entityId = 0x0102030405060708L,
name = "x",
gateA = byteArrayOf(0xAA.toByte(), 0xBB.toByte()),
gateB = 0x11223344,
),
)
}
test("structural reserved bytes survive bytes roundtrip") {
val pkt = LoadEntityPacket(1L, "y", null, null)
val bytes = LoadEntityCodec.encodeToBytes(pkt)
LoadEntityCodec.assertBytesRoundtrip(bytes)
}
})
+3
View File
@@ -1,4 +1,7 @@
plugins { plugins {
id("buildsrc.convention.kotlin-jvm") id("buildsrc.convention.kotlin-jvm")
id("buildsrc.convention.spotless") id("buildsrc.convention.spotless")
id("buildsrc.convention.sonarlint")
} }
dependencies { testImplementation(libs.bundles.kotest) }
@@ -0,0 +1,75 @@
package de.fiereu.openmmo.common.auth
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.time.Clock
import java.time.Instant
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
/** Opaque token issued by the login server and validated by the game server. */
data class SessionToken(
val userId: Long,
val issuedAt: Instant,
val bytes: ByteArray,
) {
override fun equals(other: Any?): Boolean =
other is SessionToken &&
userId == other.userId &&
issuedAt == other.issuedAt &&
bytes.contentEquals(other.bytes)
override fun hashCode(): Int =
(userId.hashCode() * 31 + issuedAt.hashCode()) * 31 + bytes.contentHashCode()
}
class SessionTokenIssuer(secret: ByteArray, private val clock: Clock = Clock.systemUTC()) {
init {
require(secret.isNotEmpty()) { "session token secret must not be empty" }
}
private val secretKey = SecretKeySpec(secret, MAC_ALGORITHM)
fun issue(userId: Long): SessionToken {
val issuedAt = clock.instant()
val bytes = build(userId, issuedAt, secretKey)
return SessionToken(userId, issuedAt, bytes)
}
}
class SessionTokenVerifier(secret: ByteArray) {
init {
require(secret.isNotEmpty()) { "session token secret must not be empty" }
}
private val secretKey = SecretKeySpec(secret, MAC_ALGORITHM)
fun verify(bytes: ByteArray): SessionToken? {
if (bytes.size != TOKEN_SIZE) return null
val buf = ByteBuffer.wrap(bytes)
val userId = buf.long
val epochSeconds = buf.long
val issuedAt = Instant.ofEpochSecond(epochSeconds)
val expected = build(userId, issuedAt, secretKey)
if (!MessageDigest.isEqual(bytes, expected)) return null
return SessionToken(userId, issuedAt, bytes)
}
}
private const val MAC_ALGORITHM = "HmacSHA256"
private const val PREFIX_SIZE = 16
private const val MAC_SIZE = 16
private const val TOKEN_SIZE = PREFIX_SIZE + MAC_SIZE
private fun build(userId: Long, issuedAt: Instant, key: SecretKeySpec): ByteArray {
val out = ByteArray(TOKEN_SIZE)
val prefix = ByteBuffer.wrap(out, 0, PREFIX_SIZE)
prefix.putLong(userId)
prefix.putLong(issuedAt.epochSecond)
val mac = Mac.getInstance(MAC_ALGORITHM)
mac.init(key)
mac.update(out, 0, PREFIX_SIZE)
val tag = mac.doFinal()
System.arraycopy(tag, 0, out, PREFIX_SIZE, MAC_SIZE)
return out
}
@@ -0,0 +1,38 @@
package de.fiereu.openmmo.common.io
import java.io.InputStream
import java.security.KeyFactory
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.Base64
object PemKeyLoader {
fun loadEcPublic(stream: InputStream): ECPublicKey {
val der = readPem(stream)
val spec = X509EncodedKeySpec(der)
return KeyFactory.getInstance("EC").generatePublic(spec) as ECPublicKey
}
fun loadEcPrivate(stream: InputStream): ECPrivateKey {
val der = readPem(stream)
val spec = PKCS8EncodedKeySpec(der)
return KeyFactory.getInstance("EC").generatePrivate(spec) as ECPrivateKey
}
private fun readPem(stream: InputStream): ByteArray {
val text = stream.bufferedReader(Charsets.US_ASCII).use { it.readText() }
val body =
text
.lineSequence()
.map(String::trim)
.filter { it.isNotEmpty() && !it.startsWith("-----") }
.joinToString("")
return Base64.getDecoder().decode(body)
}
}
fun resource(name: String): InputStream =
PemKeyLoader::class.java.classLoader.getResourceAsStream(name)
?: error("classpath resource not found: $name")
@@ -0,0 +1,48 @@
package de.fiereu.openmmo.common.auth
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import java.time.Clock
import java.time.Instant
import java.time.ZoneOffset
class SessionTokenTest :
FunSpec({
val secret = ByteArray(32) { it.toByte() }
test("issuer + verifier roundtrip recovers userId and issuedAt") {
val fixed = Clock.fixed(Instant.ofEpochSecond(1_700_000_000), ZoneOffset.UTC)
val issuer = SessionTokenIssuer(secret, fixed)
val token = issuer.issue(userId = 42L)
val verified = SessionTokenVerifier(secret).verify(token.bytes)
verified.shouldNotBeNull()
verified.userId shouldBe 42L
verified.issuedAt shouldBe Instant.ofEpochSecond(1_700_000_000)
}
test("tampered bytes fail verification") {
val token = SessionTokenIssuer(secret).issue(userId = 1L)
val mutated = token.bytes.copyOf()
mutated[0] = (mutated[0] + 1).toByte()
SessionTokenVerifier(secret).verify(mutated) shouldBe null
}
test("different secret fails verification") {
val token = SessionTokenIssuer(secret).issue(userId = 1L)
val other = ByteArray(32) { (it + 1).toByte() }
SessionTokenVerifier(other).verify(token.bytes) shouldBe null
}
test("wrong length fails verification fast") {
SessionTokenVerifier(secret).verify(ByteArray(0)) shouldBe null
SessionTokenVerifier(secret).verify(ByteArray(31)) shouldBe null
SessionTokenVerifier(secret).verify(ByteArray(33)) shouldBe null
}
test("empty secret rejected") {
shouldThrow<IllegalArgumentException> { SessionTokenIssuer(ByteArray(0)) }
shouldThrow<IllegalArgumentException> { SessionTokenVerifier(ByteArray(0)) }
}
})
+2 -2
View File
@@ -15,5 +15,5 @@ openmmo.db.game.password=${GAME_DB_PASSWORD}
pokemmo.mainClass=com.pokeemu.client.Client pokemmo.mainClass=com.pokeemu.client.Client
# May be overridden by the user # May be overridden by the user
pokemmo.executable=${HOME}/.local/share/pokemmo/PokeMMO.exe pokemmo.executable=C:/Program Files/PokeMMO/PokeMMO.exe
pokemmo.workingDir=${HOME}/.local/share/pokemmo/ pokemmo.workingDir=C:/Program Files/PokeMMO
+9 -4
View File
@@ -5,9 +5,10 @@ kotlinx-coroutines = "1.10.2"
kotlin-logging = "7.0.7" # sl4j wrapper for Kotlin kotlin-logging = "7.0.7" # sl4j wrapper for Kotlin
logback = "1.5.13" logback = "1.5.13"
slf4j = "2.0.17" slf4j = "2.0.17"
asm = "9.8" bytebuddy = "1.17.5"
jte = "3.2.1"
spotless = "7.2.1" spotless = "7.2.1"
shadow = "9.0.2" sonarlint = "7.1.1"
bouncycastle = "1.81" bouncycastle = "1.81"
junit5 = "6.0.0-M2" junit5 = "6.0.0-M2"
kotest = "6.1.11" kotest = "6.1.11"
@@ -24,6 +25,7 @@ ineter = "0.3.1"
[libraries] [libraries]
kotlinGradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } kotlinGradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
spotlessGradlePlugin = { module = "com.diffplug.spotless:spotless-plugin-gradle", version.ref = "spotless" } spotlessGradlePlugin = { module = "com.diffplug.spotless:spotless-plugin-gradle", version.ref = "spotless" }
sonarlintGradlePlugin = { module = "name.remal.sonarlint:name.remal.sonarlint.gradle.plugin", version.ref = "sonarlint" }
kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" }
kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core-jvm", version.ref = "kotlinx-serialization" } kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core-jvm", version.ref = "kotlinx-serialization" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json-jvm", version.ref = "kotlinx-serialization" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json-jvm", version.ref = "kotlinx-serialization" }
@@ -32,7 +34,10 @@ kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-t
kotlin-logging = { module = "io.github.oshai:kotlin-logging-jvm", version.ref = "kotlin-logging" } kotlin-logging = { module = "io.github.oshai:kotlin-logging-jvm", version.ref = "kotlin-logging" }
logback = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } logback = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
slf4j = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } slf4j = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" }
asm = { module = "org.ow2.asm:asm", version.ref = "asm" } bytebuddy = { module = "net.bytebuddy:byte-buddy", version.ref = "bytebuddy" }
bytebuddy-agent = { module = "net.bytebuddy:byte-buddy-agent", version.ref = "bytebuddy" }
jte = { module = "gg.jte:jte", version.ref = "jte" }
jte-kotlin = { module = "gg.jte:jte-kotlin", version.ref = "jte" }
bouncycastle-pkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bouncycastle" } bouncycastle-pkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bouncycastle" }
bouncycastle-provider = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" } bouncycastle-provider = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
junit5 = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit5" } junit5 = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit5" }
@@ -55,12 +60,12 @@ ineter = { module = "com.github.maltalex:ineter", version.ref = "ineter" }
[bundles] [bundles]
crypto = ["bouncycastle-pkix", "bouncycastle-provider"] crypto = ["bouncycastle-pkix", "bouncycastle-provider"]
bytebuddy = ["bytebuddy", "bytebuddy-agent"]
jooq = ["jooq", "jooq-kotlin", "jooq-meta", "jooq-codegen"] jooq = ["jooq", "jooq-kotlin", "jooq-meta", "jooq-codegen"]
kotest = ["kotest-core", "kotest-assertions", "kotest-framework"] kotest = ["kotest-core", "kotest-assertions", "kotest-framework"]
[plugins] [plugins]
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
shadow = { id = "com.gradleup.shadow", version.ref = "shadow" }
jooq = { id = "org.jooq.jooq-codegen-gradle", version.ref = "jooq" } jooq = { id = "org.jooq.jooq-codegen-gradle", version.ref = "jooq" }
flyway = { id = "org.flywaydb.flyway", version.ref = "flyway" } flyway = { id = "org.flywaydb.flyway", version.ref = "flyway" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
+99
View File
@@ -0,0 +1,99 @@
import javax.inject.Inject
import org.gradle.process.ExecOperations
plugins {
id("buildsrc.convention.kotlin-jvm")
id("buildsrc.convention.spotless")
id("buildsrc.convention.sonarlint")
}
dependencies {
api(project(":common"))
api(project(":protocols.game"))
api(libs.dagger)
}
val generator: SourceSet by sourceSets.creating
dependencies {
"generatorImplementation"(libs.jte)
"generatorImplementation"(libs.kotlinx.serialization.json)
}
abstract class CloneOrUpdateGitRepoTask : DefaultTask() {
@get:Input abstract val remote: Property<String>
@get:Input abstract val ref: Property<String>
@get:OutputDirectory abstract val target: DirectoryProperty
@get:Inject abstract val execOps: ExecOperations
@TaskAction
fun run() {
val dir = target.get().asFile
val refValue = ref.get()
if (File(dir, ".git").exists()) {
execOps.exec {
workingDir = dir
commandLine("git", "fetch", "--depth", "1", "origin", refValue)
}
execOps.exec {
workingDir = dir
commandLine("git", "checkout", "--detach", "FETCH_HEAD")
}
} else {
if (dir.exists()) dir.deleteRecursively()
dir.parentFile.mkdirs()
execOps.exec {
commandLine(
"git",
"clone",
"--depth",
"1",
"--branch",
refValue,
remote.get(),
dir.absolutePath,
)
}
}
}
}
val pokeemeraldRef = providers.gradleProperty("pokemmo.pokeemerald.ref").orElse("master")
val clonePokeemerald by
tasks.registering(CloneOrUpdateGitRepoTask::class) {
group = "openmmo"
description = "Clone or fast-forward pret/pokeemerald into build/pokeemerald"
remote.set("https://github.com/pret/pokeemerald.git")
ref.set(pokeemeraldRef)
target.set(layout.buildDirectory.dir("pokeemerald"))
}
val pokeemeraldDir = layout.buildDirectory.dir("pokeemerald")
val generatedSrc = layout.buildDirectory.dir("generated/source/maps/main/kotlin")
val templatesDir = layout.projectDirectory.dir("src/generator/jte")
val jteCacheDir = layout.buildDirectory.dir("jte-classes")
val pokeemeraldArg = pokeemeraldDir.get().asFile.absolutePath
val generatedArg = generatedSrc.get().asFile.absolutePath
val templatesArg = templatesDir.asFile.absolutePath
val jteCacheArg = jteCacheDir.get().asFile.absolutePath
val generateMaps by
tasks.registering(JavaExec::class) {
group = "openmmo"
description = "Render MapDefaults.kt from pokeemerald data via JTE"
dependsOn(clonePokeemerald, tasks.named("${generator.name}Classes"))
inputs.dir(pokeemeraldDir)
inputs.dir(templatesDir)
outputs.dir(generatedSrc)
classpath = generator.runtimeClasspath
mainClass.set("de.fiereu.openmmo.maps.generator.Main")
args = listOf(pokeemeraldArg, generatedArg, templatesArg, jteCacheArg)
}
sourceSets.main { kotlin.srcDir(generateMaps) }
+52
View File
@@ -0,0 +1,52 @@
@import de.fiereu.openmmo.maps.generator.ParsedMap
@import de.fiereu.openmmo.maps.generator.RenderUtil
@import java.util.List
@param List<List<ParsedMap>> chunks
package de.fiereu.openmmo.maps
import de.fiereu.openmmo.common.Tile2D
import de.fiereu.openmmo.common.enums.EncounterType
import de.fiereu.openmmo.common.enums.Lighting
import de.fiereu.openmmo.common.enums.MapType
import de.fiereu.openmmo.common.enums.Weather
import de.fiereu.openmmo.net.game.packets.MapData
internal object MapDefaults {
fun loadInto(mgr: MapManager) {
@for(int i = 0; i < chunks.size(); i++)
chunk${i}(mgr)
@endfor
}
@for(int chunkIndex = 0; chunkIndex < chunks.size(); chunkIndex++)
private fun chunk${chunkIndex}(mgr: MapManager) {
@for(ParsedMap map : chunks.get(chunkIndex))
// ${map.getSourceName()} (${map.getMapId()})
mgr.register(
MapDef(
regionId = ${map.getRegion()},
bankId = ${map.getBank()},
mapId = ${map.getIndex()},
width = ${map.getWidth()},
height = ${map.getHeight()},
paletteIdx1 = ${map.getPaletteIdx1()},
paletteIdx2 = ${map.getPaletteIdx2()},
unknownShort = ${map.getMusicId()},
unknownByte = ${map.getMapsecId()},
borderTiles = ${RenderUtil.INSTANCE.borderTiles(map.getBorderTiles())},
lighting = ${map.getLighting()},
weather = ${map.getWeather()},
mapType = ${map.getMapType()},
encounterType = ${map.getEncounterType()},
connections = ${RenderUtil.INSTANCE.connections(map.getConnections())},
warps = ${RenderUtil.INSTANCE.warps(map.getWarps())},
npcs = ${RenderUtil.INSTANCE.npcs(map.getVisibleNpcs())},
bgEvents = ${RenderUtil.INSTANCE.bgEvents(map.getBgEvents())},
)
)
@endfor
}
@endfor
}
@@ -0,0 +1,201 @@
package de.fiereu.openmmo.maps.generator
internal const val BANK_GROUP_OFFSET = 50
internal val dirMap =
mapOf("down" to 1, "up" to 2, "left" to 3, "right" to 4, "dive" to 5, "emerge" to 6)
internal val movementTypes =
mapOf(
"MOVEMENT_TYPE_NONE" to 0,
"MOVEMENT_TYPE_LOOK_AROUND" to 1,
"MOVEMENT_TYPE_WANDER_AROUND" to 2,
"MOVEMENT_TYPE_WANDER_UP_AND_DOWN" to 3,
"MOVEMENT_TYPE_WANDER_DOWN_AND_UP" to 4,
"MOVEMENT_TYPE_WANDER_LEFT_AND_RIGHT" to 5,
"MOVEMENT_TYPE_WANDER_RIGHT_AND_LEFT" to 6,
"MOVEMENT_TYPE_FACE_UP" to 7,
"MOVEMENT_TYPE_FACE_DOWN" to 8,
"MOVEMENT_TYPE_FACE_LEFT" to 9,
"MOVEMENT_TYPE_FACE_RIGHT" to 10,
"MOVEMENT_TYPE_PLAYER" to 11,
"MOVEMENT_TYPE_BERRY_TREE_GROWTH" to 12,
"MOVEMENT_TYPE_FACE_DOWN_AND_UP" to 13,
"MOVEMENT_TYPE_FACE_LEFT_AND_RIGHT" to 14,
"MOVEMENT_TYPE_FACE_UP_AND_LEFT" to 15,
"MOVEMENT_TYPE_FACE_UP_AND_RIGHT" to 16,
"MOVEMENT_TYPE_FACE_DOWN_AND_LEFT" to 17,
"MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT" to 18,
"MOVEMENT_TYPE_FACE_DOWN_UP_AND_LEFT" to 19,
"MOVEMENT_TYPE_FACE_DOWN_UP_AND_RIGHT" to 20,
"MOVEMENT_TYPE_FACE_UP_LEFT_AND_RIGHT" to 21,
"MOVEMENT_TYPE_FACE_DOWN_LEFT_AND_RIGHT" to 22,
"MOVEMENT_TYPE_ROTATE_COUNTERCLOCKWISE" to 23,
"MOVEMENT_TYPE_ROTATE_CLOCKWISE" to 24,
"MOVEMENT_TYPE_WALK_UP_AND_DOWN" to 25,
"MOVEMENT_TYPE_WALK_DOWN_AND_UP" to 26,
"MOVEMENT_TYPE_WALK_LEFT_AND_RIGHT" to 27,
"MOVEMENT_TYPE_WALK_RIGHT_AND_LEFT" to 28,
"MOVEMENT_TYPE_WALK_IN_PLACE_DOWN" to 64,
"MOVEMENT_TYPE_WALK_IN_PLACE_UP" to 65,
"MOVEMENT_TYPE_WALK_IN_PLACE_LEFT" to 66,
"MOVEMENT_TYPE_WALK_IN_PLACE_RIGHT" to 67,
"MOVEMENT_TYPE_JOG_IN_PLACE_DOWN" to 68,
"MOVEMENT_TYPE_JOG_IN_PLACE_UP" to 69,
"MOVEMENT_TYPE_JOG_IN_PLACE_LEFT" to 70,
"MOVEMENT_TYPE_JOG_IN_PLACE_RIGHT" to 71,
"MOVEMENT_TYPE_RUN_IN_PLACE_DOWN" to 72,
"MOVEMENT_TYPE_RUN_IN_PLACE_UP" to 73,
"MOVEMENT_TYPE_RUN_IN_PLACE_LEFT" to 74,
"MOVEMENT_TYPE_RUN_IN_PLACE_RIGHT" to 75,
"MOVEMENT_TYPE_INVISIBLE" to 76,
)
internal val gfxIds =
mapOf(
"OBJ_EVENT_GFX_BRENDAN_NORMAL" to 0,
"OBJ_EVENT_GFX_BRENDAN_MACH_BIKE" to 1,
"OBJ_EVENT_GFX_BRENDAN_SURFING" to 2,
"OBJ_EVENT_GFX_BRENDAN_FIELD_MOVE" to 3,
"OBJ_EVENT_GFX_QUINTY_PLUMP" to 4,
"OBJ_EVENT_GFX_NINJA_BOY" to 5,
"OBJ_EVENT_GFX_TWIN" to 6,
"OBJ_EVENT_GFX_BOY_1" to 7,
"OBJ_EVENT_GFX_GIRL_1" to 8,
"OBJ_EVENT_GFX_BOY_2" to 9,
"OBJ_EVENT_GFX_GIRL_2" to 10,
"OBJ_EVENT_GFX_LITTLE_BOY" to 11,
"OBJ_EVENT_GFX_LITTLE_GIRL" to 12,
"OBJ_EVENT_GFX_BOY_3" to 13,
"OBJ_EVENT_GFX_GIRL_3" to 14,
"OBJ_EVENT_GFX_RICH_BOY" to 15,
"OBJ_EVENT_GFX_WOMAN_1" to 16,
"OBJ_EVENT_GFX_FAT_MAN" to 17,
"OBJ_EVENT_GFX_POKEFAN_F" to 18,
"OBJ_EVENT_GFX_MAN_1" to 19,
"OBJ_EVENT_GFX_WOMAN_2" to 20,
"OBJ_EVENT_GFX_EXPERT_M" to 21,
"OBJ_EVENT_GFX_EXPERT_F" to 22,
"OBJ_EVENT_GFX_MAN_2" to 23,
"OBJ_EVENT_GFX_WOMAN_3" to 24,
"OBJ_EVENT_GFX_POKEFAN_M" to 25,
"OBJ_EVENT_GFX_WOMAN_4" to 26,
"OBJ_EVENT_GFX_COOK" to 27,
"OBJ_EVENT_GFX_LINK_RECEPTIONIST" to 28,
"OBJ_EVENT_GFX_OLD_MAN" to 29,
"OBJ_EVENT_GFX_OLD_WOMAN" to 30,
"OBJ_EVENT_GFX_CAMPER" to 31,
"OBJ_EVENT_GFX_PICNICKER" to 32,
"OBJ_EVENT_GFX_MAN_3" to 33,
"OBJ_EVENT_GFX_WOMAN_5" to 34,
"OBJ_EVENT_GFX_YOUNGSTER" to 35,
"OBJ_EVENT_GFX_BUG_CATCHER" to 36,
"OBJ_EVENT_GFX_PSYCHIC_M" to 37,
"OBJ_EVENT_GFX_SCHOOL_KID_M" to 38,
"OBJ_EVENT_GFX_MANIAC" to 39,
"OBJ_EVENT_GFX_HEX_MANIAC" to 40,
"OBJ_EVENT_GFX_RAYQUAZA_STILL" to 41,
"OBJ_EVENT_GFX_SWIMMER_M" to 42,
"OBJ_EVENT_GFX_SWIMMER_F" to 43,
"OBJ_EVENT_GFX_BLACK_BELT" to 44,
"OBJ_EVENT_GFX_BEAUTY" to 45,
"OBJ_EVENT_GFX_SCIENTIST_1" to 46,
"OBJ_EVENT_GFX_LASS" to 47,
"OBJ_EVENT_GFX_GENTLEMAN" to 48,
"OBJ_EVENT_GFX_SAILOR" to 49,
"OBJ_EVENT_GFX_FISHERMAN" to 50,
"OBJ_EVENT_GFX_RUNNING_TRIATHLETE_M" to 51,
"OBJ_EVENT_GFX_RUNNING_TRIATHLETE_F" to 52,
"OBJ_EVENT_GFX_TUBER_F" to 53,
"OBJ_EVENT_GFX_TUBER_M" to 54,
"OBJ_EVENT_GFX_HIKER" to 55,
"OBJ_EVENT_GFX_CYCLING_TRIATHLETE_M" to 56,
"OBJ_EVENT_GFX_CYCLING_TRIATHLETE_F" to 57,
"OBJ_EVENT_GFX_NURSE" to 58,
"OBJ_EVENT_GFX_ITEM_BALL" to 59,
"OBJ_EVENT_GFX_BERRY_TREE" to 60,
"OBJ_EVENT_GFX_BERRY_TREE_EARLY_STAGES" to 61,
"OBJ_EVENT_GFX_BERRY_TREE_LATE_STAGES" to 62,
"OBJ_EVENT_GFX_BRENDAN_ACRO_BIKE" to 63,
"OBJ_EVENT_GFX_PROF_BIRCH" to 64,
"OBJ_EVENT_GFX_MAN_4" to 65,
"OBJ_EVENT_GFX_MAN_5" to 66,
"OBJ_EVENT_GFX_REPORTER_M" to 67,
"OBJ_EVENT_GFX_REPORTER_F" to 68,
"OBJ_EVENT_GFX_BARD" to 69,
"OBJ_EVENT_GFX_ANABEL" to 70,
"OBJ_EVENT_GFX_TUCKER" to 71,
"OBJ_EVENT_GFX_GRETA" to 72,
"OBJ_EVENT_GFX_SPENSER" to 73,
"OBJ_EVENT_GFX_NOLAND" to 74,
"OBJ_EVENT_GFX_LUCY" to 75,
"OBJ_EVENT_GFX_MART_EMPLOYEE" to 83,
"OBJ_EVENT_GFX_TRUCK" to 94,
"OBJ_EVENT_GFX_VIGOROTH_CARRYING_BOX" to 95,
"OBJ_EVENT_GFX_VIGOROTH_FACING_AWAY" to 96,
"OBJ_EVENT_GFX_RIVAL_BRENDAN_NORMAL" to 100,
"OBJ_EVENT_GFX_RIVAL_MAY_NORMAL" to 105,
"OBJ_EVENT_GFX_SCIENTIST_2" to 115,
"OBJ_EVENT_GFX_NORMAN" to 129,
"OBJ_EVENT_GFX_MOM" to 215,
"OBJ_EVENT_GFX_VAR_0" to 240,
)
internal val weatherMap =
mapOf(
"WEATHER_NONE" to "Weather.IN_HOUSE_WEATHER",
"WEATHER_SUNNY" to "Weather.REGULAR_WEATHER",
"WEATHER_RAIN" to "Weather.RAINY_WEATHER",
"WEATHER_SNOW" to "Weather.THREE_SNOW_FLAKES",
"WEATHER_FOG_HORIZONTAL" to "Weather.STEADY_MIST",
"WEATHER_FOG_DIAGONAL" to "Weather.STEADY_MIST",
"WEATHER_SHADE" to "Weather.CLOUDY",
"WEATHER_UNDERWATER_BUBBLES" to "Weather.UNDERWATER_MIST",
"WEATHER_VOLCANIC_ASH" to "Weather.DENSE_BRIGHT_MIST",
)
internal val mapTypeMap =
mapOf(
"MAP_TYPE_INDOOR" to "MapType.INSIDE",
"MAP_TYPE_TOWN" to "MapType.UNKNOWN_0x01",
"MAP_TYPE_CITY" to "MapType.CITY",
"MAP_TYPE_ROUTE" to "MapType.ROUTE",
"MAP_TYPE_UNDERGROUND" to "MapType.UNDERGROUND",
"MAP_TYPE_UNDERWATER" to "MapType.UNDERWATER",
"MAP_TYPE_OCEAN_ROUTE" to "MapType.ROUTE",
"MAP_TYPE_SECRET_BASE" to "MapType.SECRET_BASE",
)
private const val ENCOUNTER_RANDOM = "EncounterType.RANDOM"
private const val ENCOUNTER_UNKNOWN_0X03 = "EncounterType.UNKNOWN_0x03"
internal val encounterMap =
mapOf(
"MAP_TYPE_INDOOR" to ENCOUNTER_RANDOM,
"MAP_TYPE_TOWN" to ENCOUNTER_RANDOM,
"MAP_TYPE_CITY" to ENCOUNTER_RANDOM,
"MAP_TYPE_ROUTE" to ENCOUNTER_RANDOM,
"MAP_TYPE_UNDERGROUND" to ENCOUNTER_RANDOM,
"MAP_TYPE_UNDERWATER" to ENCOUNTER_UNKNOWN_0X03,
"MAP_TYPE_OCEAN_ROUTE" to ENCOUNTER_RANDOM,
"MAP_TYPE_SECRET_BASE" to ENCOUNTER_UNKNOWN_0X03,
)
internal val defaultVisibleNpcs =
mapOf(
"LittlerootTown_MaysHouse_1F" to listOf(0),
"LittlerootTown_BrendansHouse_1F" to listOf(3, 5),
"LittlerootTown_ProfessorBirchsLab" to listOf(0),
)
internal fun movementToFacingDir(movementType: Int): Int =
when (movementType) {
7 -> 1
8 -> 0
9 -> 2
10 -> 3
in 64..67 -> movementType - 64
in 68..71 -> movementType - 68
in 72..75 -> movementType - 72
else -> 0
}
@@ -0,0 +1,21 @@
@file:JvmName("Main")
package de.fiereu.openmmo.maps.generator
import java.io.File
fun main(args: Array<String>) {
require(args.size == 4) {
"Usage: <pokeemerald-dir> <output-dir> <templates-dir> <class-cache-dir> got ${args.toList()}"
}
val pokeemeraldDir = File(args[0])
val outputDir = File(args[1])
val templatesDir = File(args[2])
val classCacheDir = File(args[3])
println("[maps] parsing pokeemerald from $pokeemeraldDir")
val maps = PokeemeraldParser(pokeemeraldDir).parseAll()
println("[maps] parsed ${maps.size} maps. writing to $outputDir")
MapsRenderer(templatesDir, outputDir, classCacheDir).render(maps)
println("[maps] done")
}
@@ -0,0 +1,31 @@
package de.fiereu.openmmo.maps.generator
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.output.FileOutput
import gg.jte.resolve.DirectoryCodeResolver
import java.io.File
class MapsRenderer(
private val templatesDir: File,
private val outputDir: File,
private val classCacheDir: File,
private val chunkSize: Int = 60,
) {
fun render(maps: List<ParsedMap>) {
classCacheDir.mkdirs()
val engine =
TemplateEngine.create(
DirectoryCodeResolver(templatesDir.toPath()),
classCacheDir.toPath(),
ContentType.Plain,
)
val chunks = maps.chunked(chunkSize)
val target = File(outputDir, "de/fiereu/openmmo/maps/MapDefaults.kt")
target.parentFile.mkdirs()
FileOutput(target.toPath()).use { out ->
engine.render("MapsRegistry.jte", mapOf("chunks" to chunks), out)
}
}
}
@@ -0,0 +1,63 @@
package de.fiereu.openmmo.maps.generator
data class ParsedMap(
val sourceName: String,
val mapId: String,
val region: Int,
val bank: Int,
val index: Int,
val width: Int,
val height: Int,
val paletteIdx1: Int,
val paletteIdx2: Int,
val musicId: Int,
val mapsecId: Int,
val borderTiles: List<Int>,
val lighting: String,
val weather: String,
val mapType: String,
val encounterType: String,
val connections: List<ParsedConnection>,
val warps: List<ParsedWarp>,
val visibleNpcs: List<ParsedNpc>,
val bgEvents: List<ParsedBgEvent>,
)
data class ParsedConnection(
val direction: Int,
val offset: Int,
val targetBank: Int,
val targetMap: Int,
)
data class ParsedWarp(
val x: Int,
val y: Int,
val elevation: Int,
val targetBank: Int,
val targetMap: Int,
val targetX: Int,
val targetY: Int,
val targetElevation: Int,
)
data class ParsedNpc(
val entityIdx: Int,
val graphicsId: Int,
val x: Int,
val y: Int,
val elevation: Int,
val movementType: Int,
val movementRangeX: Int,
val movementRangeY: Int,
val trainerType: Int,
val facing: Int,
val script: String,
)
data class ParsedBgEvent(
val x: Int,
val y: Int,
val facingDir: String,
val script: String,
)
@@ -0,0 +1,262 @@
package de.fiereu.openmmo.maps.generator
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
class PokeemeraldParser(private val rootDir: File) {
private val json = Json { ignoreUnknownKeys = true }
fun parseAll(): List<ParsedMap> {
val mapGroups = readJson(File(rootDir, "data/maps/map_groups.json")).jsonObject
val groupOrder =
(mapGroups["group_order"] ?: error("group_order missing")).jsonArray.map {
it.jsonPrimitive.content
}
val groupEntries: Map<String, List<String>> =
groupOrder.associateWith { group ->
(mapGroups[group]?.jsonArray ?: error("group $group missing")).map {
it.jsonPrimitive.content
}
}
val layouts: Map<String, JsonObject> =
(readJson(File(rootDir, "data/layouts/layouts.json")).jsonObject["layouts"]
?: error("layouts missing"))
.jsonArray
.mapNotNull { it as? JsonObject }
.filter { it["id"]?.jsonPrimitive?.contentOrNull != null }
.associateBy { it["id"]?.jsonPrimitive?.content ?: error("layout id") }
val musicIds = readDefineTable(File(rootDir, "include/constants/songs.h"), "MUS_")
val mapsecIds = readMapsecIds()
val tilesetPaletteIds = readTilesetPaletteIds()
// Pre-parse every map.json once so warp lookups don't re-read files.
data class Address(val groupIndex: Int, val mapIndex: Int, val mapName: String)
val addresses = mutableMapOf<String, Address>()
val mapJsons = mutableMapOf<String, JsonObject>()
for ((groupIndex, groupName) in groupOrder.withIndex()) {
val maps = groupEntries[groupName] ?: continue
for ((mapIndex, mapDirName) in maps.withIndex()) {
val mapJsonFile = File(rootDir, "data/maps/$mapDirName/map.json")
if (!mapJsonFile.exists()) continue
val parsed = readJson(mapJsonFile).jsonObject
mapJsons[mapDirName] = parsed
addresses[mapDirName] = Address(groupIndex, mapIndex, mapDirName)
val mapId = parsed["id"]?.jsonPrimitive?.contentOrNull
if (mapId != null) addresses[mapId] = Address(groupIndex, mapIndex, mapDirName)
}
}
val results = mutableListOf<ParsedMap>()
for ((groupIndex, groupName) in groupOrder.withIndex()) {
val maps = groupEntries[groupName] ?: continue
for ((mapIndex, mapDirName) in maps.withIndex()) {
val mapJson = mapJsons[mapDirName] ?: continue
val layoutId = mapJson["layout"]?.jsonPrimitive?.contentOrNull ?: continue
val layout = layouts[layoutId] ?: continue
val mapType = mapJson["map_type"]?.jsonPrimitive?.contentOrNull ?: "MAP_TYPE_INDOOR"
val primaryTileset = layout["primary_tileset"]?.jsonPrimitive?.contentOrNull
val secondaryTileset = layout["secondary_tileset"]?.jsonPrimitive?.contentOrNull
val pal1 = tilesetPaletteIds[primaryTileset] ?: 80
val pal2 = tilesetPaletteIds[secondaryTileset] ?: 82
val musicName = mapJson["music"]?.jsonPrimitive?.contentOrNull ?: "MUS_NONE"
val mapsecName =
mapJson["region_map_section"]?.jsonPrimitive?.contentOrNull ?: "MAPSEC_NONE"
val connections =
mapJson["connections"]?.jsonArrayOrNull()?.mapNotNull { conn ->
val obj = conn.jsonObject
val dirName = obj["direction"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val dir = dirMap[dirName] ?: error("Unknown connection direction '$dirName'")
val mapName = obj["map"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val addr = addresses[mapName] ?: return@mapNotNull null
val offset = obj["offset"]?.jsonPrimitive?.intOrNull ?: 0
ParsedConnection(
direction = dir,
offset = offset,
targetBank = addr.groupIndex + BANK_GROUP_OFFSET,
targetMap = addr.mapIndex,
)
} ?: emptyList()
val warps =
mapJson["warp_events"]?.jsonArrayOrNull()?.mapNotNull { warp ->
val obj = warp.jsonObject
val destName = obj["dest_map"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val destAddr = addresses[destName] ?: return@mapNotNull null
val x = obj["x"]?.jsonPrimitive?.intOrNull ?: 0
val y = obj["y"]?.jsonPrimitive?.intOrNull ?: 0
val srcElevation = obj["elevation"]?.jsonPrimitive?.intOrNull ?: 0
val destWarpId =
obj["dest_warp_id"]?.jsonPrimitive?.let {
it.intOrNull ?: it.content.toIntOrNull()
} ?: 0
val destWarps =
mapJsons[destAddr.mapName]?.get("warp_events")?.jsonArrayOrNull().orEmpty()
val target =
destWarps.getOrNull(destWarpId)?.jsonObject
?: return@mapNotNull ParsedWarp(
x = x,
y = y,
elevation = (srcElevation - 1).coerceAtLeast(0),
targetBank = destAddr.groupIndex + BANK_GROUP_OFFSET,
targetMap = destAddr.mapIndex,
targetX = x,
targetY = y,
targetElevation = 0,
)
val tx = target["x"]?.jsonPrimitive?.intOrNull ?: x
val ty = target["y"]?.jsonPrimitive?.intOrNull ?: y
val targetElevation =
((target["elevation"]?.jsonPrimitive?.intOrNull ?: 0) - 1).coerceAtLeast(0)
ParsedWarp(
x = x,
y = y,
elevation = (srcElevation - 1).coerceAtLeast(0),
targetBank = destAddr.groupIndex + BANK_GROUP_OFFSET,
targetMap = destAddr.mapIndex,
targetX = tx,
targetY = ty,
targetElevation = targetElevation,
)
} ?: emptyList()
val rawNpcs = mapJson["object_events"]?.jsonArrayOrNull().orEmpty()
val visibleOverride = defaultVisibleNpcs[mapDirName]
val visibleNpcs =
rawNpcs.mapIndexedNotNull { idx, npcElement ->
val npc = npcElement.jsonObject
val isVisible =
if (visibleOverride != null) idx in visibleOverride
else npc["flag"]?.jsonPrimitive?.contentOrNull == "0"
if (!isVisible) return@mapIndexedNotNull null
val gfxName =
npc["graphics_id"]?.jsonPrimitive?.contentOrNull ?: "OBJ_EVENT_GFX_BOY_1"
val movementName =
npc["movement_type"]?.jsonPrimitive?.contentOrNull ?: "MOVEMENT_TYPE_NONE"
val movement = movementTypes[movementName] ?: 0
val trainerType =
if (npc["trainer_type"]?.jsonPrimitive?.contentOrNull == "TRAINER_TYPE_NONE") 0
else 1
ParsedNpc(
entityIdx = idx,
graphicsId = gfxIds[gfxName] ?: 0,
x = npc["x"]?.jsonPrimitive?.intOrNull ?: 0,
y = npc["y"]?.jsonPrimitive?.intOrNull ?: 0,
elevation = npc["elevation"]?.jsonPrimitive?.intOrNull ?: 3,
movementType = movement,
movementRangeX = npc["movement_range_x"]?.jsonPrimitive?.intOrNull ?: 0,
movementRangeY = npc["movement_range_y"]?.jsonPrimitive?.intOrNull ?: 0,
trainerType = trainerType,
facing = movementToFacingDir(movement),
script = npc["script"]?.jsonPrimitive?.contentOrNull ?: "0x0",
)
}
val bgEvents =
mapJson["bg_events"]?.jsonArrayOrNull()?.map { be ->
val obj = be.jsonObject
ParsedBgEvent(
x = obj["x"]?.jsonPrimitive?.intOrNull ?: 0,
y = obj["y"]?.jsonPrimitive?.intOrNull ?: 0,
facingDir =
obj["player_facing_dir"]?.jsonPrimitive?.contentOrNull
?: "BG_EVENT_PLAYER_FACING_ANY",
script = obj["script"]?.jsonPrimitive?.contentOrNull ?: "0x0",
)
} ?: emptyList()
val borderTiles =
layout["border_filepath"]?.jsonPrimitive?.contentOrNull?.let {
readBorderTiles(File(rootDir, it))
} ?: emptyList()
results +=
ParsedMap(
sourceName = mapDirName,
mapId = mapJson["id"]?.jsonPrimitive?.contentOrNull ?: mapDirName,
region = 1,
bank = groupIndex + BANK_GROUP_OFFSET,
index = mapIndex,
width = layout["width"]?.jsonPrimitive?.intOrNull ?: 20,
height = layout["height"]?.jsonPrimitive?.intOrNull ?: 15,
paletteIdx1 = pal1,
paletteIdx2 = pal2,
musicId = musicIds[musicName] ?: 405,
mapsecId = mapsecIds[mapsecName] ?: 0,
borderTiles = borderTiles,
lighting = "Lighting.REGULAR",
weather =
weatherMap[mapJson["weather"]?.jsonPrimitive?.contentOrNull]
?: "Weather.REGULAR_WEATHER",
mapType = mapTypeMap[mapType] ?: "MapType.INSIDE",
encounterType = encounterMap[mapType] ?: "EncounterType.RANDOM",
connections = connections,
warps = warps,
visibleNpcs = visibleNpcs,
bgEvents = bgEvents,
)
}
}
return results
}
private fun readJson(file: File): JsonElement = json.parseToJsonElement(file.readText())
private fun readDefineTable(file: File, prefix: String): Map<String, Int> {
if (!file.exists()) return emptyMap()
val pattern = Regex("""^#define\s+($prefix\w+)\s+(\d+)""")
return file
.readLines()
.mapNotNull { pattern.find(it.trim()) }
.associate { it.groupValues[1] to it.groupValues[2].toInt() }
}
private fun readMapsecIds(): Map<String, Int> {
val file = File(rootDir, "src/data/region_map/region_map_sections.json")
if (!file.exists()) return emptyMap()
val sections = readJson(file).jsonObject["map_sections"]?.jsonArray ?: return emptyMap()
return sections
.mapIndexedNotNull { i, el ->
el.jsonObject["id"]?.jsonPrimitive?.contentOrNull?.let { it to i }
}
.toMap()
}
private fun readTilesetPaletteIds(): Map<String, Int> {
val file = File(rootDir, "src/data/tilesets/headers.h")
if (!file.exists()) return emptyMap()
val pattern = Regex("""^const struct Tileset\s+(gTileset_\w+)\s*=""")
var index = 0
val out = mutableMapOf<String, Int>()
file.forEachLine { line ->
val m = pattern.find(line.trim()) ?: return@forEachLine
out[m.groupValues[1]] = 100 + index
index++
}
return out
}
private fun readBorderTiles(file: File): List<Int> {
if (!file.exists()) return emptyList()
val bytes = file.readBytes()
val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val out = mutableListOf<Int>()
while (buf.remaining() >= 2) out += buf.short.toInt() and 0xFFFF
return out
}
private fun JsonElement.jsonArrayOrNull() = (this as? kotlinx.serialization.json.JsonArray)
}
@@ -0,0 +1,8 @@
package de.fiereu.openmmo.maps
data class BgEventDef(
val x: Int,
val y: Int,
val facingDir: String,
val script: String,
)
@@ -0,0 +1,32 @@
package de.fiereu.openmmo.maps
import de.fiereu.openmmo.common.Tile2D
import de.fiereu.openmmo.common.enums.EncounterType
import de.fiereu.openmmo.common.enums.Lighting
import de.fiereu.openmmo.common.enums.MapType
import de.fiereu.openmmo.common.enums.Weather
import de.fiereu.openmmo.net.game.packets.MapData
class MapDef(
val regionId: Byte,
val bankId: Byte,
val mapId: Byte,
val width: Int = 20,
val height: Int = 15,
val paletteIdx1: Int = 12,
val paletteIdx2: Int = 14,
val borderWidth: Int = 2,
val borderHeight: Int = 2,
val unknownShort: Int = 0,
val unknownByte: Int = 0,
val borderTiles: List<Tile2D> = listOf(Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0)),
val lighting: Lighting = Lighting.REGULAR,
val weather: Weather = Weather.REGULAR_WEATHER,
val mapType: MapType = MapType.CITY,
val encounterType: EncounterType = EncounterType.RANDOM,
val wildEncounters: List<WildEncounterTable> = emptyList(),
val connections: List<MapData.GbaConnection> = emptyList(),
val warps: List<WarpTile> = emptyList(),
val npcs: List<NpcDef> = emptyList(),
val bgEvents: List<BgEventDef> = emptyList(),
)
@@ -0,0 +1,64 @@
package de.fiereu.openmmo.maps
import de.fiereu.openmmo.net.game.packets.LoadMapPacket
import de.fiereu.openmmo.net.game.packets.MapData
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MapManager @Inject constructor() {
private val maps = ConcurrentHashMap<Long, MapDef>()
init {
MapDefaults.loadInto(this)
}
fun register(map: MapDef) {
maps[key(map.regionId, map.bankId, map.mapId)] = map
}
fun getMap(regionId: Byte, bankId: Byte, mapId: Byte): MapDef? =
maps[key(regionId, bankId, mapId)]
fun getMap(regionId: Int, bankId: Int, mapId: Int): MapDef? =
getMap(regionId.toByte(), bankId.toByte(), mapId.toByte())
fun size(): Int = maps.size
fun createLoadMapPacket(
map: MapDef,
reloadPlayer: Boolean = false,
deleteCache: Boolean = false,
): LoadMapPacket =
LoadMapPacket(
reloadPlayer = reloadPlayer,
deleteCache = deleteCache,
regionId = map.regionId.toInt() and 0xFF,
bankId = map.bankId.toInt() and 0xFF,
mapId = map.mapId.toInt() and 0xFF,
mapData =
MapData.GbaMapData(
width = map.width,
height = map.height,
paletteIdx1 = map.paletteIdx1,
paletteIdx2 = map.paletteIdx2,
borderWidth = map.borderWidth,
borderHeight = map.borderHeight,
unknownShort = map.unknownShort,
unknownByte = map.unknownByte,
borderTiles = map.borderTiles,
lighting = map.lighting,
weather = map.weather,
mapType = map.mapType,
encounterType = map.encounterType,
connections = map.connections,
),
)
private fun key(regionId: Byte, bankId: Byte, mapId: Byte): Long =
((regionId.toLong() and 0xFF) shl 16) or
((bankId.toLong() and 0xFF) shl 8) or
(mapId.toLong() and 0xFF)
}
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.maps
data class NpcDef(
val entityIdx: Int,
val graphicsId: Int,
val x: Int,
val y: Int,
val elevation: Int,
val movementType: Int,
val movementRangeX: Int,
val movementRangeY: Int,
val trainerType: Int,
val facing: Int,
val script: String = "0x0",
)
@@ -0,0 +1,16 @@
package de.fiereu.openmmo.maps
import de.fiereu.openmmo.common.enums.Direction
data class WarpTile(
val x: Int,
val y: Int,
val elevation: Int = 0,
val targetRegionId: Byte,
val targetBankId: Byte,
val targetMapId: Byte,
val targetX: Int,
val targetY: Int,
val targetElevation: Int = 0,
val facingDirection: Direction? = null,
)
@@ -0,0 +1,5 @@
package de.fiereu.openmmo.maps
data class WildEncounterTable(val encounterRate: Int, val pokemon: List<WildPokemon>)
data class WildPokemon(val dexId: Int, val minLevel: Int, val maxLevel: Int, val weight: Int)
@@ -1,16 +1,15 @@
plugins { plugins {
id("buildsrc.convention.kotlin-jvm") id("buildsrc.convention.kotlin-jvm")
id("buildsrc.convention.spotless") id("buildsrc.convention.spotless")
id("buildsrc.convention.sonarlint")
} }
dependencies { dependencies {
api(libs.kotlinx.serialization.core) api(project(":bytecodec"))
api(libs.netty) api(libs.netty)
api(libs.ineter) api(libs.kotlinx.coroutines)
implementation(libs.slf4j)
implementation(libs.kotlin.logging) implementation(libs.kotlin.logging)
implementation(libs.kotlin.reflect)
testImplementation(libs.bundles.kotest) testImplementation(libs.bundles.kotest)
testImplementation(libs.kotlinx.coroutines.test)
testRuntimeOnly(libs.logback)
} }
@@ -0,0 +1,48 @@
package de.fiereu.network
import io.netty.bootstrap.Bootstrap
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
fun ServerBootstrap.installNetwork(
identity: SessionIdentity.ServerRoot,
applicationProtocol: Protocol,
applicationHandlerFactory: () -> ProtocolHandler,
options: PipelineOptions = PipelineOptions(),
): ServerBootstrap =
childHandler(
object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
installPipeline(
pipeline = ch.pipeline(),
side = Side.SERVER,
identity = identity,
applicationProtocol = applicationProtocol,
applicationHandlerFactory = applicationHandlerFactory,
options = options,
)
}
},
)
fun Bootstrap.installNetwork(
identity: SessionIdentity.ClientTrust,
applicationProtocol: Protocol,
applicationHandlerFactory: () -> ProtocolHandler,
options: PipelineOptions = PipelineOptions(),
): Bootstrap =
handler(
object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
installPipeline(
pipeline = ch.pipeline(),
side = Side.CLIENT,
identity = identity,
applicationProtocol = applicationProtocol,
applicationHandlerFactory = applicationHandlerFactory,
options = options,
)
}
},
)
@@ -0,0 +1,14 @@
package de.fiereu.network
enum class Direction {
C2S,
S2C;
fun isIncomingFor(side: Side): Boolean =
when (this) {
C2S -> side == Side.SERVER
S2C -> side == Side.CLIENT
}
fun isOutgoingFor(side: Side): Boolean = !isIncomingFor(side)
}
@@ -0,0 +1,31 @@
package de.fiereu.network
import kotlin.reflect.KClass
open class NetworkException(message: String, cause: Throwable? = null) :
RuntimeException(message, cause)
class UnknownOpcodeException(val opcode: UByte, val side: Side) :
NetworkException("No incoming codec for opcode 0x${opcode.toString(16)} on $side")
class UnknownPacketTypeException(val type: KClass<*>, val side: Side) :
NetworkException("No outgoing registration for ${type.simpleName} on $side")
class ChecksumMismatchException : NetworkException("Checksum verification failed")
class TrailingBytesException(val opcode: UByte, val remaining: Int) :
NetworkException(
"Codec for opcode 0x${opcode.toString(16)} did not consume $remaining trailing byte(s)")
class EmptyFrameException : NetworkException("Received empty frame")
open class HandshakeException(message: String, cause: Throwable? = null) :
NetworkException(message, cause)
class StaleClientHelloException(val skewSeconds: Long) :
HandshakeException("ClientHello timestamp drift: ${skewSeconds}s")
class InvalidServerSignatureException :
HandshakeException("ServerHello signature does not match trusted root key")
class HandlerRegistrationException(message: String) : NetworkException(message)
@@ -0,0 +1,29 @@
package de.fiereu.network
import de.fiereu.bytecodec.ReadBuffer
import de.fiereu.bytecodec.WriteBuffer
import io.netty.buffer.ByteBuf
class NettyReadBuffer(private val buf: ByteBuf) : ReadBuffer {
override fun readByte(): Byte = buf.readByte()
override fun readBytes(dst: ByteArray, offset: Int, length: Int) {
buf.readBytes(dst, offset, length)
}
override fun skip(n: Int) {
buf.skipBytes(n)
}
override fun remaining(): Int = buf.readableBytes()
}
class NettyWriteBuffer(private val buf: ByteBuf) : WriteBuffer {
override fun writeByte(value: Byte) {
buf.writeByte(value.toInt())
}
override fun writeBytes(src: ByteArray, offset: Int, length: Int) {
buf.writeBytes(src, offset, length)
}
}
@@ -0,0 +1,12 @@
package de.fiereu.network
import io.netty.channel.ChannelFuture
data class PacketEvent<T : Any>(
val packet: T,
val session: SessionContext,
)
fun PacketEvent<*>.respond(packet: Any): ChannelFuture = session.send(packet)
fun PacketEvent<*>.disconnect(reason: () -> String = { "no reason" }) = session.close(reason)
@@ -0,0 +1,76 @@
package de.fiereu.network
import de.fiereu.network.checksum.NoOpChecksum
import de.fiereu.network.cipher.NoOpSessionCipher
import de.fiereu.network.handlers.ChecksumFrameDecoder
import de.fiereu.network.handlers.ChecksumFrameEncoder
import de.fiereu.network.handlers.CipherDecoder
import de.fiereu.network.handlers.CipherEncoder
import de.fiereu.network.handlers.PacketFrameDecoder
import de.fiereu.network.handlers.PacketFrameEncoder
import de.fiereu.network.handshake.ClientSessionHandshakeHandler
import de.fiereu.network.handshake.ServerSessionHandshakeHandler
import de.fiereu.network.internal.MutableSessionContext
import de.fiereu.network.internal.SESSION_KEY
import io.netty.channel.ChannelPipeline
import io.netty.handler.logging.LogLevel
import io.netty.handler.logging.LoggingHandler
import io.netty.handler.timeout.WriteTimeoutHandler
import java.util.concurrent.TimeUnit
fun installPipeline(
pipeline: ChannelPipeline,
side: Side,
identity: SessionIdentity,
applicationProtocol: Protocol,
applicationHandlerFactory: () -> ProtocolHandler,
options: PipelineOptions = PipelineOptions(),
) {
val channel = pipeline.channel()
val session = MutableSessionContext(side, channel, applicationProtocol)
channel.attr(SESSION_KEY).set(session)
val handshakeHandler: ProtocolHandler =
when (side) {
Side.SERVER -> {
require(identity is SessionIdentity.ServerRoot) {
"Server side requires SessionIdentity.ServerRoot"
}
ServerSessionHandshakeHandler(
rootPrivate = identity.rootPrivate,
applicationProtocol = applicationProtocol,
applicationHandlerFactory = applicationHandlerFactory,
options = options,
)
}
Side.CLIENT -> {
require(identity is SessionIdentity.ClientTrust) {
"Client side requires SessionIdentity.ClientTrust"
}
ClientSessionHandshakeHandler(
rootPublic = identity.rootPublic,
applicationProtocol = applicationProtocol,
applicationHandlerFactory = applicationHandlerFactory,
options = options,
)
}
}
pipeline.addLast(
PipelineNames.WRITE_TIMEOUT,
WriteTimeoutHandler(options.writeTimeout.inWholeSeconds, TimeUnit.SECONDS),
)
if (options.frameLogging) {
pipeline.addLast(PipelineNames.FRAME_LOGGER, LoggingHandler(LogLevel.TRACE))
}
pipeline.addLast(PipelineNames.FRAME_DECODER, PacketFrameDecoder(options.maxFrameLength))
pipeline.addLast(PipelineNames.FRAME_ENCODER, PacketFrameEncoder())
pipeline.addLast(PipelineNames.CHECKSUM_DECODER, ChecksumFrameDecoder(NoOpChecksum))
pipeline.addLast(PipelineNames.CHECKSUM_ENCODER, ChecksumFrameEncoder(NoOpChecksum))
pipeline.addLast(PipelineNames.CIPHER_DECODER, CipherDecoder(NoOpSessionCipher))
pipeline.addLast(PipelineNames.CIPHER_ENCODER, CipherEncoder(NoOpSessionCipher))
if (options.frameLogging) {
pipeline.addLast(PipelineNames.PROTOCOL_LOGGER, LoggingHandler(LogLevel.TRACE))
}
pipeline.addLast(PipelineNames.PROTOCOL_HANDLER, handshakeHandler)
}
@@ -0,0 +1,16 @@
package de.fiereu.network
object PipelineNames {
const val WRITE_TIMEOUT = "write-timeout"
const val FRAME_LOGGER = "frame-logger"
const val FRAME_DECODER = "frame-decoder"
const val FRAME_ENCODER = "frame-encoder"
const val CHECKSUM_DECODER = "checksum-decoder"
const val CHECKSUM_ENCODER = "checksum-encoder"
const val CIPHER_DECODER = "cipher-decoder"
const val CIPHER_ENCODER = "cipher-encoder"
const val COMPRESSION_DECODER = "compression-decoder"
const val COMPRESSION_ENCODER = "compression-encoder"
const val PROTOCOL_LOGGER = "protocol-logger"
const val PROTOCOL_HANDLER = "protocol-handler"
}
@@ -0,0 +1,14 @@
package de.fiereu.network
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
data class PipelineOptions(
val checksumSize: Int = 16,
val writeTimeout: Duration = 25.minutes,
val maxFrameLength: Int = 0xFFFF,
val compressionThreshold: Int = 256,
val maxHelloSkew: Duration = 10.seconds,
val frameLogging: Boolean = false,
)
@@ -0,0 +1,73 @@
package de.fiereu.network
import de.fiereu.bytecodec.Codec
import kotlin.reflect.KClass
abstract class Protocol {
open val compressed: Boolean = false
data class Registration<T : Any>(
val opcode: UByte,
val direction: Direction,
val codec: Codec<T>,
val type: KClass<T>,
)
private val mutableRegistrations = mutableListOf<Registration<*>>()
private val byOpcode = mutableMapOf<Pair<UByte, Direction>, Registration<*>>()
private val byType = mutableMapOf<Pair<KClass<*>, Direction>, Registration<*>>()
val registrations: List<Registration<*>>
get() = mutableRegistrations
fun <T : Any> c2s(opcode: UByte, codec: Codec<T>, type: KClass<T>) {
register(Registration(opcode, Direction.C2S, codec, type))
}
fun <T : Any> s2c(opcode: UByte, codec: Codec<T>, type: KClass<T>) {
register(Registration(opcode, Direction.S2C, codec, type))
}
fun <T : Any> bidi(opcode: UByte, codec: Codec<T>, type: KClass<T>) {
register(Registration(opcode, Direction.C2S, codec, type))
register(Registration(opcode, Direction.S2C, codec, type))
}
private fun register(reg: Registration<*>) {
val opKey = reg.opcode to reg.direction
check(byOpcode.put(opKey, reg) == null) {
"Duplicate registration for opcode 0x${reg.opcode.toString(16)} ${reg.direction}"
}
val typeKey = reg.type to reg.direction
check(byType.put(typeKey, reg) == null) {
"Duplicate registration for ${reg.type.simpleName} ${reg.direction}"
}
mutableRegistrations += reg
}
fun incomingCodec(side: Side, opcode: UByte): Codec<*>? =
incomingRegistration(side, opcode)?.codec
fun incomingRegistration(side: Side, opcode: UByte): Registration<*>? {
val direction = if (side == Side.SERVER) Direction.C2S else Direction.S2C
return byOpcode[opcode to direction]
}
fun outgoingRegistration(side: Side, type: KClass<*>): Registration<*>? {
val direction = if (side == Side.SERVER) Direction.S2C else Direction.C2S
return byType[type to direction]
}
}
inline fun <reified T : Any> Protocol.c2s(opcode: UByte, codec: Codec<T>) {
c2s(opcode, codec, T::class)
}
inline fun <reified T : Any> Protocol.s2c(opcode: UByte, codec: Codec<T>) {
s2c(opcode, codec, T::class)
}
inline fun <reified T : Any> Protocol.bidi(opcode: UByte, codec: Codec<T>) {
bidi(opcode, codec, T::class)
}
@@ -0,0 +1,132 @@
package de.fiereu.network
import de.fiereu.bytecodec.Codec
import de.fiereu.network.internal.OutgoingPacket
import de.fiereu.network.internal.SESSION_KEY
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelDuplexHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPromise
private val log = KotlinLogging.logger {}
abstract class ProtocolHandler(
val protocol: Protocol,
val side: Side,
) : ChannelDuplexHandler() {
protected lateinit var session: SessionContext
private set
override fun handlerAdded(ctx: ChannelHandlerContext) {
val attached =
ctx.channel().attr(SESSION_KEY).get()
?: error("No SessionContext attached to channel ${ctx.channel()}")
session = attached
}
override fun channelActive(ctx: ChannelHandlerContext) {
try {
onActive()
} catch (t: Throwable) {
onErrorInternal(ctx, t)
return
}
ctx.fireChannelActive()
}
override fun channelInactive(ctx: ChannelHandlerContext) {
try {
onInactive()
} finally {
ctx.fireChannelInactive()
}
}
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
if (msg !is ByteBuf) {
ctx.fireChannelRead(msg)
return
}
try {
if (msg.readableBytes() < 1) throw EmptyFrameException()
val opcode = (msg.readByte().toInt() and 0xFF).toUByte()
val registration = protocol.incomingRegistration(side, opcode)
if (registration == null) {
log.error { "No incoming codec for opcode 0x${opcode.toString(16)} on $side" }
return
}
val packet = decode(registration.codec, msg)
val trailing = msg.readableBytes()
if (trailing > 0) throw TrailingBytesException(opcode, trailing)
try {
onPacket(PacketEvent(packet, session))
} catch (t: Throwable) {
onErrorInternal(ctx, t)
}
} catch (t: Throwable) {
onErrorInternal(ctx, t)
} finally {
msg.release()
}
}
override fun write(ctx: ChannelHandlerContext, msg: Any, promise: ChannelPromise) {
val (registration, value) =
when (msg) {
is OutgoingPacket -> msg.registration to msg.value
is ByteBuf -> {
ctx.write(msg, promise)
return
}
else -> {
val reg =
protocol.outgoingRegistration(side, msg::class)
?: throw UnknownPacketTypeException(msg::class, side)
reg to msg
}
}
val buffer = ctx.alloc().buffer()
var success = false
try {
buffer.writeByte(registration.opcode.toInt())
encode(registration.codec, value, buffer)
success = true
} finally {
if (!success) buffer.release()
}
ctx.write(buffer, promise)
}
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
onErrorInternal(ctx, cause)
}
private fun onErrorInternal(ctx: ChannelHandlerContext, cause: Throwable) {
try {
onError(cause)
} catch (t: Throwable) {
log.error(t) { "onError handler threw; closing channel" }
ctx.close()
}
}
open fun onActive() {}
abstract fun onPacket(event: PacketEvent<*>)
open fun onInactive() {}
open fun onError(cause: Throwable) {
log.warn(cause) { "Handler error on ${session.remoteAddress}" }
session.close { "Handler error: ${cause.message}" }
}
private fun <T : Any> decode(codec: Codec<T>, buf: ByteBuf): T = codec.read(NettyReadBuffer(buf))
@Suppress("UNCHECKED_CAST")
private fun encode(codec: Codec<*>, value: Any, buf: ByteBuf) {
(codec as Codec<Any>).write(NettyWriteBuffer(buf), value)
}
}
@@ -0,0 +1,24 @@
package de.fiereu.network
import kotlin.reflect.KClass
class SessionAttribute<T : Any>(val name: String, val type: KClass<T>) {
override fun toString(): String = "SessionAttribute($name)"
companion object {
inline fun <reified T : Any> of(name: String): SessionAttribute<T> =
SessionAttribute(name, T::class)
}
}
interface SessionAttributes {
operator fun <T : Any> get(key: SessionAttribute<T>): T?
operator fun <T : Any> set(key: SessionAttribute<T>, value: T)
fun <T : Any> remove(key: SessionAttribute<T>): T?
fun <T : Any> getOrPut(key: SessionAttribute<T>, default: () -> T): T
fun contains(key: SessionAttribute<*>): Boolean
}
@@ -0,0 +1,26 @@
package de.fiereu.network
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import java.net.SocketAddress
import java.time.Instant
interface SessionContext {
val side: Side
val channel: Channel
val remoteAddress: SocketAddress
val phase: SessionPhase
val handshakeCompletedAt: Instant?
val attributes: SessionAttributes
fun send(packet: Any): ChannelFuture
fun close(reason: () -> String = { "no reason" })
fun onPhase(phase: SessionPhase, listener: () -> Unit)
}
@@ -0,0 +1,10 @@
package de.fiereu.network
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
sealed interface SessionIdentity {
data class ServerRoot(val rootPrivate: ECPrivateKey) : SessionIdentity
data class ClientTrust(val rootPublic: ECPublicKey) : SessionIdentity
}
@@ -0,0 +1,7 @@
package de.fiereu.network
enum class SessionPhase {
HANDSHAKE,
ESTABLISHED,
CLOSED,
}
@@ -0,0 +1,7 @@
package de.fiereu.network
import de.fiereu.network.internal.SESSION_KEY
import io.netty.channel.Channel
/** Look up the [SessionContext] attached by [installPipeline] for this channel. */
fun Channel.session(): SessionContext? = attr(SESSION_KEY).get()
@@ -0,0 +1,6 @@
package de.fiereu.network
enum class Side {
SERVER,
CLIENT,
}
@@ -0,0 +1,54 @@
package de.fiereu.network
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlin.reflect.KClass
private val log = KotlinLogging.logger {}
abstract class TypedProtocolHandler<P : Protocol>(
protocol: P,
side: Side,
) : ProtocolHandler(protocol, side) {
@Volatile private var sealed = false
private val handlers = mutableMapOf<KClass<*>, (PacketEvent<*>) -> Unit>()
protected inline fun <reified T : Any> on(noinline handler: (PacketEvent<T>) -> Unit) {
register(T::class, handler)
}
@PublishedApi
internal fun <T : Any> register(type: KClass<T>, handler: (PacketEvent<T>) -> Unit) {
if (sealed) {
throw HandlerRegistrationException(
"Cannot register handler for ${type.simpleName} after the first packet",
)
}
if (handlers.containsKey(type)) {
throw HandlerRegistrationException(
"Duplicate handler registration for ${type.simpleName}",
)
}
@Suppress("UNCHECKED_CAST")
handlers[type] = handler as (PacketEvent<*>) -> Unit
}
open fun isRegistered(type: KClass<*>): Boolean = handlers.containsKey(type)
protected open fun onUnhandled(event: PacketEvent<*>) {
log.error { "Unhandled packet ${event.packet::class.simpleName} on $side" }
}
final override fun onPacket(event: PacketEvent<*>) {
sealed = true
val handler = handlers[event.packet::class]
if (handler != null) {
handler(event)
} else if (!tryHandleAlternate(event)) {
onUnhandled(event)
}
}
protected open fun tryHandleAlternate(event: PacketEvent<*>): Boolean = false
}
@@ -0,0 +1,11 @@
package de.fiereu.network.checksum
import io.netty.buffer.ByteBuf
interface Checksum {
val size: Int
fun calculate(data: ByteBuf): ByteArray
fun verify(data: ByteBuf, expected: ByteArray): Boolean
}
@@ -0,0 +1,11 @@
package de.fiereu.network.checksum
object ChecksumFactory {
fun create(size: Int, key: ByteArray = ByteArray(0)): Checksum =
when (size) {
0 -> NoOpChecksum
2 -> Crc16Checksum()
in 4..32 -> HmacSha256Checksum(size, key)
else -> throw IllegalArgumentException("Unsupported checksum size: $size")
}
}
@@ -0,0 +1,293 @@
package de.fiereu.network.checksum
import io.netty.buffer.ByteBuf
class Crc16Checksum : Checksum {
override val size: Int = 2
override fun calculate(data: ByteBuf): ByteArray {
val sum = hash(data)
return byteArrayOf((sum and 0xFF).toByte(), ((sum shr 8) and 0xFF).toByte())
}
override fun verify(data: ByteBuf, expected: ByteArray): Boolean {
if (expected.size != size) return false
val actual = hash(data)
val expectedSum = ((expected[1].toInt() and 0xFF) shl 8) or (expected[0].toInt() and 0xFF)
return actual == expectedSum
}
private fun hash(data: ByteBuf): Int {
var sum = 0
val end = data.writerIndex()
var i = data.readerIndex()
while (i < end) {
val b = data.getByte(i).toInt() and 0xFF
sum = (sum ushr 8) xor TABLE[(sum xor b) and 0xFF]
i++
}
return sum and 0xFFFF
}
companion object {
private val TABLE =
intArrayOf(
0x0000,
0xc0c1,
0xc181,
0x0140,
0xc301,
0x03c0,
0x0280,
0xc241,
0xc601,
0x06c0,
0x0780,
0xc741,
0x0500,
0xc5c1,
0xc481,
0x0440,
0xcc01,
0x0cc0,
0x0d80,
0xcd41,
0x0f00,
0xcfc1,
0xce81,
0x0e40,
0x0a00,
0xcac1,
0xcb81,
0x0b40,
0xc901,
0x09c0,
0x0880,
0xc841,
0xd801,
0x18c0,
0x1980,
0xd941,
0x1b00,
0xdbc1,
0xda81,
0x1a40,
0x1e00,
0xdec1,
0xdf81,
0x1f40,
0xdd01,
0x1dc0,
0x1c80,
0xdc41,
0x1400,
0xd4c1,
0xd581,
0x1540,
0xd701,
0x17c0,
0x1680,
0xd641,
0xd201,
0x12c0,
0x1380,
0xd341,
0x1100,
0xd1c1,
0xd081,
0x1040,
0xf001,
0x30c0,
0x3180,
0xf141,
0x3300,
0xf3c1,
0xf281,
0x3240,
0x3600,
0xf6c1,
0xf781,
0x3740,
0xf501,
0x35c0,
0x3480,
0xf441,
0x3c00,
0xfcc1,
0xfd81,
0x3d40,
0xff01,
0x3fc0,
0x3e80,
0xfe41,
0xfa01,
0x3ac0,
0x3b80,
0xfb41,
0x3900,
0xf9c1,
0xf881,
0x3840,
0x2800,
0xe8c1,
0xe981,
0x2940,
0xeb01,
0x2bc0,
0x2a80,
0xea41,
0xee01,
0x2ec0,
0x2f80,
0xef41,
0x2d00,
0xedc1,
0xec81,
0x2c40,
0xe401,
0x24c0,
0x2580,
0xe541,
0x2700,
0xe7c1,
0xe681,
0x2640,
0x2200,
0xe2c1,
0xe381,
0x2340,
0xe101,
0x21c0,
0x2080,
0xe041,
0xa001,
0x60c0,
0x6180,
0xa141,
0x6300,
0xa3c1,
0xa281,
0x6240,
0x6600,
0xa6c1,
0xa781,
0x6740,
0xa501,
0x65c0,
0x6480,
0xa441,
0x6c00,
0xacc1,
0xad81,
0x6d40,
0xaf01,
0x6fc0,
0x6e80,
0xae41,
0xaa01,
0x6ac0,
0x6b80,
0xab41,
0x6900,
0xa9c1,
0xa881,
0x6840,
0x7800,
0xb8c1,
0xb981,
0x7940,
0xbb01,
0x7bc0,
0x7a80,
0xba41,
0xbe01,
0x7ec0,
0x7f80,
0xbf41,
0x7d00,
0xbdc1,
0xbc81,
0x7c40,
0xb401,
0x74c0,
0x7580,
0xb541,
0x7700,
0xb7c1,
0xb681,
0x7640,
0x7200,
0xb2c1,
0xb381,
0x7340,
0xb101,
0x71c0,
0x7080,
0xb041,
0x5000,
0x90c1,
0x9181,
0x5140,
0x9301,
0x53c0,
0x5280,
0x9241,
0x9601,
0x56c0,
0x5780,
0x9741,
0x5500,
0x95c1,
0x9481,
0x5440,
0x9c01,
0x5cc0,
0x5d80,
0x9d41,
0x5f00,
0x9fc1,
0x9e81,
0x5e40,
0x5a00,
0x9ac1,
0x9b81,
0x5b40,
0x9901,
0x59c0,
0x5880,
0x9841,
0x8801,
0x48c0,
0x4980,
0x8941,
0x4b00,
0x8bc1,
0x8a81,
0x4a40,
0x4e00,
0x8ec1,
0x8f81,
0x4f40,
0x8d01,
0x4dc0,
0x4c80,
0x8c41,
0x4400,
0x84c1,
0x8581,
0x4540,
0x8701,
0x47c0,
0x4680,
0x8641,
0x8201,
0x42c0,
0x4380,
0x8341,
0x4100,
0x81c1,
0x8081,
0x4040,
)
}
}
@@ -0,0 +1,48 @@
package de.fiereu.network.checksum
import io.netty.buffer.ByteBuf
import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
class HmacSha256Checksum(
override val size: Int,
key: ByteArray,
) : Checksum {
init {
require(size in 4..32) { "HMAC-SHA256 size must be between 4 and 32 bytes" }
}
private val mac: Mac =
Mac.getInstance("HmacSHA256").also { it.init(SecretKeySpec(key, "HmacSHA256")) }
private var calculateRound = 0
private var verifyRound = 0
override fun calculate(data: ByteBuf): ByteArray {
val bytes = ByteArray(data.readableBytes())
data.getBytes(data.readerIndex(), bytes)
mac.update(bytes)
mac.update(roundBytes(calculateRound++))
return mac.doFinal().copyOfRange(0, size)
}
override fun verify(data: ByteBuf, expected: ByteArray): Boolean {
if (expected.size != size) return false
val bytes = ByteArray(data.readableBytes())
data.getBytes(data.readerIndex(), bytes)
mac.update(bytes)
mac.update(roundBytes(verifyRound++))
val actual = mac.doFinal().copyOfRange(0, size)
return MessageDigest.isEqual(actual, expected)
}
private fun roundBytes(value: Int): ByteArray =
byteArrayOf(
((value ushr 24) and 0xFF).toByte(),
((value ushr 16) and 0xFF).toByte(),
((value ushr 8) and 0xFF).toByte(),
(value and 0xFF).toByte(),
)
}
@@ -0,0 +1,13 @@
package de.fiereu.network.checksum
import io.netty.buffer.ByteBuf
object NoOpChecksum : Checksum {
override val size: Int = 0
private val EMPTY = ByteArray(0)
override fun calculate(data: ByteBuf): ByteArray = EMPTY
override fun verify(data: ByteBuf, expected: ByteArray): Boolean = true
}
@@ -0,0 +1,93 @@
package de.fiereu.network.cipher
import io.netty.buffer.ByteBuf
import java.security.MessageDigest
import java.security.PrivateKey
import java.security.PublicKey
import javax.crypto.Cipher
import javax.crypto.KeyAgreement
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
class AesCtrSessionCipher
private constructor(
private val encryptCipher: Cipher,
private val decryptCipher: Cipher,
) : SessionCipher {
enum class Role {
SERVER,
CLIENT
}
override fun encrypt(input: ByteBuf, output: ByteBuf) {
apply(encryptCipher, input, output)
}
override fun decrypt(input: ByteBuf, output: ByteBuf) {
apply(decryptCipher, input, output)
}
private fun apply(cipher: Cipher, input: ByteBuf, output: ByteBuf) {
val len = input.readableBytes()
if (len == 0) return
val src = ByteArray(len)
input.readBytes(src)
val dst = cipher.update(src) ?: return
if (dst.isNotEmpty()) {
output.writeBytes(dst)
}
}
companion object {
private val IV_SALT = "IVDERIV".toByteArray(Charsets.US_ASCII)
private val CLIENT_KEY_SALT = "KeySalt".toByteArray(Charsets.US_ASCII) + byteArrayOf(1)
private val SERVER_KEY_SALT = "KeySalt".toByteArray(Charsets.US_ASCII) + byteArrayOf(2)
fun ecdh(localPrivate: PrivateKey, remotePublic: PublicKey): ByteArray {
val agreement = KeyAgreement.getInstance("ECDH")
agreement.init(localPrivate)
agreement.doPhase(remotePublic, true)
return agreement.generateSecret()
}
fun derive(secret: ByteArray, role: Role): AesCtrSessionCipher {
val (outSeed, inSeed) = directionalSeeds(secret, role)
return AesCtrSessionCipher(
encryptCipher = createCipher(Cipher.ENCRYPT_MODE, outSeed),
decryptCipher = createCipher(Cipher.DECRYPT_MODE, inSeed),
)
}
internal fun directionalSeeds(secret: ByteArray, role: Role): Pair<ByteArray, ByteArray> {
val clientSeed = tripleHash(secret, CLIENT_KEY_SALT)
val serverSeed = tripleHash(secret, SERVER_KEY_SALT)
return when (role) {
Role.SERVER -> serverSeed to clientSeed
Role.CLIENT -> clientSeed to serverSeed
}
}
fun derive(
localPrivate: PrivateKey,
remotePublic: PublicKey,
role: Role,
): AesCtrSessionCipher = derive(ecdh(localPrivate, remotePublic), role)
internal fun tripleHash(secret: ByteArray, salt: ByteArray): ByteArray {
val sha = MessageDigest.getInstance("SHA-256")
sha.update(salt)
sha.update(secret)
sha.update(salt)
return sha.digest().copyOfRange(0, 16)
}
private fun createCipher(mode: Int, seed: ByteArray): Cipher {
val cipher = Cipher.getInstance("AES/CTR/NoPadding")
val key = SecretKeySpec(seed, "AES")
val iv = IvParameterSpec(tripleHash(seed, IV_SALT))
cipher.init(mode, key, iv)
return cipher
}
}
}
@@ -0,0 +1,19 @@
package de.fiereu.network.cipher
import io.netty.buffer.ByteBuf
interface SessionCipher {
fun encrypt(input: ByteBuf, output: ByteBuf)
fun decrypt(input: ByteBuf, output: ByteBuf)
}
object NoOpSessionCipher : SessionCipher {
override fun encrypt(input: ByteBuf, output: ByteBuf) {
output.writeBytes(input)
}
override fun decrypt(input: ByteBuf, output: ByteBuf) {
output.writeBytes(input)
}
}
@@ -0,0 +1,84 @@
package de.fiereu.network.coroutines
import de.fiereu.network.HandlerRegistrationException
import de.fiereu.network.PacketEvent
import de.fiereu.network.Protocol
import de.fiereu.network.Side
import de.fiereu.network.TypedProtocolHandler
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.channel.ChannelHandlerContext
import kotlin.reflect.KClass
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
private val log = KotlinLogging.logger {}
abstract class CoroutineProtocolHandler<P : Protocol>(
protocol: P,
side: Side,
private val coroutineScope: CoroutineScope,
) : TypedProtocolHandler<P>(protocol, side) {
private val suspendHandlers = mutableMapOf<KClass<*>, suspend (PacketEvent<*>) -> Unit>()
private val mailbox: Channel<PacketEvent<*>> = Channel(Channel.UNLIMITED)
@Volatile private var consumerJob: Job? = null
protected inline fun <reified T : Any> onSuspend(
noinline handler: suspend (PacketEvent<T>) -> Unit,
) {
registerSuspend(T::class, handler)
}
@PublishedApi
internal fun <T : Any> registerSuspend(
type: KClass<T>,
handler: suspend (PacketEvent<T>) -> Unit,
) {
if (isRegistered(type) || suspendHandlers.containsKey(type)) {
throw HandlerRegistrationException(
"Duplicate handler registration for ${type.simpleName}",
)
}
@Suppress("UNCHECKED_CAST")
suspendHandlers[type] = handler as suspend (PacketEvent<*>) -> Unit
}
override fun handlerAdded(ctx: ChannelHandlerContext) {
super.handlerAdded(ctx)
consumerJob =
coroutineScope.launch {
for (event in mailbox) {
val handler = suspendHandlers[event.packet::class] ?: continue
try {
handler(event)
} catch (t: Throwable) {
log.warn(t) { "Suspend handler for ${event.packet::class.simpleName} threw" }
ctx.executor().execute { onError(t) }
}
}
}
}
override fun handlerRemoved(ctx: ChannelHandlerContext) {
mailbox.close()
consumerJob?.cancel()
consumerJob = null
}
override fun isRegistered(type: KClass<*>): Boolean =
super.isRegistered(type) || suspendHandlers.containsKey(type)
final override fun tryHandleAlternate(event: PacketEvent<*>): Boolean {
if (event.packet::class !in suspendHandlers) return false
val result = mailbox.trySend(event)
if (!result.isSuccess) {
log.warn { "Mailbox rejected packet ${event.packet::class.simpleName}" }
onError(IllegalStateException("Coroutine mailbox closed"))
}
return true
}
}
@@ -0,0 +1,33 @@
package de.fiereu.network.handlers
import de.fiereu.network.ChecksumMismatchException
import de.fiereu.network.checksum.Checksum
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
class ChecksumFrameDecoder(@Volatile var checksum: Checksum) : ByteToMessageDecoder() {
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
val checksum = this.checksum
val tagSize = checksum.size
val total = buffer.readableBytes()
if (tagSize == 0) {
out += buffer.readRetainedSlice(total)
return
}
if (total < tagSize) {
throw ChecksumMismatchException()
}
val payloadSize = total - tagSize
val expected = ByteArray(tagSize)
buffer.getBytes(buffer.readerIndex() + payloadSize, expected)
val payload = buffer.slice(buffer.readerIndex(), payloadSize)
if (!checksum.verify(payload, expected)) {
buffer.skipBytes(total)
throw ChecksumMismatchException()
}
out += payload.retain()
buffer.skipBytes(total)
}
}
@@ -0,0 +1,19 @@
package de.fiereu.network.handlers
import de.fiereu.network.checksum.Checksum
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
class ChecksumFrameEncoder(@Volatile var checksum: Checksum) : MessageToByteEncoder<ByteBuf>() {
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
val checksum = this.checksum
val len = msg.readableBytes()
val tag = if (checksum.size > 0) checksum.calculate(msg) else null
out.writeBytes(msg, msg.readerIndex(), len)
if (tag != null) {
out.writeBytes(tag)
}
}
}
@@ -0,0 +1,21 @@
package de.fiereu.network.handlers
import de.fiereu.network.cipher.SessionCipher
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
class CipherDecoder(@Volatile var cipher: SessionCipher) : ByteToMessageDecoder() {
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
val len = buffer.readableBytes()
if (len == 0) return
val output = ctx.alloc().buffer(len)
try {
cipher.decrypt(buffer, output)
out += output.retain()
} finally {
output.release()
}
}
}
@@ -0,0 +1,13 @@
package de.fiereu.network.handlers
import de.fiereu.network.cipher.SessionCipher
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
class CipherEncoder(@Volatile var cipher: SessionCipher) : MessageToByteEncoder<ByteBuf>() {
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
cipher.encrypt(msg, out)
}
}
@@ -0,0 +1,47 @@
package de.fiereu.network.handlers
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
import java.util.zip.Inflater
class CompressionDecoder : ByteToMessageDecoder() {
private val inflater = Inflater(true)
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
if (buffer.readableBytes() < 2) return
val opcode = buffer.readByte()
val flag = buffer.readByte().toInt()
val payloadLen = buffer.readableBytes()
val output = ctx.alloc().buffer(payloadLen * 2 + 1)
try {
output.writeByte(opcode.toInt())
if (flag == 0) {
output.writeBytes(buffer, buffer.readerIndex(), payloadLen)
buffer.skipBytes(payloadLen)
} else {
val input = ByteArray(payloadLen)
buffer.readBytes(input)
inflater.reset()
inflater.setInput(input)
val chunk = ByteArray(0x4000)
while (!inflater.finished() && !inflater.needsInput()) {
val written = inflater.inflate(chunk)
if (written == 0) break
output.writeBytes(chunk, 0, written)
}
if (output.readableBytes() >= 2) {
output.writerIndex(output.writerIndex() - 2)
}
}
out += output.retain()
} finally {
output.release()
}
}
override fun handlerRemoved0(ctx: ChannelHandlerContext) {
inflater.end()
}
}
@@ -0,0 +1,42 @@
package de.fiereu.network.handlers
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToByteEncoder
import java.util.zip.Deflater
class CompressionEncoder(private val threshold: Int = 256) : MessageToByteEncoder<ByteBuf>() {
private val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true)
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
if (msg.readableBytes() < 1) return
val opcode = msg.readByte()
out.writeByte(opcode.toInt())
val payloadLen = msg.readableBytes()
if (payloadLen < threshold) {
out.writeByte(0)
out.writeBytes(msg, msg.readerIndex(), payloadLen)
msg.skipBytes(payloadLen)
return
}
val input = ByteArray(payloadLen + 2)
msg.getBytes(msg.readerIndex(), input, 0, payloadLen)
input[payloadLen] = 0xFF.toByte()
input[payloadLen + 1] = 0xFF.toByte()
msg.skipBytes(payloadLen)
out.writeByte(1)
deflater.reset()
deflater.setInput(input)
val chunk = ByteArray(0x4000)
while (true) {
val written = deflater.deflate(chunk, 0, chunk.size, Deflater.SYNC_FLUSH)
if (written == 0) break
out.writeBytes(chunk, 0, written)
}
}
override fun handlerRemoved(ctx: ChannelHandlerContext) {
deflater.end()
}
}
@@ -0,0 +1,15 @@
package de.fiereu.network.handlers
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
import java.nio.ByteOrder
class PacketFrameDecoder(maxFrameLength: Int = 0xFFFF) :
LengthFieldBasedFrameDecoder(
ByteOrder.LITTLE_ENDIAN,
maxFrameLength,
0,
UShort.SIZE_BYTES,
-UShort.SIZE_BYTES,
UShort.SIZE_BYTES,
false,
)
@@ -0,0 +1,12 @@
package de.fiereu.network.handlers
import io.netty.handler.codec.LengthFieldPrepender
import java.nio.ByteOrder
class PacketFrameEncoder :
LengthFieldPrepender(
ByteOrder.LITTLE_ENDIAN,
UShort.SIZE_BYTES,
0,
true,
)
@@ -0,0 +1,76 @@
package de.fiereu.network.handshake
import de.fiereu.network.InvalidServerSignatureException
import de.fiereu.network.PipelineNames
import de.fiereu.network.PipelineOptions
import de.fiereu.network.Protocol
import de.fiereu.network.ProtocolHandler
import de.fiereu.network.SessionPhase
import de.fiereu.network.Side
import de.fiereu.network.TypedProtocolHandler
import de.fiereu.network.cipher.AesCtrSessionCipher
import de.fiereu.network.handlers.ChecksumFrameDecoder
import de.fiereu.network.handlers.ChecksumFrameEncoder
import de.fiereu.network.handlers.CipherDecoder
import de.fiereu.network.handlers.CipherEncoder
import de.fiereu.network.handlers.CompressionDecoder
import de.fiereu.network.internal.MutableSessionContext
import io.github.oshai.kotlinlogging.KotlinLogging
import java.security.interfaces.ECPublicKey
private val log = KotlinLogging.logger {}
internal class ClientSessionHandshakeHandler(
private val rootPublic: ECPublicKey,
private val applicationProtocol: Protocol,
private val applicationHandlerFactory: () -> ProtocolHandler,
private val options: PipelineOptions,
) : TypedProtocolHandler<SessionHandshakeProtocol>(SessionHandshakeProtocol, Side.CLIENT) {
private val ephemeralKeyPair = EcKeys.generateEphemeralKeyPair()
override fun onActive() {
session.send(ClientHelloPacket(timestamp = System.currentTimeMillis()))
}
init {
on<ServerHelloPacket> { event ->
val publicBytes = EcKeys.toUncompressedPoint(event.packet.ephemeralPublic)
if (!EcKeys.verify(rootPublic, publicBytes, event.packet.signature)) {
throw InvalidServerSignatureException()
}
val crypto =
SessionCryptoState.derive(
localPrivate = ephemeralKeyPair.private,
remotePublic = event.packet.ephemeralPublic,
role = AesCtrSessionCipher.Role.CLIENT,
checksumSize = event.packet.checksumSize,
)
event.session.send(
ClientReadyPacket(ephemeralPublic = ephemeralKeyPair.public as ECPublicKey),
)
val pipeline = event.session.channel.pipeline()
(pipeline.get(PipelineNames.CHECKSUM_DECODER) as ChecksumFrameDecoder).checksum =
crypto.incomingChecksum
(pipeline.get(PipelineNames.CHECKSUM_ENCODER) as ChecksumFrameEncoder).checksum =
crypto.outgoingChecksum
(pipeline.get(PipelineNames.CIPHER_DECODER) as CipherDecoder).cipher = crypto.cipher
(pipeline.get(PipelineNames.CIPHER_ENCODER) as CipherEncoder).cipher = crypto.cipher
if (applicationProtocol.compressed) {
pipeline.addBefore(
PipelineNames.PROTOCOL_HANDLER,
PipelineNames.COMPRESSION_DECODER,
CompressionDecoder(),
)
}
val appHandler = applicationHandlerFactory()
pipeline.replace(
PipelineNames.PROTOCOL_HANDLER,
PipelineNames.PROTOCOL_HANDLER,
appHandler,
)
(event.session as MutableSessionContext).transitionTo(SessionPhase.ESTABLISHED)
log.debug { "Client handshake complete with ${event.session.remoteAddress}" }
}
}
}
@@ -0,0 +1,78 @@
package de.fiereu.network.handshake
import java.math.BigInteger
import java.security.AlgorithmParameters
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.Signature
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
import java.security.spec.ECGenParameterSpec
import java.security.spec.ECParameterSpec
import java.security.spec.ECPoint
import java.security.spec.ECPublicKeySpec
internal object EcKeys {
private const val UNCOMPRESSED_INDICATOR: Byte = 0x04
private const val CURVE = "secp256r1"
private val keyFactory = KeyFactory.getInstance("EC")
private val parameters: ECParameterSpec by lazy {
val params = AlgorithmParameters.getInstance("EC")
params.init(ECGenParameterSpec(CURVE))
params.getParameterSpec(ECParameterSpec::class.java)
}
private val keyByteLength: Int by lazy {
(parameters.order.bitLength() + Byte.SIZE_BITS - 1) / Byte.SIZE_BITS
}
fun generateEphemeralKeyPair(): KeyPair {
val gen = KeyPairGenerator.getInstance("EC")
gen.initialize(ECGenParameterSpec(CURVE))
return gen.generateKeyPair()
}
fun toUncompressedPoint(key: ECPublicKey): ByteArray {
val point = key.w
val keyLength = keyByteLength
val data = ByteArray(1 + 2 * keyLength)
data[0] = UNCOMPRESSED_INDICATOR
writeFieldInto(data, 1, point.affineX.toByteArray(), keyLength)
writeFieldInto(data, 1 + keyLength, point.affineY.toByteArray(), keyLength)
return data
}
fun fromUncompressedPoint(bytes: ByteArray): ECPublicKey {
require(bytes.isNotEmpty() && bytes[0] == UNCOMPRESSED_INDICATOR) {
"Invalid uncompressed point indicator"
}
val keyLength = keyByteLength
require(bytes.size == 1 + 2 * keyLength) { "Invalid EC point length: ${bytes.size}" }
val x = BigInteger(1, bytes.copyOfRange(1, 1 + keyLength))
val y = BigInteger(1, bytes.copyOfRange(1 + keyLength, 1 + 2 * keyLength))
return keyFactory.generatePublic(ECPublicKeySpec(ECPoint(x, y), parameters)) as ECPublicKey
}
private fun writeFieldInto(dst: ByteArray, offset: Int, src: ByteArray, length: Int) {
when {
src.size <= length -> System.arraycopy(src, 0, dst, offset + length - src.size, src.size)
src.size == length + 1 && src[0] == 0.toByte() ->
System.arraycopy(src, 1, dst, offset, length)
else -> error("EC coordinate too large: ${src.size}")
}
}
fun sign(privateKey: ECPrivateKey, data: ByteArray): ByteArray {
val sig = Signature.getInstance("SHA256withECDSA")
sig.initSign(privateKey)
sig.update(data)
return sig.sign()
}
fun verify(publicKey: ECPublicKey, data: ByteArray, signature: ByteArray): Boolean {
val sig = Signature.getInstance("SHA256withECDSA")
sig.initVerify(publicKey)
sig.update(data)
return sig.verify(signature)
}
}
@@ -0,0 +1,69 @@
package de.fiereu.network.handshake
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.S64LE
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
import de.fiereu.bytecodec.bytesPrefixed
import java.security.interfaces.ECPublicKey
import kotlin.random.Random
private const val XOR_KEY_RANDOM = 3214621489648854472L
private const val XOR_KEY_TIMESTAMP = -4214651440992349575L
data class ClientHelloPacket(val timestamp: Long)
data class ServerHelloPacket(
val ephemeralPublic: ECPublicKey,
val signature: ByteArray,
val checksumSize: Int,
) {
override fun equals(other: Any?): Boolean =
other is ServerHelloPacket &&
ephemeralPublic == other.ephemeralPublic &&
signature.contentEquals(other.signature) &&
checksumSize == other.checksumSize
override fun hashCode(): Int =
(ephemeralPublic.hashCode() * 31 + signature.contentHashCode()) * 31 + checksumSize
}
data class ClientReadyPacket(val ephemeralPublic: ECPublicKey)
object ClientHelloCodec : PacketCodec<ClientHelloPacket>() {
override fun CodecScope<ClientHelloPacket>.body(): ClientHelloPacket {
var random = 0L
val xoredRandom =
field(S64LE) {
random = Random.nextLong()
random xor XOR_KEY_RANDOM
}
val xoredTimestamp = field(S64LE) { it.timestamp xor XOR_KEY_TIMESTAMP xor random }
val readRandom = xoredRandom xor XOR_KEY_RANDOM
val timestamp = xoredTimestamp xor XOR_KEY_TIMESTAMP xor readRandom
return ClientHelloPacket(timestamp)
}
}
private val LengthPrefixedBytes = bytesPrefixed(U16LE)
object ServerHelloCodec : PacketCodec<ServerHelloPacket>() {
override fun CodecScope<ServerHelloPacket>.body(): ServerHelloPacket {
val pubKey = field(LengthPrefixedBytes) { EcKeys.toUncompressedPoint(it.ephemeralPublic) }
val signature = field(LengthPrefixedBytes, ServerHelloPacket::signature)
val checksumSize = field(U8, ServerHelloPacket::checksumSize)
return ServerHelloPacket(
ephemeralPublic = EcKeys.fromUncompressedPoint(pubKey),
signature = signature,
checksumSize = checksumSize,
)
}
}
object ClientReadyCodec : PacketCodec<ClientReadyPacket>() {
override fun CodecScope<ClientReadyPacket>.body(): ClientReadyPacket {
val bytes = field(LengthPrefixedBytes) { EcKeys.toUncompressedPoint(it.ephemeralPublic) }
return ClientReadyPacket(EcKeys.fromUncompressedPoint(bytes))
}
}
@@ -0,0 +1,85 @@
package de.fiereu.network.handshake
import de.fiereu.network.PipelineNames
import de.fiereu.network.PipelineOptions
import de.fiereu.network.Protocol
import de.fiereu.network.ProtocolHandler
import de.fiereu.network.SessionPhase
import de.fiereu.network.Side
import de.fiereu.network.StaleClientHelloException
import de.fiereu.network.TypedProtocolHandler
import de.fiereu.network.cipher.AesCtrSessionCipher
import de.fiereu.network.handlers.ChecksumFrameDecoder
import de.fiereu.network.handlers.ChecksumFrameEncoder
import de.fiereu.network.handlers.CipherDecoder
import de.fiereu.network.handlers.CipherEncoder
import de.fiereu.network.handlers.CompressionEncoder
import de.fiereu.network.internal.MutableSessionContext
import io.github.oshai.kotlinlogging.KotlinLogging
import java.security.interfaces.ECPrivateKey
import kotlin.math.abs
private val log = KotlinLogging.logger {}
internal class ServerSessionHandshakeHandler(
private val rootPrivate: ECPrivateKey,
private val applicationProtocol: Protocol,
private val applicationHandlerFactory: () -> ProtocolHandler,
private val options: PipelineOptions,
) : TypedProtocolHandler<SessionHandshakeProtocol>(SessionHandshakeProtocol, Side.SERVER) {
private val ephemeralKeyPair = EcKeys.generateEphemeralKeyPair()
init {
on<ClientHelloPacket> { event ->
val skew = abs(System.currentTimeMillis() - event.packet.timestamp)
if (skew > options.maxHelloSkew.inWholeMilliseconds) {
throw StaleClientHelloException(skew)
}
val publicBytes =
EcKeys.toUncompressedPoint(
ephemeralKeyPair.public as java.security.interfaces.ECPublicKey,
)
val signature = EcKeys.sign(rootPrivate, publicBytes)
event.session.send(
ServerHelloPacket(
ephemeralPublic = ephemeralKeyPair.public as java.security.interfaces.ECPublicKey,
signature = signature,
checksumSize = options.checksumSize,
),
)
}
on<ClientReadyPacket> { event ->
val crypto =
SessionCryptoState.derive(
localPrivate = ephemeralKeyPair.private,
remotePublic = event.packet.ephemeralPublic,
role = AesCtrSessionCipher.Role.SERVER,
checksumSize = options.checksumSize,
)
val pipeline = event.session.channel.pipeline()
(pipeline.get(PipelineNames.CHECKSUM_DECODER) as ChecksumFrameDecoder).checksum =
crypto.incomingChecksum
(pipeline.get(PipelineNames.CHECKSUM_ENCODER) as ChecksumFrameEncoder).checksum =
crypto.outgoingChecksum
(pipeline.get(PipelineNames.CIPHER_DECODER) as CipherDecoder).cipher = crypto.cipher
(pipeline.get(PipelineNames.CIPHER_ENCODER) as CipherEncoder).cipher = crypto.cipher
if (applicationProtocol.compressed) {
pipeline.addBefore(
PipelineNames.PROTOCOL_HANDLER,
PipelineNames.COMPRESSION_ENCODER,
CompressionEncoder(options.compressionThreshold),
)
}
val appHandler = applicationHandlerFactory()
pipeline.replace(
PipelineNames.PROTOCOL_HANDLER,
PipelineNames.PROTOCOL_HANDLER,
appHandler,
)
(event.session as MutableSessionContext).transitionTo(SessionPhase.ESTABLISHED)
log.debug { "Handshake complete for ${event.session.remoteAddress}" }
}
}
}
@@ -0,0 +1,32 @@
package de.fiereu.network.handshake
import de.fiereu.network.checksum.Checksum
import de.fiereu.network.checksum.ChecksumFactory
import de.fiereu.network.cipher.AesCtrSessionCipher
import de.fiereu.network.cipher.SessionCipher
import java.security.PrivateKey
import java.security.PublicKey
internal class SessionCryptoState(
val cipher: SessionCipher,
val incomingChecksum: Checksum,
val outgoingChecksum: Checksum,
) {
companion object {
fun derive(
localPrivate: PrivateKey,
remotePublic: PublicKey,
role: AesCtrSessionCipher.Role,
checksumSize: Int,
): SessionCryptoState {
val secret = AesCtrSessionCipher.ecdh(localPrivate, remotePublic)
val cipher = AesCtrSessionCipher.derive(secret, role)
val (outSeed, inSeed) = AesCtrSessionCipher.directionalSeeds(secret, role)
return SessionCryptoState(
cipher = cipher,
incomingChecksum = ChecksumFactory.create(checksumSize, inSeed),
outgoingChecksum = ChecksumFactory.create(checksumSize, outSeed),
)
}
}
}
@@ -0,0 +1,11 @@
package de.fiereu.network.handshake
import de.fiereu.network.Protocol
object SessionHandshakeProtocol : Protocol() {
init {
bidi(0x00u, ClientHelloCodec, ClientHelloPacket::class)
bidi(0x01u, ServerHelloCodec, ServerHelloPacket::class)
bidi(0x02u, ClientReadyCodec, ClientReadyPacket::class)
}
}
@@ -0,0 +1,110 @@
package de.fiereu.network.internal
import de.fiereu.network.Protocol
import de.fiereu.network.SessionAttribute
import de.fiereu.network.SessionAttributes
import de.fiereu.network.SessionContext
import de.fiereu.network.SessionPhase
import de.fiereu.network.Side
import io.github.oshai.kotlinlogging.KotlinLogging
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.util.AttributeKey
import java.net.SocketAddress
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
private val log = KotlinLogging.logger {}
internal val SESSION_KEY: AttributeKey<MutableSessionContext> =
AttributeKey.valueOf("de.fiereu.network.session")
internal class MutableSessionContext(
override val side: Side,
override val channel: Channel,
internal val applicationProtocol: Protocol,
) : SessionContext {
override val remoteAddress: SocketAddress
get() = channel.remoteAddress()
@Volatile
override var phase: SessionPhase = SessionPhase.HANDSHAKE
private set
@Volatile
override var handshakeCompletedAt: Instant? = null
private set
override val attributes: SessionAttributes = ConcurrentAttributes()
private val listenersLock = Any()
private val listeners = mutableMapOf<SessionPhase, MutableList<() -> Unit>>()
internal fun transitionTo(next: SessionPhase) {
val toFire: List<() -> Unit>
synchronized(listenersLock) {
if (phase == next) return
phase = next
if (next == SessionPhase.ESTABLISHED) {
handshakeCompletedAt = Instant.now()
}
toFire = listeners[next]?.toList() ?: emptyList()
}
for (listener in toFire) {
try {
listener()
} catch (t: Throwable) {
log.warn(t) { "Phase listener for $next threw" }
}
}
}
override fun send(packet: Any): ChannelFuture = channel.writeAndFlush(packet)
override fun close(reason: () -> String) {
val message = reason()
log.debug { "Closing session $remoteAddress: $message" }
channel.close()
}
override fun onPhase(phase: SessionPhase, listener: () -> Unit) {
val fireNow: Boolean
synchronized(listenersLock) {
if (this.phase == phase) {
fireNow = true
} else {
fireNow = false
listeners.getOrPut(phase) { mutableListOf() } += listener
}
}
if (fireNow) {
listener()
}
}
}
internal data class OutgoingPacket(
val registration: Protocol.Registration<*>,
val value: Any,
)
private class ConcurrentAttributes : SessionAttributes {
private val map = ConcurrentHashMap<SessionAttribute<*>, Any>()
@Suppress("UNCHECKED_CAST")
override fun <T : Any> get(key: SessionAttribute<T>): T? = map[key] as T?
override fun <T : Any> set(key: SessionAttribute<T>, value: T) {
map[key] = value
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any> remove(key: SessionAttribute<T>): T? = map.remove(key) as T?
@Suppress("UNCHECKED_CAST")
override fun <T : Any> getOrPut(key: SessionAttribute<T>, default: () -> T): T =
map.getOrPut(key) { default() } as T
override fun contains(key: SessionAttribute<*>): Boolean = map.containsKey(key)
}
@@ -0,0 +1,30 @@
package de.fiereu.network
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.Unpooled
class NettyBuffersTest :
FunSpec({
test("NettyReadBuffer matches ByteBuf state") {
val buf = Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4))
val read = NettyReadBuffer(buf)
read.readByte() shouldBe 1
read.remaining() shouldBe 3
val dst = ByteArray(2)
read.readBytes(dst)
dst shouldBe byteArrayOf(2, 3)
read.skip(1)
read.remaining() shouldBe 0
}
test("NettyWriteBuffer writes through to ByteBuf") {
val buf = Unpooled.buffer()
val write = NettyWriteBuffer(buf)
write.writeByte(0xAB.toByte())
write.writeBytes(byteArrayOf(0xCD.toByte(), 0xEF.toByte()))
val read = ByteArray(3)
buf.readBytes(read)
read shouldBe byteArrayOf(0xAB.toByte(), 0xCD.toByte(), 0xEF.toByte())
}
})
@@ -0,0 +1,73 @@
package de.fiereu.network
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.U16LE
import de.fiereu.bytecodec.U8
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private data class Hello(val n: Int)
private data class World(val n: Int)
private object HelloCodec : PacketCodec<Hello>() {
override fun CodecScope<Hello>.body() = Hello(field(U16LE, Hello::n))
}
private object WorldCodec : PacketCodec<World>() {
override fun CodecScope<World>.body() = World(field(U8, World::n))
}
private data class Beep(val n: Int)
private object BeepCodec : PacketCodec<Beep>() {
override fun CodecScope<Beep>.body() = Beep(field(U16LE, Beep::n))
}
private object SampleProtocol : Protocol() {
init {
c2s<Hello>(0x10u, HelloCodec)
s2c<World>(0x20u, WorldCodec)
bidi<Beep>(0x30u, BeepCodec)
}
}
class ProtocolTest :
FunSpec({
test("incoming lookup depends on side") {
SampleProtocol.incomingCodec(Side.SERVER, 0x10u) shouldBe HelloCodec
SampleProtocol.incomingCodec(Side.CLIENT, 0x10u) shouldBe null
SampleProtocol.incomingCodec(Side.CLIENT, 0x20u) shouldBe WorldCodec
}
test("outgoing lookup depends on side") {
SampleProtocol.outgoingRegistration(Side.CLIENT, Hello::class)?.opcode shouldBe 0x10u
SampleProtocol.outgoingRegistration(Side.SERVER, World::class)?.opcode shouldBe 0x20u
}
test("bidi registers both directions") {
SampleProtocol.incomingCodec(Side.SERVER, 0x30u) shouldBe BeepCodec
SampleProtocol.incomingCodec(Side.CLIENT, 0x30u) shouldBe BeepCodec
SampleProtocol.outgoingRegistration(Side.SERVER, Beep::class)?.opcode shouldBe 0x30u
SampleProtocol.outgoingRegistration(Side.CLIENT, Beep::class)?.opcode shouldBe 0x30u
}
test("duplicate registration throws") {
shouldThrow<IllegalStateException> {
object : Protocol() {
init {
c2s<Hello>(0x01u, HelloCodec)
c2s<Hello>(0x02u, HelloCodec)
}
}
}
}
test("Direction.isIncomingFor") {
Direction.C2S.isIncomingFor(Side.SERVER) shouldBe true
Direction.C2S.isIncomingFor(Side.CLIENT) shouldBe false
Direction.S2C.isIncomingFor(Side.CLIENT) shouldBe true
}
})
@@ -0,0 +1,133 @@
package de.fiereu.network
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.U16LE
import de.fiereu.network.internal.MutableSessionContext
import de.fiereu.network.internal.OutgoingPacket
import de.fiereu.network.internal.SESSION_KEY
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
private data class Ping(val n: Int)
private data class Pong(val n: Int)
private object PingCodec : PacketCodec<Ping>() {
override fun CodecScope<Ping>.body() = Ping(field(U16LE, Ping::n))
}
private object PongCodec : PacketCodec<Pong>() {
override fun CodecScope<Pong>.body() = Pong(field(U16LE, Pong::n))
}
private object PingPongProtocol : Protocol() {
init {
c2s<Ping>(0xA0u, PingCodec)
s2c<Pong>(0xA1u, PongCodec)
}
}
private class ServerHandler :
TypedProtocolHandler<PingPongProtocol>(PingPongProtocol, Side.SERVER) {
val seen = mutableListOf<Ping>()
init {
on<Ping> { event ->
seen += event.packet
event.session.send(Pong(event.packet.n + 1))
}
}
}
private fun channelWithHandler(handler: ProtocolHandler): EmbeddedChannel {
val channel = EmbeddedChannel()
val session = MutableSessionContext(handler.side, channel, handler.protocol)
channel.attr(SESSION_KEY).set(session)
channel.pipeline().addLast(PipelineNames.PROTOCOL_HANDLER, handler)
return channel
}
class TypedProtocolHandlerTest :
FunSpec({
test("incoming bytes dispatch to on<T>") {
val handler = ServerHandler()
val channel = channelWithHandler(handler)
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xA0.toByte(), 0x05, 0x00)))
handler.seen shouldBe listOf(Ping(5))
val out = channel.readOutbound<ByteBuf>()
out.readUnsignedByte().toInt() shouldBe 0xA1
out.readUnsignedShortLE() shouldBe 6
}
test("session.send writes through the handler") {
val handler = ServerHandler()
val channel = channelWithHandler(handler)
val session = channel.attr(SESSION_KEY).get()
session.send(Pong(42))
val out = channel.readOutbound<ByteBuf>()
out.readUnsignedByte().toInt() shouldBe 0xA1
out.readUnsignedShortLE() shouldBe 42
}
test("unknown opcode is logged but channel stays open") {
val handler = ServerHandler()
val channel = channelWithHandler(handler)
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xFE.toByte())))
channel.isOpen shouldBe true
}
test("unhandled packet logs but keeps the channel open") {
val protocol =
object : Protocol() {
init {
c2s<Ping>(0xB0u, PingCodec)
c2s<Pong>(0xB1u, PongCodec)
}
}
class OnlyPingHandler : TypedProtocolHandler<Protocol>(protocol, Side.SERVER) {
init {
on<Ping> { /* no-op */ }
}
}
val handler = OnlyPingHandler()
val channel = channelWithHandler(handler)
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xB1.toByte(), 0x01, 0x00)))
channel.isOpen shouldBe true
}
test("duplicate handler registration throws") {
shouldThrow<HandlerRegistrationException> {
object : TypedProtocolHandler<PingPongProtocol>(PingPongProtocol, Side.SERVER) {
init {
on<Ping> {}
on<Ping> {}
}
}
}
}
test("attributes survive on a session") {
val handler = ServerHandler()
val channel = channelWithHandler(handler)
val session = channel.attr(SESSION_KEY).get()
val key = SessionAttribute.of<Long>("userId")
session.attributes[key] = 42L
session.attributes[key] shouldBe 42L
session.attributes.contains(key) shouldBe true
}
test("OutgoingPacket goes through ProtocolHandler.write") {
val handler = ServerHandler()
val channel = channelWithHandler(handler)
val reg = PingPongProtocol.outgoingRegistration(Side.SERVER, Pong::class)!!
channel.writeOutbound(OutgoingPacket(reg, Pong(7)))
val out = channel.readOutbound<ByteBuf>()
out.readUnsignedByte().toInt() shouldBe 0xA1
out.readUnsignedShortLE() shouldBe 7
}
})
@@ -0,0 +1,42 @@
package de.fiereu.network.checksum
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.Unpooled
class ChecksumTest :
FunSpec({
test("NoOp produces empty tag") {
NoOpChecksum.size shouldBe 0
NoOpChecksum.calculate(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3))).size shouldBe 0
NoOpChecksum.verify(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3)), ByteArray(0)) shouldBe
true
}
test("CRC16 verify matches calculate") {
val c = Crc16Checksum()
val data = byteArrayOf(0x10, 0x20, 0x30, 0x40, 0x50)
val tag = c.calculate(Unpooled.wrappedBuffer(data))
tag.size shouldBe 2
Crc16Checksum().verify(Unpooled.wrappedBuffer(data), tag) shouldBe true
Crc16Checksum().verify(Unpooled.wrappedBuffer(byteArrayOf(0, 0)), tag) shouldBe false
}
test("HMAC-SHA256 round counter advances on every verify") {
val key = ByteArray(16) { it.toByte() }
val calc = HmacSha256Checksum(8, key)
val ver = HmacSha256Checksum(8, key)
val data = byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())
val tag0 = calc.calculate(Unpooled.wrappedBuffer(data))
val tag1 = calc.calculate(Unpooled.wrappedBuffer(data))
tag0.contentEquals(tag1) shouldBe false
ver.verify(Unpooled.wrappedBuffer(data), tag0) shouldBe true
ver.verify(Unpooled.wrappedBuffer(data), tag1) shouldBe true
}
test("ChecksumFactory dispatches on size") {
ChecksumFactory.create(0).size shouldBe 0
ChecksumFactory.create(2).size shouldBe 2
ChecksumFactory.create(8, ByteArray(16)).size shouldBe 8
}
})
@@ -0,0 +1,47 @@
package de.fiereu.network.cipher
import de.fiereu.network.handshake.EcKeys
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.Unpooled
class AesCtrSessionCipherTest :
FunSpec({
test("derived ciphers interoperate across roles") {
val serverEphemeral = EcKeys.generateEphemeralKeyPair()
val clientEphemeral = EcKeys.generateEphemeralKeyPair()
val serverCipher =
AesCtrSessionCipher.derive(
localPrivate = serverEphemeral.private,
remotePublic = clientEphemeral.public,
role = AesCtrSessionCipher.Role.SERVER,
)
val clientCipher =
AesCtrSessionCipher.derive(
localPrivate = clientEphemeral.private,
remotePublic = serverEphemeral.public,
role = AesCtrSessionCipher.Role.CLIENT,
)
val plaintext = "the quick brown fox jumps over the lazy dog".toByteArray()
val srcServerOut = Unpooled.wrappedBuffer(plaintext)
val encrypted = Unpooled.buffer()
serverCipher.encrypt(srcServerOut, encrypted)
val decrypted = Unpooled.buffer()
clientCipher.decrypt(encrypted, decrypted)
val read = ByteArray(decrypted.readableBytes())
decrypted.readBytes(read)
read shouldBe plaintext
}
test("NoOpSessionCipher passes through") {
val src = Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3))
val dst = Unpooled.buffer()
NoOpSessionCipher.encrypt(src, dst)
val arr = ByteArray(3)
dst.readBytes(arr)
arr shouldBe byteArrayOf(1, 2, 3)
}
})
@@ -0,0 +1,124 @@
package de.fiereu.network.coroutines
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.U16LE
import de.fiereu.network.HandlerRegistrationException
import de.fiereu.network.PipelineNames
import de.fiereu.network.Protocol
import de.fiereu.network.ProtocolHandler
import de.fiereu.network.Side
import de.fiereu.network.c2s
import de.fiereu.network.internal.MutableSessionContext
import de.fiereu.network.internal.SESSION_KEY
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
private data class Slow(val id: Int)
private data class Fast(val id: Int)
private object SlowCodec : PacketCodec<Slow>() {
override fun CodecScope<Slow>.body() = Slow(field(U16LE, Slow::id))
}
private object FastCodec : PacketCodec<Fast>() {
override fun CodecScope<Fast>.body() = Fast(field(U16LE, Fast::id))
}
private object MixedProtocol : Protocol() {
init {
c2s<Slow>(0xC0u, SlowCodec)
c2s<Fast>(0xC1u, FastCodec)
}
}
private fun channelWithHandler(handler: ProtocolHandler): EmbeddedChannel {
val channel = EmbeddedChannel()
val session = MutableSessionContext(handler.side, channel, handler.protocol)
channel.attr(SESSION_KEY).set(session)
channel.pipeline().addLast(PipelineNames.PROTOCOL_HANDLER, handler)
return channel
}
class CoroutineProtocolHandlerTest :
FunSpec({
test("onSuspend handler runs on the supplied scope") {
val scope = CoroutineScope(Dispatchers.Default + Job())
val received = CompletableDeferred<Slow>()
val handler =
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
init {
onSuspend<Slow> { event -> received.complete(event.packet) }
}
}
val channel = channelWithHandler(handler)
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC0.toByte(), 0x07, 0x00)))
runBlocking { withTimeout(2000) { received.await() } shouldBe Slow(7) }
scope.cancel()
}
test("sync on<T> and onSuspend coexist") {
val scope = CoroutineScope(Dispatchers.Default + Job())
val syncSeen = mutableListOf<Fast>()
val asyncSeen = CompletableDeferred<Slow>()
val handler =
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
init {
on<Fast> { event -> syncSeen += event.packet }
onSuspend<Slow> { event -> asyncSeen.complete(event.packet) }
}
}
val channel = channelWithHandler(handler)
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC1.toByte(), 0x03, 0x00)))
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC0.toByte(), 0x09, 0x00)))
syncSeen shouldBe listOf(Fast(3))
runBlocking { withTimeout(2000) { asyncSeen.await() } shouldBe Slow(9) }
scope.cancel()
}
test("registering the same type twice across sync/suspend throws") {
val scope = CoroutineScope(Dispatchers.Default + Job())
shouldThrow<HandlerRegistrationException> {
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
init {
on<Slow> {}
onSuspend<Slow> {}
}
}
}
scope.cancel()
}
test("mailbox preserves ordering") {
val scope = CoroutineScope(Dispatchers.Default + Job())
val seen = mutableListOf<Int>()
val all = CompletableDeferred<Unit>()
val handler =
object : CoroutineProtocolHandler<MixedProtocol>(MixedProtocol, Side.SERVER, scope) {
init {
onSuspend<Slow> { event ->
seen += event.packet.id
if (seen.size == 5) all.complete(Unit)
}
}
}
val channel = channelWithHandler(handler)
for (i in 1..5) {
channel.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(0xC0.toByte(), i.toByte(), 0x00)))
}
runBlocking { withTimeout(2000) { all.await() } }
seen shouldBe listOf(1, 2, 3, 4, 5)
scope.cancel()
}
})
@@ -0,0 +1,52 @@
package de.fiereu.network.handlers
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
class CompressionTest :
FunSpec({
test("payload below threshold preserves opcode and writes flag=0") {
val enc = EmbeddedChannel(CompressionEncoder(threshold = 16))
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0xAA.toByte(), 1, 2, 3, 4)))
val out = enc.readOutbound<ByteBuf>()
out.readableBytes() shouldBe 6
out.readByte() shouldBe 0xAA.toByte()
out.readByte() shouldBe 0
val rest = ByteArray(4)
out.readBytes(rest)
rest shouldBe byteArrayOf(1, 2, 3, 4)
}
test("encoder + decoder roundtrip for raw payload") {
val enc = EmbeddedChannel(CompressionEncoder(threshold = 16))
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0xAA.toByte(), 1, 2, 3, 4)))
val compressed = enc.readOutbound<ByteBuf>()
val dec = EmbeddedChannel(CompressionDecoder())
dec.writeInbound(compressed)
val out = dec.readInbound<ByteBuf>()
out.readableBytes() shouldBe 5
out.readByte() shouldBe 0xAA.toByte()
val rest = ByteArray(4)
out.readBytes(rest)
rest shouldBe byteArrayOf(1, 2, 3, 4)
}
test("encoder + decoder roundtrip for compressed payload") {
val payload = ByteArray(512) { (it and 0x0F).toByte() }
val enc = EmbeddedChannel(CompressionEncoder(threshold = 64))
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0xBB.toByte()) + payload))
val compressed = enc.readOutbound<ByteBuf>()
compressed.getByte(0) shouldBe 0xBB.toByte()
compressed.getByte(1) shouldBe 1
val dec = EmbeddedChannel(CompressionDecoder())
dec.writeInbound(compressed)
val out = dec.readInbound<ByteBuf>()
out.readByte() shouldBe 0xBB.toByte()
val read = ByteArray(out.readableBytes())
out.readBytes(read)
read shouldBe payload
}
})
@@ -0,0 +1,83 @@
package de.fiereu.network.handlers
import de.fiereu.network.ChecksumMismatchException
import de.fiereu.network.checksum.Crc16Checksum
import de.fiereu.network.checksum.NoOpChecksum
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.embedded.EmbeddedChannel
private fun EmbeddedChannel.drainOutbound(): ByteBuf {
val out = Unpooled.buffer()
while (true) {
val obj = readOutbound<Any>() ?: break
if (obj is ByteBuf) {
out.writeBytes(obj)
obj.release()
}
}
return out
}
private fun rootCause(t: Throwable): Throwable {
var c: Throwable = t
while (c.cause != null && c.cause !== c) c = c.cause!!
return c
}
class FrameAndChecksumTest :
FunSpec({
test("PacketFrameEncoder writes LE length prefix including itself") {
val channel = EmbeddedChannel(PacketFrameEncoder())
channel.writeOutbound(
Unpooled.wrappedBuffer(byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())))
val out = channel.drainOutbound()
out.readableBytes() shouldBe 5
out.readUnsignedShortLE() shouldBe 5
val rest = ByteArray(3)
out.readBytes(rest)
rest shouldBe byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())
}
test("PacketFrameDecoder strips the length prefix") {
val encoder = EmbeddedChannel(PacketFrameEncoder())
encoder.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4)))
val framed = encoder.drainOutbound()
val decoder = EmbeddedChannel(PacketFrameDecoder())
decoder.writeInbound(framed)
val out = decoder.readInbound<ByteBuf>()
out.readableBytes() shouldBe 4
}
test("ChecksumFrameEncoder appends tag; decoder strips it") {
val enc = EmbeddedChannel(ChecksumFrameEncoder(Crc16Checksum()))
enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4)))
val withTag = enc.drainOutbound()
withTag.readableBytes() shouldBe 6
val dec = EmbeddedChannel(ChecksumFrameDecoder(Crc16Checksum()))
dec.writeInbound(withTag)
val out = dec.readInbound<ByteBuf>()
out.readableBytes() shouldBe 4
}
test("ChecksumFrameDecoder throws on mismatch") {
val dec = EmbeddedChannel(ChecksumFrameDecoder(Crc16Checksum()))
val thrown =
shouldThrow<Throwable> {
dec.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4, 0, 0)))
}
(rootCause(thrown) is ChecksumMismatchException) shouldBe true
}
test("NoOpChecksum decoder passes payload through") {
val dec = EmbeddedChannel(ChecksumFrameDecoder(NoOpChecksum))
dec.writeInbound(Unpooled.wrappedBuffer(byteArrayOf(9, 9, 9)))
val out = dec.readInbound<ByteBuf>()
out.readableBytes() shouldBe 3
}
})
@@ -0,0 +1,117 @@
package de.fiereu.network.handshake
import de.fiereu.bytecodec.CodecScope
import de.fiereu.bytecodec.PacketCodec
import de.fiereu.bytecodec.U16LE
import de.fiereu.network.PipelineOptions
import de.fiereu.network.Protocol
import de.fiereu.network.ProtocolHandler
import de.fiereu.network.SessionIdentity
import de.fiereu.network.SessionPhase
import de.fiereu.network.Side
import de.fiereu.network.TypedProtocolHandler
import de.fiereu.network.bidi
import de.fiereu.network.installPipeline
import de.fiereu.network.internal.SESSION_KEY
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
import io.netty.channel.embedded.EmbeddedChannel
import java.security.interfaces.ECPrivateKey
import java.security.interfaces.ECPublicKey
private data class Echo(val value: Int)
private object EchoCodec : PacketCodec<Echo>() {
override fun CodecScope<Echo>.body() = Echo(field(U16LE, Echo::value))
}
private object EchoProtocol : Protocol() {
init {
bidi<Echo>(0x55u, EchoCodec)
}
}
private class CollectingHandler(side: Side) :
TypedProtocolHandler<EchoProtocol>(EchoProtocol, side) {
val received = mutableListOf<Echo>()
init {
on<Echo> { event -> received += event.packet }
}
}
private fun drain(from: EmbeddedChannel, into: EmbeddedChannel) {
while (true) {
val obj = from.readOutbound<ByteBuf>() ?: break
into.writeInbound(obj)
}
}
class EndToEndHandshakeTest :
FunSpec({
test("server and client exchange a full handshake and an application packet") {
val rootKeyPair = EcKeys.generateEphemeralKeyPair()
val rootPrivate = rootKeyPair.private as ECPrivateKey
val rootPublic = rootKeyPair.public as ECPublicKey
val serverApp = CollectingHandler(Side.SERVER)
val clientApp = CollectingHandler(Side.CLIENT)
val options = PipelineOptions(checksumSize = 8)
val serverChannel =
EmbeddedChannel(
object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
installPipeline(
pipeline = ch.pipeline(),
side = Side.SERVER,
identity = SessionIdentity.ServerRoot(rootPrivate),
applicationProtocol = EchoProtocol,
applicationHandlerFactory = { serverApp as ProtocolHandler },
options = options,
)
}
},
)
val clientChannel =
EmbeddedChannel(
object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
installPipeline(
pipeline = ch.pipeline(),
side = Side.CLIENT,
identity = SessionIdentity.ClientTrust(rootPublic),
applicationProtocol = EchoProtocol,
applicationHandlerFactory = { clientApp as ProtocolHandler },
options = options,
)
}
},
)
// Client sends ClientHello on channelActive (called during init for EmbeddedChannel)
drain(clientChannel, serverChannel)
// Server replies ServerHello
drain(serverChannel, clientChannel)
// Client replies ClientReady
drain(clientChannel, serverChannel)
serverChannel.attr(SESSION_KEY).get().phase shouldBe SessionPhase.ESTABLISHED
clientChannel.attr(SESSION_KEY).get().phase shouldBe SessionPhase.ESTABLISHED
// Client sends an application packet through the encrypted pipeline
clientChannel.attr(SESSION_KEY).get().send(Echo(0xCAFE))
drain(clientChannel, serverChannel)
serverApp.received shouldBe listOf(Echo(0xCAFE))
// Server responds
serverChannel.attr(SESSION_KEY).get().send(Echo(0xBABE))
drain(serverChannel, clientChannel)
clientApp.received shouldBe listOf(Echo(0xBABE))
}
})
@@ -0,0 +1,39 @@
package de.fiereu.network.handshake
import de.fiereu.bytecodec.test.assertValueRoundtrip
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.security.interfaces.ECPublicKey
class HandshakeCodecsTest :
FunSpec({
test("ClientHello roundtrip recovers timestamp despite XOR obfuscation") {
val ts = 1764115200L
val bytes = ClientHelloCodec.encodeToBytes(ClientHelloPacket(ts))
bytes.size shouldBe 16
ClientHelloCodec.decodeBytes(bytes).timestamp shouldBe ts
}
test("ServerHello roundtrips pubkey, signature, checksum size") {
val keyPair = EcKeys.generateEphemeralKeyPair()
val pkt =
ServerHelloPacket(
ephemeralPublic = keyPair.public as ECPublicKey,
signature = ByteArray(64) { it.toByte() },
checksumSize = 16,
)
val bytes = ServerHelloCodec.encodeToBytes(pkt)
val decoded = ServerHelloCodec.decodeBytes(bytes)
decoded.ephemeralPublic shouldBe pkt.ephemeralPublic
decoded.signature shouldBe pkt.signature
decoded.checksumSize shouldBe 16
}
test("ClientReady roundtrips public key") {
val keyPair = EcKeys.generateEphemeralKeyPair()
val pkt = ClientReadyPacket(ephemeralPublic = keyPair.public as ECPublicKey)
ClientReadyCodec.assertValueRoundtrip(pkt)
}
})
@@ -1,3 +1,3 @@
Removed on request of pokemmo.eu. Removed on request of pokemmo.eu.
Date: 2026-08-17 Date: 2026-08-17
Nonce: 0485ce0df8a74237b94853f3ed55fd38 Nonce: 83616ef24a6849d7bd35ff77cfa88667
@@ -1,3 +0,0 @@
Removed on request of pokemmo.eu.
Date: 2026-08-17
Nonce: 746fedca4ccc49109f8f64ba0b924c6e
@@ -1,222 +0,0 @@
package de.fiereu.openmmo.protocols.game
import de.fiereu.openmmo.protocols.Protocol
import de.fiereu.openmmo.protocols.game.packets.CharacterListDeserializer
import de.fiereu.openmmo.protocols.game.packets.CharacterListSerializer
import de.fiereu.openmmo.protocols.game.packets.ChatMessageDeserialize
import de.fiereu.openmmo.protocols.game.packets.ChatMessageSerialize
import de.fiereu.openmmo.protocols.game.packets.CreateCharacterDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogChoiceDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogChoiceSerializer
import de.fiereu.openmmo.protocols.game.packets.DialogDataDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogDataSerializer
import de.fiereu.openmmo.protocols.game.packets.DialogOptionDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogOptionSerializer
import de.fiereu.openmmo.protocols.game.packets.DialogStateDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogStateSerializer
import de.fiereu.openmmo.protocols.game.packets.EntityInteractDeserializer
import de.fiereu.openmmo.protocols.game.packets.EntityInteractSerializer
import de.fiereu.openmmo.protocols.game.packets.EntityLeaveDeserializer
import de.fiereu.openmmo.protocols.game.packets.EntityLeaveSerializer
import de.fiereu.openmmo.protocols.game.packets.EntityMovePacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.EntityMovePacketSerializer
import de.fiereu.openmmo.protocols.game.packets.FaceDirectionDeserializer
import de.fiereu.openmmo.protocols.game.packets.FaceDirectionSerializer
import de.fiereu.openmmo.protocols.game.packets.InteractiveResponseDeserializer
import de.fiereu.openmmo.protocols.game.packets.InteractiveSerializer
import de.fiereu.openmmo.protocols.game.packets.JoinPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.JoinPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.JoinResponseDeserializer
import de.fiereu.openmmo.protocols.game.packets.JoinResponseSerializer
import de.fiereu.openmmo.protocols.game.packets.KeepAlivePacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.KeepAlivePacketSerializer
import de.fiereu.openmmo.protocols.game.packets.LoadEntityDeserializer
import de.fiereu.openmmo.protocols.game.packets.LoadEntitySerializer
import de.fiereu.openmmo.protocols.game.packets.LoadMapPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.LoadMapPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionAckDeserializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionAckSerializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionDeserializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionSerializer
import de.fiereu.openmmo.protocols.game.packets.MovementPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.MovementPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.NpcAnimationDeserializer
import de.fiereu.openmmo.protocols.game.packets.NpcAnimationSerializer
import de.fiereu.openmmo.protocols.game.packets.NpcSpawnDeserializer
import de.fiereu.openmmo.protocols.game.packets.NpcSpawnSerializer
import de.fiereu.openmmo.protocols.game.packets.NpcUpdateDeserializer
import de.fiereu.openmmo.protocols.game.packets.NpcUpdateSerializer
import de.fiereu.openmmo.protocols.game.packets.NullPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.PokemonContainerDeserializer
import de.fiereu.openmmo.protocols.game.packets.PokemonContainerSerializer
import de.fiereu.openmmo.protocols.game.packets.RenderScreenDeserializer
import de.fiereu.openmmo.protocols.game.packets.RenderScreenSerializer
import de.fiereu.openmmo.protocols.game.packets.RequestCharactersDeserializer
import de.fiereu.openmmo.protocols.game.packets.RequestCharactersPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.RequestPlayerDeserializePacket
import de.fiereu.openmmo.protocols.game.packets.RequestPlayerSerializer
import de.fiereu.openmmo.protocols.game.packets.SelectCharacterDeserializer
import de.fiereu.openmmo.protocols.game.packets.SelectCharacterSerializer
import de.fiereu.openmmo.protocols.game.packets.SelectedCharacterDeserializer
import de.fiereu.openmmo.protocols.game.packets.SelectedCharacterSerializer
import de.fiereu.openmmo.protocols.game.packets.TokenPayloadSerializer
import de.fiereu.openmmo.protocols.incomingPacket
import de.fiereu.openmmo.protocols.outgoingPacket
/**
* Game Protocol implementation. This protocol handles in-game communication after the TLS handshake
* is complete.
*/
abstract class GameProtocol : Protocol() {
override val async: Boolean = true
override val compressed: Boolean = true
}
class GameServerProtocol : GameProtocol() {
init {
// Game server: client sends 0x01 as first packet (client info / "JoinGame")
incomingPacket(0x01u, JoinPacketDeserializer())
outgoingPacket(0x01u, JoinResponseSerializer())
incomingPacket(0x02u, RequestCharactersDeserializer())
outgoingPacket(0x02u, CharacterListSerializer())
incomingPacket(0x03u, CreateCharacterDeserializer())
incomingPacket(0x04u, SelectCharacterDeserializer())
outgoingPacket(0x04u, SelectedCharacterSerializer())
incomingPacket(0x05u, RequestPlayerDeserializePacket())
outgoingPacket(0x05u, LoadEntitySerializer())
incomingPacket(0x06u, MovementPacketDeserializer()) // Client movement
outgoingPacket(0xEAu, EntityMovePacketSerializer()) // Entity move broadcast
incomingPacket(0x07u, FaceDirectionDeserializer()) // Face direction
outgoingPacket(0x08u, EntityLeaveSerializer()) // Entity leave area
incomingPacket(0x09u, ChatMessageDeserialize()) // Chat message
outgoingPacket(0x09u, ChatMessageSerialize())
outgoingPacket(0x10u, LoadMapPacketSerializer()) // Load map
incomingPacket(0x10u, LoadMapPacketDeserializer())
outgoingPacket(0x13u, PokemonContainerSerializer()) // Pokemon data
incomingPacket(0x13u, PokemonContainerDeserializer())
incomingPacket(0x20u, NullPacketDeserializer()) // Token exchange (heartbeat/token)
outgoingPacket(0x20u, TokenPayloadSerializer())
outgoingPacket(0xB4u, RenderScreenSerializer()) // Render screen
incomingPacket(0xB4u, RenderScreenDeserializer())
incomingPacket(0xC2u, KeepAlivePacketDeserializer()) // Keepalive echo
outgoingPacket(0xC2u, KeepAlivePacketSerializer())
incomingPacket(0x0Du, DialogDataDeserializer())
outgoingPacket(0x0Du, DialogDataSerializer())
incomingPacket(0x0Eu, DialogStateDeserializer())
outgoingPacket(0x0Eu, DialogStateSerializer())
outgoingPacket(0x11u, NpcUpdateSerializer())
incomingPacket(0x12u, NpcSpawnDeserializer())
outgoingPacket(0x12u, NpcSpawnSerializer())
incomingPacket(0x1Bu, MapTransitionDeserializer())
outgoingPacket(0x1Bu, MapTransitionSerializer())
incomingPacket(0x21u, InteractiveResponseDeserializer())
outgoingPacket(0x21u, InteractiveSerializer())
incomingPacket(0x22u, EntityInteractDeserializer()) // Entity interaction start
outgoingPacket(0x22u, EntityInteractSerializer())
incomingPacket(0x25u, DialogChoiceDeserializer())
outgoingPacket(0x25u, DialogChoiceSerializer())
incomingPacket(0x26u, DialogOptionDeserializer())
outgoingPacket(0x26u, DialogOptionSerializer())
incomingPacket(0xB2u, NpcAnimationDeserializer())
outgoingPacket(0xB2u, NpcAnimationSerializer())
incomingPacket(0xB9u, MapTransitionAckDeserializer())
outgoingPacket(0xB9u, MapTransitionAckSerializer())
}
}
class GameClientProtocol : GameProtocol() {
init {
outgoingPacket(0x01u, JoinPacketSerializer()) // Client info / "JoinGame"
incomingPacket(0x01u, JoinResponseDeserializer())
outgoingPacket(0x02u, RequestCharactersPacketSerializer())
incomingPacket(0x02u, CharacterListDeserializer())
outgoingPacket(0x04u, SelectCharacterSerializer())
incomingPacket(0x04u, SelectedCharacterDeserializer())
outgoingPacket(0x05u, RequestPlayerSerializer())
incomingPacket(0x05u, LoadEntityDeserializer())
outgoingPacket(0x06u, MovementPacketSerializer()) // Client movement
incomingPacket(0xEAu, EntityMovePacketDeserializer()) // Entity move broadcast
outgoingPacket(0x07u, FaceDirectionSerializer()) // Face direction
incomingPacket(0x08u, EntityLeaveDeserializer()) // Entity leave area
outgoingPacket(0x09u, ChatMessageSerialize())
incomingPacket(0x09u, ChatMessageDeserialize())
outgoingPacket(0x10u, LoadMapPacketSerializer())
incomingPacket(0x10u, LoadMapPacketDeserializer())
outgoingPacket(0x13u, PokemonContainerSerializer())
incomingPacket(0x13u, PokemonContainerDeserializer())
outgoingPacket(0x20u, TokenPayloadSerializer())
incomingPacket(0x20u, NullPacketDeserializer())
outgoingPacket(0xB4u, RenderScreenSerializer())
incomingPacket(0xB4u, RenderScreenDeserializer())
outgoingPacket(0xC2u, KeepAlivePacketSerializer()) // Keepalive echo
incomingPacket(0xC2u, KeepAlivePacketDeserializer())
outgoingPacket(0x0Du, DialogDataSerializer())
incomingPacket(0x0Du, DialogDataDeserializer())
outgoingPacket(0x0Eu, DialogStateSerializer())
incomingPacket(0x0Eu, DialogStateDeserializer())
incomingPacket(0x11u, NpcUpdateDeserializer())
outgoingPacket(0x12u, NpcSpawnSerializer())
incomingPacket(0x12u, NpcSpawnDeserializer())
outgoingPacket(0x1Bu, MapTransitionSerializer())
incomingPacket(0x1Bu, MapTransitionDeserializer())
outgoingPacket(0x21u, InteractiveSerializer())
incomingPacket(0x21u, InteractiveResponseDeserializer())
outgoingPacket(0x22u, EntityInteractSerializer())
incomingPacket(0x22u, EntityInteractDeserializer())
outgoingPacket(0x25u, DialogChoiceSerializer())
incomingPacket(0x25u, DialogChoiceDeserializer())
outgoingPacket(0x26u, DialogOptionSerializer())
incomingPacket(0x26u, DialogOptionDeserializer())
outgoingPacket(0xB2u, NpcAnimationSerializer())
incomingPacket(0xB2u, NpcAnimationDeserializer())
outgoingPacket(0xB9u, MapTransitionAckSerializer())
incomingPacket(0xB9u, MapTransitionAckDeserializer())
}
}
@@ -1,71 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.enums.SkinSlot
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import de.fiereu.openmmo.protocols.game.packets.codecs.*
import de.fiereu.openmmo.protocols.readUtf16LE
import de.fiereu.openmmo.protocols.writeUtf16LE
import io.netty.buffer.ByteBuf
data class CharacterListPacket(val characters: List<CharacterEntry>)
data class CharacterEntry(
val characterInfo: CharacterInfo,
val skinSet: SkinSet,
val guildId: Int? = null,
val pokemon: List<Pokemon>
) {
init {
require(pokemon.size <= 6) { "Party size can't be more than 6 pokemon" }
}
}
class CharacterListSerializer : PacketSerializer<CharacterListPacket> {
override fun serialize(packet: CharacterListPacket, buffer: ByteBuf) =
buffer.run {
writeByte(packet.characters.size)
packet.characters.forEach { characterEntry ->
writeCharacterInfoLE(useLong = false, characterEntry.characterInfo)
writeSkinsLE(characterEntry.skinSet)
// TODO find out why we send 2 times the skin data
writeSkinsLE(characterEntry.skinSet, writeByte = false)
val hasGuild = characterEntry.guildId != null
buffer.writeBoolean(hasGuild)
if (hasGuild) {
writeUtf16LE("") // unused
writeIntLE(characterEntry.guildId)
}
buffer.writeByte(characterEntry.pokemon.size)
characterEntry.pokemon.forEach(::writePokemonLE)
}
}
}
class CharacterListDeserializer : PacketDeserializer<CharacterListPacket> {
override fun deserialize(buffer: ByteBuf): CharacterListPacket =
buffer.run {
val size = buffer.readByte().toInt()
val characters =
buildList(size) {
val characterInfo = readCharacterInfoLE(useLong = true)
val skinSet1 = readSkinsLE(SkinSlot.entries, readByte = true)
val skinSet2 = readSkinsLE(SkinSlot.entries, readByte = false)
val guildId =
if (readBoolean()) {
readUtf16LE() // unused
readIntLE()
} else null
val partySize = readUnsignedByte().toInt()
val pokemon = buildList(partySize) { repeat(partySize) { add(readPokemonLE()) } }
add(CharacterEntry(characterInfo, skinSet1, guildId, pokemon))
}
return CharacterListPacket(characters)
}
}
@@ -1,57 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.Language
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
data class ChatMessagePacket(
val type: ChatType,
val language: Language?,
val message: String,
val sender: String?
)
class ChatMessageSerialize : PacketSerializer<ChatMessagePacket> {
override fun serialize(packet: ChatMessagePacket, buffer: ByteBuf) {
buffer.apply {
writeByte(packet.type.ordinal)
when (packet.type) {
ChatType.TEAM -> {
writeUtf16LE(packet.message)
}
else -> {
require(packet.sender != null) { "sender must not be null" }
require(packet.language != null) { "language must not be null" }
writeLongLE(0) // TODO some id
writeUtf16LE(packet.sender)
writeByte(packet.language.ordinal)
writeByte(-1)
writeUtf16LE(packet.message)
}
}
}
}
}
class ChatMessageDeserialize : PacketDeserializer<ChatMessagePacket> {
override fun deserialize(buffer: ByteBuf): ChatMessagePacket {
when (val type = ChatType.entries[buffer.readByte().toInt()]) {
ChatType.LINK -> {
val message = buffer.readUtf16LE()
return ChatMessagePacket(type, Language.OTHER, message, null)
}
else -> {
buffer.readIntLE()
val sender = buffer.readUtf16LE()
val language = Language.entries[buffer.readByte().toInt()]
buffer.readByte()
val message = buffer.readUtf16LE()
return ChatMessagePacket(type, language, message, sender)
}
}
}
}
@@ -1,15 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.readUtf16LE
import io.netty.buffer.ByteBuf
data class CreateCharacterPacket(val name: String)
class CreateCharacterDeserializer : PacketDeserializer<CreateCharacterPacket> {
override fun deserialize(buffer: ByteBuf): CreateCharacterPacket {
val name = buffer.readUtf16LE()
buffer.skipBytes(buffer.readableBytes())
return CreateCharacterPacket(name)
}
}
@@ -1,25 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogChoicePacket(
val unk1: Int,
val unk2: Int,
)
class DialogChoiceSerializer : PacketSerializer<DialogChoicePacket> {
override fun serialize(packet: DialogChoicePacket, buffer: ByteBuf) {
buffer.writeByte(packet.unk1)
buffer.writeShortLE(packet.unk2)
}
}
class DialogChoiceDeserializer : PacketDeserializer<DialogChoicePacket> {
override fun deserialize(buffer: ByteBuf): DialogChoicePacket {
val unk1 = buffer.readByte().toInt()
val unk2 = buffer.readShortLE().toInt()
return DialogChoicePacket(unk1, unk2)
}
}
@@ -1,27 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogDataPacket(val entityId: Long, val unk1: Int, val type: Int, val data: ByteArray)
class DialogDataSerializer : PacketSerializer<DialogDataPacket> {
override fun serialize(packet: DialogDataPacket, buffer: ByteBuf) {
buffer.writeLongLE(packet.entityId)
buffer.writeByte(packet.unk1)
buffer.writeByte(packet.type)
buffer.writeBytes(packet.data)
}
}
class DialogDataDeserializer : PacketDeserializer<DialogDataPacket> {
override fun deserialize(buffer: ByteBuf): DialogDataPacket {
val entityId = buffer.readLongLE()
val unk1 = buffer.readByte().toInt()
val type = buffer.readByte().toInt()
val data = ByteArray(buffer.readableBytes())
buffer.readBytes(data)
return DialogDataPacket(entityId, unk1, type, data)
}
}
@@ -1,19 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogOptionPacket(val data: Int)
class DialogOptionSerializer : PacketSerializer<DialogOptionPacket> {
override fun serialize(packet: DialogOptionPacket, buffer: ByteBuf) {
buffer.writeIntLE(packet.data)
}
}
class DialogOptionDeserializer : PacketDeserializer<DialogOptionPacket> {
override fun deserialize(buffer: ByteBuf): DialogOptionPacket {
return DialogOptionPacket(buffer.readIntLE())
}
}
@@ -1,19 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogStatePacket(val active: Boolean)
class DialogStateSerializer : PacketSerializer<DialogStatePacket> {
override fun serialize(packet: DialogStatePacket, buffer: ByteBuf) {
buffer.writeBoolean(packet.active)
}
}
class DialogStateDeserializer : PacketDeserializer<DialogStatePacket> {
override fun deserialize(buffer: ByteBuf): DialogStatePacket {
return DialogStatePacket(buffer.readBoolean())
}
}
@@ -1,25 +0,0 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class EntityInteractPacket(
val entityId: Long,
val token: Long,
)
class EntityInteractSerializer : PacketSerializer<EntityInteractPacket> {
override fun serialize(packet: EntityInteractPacket, buffer: ByteBuf) {
buffer.writeLongLE(packet.entityId)
buffer.writeLongLE(packet.token)
}
}
class EntityInteractDeserializer : PacketDeserializer<EntityInteractPacket> {
override fun deserialize(buffer: ByteBuf): EntityInteractPacket {
val entityId = buffer.readLongLE()
val token = buffer.readLongLE()
return EntityInteractPacket(entityId, token)
}
}
Loaded 100 of 350 files, more files were not shown because too many files have changed in this diff. Show more