refactor(network): rework network module, use new bytecodec module and introduce proper packet events
This commit is contained in:
1 parent
8048827121
commit
d27a54f360
340 files changed
+7458
-62715
No files matched your search
Whitespace-only changes.
@@ -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)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ dependencyResolutionManagement {
|
|||||||
@Suppress("UnstableApiUsage")
|
@Suppress("UnstableApiUsage")
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
}
|
}
|
||||||
|
|
||||||
versionCatalogs {
|
versionCatalogs {
|
||||||
|
|||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +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) }
|
dependencies { testImplementation(libs.bundles.kotest) }
|
||||||
@@ -67,7 +67,7 @@ class NioReadBuffer(private val nio: ByteBuffer) : ReadBuffer {
|
|||||||
override fun readByte(): Byte = nio.get()
|
override fun readByte(): Byte = nio.get()
|
||||||
|
|
||||||
override fun readBytes(dst: ByteArray, offset: Int, length: Int) {
|
override fun readBytes(dst: ByteArray, offset: Int, length: Int) {
|
||||||
nio.get(dst, offset, length)
|
nio[dst, offset, length]
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun skip(n: Int) {
|
override fun skip(n: Int) {
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ fun <A, B> Codec<A>.then(other: Codec<B>): Codec<Pair<A, B>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface BitsBuilder {
|
fun interface BitsBuilder {
|
||||||
fun bit(index: Int, name: String)
|
fun bit(index: Int, name: String)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,14 +254,11 @@ internal constructor(
|
|||||||
|
|
||||||
fun bitsLE(backing: Codec<Int>, builder: BitsBuilder.() -> Unit): BitsCodec {
|
fun bitsLE(backing: Codec<Int>, builder: BitsBuilder.() -> Unit): BitsCodec {
|
||||||
val map = LinkedHashMap<String, Int>()
|
val map = LinkedHashMap<String, Int>()
|
||||||
val b =
|
val b = BitsBuilder { index, name ->
|
||||||
object : BitsBuilder {
|
require(index in 0..31) { "bit index out of range: $index" }
|
||||||
override fun bit(index: Int, name: String) {
|
require(name !in map) { "duplicate bit name: $name" }
|
||||||
require(index in 0..31) { "bit index out of range: $index" }
|
map[name] = index
|
||||||
require(name !in map) { "duplicate bit name: $name" }
|
}
|
||||||
map[name] = index
|
|
||||||
}
|
|
||||||
}
|
|
||||||
b.builder()
|
b.builder()
|
||||||
return BitsCodec(backing, map)
|
return BitsCodec(backing, map)
|
||||||
}
|
}
|
||||||
@@ -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
@@ -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
|
||||||
@@ -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" }
|
||||||
@@ -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) }
|
||||||
@@ -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
-1
@@ -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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-71
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-57
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-15
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-25
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-27
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-19
@@ -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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-19
@@ -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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-25
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-22
@@ -1,22 +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 EntityLeavePacket(
|
|
||||||
val entityId: Long,
|
|
||||||
)
|
|
||||||
|
|
||||||
class EntityLeaveSerializer : PacketSerializer<EntityLeavePacket> {
|
|
||||||
override fun serialize(packet: EntityLeavePacket, buffer: ByteBuf) {
|
|
||||||
buffer.writeLong(packet.entityId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class EntityLeaveDeserializer : PacketDeserializer<EntityLeavePacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): EntityLeavePacket {
|
|
||||||
val entityId = buffer.readLong()
|
|
||||||
return EntityLeavePacket(entityId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-41
@@ -1,41 +0,0 @@
|
|||||||
package de.fiereu.openmmo.protocols.game.packets
|
|
||||||
|
|
||||||
import de.fiereu.openmmo.common.enums.Direction
|
|
||||||
import de.fiereu.openmmo.protocols.PacketDeserializer
|
|
||||||
import de.fiereu.openmmo.protocols.PacketSerializer
|
|
||||||
import io.netty.buffer.ByteBuf
|
|
||||||
|
|
||||||
data class EntityMovePacket(
|
|
||||||
val entityId: Long,
|
|
||||||
val marker: Byte = 0x33,
|
|
||||||
val subtype: Byte = 0x03,
|
|
||||||
val seq: Byte = 0,
|
|
||||||
val x: Byte,
|
|
||||||
val y: Byte,
|
|
||||||
val direction: Direction,
|
|
||||||
)
|
|
||||||
|
|
||||||
class EntityMovePacketSerializer : PacketSerializer<EntityMovePacket> {
|
|
||||||
override fun serialize(packet: EntityMovePacket, buffer: ByteBuf) {
|
|
||||||
buffer.writeLong(packet.entityId)
|
|
||||||
buffer.writeByte(packet.marker.toInt())
|
|
||||||
buffer.writeByte(packet.subtype.toInt())
|
|
||||||
buffer.writeByte(packet.seq.toInt())
|
|
||||||
buffer.writeByte(packet.x.toInt())
|
|
||||||
buffer.writeByte(packet.y.toInt())
|
|
||||||
buffer.writeByte(packet.direction.ordinal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class EntityMovePacketDeserializer : PacketDeserializer<EntityMovePacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): EntityMovePacket {
|
|
||||||
val entityId = buffer.readLong()
|
|
||||||
val marker = buffer.readByte()
|
|
||||||
val subtype = buffer.readByte()
|
|
||||||
val seq = buffer.readByte()
|
|
||||||
val x = buffer.readByte()
|
|
||||||
val y = buffer.readByte()
|
|
||||||
val direction = Direction.entries[buffer.readByte().toInt()]
|
|
||||||
return EntityMovePacket(entityId, marker, subtype, seq, x, y, direction)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-23
@@ -1,23 +0,0 @@
|
|||||||
package de.fiereu.openmmo.protocols.game.packets
|
|
||||||
|
|
||||||
import de.fiereu.openmmo.common.enums.Direction
|
|
||||||
import de.fiereu.openmmo.protocols.PacketDeserializer
|
|
||||||
import de.fiereu.openmmo.protocols.PacketSerializer
|
|
||||||
import io.netty.buffer.ByteBuf
|
|
||||||
|
|
||||||
data class FaceDirectionPacket(
|
|
||||||
val direction: Direction,
|
|
||||||
)
|
|
||||||
|
|
||||||
class FaceDirectionSerializer : PacketSerializer<FaceDirectionPacket> {
|
|
||||||
override fun serialize(packet: FaceDirectionPacket, buffer: ByteBuf) {
|
|
||||||
buffer.writeByte(packet.direction.ordinal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class FaceDirectionDeserializer : PacketDeserializer<FaceDirectionPacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): FaceDirectionPacket {
|
|
||||||
val direction = Direction.entries[buffer.readByte().toInt()]
|
|
||||||
return FaceDirectionPacket(direction)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-40
@@ -1,40 +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 InteractivePacket(
|
|
||||||
val id: Int,
|
|
||||||
val type: Int,
|
|
||||||
val unk1: Int,
|
|
||||||
val unk2: Int,
|
|
||||||
val targetEntityId: Long,
|
|
||||||
val unk3: Int,
|
|
||||||
val unk4: Int,
|
|
||||||
)
|
|
||||||
|
|
||||||
class InteractiveSerializer : PacketSerializer<InteractivePacket> {
|
|
||||||
override fun serialize(packet: InteractivePacket, buffer: ByteBuf) {
|
|
||||||
buffer.writeByte(packet.id)
|
|
||||||
buffer.writeByte(packet.type)
|
|
||||||
buffer.writeIntLE(packet.unk1)
|
|
||||||
buffer.writeIntLE(packet.unk2)
|
|
||||||
buffer.writeLongLE(packet.targetEntityId)
|
|
||||||
buffer.writeShortLE(packet.unk3)
|
|
||||||
buffer.writeShortLE(packet.unk4)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class InteractiveDeserializer : PacketDeserializer<InteractivePacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): InteractivePacket {
|
|
||||||
val id = buffer.readByte().toInt()
|
|
||||||
val type = buffer.readByte().toInt()
|
|
||||||
val unk1 = buffer.readIntLE()
|
|
||||||
val unk2 = buffer.readIntLE()
|
|
||||||
val targetEntityId = buffer.readLongLE()
|
|
||||||
val unk3 = buffer.readShortLE().toInt()
|
|
||||||
val unk4 = buffer.readShortLE().toInt()
|
|
||||||
return InteractivePacket(id, type, unk1, unk2, targetEntityId, unk3, unk4)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-25
@@ -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 InteractiveResponsePacket(
|
|
||||||
val id: Int,
|
|
||||||
val unk: Int,
|
|
||||||
)
|
|
||||||
|
|
||||||
class InteractiveResponseSerializer : PacketSerializer<InteractiveResponsePacket> {
|
|
||||||
override fun serialize(packet: InteractiveResponsePacket, buffer: ByteBuf) {
|
|
||||||
buffer.writeByte(packet.id)
|
|
||||||
buffer.writeByte(packet.unk)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class InteractiveResponseDeserializer : PacketDeserializer<InteractiveResponsePacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): InteractiveResponsePacket {
|
|
||||||
val id = buffer.readByte().toInt()
|
|
||||||
val unk = buffer.readByte().toInt()
|
|
||||||
return InteractiveResponsePacket(id, unk)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-173
@@ -1,173 +0,0 @@
|
|||||||
package de.fiereu.openmmo.protocols.game.packets
|
|
||||||
|
|
||||||
import de.fiereu.openmmo.common.enums.Arch
|
|
||||||
import de.fiereu.openmmo.common.enums.Bitness
|
|
||||||
import de.fiereu.openmmo.common.enums.Platform
|
|
||||||
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 RomInfo(val code: String, val id: Byte, val type: Byte)
|
|
||||||
|
|
||||||
abstract class GameAuthenticationData
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Used when a player reconnects to the game server after a disconnection. This data typically
|
|
||||||
* includes the sessions unique id and a session key that was issued by the login server to
|
|
||||||
* re-establish the session.
|
|
||||||
*/
|
|
||||||
data class ReconnectAuthData(val sessionId: Long, val sessionKey: ByteArray) :
|
|
||||||
GameAuthenticationData()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Used when a player is joining the game server for the first time after logging in. This data
|
|
||||||
* typically includes the user's unique id and a session key that was issued by the login server to
|
|
||||||
* authenticate the session.
|
|
||||||
*/
|
|
||||||
data class NewAuthData(
|
|
||||||
val userId: Int,
|
|
||||||
val sessionKey: ByteArray,
|
|
||||||
) : GameAuthenticationData()
|
|
||||||
|
|
||||||
data class JoinGamePacket(
|
|
||||||
val authData: GameAuthenticationData,
|
|
||||||
val mac: ByteArray,
|
|
||||||
val clientRevision: Int,
|
|
||||||
val installationRevision: Int,
|
|
||||||
val currentChatLanguage: Byte,
|
|
||||||
val chatLanguages: Short,
|
|
||||||
val matchmakingLanguages: Short,
|
|
||||||
val romMask: Byte,
|
|
||||||
val roms: List<RomInfo>,
|
|
||||||
val clientInfo: Map<Byte, String>,
|
|
||||||
val platform: Platform,
|
|
||||||
val arch: Arch,
|
|
||||||
val bitness: Bitness,
|
|
||||||
val unk1: ByteArray
|
|
||||||
)
|
|
||||||
|
|
||||||
class JoinPacketSerializer : PacketSerializer<JoinGamePacket> {
|
|
||||||
override fun serialize(packet: JoinGamePacket, buffer: ByteBuf) {
|
|
||||||
when (packet.authData) {
|
|
||||||
is NewAuthData -> {
|
|
||||||
buffer.writeByte(0x00)
|
|
||||||
buffer.writeIntLE(packet.authData.userId)
|
|
||||||
buffer.writeByte(packet.authData.sessionKey.size)
|
|
||||||
buffer.writeBytes(packet.authData.sessionKey)
|
|
||||||
}
|
|
||||||
is ReconnectAuthData -> {
|
|
||||||
buffer.writeByte(0x01)
|
|
||||||
buffer.writeLongLE(packet.authData.sessionId)
|
|
||||||
buffer.writeByte(packet.authData.sessionKey.size)
|
|
||||||
buffer.writeBytes(packet.authData.sessionKey)
|
|
||||||
}
|
|
||||||
else ->
|
|
||||||
throw IllegalArgumentException(
|
|
||||||
"Unsupported authentication data type: ${packet.authData::class.simpleName}")
|
|
||||||
}
|
|
||||||
buffer.writeBytes(packet.mac)
|
|
||||||
buffer.writeIntLE(packet.clientRevision)
|
|
||||||
buffer.writeIntLE(packet.installationRevision)
|
|
||||||
buffer.writeByte(packet.currentChatLanguage.toInt())
|
|
||||||
buffer.writeShortLE(packet.chatLanguages.toInt())
|
|
||||||
buffer.writeShortLE(packet.matchmakingLanguages.toInt())
|
|
||||||
buffer.writeByte(packet.romMask.toInt())
|
|
||||||
|
|
||||||
buffer.writeByte(packet.roms.size)
|
|
||||||
for (rom in packet.roms) {
|
|
||||||
buffer.writeUtf16LE(rom.code)
|
|
||||||
buffer.writeByte(rom.id.toInt())
|
|
||||||
buffer.writeByte(rom.type.toInt())
|
|
||||||
}
|
|
||||||
|
|
||||||
buffer.writeByte(packet.clientInfo.size)
|
|
||||||
for ((key, value) in packet.clientInfo) {
|
|
||||||
buffer.writeByte(key.toInt())
|
|
||||||
buffer.writeUtf16LE(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
buffer.writeByte(packet.platform.ordinal)
|
|
||||||
buffer.writeByte(packet.arch.ordinal)
|
|
||||||
buffer.writeByte(packet.bitness.ordinal)
|
|
||||||
|
|
||||||
buffer.writeByte(packet.unk1.size)
|
|
||||||
buffer.writeBytes(packet.unk1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class JoinPacketDeserializer : PacketDeserializer<JoinGamePacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): JoinGamePacket {
|
|
||||||
val authOption = buffer.readByte()
|
|
||||||
val authenticationData =
|
|
||||||
when (authOption) {
|
|
||||||
0x00.toByte() -> {
|
|
||||||
val userId = buffer.readIntLE()
|
|
||||||
val sessionKeyLength = buffer.readUnsignedByte().toInt()
|
|
||||||
val sessionKey = ByteArray(sessionKeyLength)
|
|
||||||
buffer.readBytes(sessionKey)
|
|
||||||
NewAuthData(userId, sessionKey)
|
|
||||||
}
|
|
||||||
0x01.toByte() -> {
|
|
||||||
val playerId = buffer.readLongLE()
|
|
||||||
val sessionKeyLength = buffer.readUnsignedByte().toInt()
|
|
||||||
val sessionKey = ByteArray(sessionKeyLength)
|
|
||||||
buffer.readBytes(sessionKey)
|
|
||||||
ReconnectAuthData(playerId, sessionKey)
|
|
||||||
}
|
|
||||||
else -> throw IllegalArgumentException("Unsupported authentication option: $authOption")
|
|
||||||
}
|
|
||||||
|
|
||||||
val mac = ByteArray(6)
|
|
||||||
buffer.readBytes(mac)
|
|
||||||
|
|
||||||
val clientRevision = buffer.readIntLE()
|
|
||||||
val installationRevision = buffer.readIntLE()
|
|
||||||
val currentChatLanguage = buffer.readByte()
|
|
||||||
val chatLanguages = buffer.readShortLE()
|
|
||||||
val ignoreLanguages = buffer.readShortLE()
|
|
||||||
val romMask = buffer.readByte()
|
|
||||||
|
|
||||||
val romCount = buffer.readUnsignedByte().toInt()
|
|
||||||
val roms = mutableListOf<RomInfo>()
|
|
||||||
for (i in 0 until romCount) {
|
|
||||||
val code = buffer.readUtf16LE()
|
|
||||||
val id = buffer.readByte()
|
|
||||||
val type = buffer.readByte()
|
|
||||||
roms.add(RomInfo(code, id, type))
|
|
||||||
}
|
|
||||||
|
|
||||||
val clientInfoCount = buffer.readUnsignedByte().toInt()
|
|
||||||
val clientInfo = mutableMapOf<Byte, String>()
|
|
||||||
for (i in 0 until clientInfoCount) {
|
|
||||||
val key = buffer.readByte()
|
|
||||||
val value = buffer.readUtf16LE()
|
|
||||||
clientInfo[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
val platform = Platform.from(buffer.readByte().toInt())
|
|
||||||
val arch = Arch.from(buffer.readByte().toInt())
|
|
||||||
val bitness = Bitness.from(buffer.readByte().toInt())
|
|
||||||
|
|
||||||
val unk1 = buffer.readByte().toInt()
|
|
||||||
val unk2 = ByteArray(unk1)
|
|
||||||
buffer.readBytes(unk2)
|
|
||||||
|
|
||||||
return JoinGamePacket(
|
|
||||||
authenticationData,
|
|
||||||
mac,
|
|
||||||
clientRevision,
|
|
||||||
installationRevision,
|
|
||||||
currentChatLanguage,
|
|
||||||
chatLanguages,
|
|
||||||
ignoreLanguages,
|
|
||||||
romMask,
|
|
||||||
roms,
|
|
||||||
clientInfo,
|
|
||||||
platform,
|
|
||||||
arch,
|
|
||||||
bitness,
|
|
||||||
unk2)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
package de.fiereu.openmmo.protocols.game.packets
|
|
||||||
|
|
||||||
import de.fiereu.openmmo.protocols.PacketDeserializer
|
|
||||||
import de.fiereu.openmmo.protocols.PacketSerializer
|
|
||||||
import de.fiereu.openmmo.protocols.readUtf16LE
|
|
||||||
import de.fiereu.openmmo.protocols.writeUtf16LE
|
|
||||||
import io.netty.buffer.ByteBuf
|
|
||||||
import java.time.LocalDate
|
|
||||||
import java.time.ZoneId
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Some info to the packet:
|
|
||||||
* The packet is sent in response to a JoinGamePacket BUT
|
|
||||||
* seems to also be sent as some kind of time sync packet
|
|
||||||
*/
|
|
||||||
data class JoinResponsePacket(
|
|
||||||
val canJoin: Boolean,
|
|
||||||
val stats: GameStats? = null
|
|
||||||
// we dont need TimeInfo here since it can be calculated on the fly
|
|
||||||
) {
|
|
||||||
data class GameStats(val playtime: Int, val rewardPoints: Int, val balance: Int)
|
|
||||||
}
|
|
||||||
|
|
||||||
class JoinResponseSerializer : PacketSerializer<JoinResponsePacket> {
|
|
||||||
override fun serialize(packet: JoinResponsePacket, buffer: ByteBuf) {
|
|
||||||
buffer.writeBoolean(packet.canJoin)
|
|
||||||
if (!packet.canJoin) return // no further data is sent
|
|
||||||
|
|
||||||
// the following fields are not used by the client, so we send empty/default values
|
|
||||||
buffer.writeUtf16LE("")
|
|
||||||
buffer.writeByte(0)
|
|
||||||
|
|
||||||
requireNotNull(packet.stats) { "Stats must be provided if canJoin is true" }
|
|
||||||
buffer.writeIntLE(packet.stats.playtime) // Playtime
|
|
||||||
buffer.writeIntLE(packet.stats.rewardPoints) // Reward Points
|
|
||||||
buffer.writeIntLE(packet.stats.balance) // Balance (pokeyen obvsly)
|
|
||||||
|
|
||||||
// start of current day in epoch seconds
|
|
||||||
// used to calculate the current hour
|
|
||||||
buffer.writeIntLE(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toEpochSecond().toInt())
|
|
||||||
// Used to calculate server time / desync
|
|
||||||
buffer.writeIntLE(((System.currentTimeMillis() / 1000).toInt()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class JoinResponseDeserializer : PacketDeserializer<JoinResponseDeserializer.JoinResponsePacket> {
|
|
||||||
data class JoinResponsePacket(
|
|
||||||
val canJoin: Boolean,
|
|
||||||
val stats: GameStats? = null,
|
|
||||||
val time: TimeInfo? = null
|
|
||||||
) {
|
|
||||||
|
|
||||||
data class GameStats(val playtime: Int, val rewardPoints: Int, val balance: Int)
|
|
||||||
|
|
||||||
data class TimeInfo(val serverDayStartSecond: Int, val serverCurrentSecond: Int)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun deserialize(buffer: ByteBuf): JoinResponsePacket {
|
|
||||||
if (!buffer.readBoolean()) {
|
|
||||||
return JoinResponsePacket(false, null)
|
|
||||||
}
|
|
||||||
|
|
||||||
// unused
|
|
||||||
buffer.readUtf16LE()
|
|
||||||
buffer.readByte()
|
|
||||||
|
|
||||||
val playtime = buffer.readUnsignedIntLE().toInt()
|
|
||||||
val rewardPoints = buffer.readUnsignedIntLE().toInt()
|
|
||||||
val balance = buffer.readUnsignedIntLE().toInt()
|
|
||||||
|
|
||||||
val serverDayStartSecond = buffer.readUnsignedIntLE().toInt()
|
|
||||||
val serverCurrentSecond = buffer.readUnsignedIntLE().toInt()
|
|
||||||
|
|
||||||
return JoinResponsePacket(
|
|
||||||
true,
|
|
||||||
JoinResponsePacket.GameStats(playtime, rewardPoints, balance),
|
|
||||||
JoinResponsePacket.TimeInfo(serverDayStartSecond, serverCurrentSecond))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-26
@@ -1,26 +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 KeepAlivePacket(
|
|
||||||
val canJoin: Boolean,
|
|
||||||
val sessionData: ByteArray,
|
|
||||||
)
|
|
||||||
|
|
||||||
class KeepAlivePacketSerializer : PacketSerializer<KeepAlivePacket> {
|
|
||||||
override fun serialize(packet: KeepAlivePacket, buffer: ByteBuf) {
|
|
||||||
buffer.writeBoolean(packet.canJoin)
|
|
||||||
buffer.writeBytes(packet.sessionData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class KeepAlivePacketDeserializer : PacketDeserializer<KeepAlivePacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): KeepAlivePacket {
|
|
||||||
val canJoin = buffer.readBoolean()
|
|
||||||
val sessionData = ByteArray(buffer.readableBytes())
|
|
||||||
buffer.readBytes(sessionData)
|
|
||||||
return KeepAlivePacket(canJoin, sessionData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-140
@@ -1,140 +0,0 @@
|
|||||||
package de.fiereu.openmmo.protocols.game.packets
|
|
||||||
|
|
||||||
import de.fiereu.openmmo.common.enums.Direction
|
|
||||||
import de.fiereu.openmmo.common.enums.EntityStatus
|
|
||||||
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.SkinSet
|
|
||||||
import de.fiereu.openmmo.protocols.game.packets.codecs.readSkinsLE
|
|
||||||
import de.fiereu.openmmo.protocols.game.packets.codecs.writeSkinsLE
|
|
||||||
import de.fiereu.openmmo.protocols.readUtf16LE
|
|
||||||
import de.fiereu.openmmo.protocols.writeShortLE
|
|
||||||
import de.fiereu.openmmo.protocols.writeUtf16LE
|
|
||||||
import io.netty.buffer.ByteBuf
|
|
||||||
|
|
||||||
data class LoadEntityPacket(
|
|
||||||
val entityId: Long,
|
|
||||||
val skin: SkinSet,
|
|
||||||
val name: String,
|
|
||||||
val regionId: Int,
|
|
||||||
val bankId: Int,
|
|
||||||
val mapId: Int,
|
|
||||||
val x: Int,
|
|
||||||
val y: Int,
|
|
||||||
val z: Int,
|
|
||||||
val facing: Direction,
|
|
||||||
val transportation: Int = 0,
|
|
||||||
val entityNameplateType: Int = 0,
|
|
||||||
val status: EntityStatus,
|
|
||||||
val hasFollower: Boolean,
|
|
||||||
val followerDexId: Short,
|
|
||||||
)
|
|
||||||
|
|
||||||
class LoadEntitySerializer : PacketSerializer<LoadEntityPacket> {
|
|
||||||
override fun serialize(packet: LoadEntityPacket, buffer: ByteBuf) =
|
|
||||||
buffer.run {
|
|
||||||
writeLongLE(packet.entityId)
|
|
||||||
writeByte(0)
|
|
||||||
writeSkinsLE(packet.skin)
|
|
||||||
writeUtf16LE(packet.name)
|
|
||||||
writeByte(packet.regionId)
|
|
||||||
writeByte(packet.bankId)
|
|
||||||
writeByte(packet.mapId)
|
|
||||||
writeShortLE(packet.x)
|
|
||||||
writeShortLE(packet.y)
|
|
||||||
writeByte(packet.z)
|
|
||||||
writeByte(packet.facing.ordinal)
|
|
||||||
writeByte(packet.transportation)
|
|
||||||
writeByte(packet.entityNameplateType)
|
|
||||||
|
|
||||||
var flags = 0
|
|
||||||
if (packet.hasFollower) flags = flags or 0x04
|
|
||||||
writeShortLE(flags)
|
|
||||||
if (flags and 0x01 != 0) {
|
|
||||||
writeByte(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flags and 0x02 != 0) {
|
|
||||||
writeByte(0)
|
|
||||||
writeShortLE(flags)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flags and 0x04 != 0) {
|
|
||||||
writeShortLE(packet.followerDexId)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flags and 0x08 != 0) {
|
|
||||||
writeByte(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flags and 0x10 != 0) {
|
|
||||||
writeIntLE(0)
|
|
||||||
writeUtf16LE("")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class LoadEntityDeserializer : PacketDeserializer<LoadEntityPacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): LoadEntityPacket =
|
|
||||||
buffer.run {
|
|
||||||
val entityId = readLong()
|
|
||||||
readByte() // Skip padding byte
|
|
||||||
val skin = readSkinsLE(SkinSlot.entries)
|
|
||||||
val name = readUtf16LE()
|
|
||||||
val regionId = readByte().toInt()
|
|
||||||
val bankId = readByte().toInt()
|
|
||||||
val mapId = readByte().toInt()
|
|
||||||
val x = readShortLE()
|
|
||||||
val y = readShortLE()
|
|
||||||
val z = readByte().toInt()
|
|
||||||
val facing = Direction.entries[readByte().toInt()]
|
|
||||||
val transportation = readByte().toInt()
|
|
||||||
val entityNameplateType = readByte().toInt()
|
|
||||||
|
|
||||||
val flags = readUnsignedShortLE()
|
|
||||||
if (flags and 0x01 != 0) {
|
|
||||||
readByte()
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flags and 0x02 != 0) {
|
|
||||||
readByte()
|
|
||||||
readUnsignedShortLE()
|
|
||||||
}
|
|
||||||
|
|
||||||
val hasFollower = (flags and 0x04) != 0
|
|
||||||
val followerDexId =
|
|
||||||
if (hasFollower) {
|
|
||||||
readShortLE()
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flags and 0x08 != 0) {
|
|
||||||
readByte()
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flags and 0x10 != 0) {
|
|
||||||
readInt() // Skip int value
|
|
||||||
readUtf16LE() // Skip string
|
|
||||||
}
|
|
||||||
|
|
||||||
LoadEntityPacket(
|
|
||||||
entityId = entityId,
|
|
||||||
skin = skin,
|
|
||||||
name = name,
|
|
||||||
regionId = regionId,
|
|
||||||
bankId = bankId,
|
|
||||||
mapId = mapId,
|
|
||||||
x = x.toInt(),
|
|
||||||
y = y.toInt(),
|
|
||||||
z = z,
|
|
||||||
facing = facing,
|
|
||||||
transportation = transportation,
|
|
||||||
entityNameplateType = entityNameplateType,
|
|
||||||
status = EntityStatus.NONE,
|
|
||||||
hasFollower = hasFollower,
|
|
||||||
followerDexId = followerDexId,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-234
@@ -1,234 +0,0 @@
|
|||||||
package de.fiereu.openmmo.protocols.game.packets
|
|
||||||
|
|
||||||
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.common.utils.gzipCompress
|
|
||||||
import de.fiereu.openmmo.common.utils.gzipDecompress
|
|
||||||
import de.fiereu.openmmo.common.utils.isNdsRegion
|
|
||||||
import de.fiereu.openmmo.protocols.PacketDeserializer
|
|
||||||
import de.fiereu.openmmo.protocols.PacketSerializer
|
|
||||||
import de.fiereu.openmmo.protocols.game.packets.codecs.readTile2DLE
|
|
||||||
import de.fiereu.openmmo.protocols.game.packets.codecs.writeTile2DLE
|
|
||||||
import de.fiereu.openmmo.protocols.readUtf16LE
|
|
||||||
import de.fiereu.openmmo.protocols.writeUtf16LE
|
|
||||||
import io.netty.buffer.ByteBuf
|
|
||||||
|
|
||||||
data class LoadMapPacket(
|
|
||||||
val reloadPlayer: Boolean,
|
|
||||||
val deleteCache: Boolean,
|
|
||||||
val regionId: Int,
|
|
||||||
val bankId: Int,
|
|
||||||
val mapId: Int,
|
|
||||||
val mapData: MapData
|
|
||||||
) {
|
|
||||||
init {
|
|
||||||
when (mapData) {
|
|
||||||
is MapData.NdsMapData -> require(isNdsRegion(regionId)) { "MapData is invalid" }
|
|
||||||
is MapData.GbaMapData -> require(!isNdsRegion(regionId)) { "MapData is invalid" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sealed interface MapData {
|
|
||||||
data class NdsMapData(val lighting: Lighting, val weather: Weather, val mapType: MapType) :
|
|
||||||
MapData
|
|
||||||
|
|
||||||
data class GbaConnection(
|
|
||||||
val direction: Int,
|
|
||||||
val unknown: Int,
|
|
||||||
val targetBank: Int,
|
|
||||||
val targetMap: Int,
|
|
||||||
)
|
|
||||||
|
|
||||||
data class GbaMapData(
|
|
||||||
val width: Int,
|
|
||||||
val height: Int,
|
|
||||||
val paletteIdx1: Int,
|
|
||||||
val paletteIdx2: Int,
|
|
||||||
val borderWidth: Int,
|
|
||||||
val borderHeight: Int,
|
|
||||||
val unknownShort: Int = 0,
|
|
||||||
val unknownByte: Int = 0,
|
|
||||||
val borderTiles: List<Tile2D>,
|
|
||||||
val lighting: Lighting,
|
|
||||||
val weather: Weather,
|
|
||||||
val mapType: MapType,
|
|
||||||
val encounterType: EncounterType,
|
|
||||||
val connections: List<GbaConnection> = emptyList(),
|
|
||||||
) : MapData {
|
|
||||||
init {
|
|
||||||
require(borderWidth * borderHeight == borderTiles.size) {
|
|
||||||
"borderTiles size doesnt match dimensions"
|
|
||||||
}
|
|
||||||
require(borderWidth * borderHeight > 0) { "BorderWidth & Height must be greater than zero" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class LoadMapPacketSerializer : PacketSerializer<LoadMapPacket> {
|
|
||||||
override fun serialize(packet: LoadMapPacket, buffer: ByteBuf) {
|
|
||||||
buffer.apply {
|
|
||||||
var flags = 0
|
|
||||||
if (packet.deleteCache) flags = flags or 1
|
|
||||||
if (packet.reloadPlayer) flags = flags or 2
|
|
||||||
|
|
||||||
writeByte(flags)
|
|
||||||
|
|
||||||
writeByte(packet.regionId) // Client will stop parsing if the region is not loaded
|
|
||||||
writeByte(packet.bankId)
|
|
||||||
writeByte(packet.mapId)
|
|
||||||
writeByte(0)
|
|
||||||
|
|
||||||
when (packet.mapData) {
|
|
||||||
is MapData.NdsMapData -> {
|
|
||||||
writeShortLE(0)
|
|
||||||
val unk = 0
|
|
||||||
writeByte(unk)
|
|
||||||
for (i in 0 until unk) {
|
|
||||||
writeShortLE(0)
|
|
||||||
writeShortLE(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
writeByte(packet.mapData.lighting.ordinal)
|
|
||||||
writeByte(packet.mapData.weather.ordinal)
|
|
||||||
writeByte(packet.mapData.mapType.ordinal)
|
|
||||||
}
|
|
||||||
is MapData.GbaMapData -> {
|
|
||||||
writeIntLE(packet.mapData.width)
|
|
||||||
writeIntLE(packet.mapData.height)
|
|
||||||
writeIntLE(packet.mapData.paletteIdx1)
|
|
||||||
writeIntLE(packet.mapData.paletteIdx2)
|
|
||||||
writeByte(packet.mapData.borderWidth)
|
|
||||||
writeByte(packet.mapData.borderHeight)
|
|
||||||
writeShortLE(packet.mapData.unknownShort)
|
|
||||||
writeByte(packet.mapData.unknownByte)
|
|
||||||
writeByte(packet.mapData.lighting.ordinal)
|
|
||||||
writeByte(packet.mapData.weather.ordinal)
|
|
||||||
writeByte(packet.mapData.mapType.ordinal)
|
|
||||||
writeByte(packet.mapData.encounterType.ordinal)
|
|
||||||
|
|
||||||
for (tile2D in packet.mapData.borderTiles) {
|
|
||||||
writeTile2DLE(tile2D)
|
|
||||||
}
|
|
||||||
|
|
||||||
val hasUnknown = false
|
|
||||||
writeBoolean(hasUnknown)
|
|
||||||
if (hasUnknown) {
|
|
||||||
val unknown = ByteArray(0)
|
|
||||||
writeIntLE(unknown.size)
|
|
||||||
writeBytes(unknown.gzipCompress())
|
|
||||||
}
|
|
||||||
|
|
||||||
val connections = packet.mapData.connections
|
|
||||||
writeByte(connections.size)
|
|
||||||
for (conn in connections) {
|
|
||||||
writeByte(conn.direction)
|
|
||||||
writeIntLE(conn.unknown)
|
|
||||||
writeByte(conn.targetBank)
|
|
||||||
writeByte(conn.targetMap)
|
|
||||||
}
|
|
||||||
|
|
||||||
val hasUnknown2 = false
|
|
||||||
writeBoolean(hasUnknown2)
|
|
||||||
if (hasUnknown2) {
|
|
||||||
writeLongLE(0)
|
|
||||||
writeUtf16LE("")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class LoadMapPacketDeserializer : PacketDeserializer<LoadMapPacket> {
|
|
||||||
override fun deserialize(buffer: ByteBuf): LoadMapPacket =
|
|
||||||
buffer.let {
|
|
||||||
val flags = buffer.readByte().toInt()
|
|
||||||
val deleteCache = (flags and 1) != 0
|
|
||||||
val reloadPlayer = (flags and 2) != 0
|
|
||||||
|
|
||||||
val regionId = buffer.readByte().toInt()
|
|
||||||
val bankId = buffer.readByte().toInt()
|
|
||||||
val mapId = buffer.readByte().toInt()
|
|
||||||
buffer.readByte()
|
|
||||||
|
|
||||||
val mapData =
|
|
||||||
if (isNdsRegion(regionId)) {
|
|
||||||
// NDS format
|
|
||||||
buffer.readShortLE()
|
|
||||||
val unk = buffer.readByte().toInt()
|
|
||||||
for (i in 0 until unk) {
|
|
||||||
buffer.readShortLE()
|
|
||||||
buffer.readShortLE()
|
|
||||||
}
|
|
||||||
val lighting = Lighting.entries[buffer.readByte().toInt()]
|
|
||||||
val weather = Weather.entries[buffer.readByte().toInt()]
|
|
||||||
val mapType = MapType.entries[buffer.readByte().toInt()]
|
|
||||||
MapData.NdsMapData(lighting, weather, mapType)
|
|
||||||
} else {
|
|
||||||
// GBA format
|
|
||||||
val width = buffer.readIntLE()
|
|
||||||
val height = buffer.readIntLE()
|
|
||||||
val paletteIdx1 = buffer.readIntLE()
|
|
||||||
val paletteIdx2 = buffer.readIntLE()
|
|
||||||
val borderWidth = buffer.readByte().toInt()
|
|
||||||
val borderHeight = buffer.readByte().toInt()
|
|
||||||
val unknownShort = buffer.readShortLE().toInt()
|
|
||||||
val unknownByte = buffer.readByte().toInt()
|
|
||||||
val lighting = Lighting.entries[buffer.readByte().toInt()]
|
|
||||||
val weather = Weather.entries[buffer.readByte().toInt()]
|
|
||||||
val mapType = MapType.entries[buffer.readByte().toInt()]
|
|
||||||
val encounterType = EncounterType.entries[buffer.readByte().toInt()]
|
|
||||||
|
|
||||||
val borderTiles = mutableListOf<Tile2D>()
|
|
||||||
for (i in 0 until (borderWidth * borderHeight)) {
|
|
||||||
borderTiles.add(buffer.readTile2DLE())
|
|
||||||
}
|
|
||||||
|
|
||||||
val hasUnknown = buffer.readBoolean()
|
|
||||||
if (hasUnknown) {
|
|
||||||
val unknownSize = buffer.readIntLE()
|
|
||||||
val unknownCompressed = ByteArray(unknownSize)
|
|
||||||
buffer.readBytes(unknownCompressed)
|
|
||||||
unknownCompressed.gzipDecompress()
|
|
||||||
}
|
|
||||||
|
|
||||||
val connectionCount = buffer.readByte().toInt()
|
|
||||||
val connections = mutableListOf<MapData.GbaConnection>()
|
|
||||||
for (i in 0 until connectionCount) {
|
|
||||||
val direction = buffer.readByte().toInt()
|
|
||||||
val unknown = buffer.readIntLE()
|
|
||||||
val targetBank = buffer.readByte().toInt()
|
|
||||||
val targetMap = buffer.readByte().toInt()
|
|
||||||
connections.add(MapData.GbaConnection(direction, unknown, targetBank, targetMap))
|
|
||||||
}
|
|
||||||
|
|
||||||
val hasUnknown2 = buffer.readBoolean()
|
|
||||||
if (hasUnknown2) {
|
|
||||||
buffer.readLongLE()
|
|
||||||
buffer.readUtf16LE()
|
|
||||||
}
|
|
||||||
|
|
||||||
MapData.GbaMapData(
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
paletteIdx1,
|
|
||||||
paletteIdx2,
|
|
||||||
borderWidth,
|
|
||||||
borderHeight,
|
|
||||||
unknownShort,
|
|
||||||
unknownByte,
|
|
||||||
borderTiles,
|
|
||||||
lighting,
|
|
||||||
weather,
|
|
||||||
mapType,
|
|
||||||
encounterType,
|
|
||||||
connections = connections)
|
|
||||||
}
|
|
||||||
|
|
||||||
LoadMapPacket(reloadPlayer, deleteCache, regionId, bankId, mapId, mapData)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Loaded 100 of 340 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user