Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add initial server list ping implementation #179

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,11 @@ kotlin {
dependencies {
implementation(libs.bundles.ktor.server)
implementation(libs.bundles.ktor.client)
implementation(libs.ktor.network)

implementation(libs.adventure.minimessage)
implementation(libs.adventure.text.serializer.gson)
implementation(libs.adventure.text.serializer.legacy)
implementation(libs.cache4k)
implementation(libs.logback.classic)
}
Expand Down
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ spotless = { id = "com.diffplug.spotless", version = "6.22.0" }
[libraries]
adventure-minimessage = { group = "net.kyori", name = "adventure-text-minimessage", version.ref = "adventure" }
adventure-text-serializer-gson = { group = "net.kyori", name = "adventure-text-serializer-gson", version.ref = "adventure" }
adventure-text-serializer-legacy = { group = "net.kyori", name = "adventure-text-serializer-legacy", version.ref = "adventure" }
cache4k = { group = "io.github.reactivecircus.cache4k", name = "cache4k", version = "0.11.0" }
kotlinx-html = { group = "org.jetbrains.kotlinx", name = "kotlinx-html", version = "0.8.0" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version = "1.6.0" }
Expand All @@ -24,6 +25,7 @@ ktor-client-okhttp = { group = "io.ktor", name = "ktor-client-okhttp", version.r
ktor-server-websockets = { group = "io.ktor", name = "ktor-server-websockets", version.ref = "ktor" }
ktor-server-caching-headers = { group = "io.ktor", name = "ktor-server-caching-headers", version.ref = "ktor" }
ktor-server-compression = { group = "io.ktor", name = "ktor-server-compression", version.ref = "ktor" }
ktor-network = { group = "io.ktor", name = "ktor-network", version.ref = "ktor" }
logback-classic = { group = "ch.qos.logback", name = "logback-classic", version = "1.4.11" }

zKtlint = { group = "com.pinterest", name = "ktlint", version.ref = "ktlint"}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import io.ktor.server.websocket.WebSockets
import io.ktor.server.websocket.pingPeriod
import io.ktor.server.websocket.timeout
import io.ktor.websocket.WebSocketDeflateExtension
import net.kyori.adventure.webui.jvm.minimessage.preview.ServerStatusPreviewManager
import java.time.Duration

public fun Application.main() {
Expand Down Expand Up @@ -48,8 +49,12 @@ public fun Application.main() {
trace { route -> [email protected](route.buildText()) }
}
}

// Initialise the server status preview manager.
ServerStatusPreviewManager(this)
}


/** Reads a string value from the `config` block in `application.conf`. */
public fun Application.getConfigString(key: String): String =
environment.config.property("ktor.config.$key").getString()
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
package net.kyori.adventure.webui.jvm.minimessage.preview

import io.ktor.network.selector.SelectorManager
import io.ktor.network.sockets.aSocket
import io.ktor.network.sockets.openReadChannel
import io.ktor.network.sockets.openWriteChannel
import io.ktor.server.application.Application
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.ByteWriteChannel
import io.ktor.utils.io.close
import io.ktor.utils.io.writeByte
import io.ktor.utils.io.writeFully
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import net.kyori.adventure.text.minimessage.MiniMessage
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer
import okhttp3.internal.and
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import kotlin.coroutines.CoroutineContext

/** Manager class for previewing server status. */
public class ServerStatusPreviewManager(
application: Application,
) : CoroutineScope {

private val logger = LoggerFactory.getLogger(ServerStatusPreviewManager::class.java)
private val managerJob = SupervisorJob(application.coroutineContext.job)
override val coroutineContext: CoroutineContext = application.coroutineContext + managerJob

init {
launch {
// Initialise the socket.
val serverSocket = aSocket(SelectorManager(Dispatchers.IO)).tcp().bind("127.0.0.1", 9002)
logger.info("Listening for pings at ${serverSocket.localAddress}")

while (true) {
// Ensure we are active so that the socket is properly closed when the application ends.
ensureActive()

val socket = serverSocket.accept()
logger.debug("Accepted socket connection from {}", socket.remoteAddress)

launch {
try {
val receiveChannel = socket.openReadChannel()
val sendChannel = socket.openWriteChannel(autoFlush = true)

// handshake
val handshakePacket = receiveChannel.readMcPacket()
val protocolVersion = handshakePacket.readVarInt()
val serverAddress = handshakePacket.readUtf8String()
val serverPort = handshakePacket.readShort()
val nextState = handshakePacket.readVarInt()

if (nextState != 1) {
// send kick
sendChannel.writeMcPacket(0) {
it.writeString(
GsonComponentSerializer.gson()
.serialize(MiniMessage.miniMessage().deserialize("<red>You cant join here!"))
)
}
} else {
// send status response
sendChannel.writeMcPacket(0) {
it.writeString(
"""{
"version": {
"name": "${
LegacyComponentSerializer.legacySection()
.serialize(MiniMessage.miniMessage().deserialize("<rainbow>MiniMessage"))
}",
"protocol": $protocolVersion
},
"description": ${
GsonComponentSerializer.gson().serialize(
MiniMessage.miniMessage().deserialize("<rainbow>MiniMessage is cool!")
)
}
}""".trimIndent()
)
}
}

sendChannel.close()
} catch (e: Exception) {
logger.error("An unknown error occurred whilst responding to a ping from ${socket.remoteAddress}", e)
}

socket.close()
}
}
}
}

private suspend fun ByteWriteChannel.writeMcPacket(packetId: Int, consumer: (packet: DataOutputStream) -> Unit) {
val stream = ByteArrayOutputStream()
val packet = DataOutputStream(stream)

consumer.invoke(packet)

val data = stream.toByteArray()
writeVarInt(data.size + 1)
writeVarInt(packetId)
writeFully(data)
}

private fun DataOutputStream.writeString(string: String) {
val bytes = string.toByteArray(Charsets.UTF_8)
writeVarInt(bytes.size)
write(bytes)
}

private fun DataOutputStream.writeVarInt(int: Int) {
var value = int
while (true) {
if ((value and 0x7F.inv()) == 0) {
writeByte(value)
return
}

writeByte((value and 0x7F) or 0x80)

value = value ushr 7
}
}

private suspend fun ByteWriteChannel.writeVarInt(int: Int) {
var value = int
while (true) {
if ((value and 0x7F.inv()) == 0) {
writeByte(value)
return
}

writeByte((value and 0x7F) or 0x80)

value = value ushr 7
}
}

private suspend fun ByteReadChannel.readMcPacket(): ByteReadChannel {
val length = readVarInt()
val packetId = readVarInt()
val data = ByteArray(length)
readFully(data, 0, length)
return ByteReadChannel(data)
}

private suspend fun ByteReadChannel.readVarInt(): Int {
var value = 0
var position = 0
var currentByte: Byte

while (true) {
currentByte = readByte()
value = value or ((currentByte and 0x7F) shl position)

if ((currentByte and 0x80) == 0) break

position += 7

if (position >= 32) throw RuntimeException("VarInt is too big")
}

return value
}

private suspend fun ByteReadChannel.readUtf8String(): String {
val length = readVarInt()
val data = ByteArray(length)
readFully(data, 0, length)
return String(data)
}
}