Skip to content

Commit

Permalink
0.4.11: update ktor, flush when writability is false, cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
creeper123123321 committed Aug 5, 2021
1 parent 4a3f410 commit 6cc2405
Show file tree
Hide file tree
Showing 13 changed files with 42 additions and 40 deletions.
4 changes: 2 additions & 2 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ compileKotlin.kotlinOptions.jvmTarget = "11"
val gitVersion: groovy.lang.Closure<String> by extra

group = "com.github.creeper123123321.viaaas"
version = "0.4.10+" + try {
version = "0.4.11+" + try {
gitVersion()
} catch (e: Exception) {
"unknown"
Expand Down Expand Up @@ -86,7 +86,7 @@ dependencies {
implementation("org.jline:jline-terminal-jansi:3.20.0")
implementation("org.slf4j:slf4j-api:$slf4jVer")

val ktorVersion = "1.6.1"
val ktorVersion = "1.6.2"
implementation("io.ktor:ktor-network-tls-certificates:$ktorVersion")
implementation("io.ktor:ktor-websockets:$ktorVersion")
implementation("io.ktor:ktor-server-netty:$ktorVersion")
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/com/viaversion/aas/AspirinServer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ object AspirinServer {
.getResourceAsStream("viaaas_info.json")!!
.reader(Charsets.UTF_8)
.readText()
).asJsonObject.get("version").asString
).asJsonObject["version"].asString
val cleanedVer get() = version.substringBefore("+")
var viaWebServer = WebDashboardServer()
private var serverFinishing = CompletableFuture<Unit>()
Expand Down Expand Up @@ -135,7 +135,7 @@ object AspirinServer {
return try {
val latestData =
httpClient.get<JsonObject>("https://api.github.com/repos/viaversion/viaaas/releases/latest")
val latest = Version(latestData.get("tag_name")!!.asString.removePrefix("v"))
val latest = Version(latestData["tag_name"]!!.asString.removePrefix("v"))
val current = Version(cleanedVer)
when {
latest > current -> "This build is outdated. Latest is $latest"
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/com/viaversion/aas/handler/ConnectionData.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class ConnectionData(
var frontVer: Int? = null,
var backServerVer: Int? = null,
) {
val frontHandler get() = frontChannel.pipeline().get(MinecraftHandler::class.java)
val frontHandler get() = frontChannel.pipeline()[MinecraftHandler::class.java]
val backHandler get() = backChannel?.pipeline()?.get(MinecraftHandler::class.java)
val frontEncrypted get() = frontChannel.pipeline().get(CryptoCodec::class.java) != null
val frontEncrypted get() = frontChannel.pipeline()[CryptoCodec::class.java] != null
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class MinecraftHandler(
}

override fun channelActive(ctx: ChannelHandlerContext) {
endRemoteAddress = (ctx.channel().pipeline().get("proxy") as? ProxyHandler)?.destinationAddress()
endRemoteAddress = (ctx.pipeline()["proxy"] as? ProxyHandler)?.destinationAddress()
?: ctx.channel().remoteAddress()
}

Expand All @@ -46,12 +46,15 @@ class MinecraftHandler(
}

override fun channelWritabilityChanged(ctx: ChannelHandlerContext) {
if (!ctx.channel().isWritable) {
ctx.executor().execute(ctx.channel()::flush) // Flush to write more
}
other?.setAutoRead(ctx.channel().isWritable)
}

private fun failedProxy(ctx: ChannelHandlerContext): Boolean {
// proxy connect future fails are handled in another part
return (ctx.channel().pipeline().get("proxy") as? ProxyHandler)?.connectFuture()?.isSuccess == false
return (ctx.pipeline()["proxy"] as? ProxyHandler)?.connectFuture()?.isSuccess == false
}

override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ class ProtocolDetectionState(val future: CompletableFuture<ProtocolVersion>) : C
handler.data.frontChannel.close()
if (packet !is StatusResponse) throw StacklessException("Unexpected packet")
val ver = JsonParser.parseString(packet.msg).asJsonObject
.getAsJsonObject("version")
.get("protocol").asInt.parseProtocol()
.getAsJsonObject("version")["protocol"].asInt.parseProtocol()
future.complete(ver)
mcLogger.info("A.D.: ${handler.endRemoteAddress} $ver")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class HandshakeState : ConnectionState {

private fun checkRateLimit(handler: MinecraftHandler, state: State) {
val socketAddress = (handler.endRemoteAddress as InetSocketAddress).address
val limit = RateLimit.rateLimitByIp.get(socketAddress)
val limit = RateLimit.rateLimitByIp[socketAddress]

if (!limit.handshakeLimiter.tryAcquire()
|| (state == State.LOGIN && !limit.loginLimiter.tryAcquire())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ class LoginState : ConnectionState {
private fun handleCompression(handler: MinecraftHandler, setCompression: SetCompression) {
val pipe = handler.data.frontChannel.pipeline()
val threshold = setCompression.threshold
val backPipe = pipe.get(MinecraftHandler::class.java).other!!.pipeline()
val backPipe = pipe[MinecraftHandler::class.java].other!!.pipeline()

if (backPipe.get("compress") != null) {
if (backPipe["compress"] != null) {
backPipe.remove("compress")
}
if (threshold != -1) {
Expand All @@ -84,7 +84,7 @@ class LoginState : ConnectionState {

forward(handler, setCompression)

if (pipe.get("compress") != null) {
if (pipe["compress"] != null) {
pipe.remove("compress")
}
if (threshold != -1) {
Expand Down Expand Up @@ -189,7 +189,7 @@ class LoginState : ConnectionState {
handler.coroutineScope.launch(Dispatchers.IO) {
try {
val profile = hasJoined(frontName, frontHash)
val id = profile.get("id")!!.asString
val id = profile["id"]!!.asString

callbackPlayerId.complete(parseUndashedId(id))
} catch (e: Exception) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/com/viaversion/aas/handler/state/Util.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private suspend fun createBackChannel(
.connect(socketAddr)
.also { it.suspendAwait() }
.channel()
(channel.pipeline().get("proxy") as? ProxyHandler)?.connectFuture()?.suspendAwait()
(channel.pipeline()["proxy"] as? ProxyHandler)?.connectFuture()?.suspendAwait()

mcLogger.info("+ ${state.name.substring(0, 1)} ${handler.endRemoteAddress} -> $socketAddr")
handler.data.backChannel = channel as SocketChannel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper
import com.viaversion.viaversion.api.protocol.remapper.TypeRemapper
import com.viaversion.viaversion.api.type.Type
import com.viaversion.viaversion.api.type.types.version.Types1_8
import com.viaversion.viaversion.protocols.protocol1_8.ClientboundPackets1_8
import com.viaversion.viaversion.protocols.protocol1_8.ServerboundPackets1_8
import de.gerrygames.viarewind.protocol.protocol1_7_6_10to1_8.ClientboundPackets1_7
import de.gerrygames.viarewind.protocol.protocol1_7_6_10to1_8.types.Types1_7_6_10
Expand All @@ -31,7 +32,7 @@ fun Protocol1_8To1_7_6.registerEntityPackets() {
val animation = packetWrapper.read(Type.UNSIGNED_BYTE) //Animation
packetWrapper.clearInputBuffer()
if (animation.toInt() == 104 || animation.toInt() == 105) {
packetWrapper.id = 0x1C //Entity Metadata
packetWrapper.packetType = ClientboundPackets1_8.ENTITY_METADATA
packetWrapper.write(Type.VAR_INT, entityId) //Entity Id
packetWrapper.write(Type.UNSIGNED_BYTE, 0.toShort()) //Index
packetWrapper.write(Type.UNSIGNED_BYTE, 0.toShort()) //Type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,17 @@ import com.viaversion.aas.protocol.id47toid5.storage.Scoreboard
import com.viaversion.aas.protocol.id47toid5.storage.Tablist
import com.viaversion.aas.protocol.xyzToPosition
import com.viaversion.aas.protocol.xyzUBytePos
import com.viaversion.viaversion.api.Via
import com.viaversion.viaversion.api.minecraft.entities.Entity1_10Types
import com.viaversion.viaversion.api.minecraft.item.Item
import com.viaversion.viaversion.api.protocol.packet.PacketWrapper
import com.viaversion.viaversion.api.protocol.packet.State
import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper
import com.viaversion.viaversion.api.protocol.remapper.TypeRemapper
import com.viaversion.viaversion.api.type.Type
import com.viaversion.viaversion.api.type.types.CustomByteType
import com.viaversion.viaversion.api.type.types.version.Types1_8
import com.viaversion.viaversion.libs.opennbt.tag.builtin.ListTag
import com.viaversion.viaversion.libs.opennbt.tag.builtin.StringTag
import com.viaversion.viaversion.protocols.protocol1_8.ClientboundPackets1_8
import com.viaversion.viaversion.protocols.protocol1_8.ServerboundPackets1_8
import com.viaversion.viaversion.util.ChatColorUtil
import de.gerrygames.viarewind.protocol.protocol1_7_6_10to1_8.ClientboundPackets1_7
Expand Down Expand Up @@ -127,14 +126,15 @@ fun Protocol1_8To1_7_6.registerPlayerPackets() {
val entryByUUID = tablist.getTabListEntry(uuid)
if (entryByName == null || entryByUUID == null) {
if (entryByName != null || entryByUUID != null) {
val remove = PacketWrapper.create(0x38, null, packetWrapper.user())
val remove = PacketWrapper.create(ClientboundPackets1_8.PLAYER_INFO, null, packetWrapper.user())
remove.write(Type.VAR_INT, 4)
remove.write(Type.VAR_INT, 1)
remove.write(Type.UUID, entryByName?.uuid ?: entryByUUID!!.uuid)
tablist.remove(entryByName ?: entryByUUID!!)
remove.send(Protocol1_8To1_7_6::class.java)
}
val packetPlayerListItem = PacketWrapper.create(0x38, null, packetWrapper.user())
val packetPlayerListItem =
PacketWrapper.create(ClientboundPackets1_8.PLAYER_INFO, null, packetWrapper.user())
val newentry = Tablist.TabListEntry(name, uuid)
if (entryByName != null || entryByUUID != null) {
newentry.displayName =
Expand All @@ -160,8 +160,10 @@ fun Protocol1_8To1_7_6.registerPlayerPackets() {
packetPlayerListItem.write(Type.STRING, newentry.displayName)
}
packetPlayerListItem.send(Protocol1_8To1_7_6::class.java)

packetWrapper.cancel()
val delayedPacket = PacketWrapper.create(0x0C, null, packetWrapper.user())
val delayedPacket =
PacketWrapper.create(ClientboundPackets1_8.SPAWN_PLAYER, null, packetWrapper.user())
delayedPacket.write(Type.VAR_INT, entityId)
delayedPacket.write(Type.UUID, uuid)
delayedPacket.write(Type.INT, x)
Expand All @@ -171,13 +173,8 @@ fun Protocol1_8To1_7_6.registerPlayerPackets() {
delayedPacket.write(Type.BYTE, pitch)
delayedPacket.write(Type.SHORT, item)
delayedPacket.write(Types1_8.METADATA_LIST, metadata)
Via.getPlatform().runSync({
try {
delayedPacket.send(Protocol1_8To1_7_6::class.java)
} catch (ex: Exception) {
ex.printStackTrace()
}
}, 1L)

delayedPacket.send(Protocol1_8To1_7_6::class.java)
} else {
entryByUUID.properties = properties
}
Expand Down Expand Up @@ -403,10 +400,11 @@ fun Protocol1_8To1_7_6.registerPlayerPackets() {
packetWrapper.write(Type.ITEM, book)
}
packetWrapper.cancel()
packetWrapper.id = -1
packetWrapper.packetType = null
val newPacketBuf = Unpooled.buffer()
packetWrapper.writeToBuffer(newPacketBuf)
val newWrapper = PacketWrapper.create(0x17, newPacketBuf, packetWrapper.user())
val newWrapper =
PacketWrapper.create(ServerboundPackets1_8.PLUGIN_MESSAGE, newPacketBuf, packetWrapper.user())
newWrapper.passthrough(Type.STRING)
newWrapper.write(Type.SHORT, newPacketBuf.readableBytes().toShort())
newWrapper.sendToServer(Protocol1_8To1_7_6::class.java)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import com.viaversion.viaversion.api.minecraft.metadata.Metadata
import com.viaversion.viaversion.api.protocol.packet.PacketWrapper
import com.viaversion.viaversion.api.type.Type
import com.viaversion.viaversion.api.type.types.version.Types1_8
import de.gerrygames.viarewind.protocol.protocol1_7_6_10to1_8.ClientboundPackets1_7
import java.util.concurrent.ConcurrentHashMap

class EntityTracker(user: UserConnection) : StoredObject(user) {
Expand All @@ -28,7 +29,7 @@ class EntityTracker(user: UserConnection) : StoredObject(user) {

fun sendMetadataBuffer(entityId: Int) {
if (!metadataBuffer.containsKey(entityId)) return
val wrapper = PacketWrapper.create(0x1C, null, this.user)
val wrapper = PacketWrapper.create(ClientboundPackets1_7.ENTITY_METADATA, null, this.user)
wrapper.write(Type.VAR_INT, entityId)
wrapper.write(Types1_8.METADATA_LIST, metadataBuffer[entityId])
MetadataRewriter.transform(clientEntityTypes[entityId], metadataBuffer[entityId]!!)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class WebDashboardServer {
id: UUID, name: String, hash: String,
address: SocketAddress, backAddress: SocketAddress
): CompletableFuture<Unit> {
val future = sessionHashCallbacks.get(hash)
val future = sessionHashCallbacks[hash]
if (!listeners.containsKey(id)) {
future.completeExceptionally(StacklessException("UUID isn't listened. Use web auth."))
} else {
Expand Down
14 changes: 7 additions & 7 deletions src/main/kotlin/com/viaversion/aas/web/WebLogin.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class WebLogin : WebState {
) {
throw StacklessException("Invalid PoW date")
}
val username = obj.get("username").asString.trim()
val username = obj["username"].asString.trim()
val uuid = generateOfflinePlayerUuid(username)

val token = webClient.server.generateToken(uuid)
Expand All @@ -45,18 +45,18 @@ class WebLogin : WebState {
webLogger.info("Token gen: ${webClient.id}: offline $username $uuid")
}
"minecraft_id_login" -> {
val username = obj.get("username").asString
val code = obj.get("code").asString
val username = obj["username"].asString
val code = obj["code"].asString

val check = AspirinServer.httpClient.submitForm<JsonObject>(
"https://api.minecraft.id/gateway/verify/${URLEncoder.encode(username, Charsets.UTF_8)}",
formParameters = parametersOf("code", code),
)

if (check.getAsJsonPrimitive("valid").asBoolean) {
val mcIdUser = check.get("username").asString
val uuid = check.get("uuid")?.asString?.let { parseUndashedId(it.replace("-", "")) }
?: webClient.server.usernameIdCache.get(mcIdUser).await()
val mcIdUser = check["username"].asString
val uuid = check["uuid"]?.asString?.let { parseUndashedId(it.replace("-", "")) }
?: webClient.server.usernameIdCache[mcIdUser].await()
?: throw StacklessException("Failed to get UUID from minecraft.id")

val token = webClient.server.generateToken(uuid)
Expand Down Expand Up @@ -105,7 +105,7 @@ class WebLogin : WebState {
webClient.ws.send(response.toString())
}
"session_hash_response" -> {
val hash = obj.get("session_hash").asString
val hash = obj["session_hash"].asString
webClient.server.sessionHashCallbacks.getIfPresent(hash)?.complete(Unit)
}
else -> throw StacklessException("invalid action!")
Expand Down

0 comments on commit 6cc2405

Please sign in to comment.