Repository: RelativityMC/raknetify
Branch: master
Commit: 76ab30a11a78
Files: 133
Total size: 553.6 KB
Directory structure:
gitextract_gavr_y8s/
├── .github/
│ └── workflows/
│ ├── build.yml
│ └── checkMappings.yml
├── .gitignore
├── .gitmodules
├── .run/
│ ├── BungeeCord Server.run.xml
│ └── Velocity Server.run.xml
├── HEADER.txt
├── Jenkinsfile
├── LICENSE
├── README.md
├── build.gradle
├── buildSrc/
│ ├── build.gradle
│ └── src/
│ └── main/
│ └── java/
│ └── com/
│ └── ishland/
│ └── buildscript/
│ └── ParseGItHubActionChangelog.java
├── bungee/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── ishland/
│ │ └── raknetify/
│ │ └── bungee/
│ │ ├── RaknetifyBungeePlugin.java
│ │ ├── connection/
│ │ │ ├── RakNetBungeeClientChannelEventListener.java
│ │ │ ├── RakNetBungeeConnectionUtil.java
│ │ │ ├── RakNetBungeePingUpdater.java
│ │ │ ├── RakNetBungeeServerChannelEventListener.java
│ │ │ └── StripFrameHandler.java
│ │ └── init/
│ │ ├── BungeeRaknetifyServer.java
│ │ └── InjectedSet.java
│ └── resources/
│ └── bungee.yml
├── common/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── ishland/
│ │ └── raknetify/
│ │ └── common/
│ │ ├── Constants.java
│ │ ├── connection/
│ │ │ ├── ByteBufCopyDecoder.java
│ │ │ ├── FrameDataBlocker.java
│ │ │ ├── MetricsSynchronizationHandler.java
│ │ │ ├── MultiChannelingStreamingCompression.java
│ │ │ ├── MultiChannellingEncryption.java
│ │ │ ├── NoFlush.java
│ │ │ ├── PacketEncryptionManager.java
│ │ │ ├── RakNetConnectionUtil.java
│ │ │ ├── RakNetSimpleMultiChannelCodec.java
│ │ │ ├── RaknetifyEventLoops.java
│ │ │ ├── SimpleMetricsLogger.java
│ │ │ ├── SynchronizationLayer.java
│ │ │ └── multichannel/
│ │ │ └── CustomPayloadChannel.java
│ │ ├── data/
│ │ │ └── ProtocolMultiChannelMappings.java
│ │ ├── package-info.java
│ │ └── util/
│ │ ├── DebugUtil.java
│ │ ├── MathUtil.java
│ │ ├── NetworkInterfaceListener.java
│ │ ├── PrefixUtil.java
│ │ ├── ReflectionUtil.java
│ │ └── ThreadLocalUtil.java
│ └── resources/
│ └── raknetify-channel-mappings.json
├── fabric/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── ishland/
│ │ └── raknetify/
│ │ └── fabric/
│ │ ├── RaknetifyFabric.java
│ │ ├── common/
│ │ │ ├── client/
│ │ │ │ ├── DebugHudUtil.java
│ │ │ │ └── DebugHudUtil1_21_9.java
│ │ │ ├── compat/
│ │ │ │ ├── package-info.java
│ │ │ │ └── viafabric/
│ │ │ │ └── ViaFabricCompatInjector.java
│ │ │ ├── connection/
│ │ │ │ ├── MultiChannellingPacketCapture.java
│ │ │ │ ├── RakNetClientConnectionUtil.java
│ │ │ │ ├── RakNetCompressionCompatibilityHandler.java
│ │ │ │ ├── RakNetFabricChannelEventListener.java
│ │ │ │ ├── RakNetFabricConnectionUtil.java
│ │ │ │ ├── RakNetMultiChannel.java
│ │ │ │ ├── RakNetNetworkTransitionUtil.java
│ │ │ │ └── encryption/
│ │ │ │ └── PacketEncryptionManagerInterface.java
│ │ │ ├── package-info.java
│ │ │ ├── quirks/
│ │ │ │ └── ClientHungerManager.java
│ │ │ └── util/
│ │ │ ├── FieldSignatureParser.java
│ │ │ ├── LegacySupportUtil.java
│ │ │ ├── MultiVersionUtil.java
│ │ │ └── NetworkStates.java
│ │ └── mixin/
│ │ ├── RaknetifyFabricMixinPlugin.java
│ │ ├── access/
│ │ │ ├── IClientConnection.java
│ │ │ ├── IClientPlayNetworkHandler.java
│ │ │ ├── IDebugHudEntries.java
│ │ │ ├── INetworkState1_20_4.java
│ │ │ ├── INetworkStateInternalPacketHandler.java
│ │ │ ├── IPacketCodecDispatcher.java
│ │ │ ├── IPacketCodecDispatcherPacketType.java
│ │ │ ├── IPacketEncryptionManager.java
│ │ │ ├── IServerPlayNetworkHandler.java
│ │ │ └── IWorld.java
│ │ ├── client/
│ │ │ ├── MixinClientPlayNetworkHandler.java
│ │ │ ├── MixinConnectionScreen1.java
│ │ │ ├── MixinMultiplayerServerListPinger.java
│ │ │ ├── MixinMultiplayerServerListPinger1.java
│ │ │ ├── MixinMultiplayerServerListPinger1_20_2.java
│ │ │ ├── MixinMultiplayerServerListPinger1_20_5.java
│ │ │ ├── MixinMultiplayerServerListPinger1_21_11.java
│ │ │ └── hud/
│ │ │ └── MixinDebugHud1_21_8.java
│ │ ├── common/
│ │ │ ├── MixinCCConnect.java
│ │ │ ├── MixinClientConnection.java
│ │ │ ├── MixinClientConnection1.java
│ │ │ ├── MixinClientConnection1_20_2.java
│ │ │ ├── MixinServerAddress.java
│ │ │ ├── encryption/
│ │ │ │ ├── MixinClientConnection.java
│ │ │ │ ├── MixinPacketDecryptor.java
│ │ │ │ ├── MixinPacketEncryptionManager.java
│ │ │ │ └── MixinPacketEncryptor.java
│ │ │ └── quirks/
│ │ │ ├── MixinPlayerEntity.java
│ │ │ └── MixinSampleSubscriptionTracker.java
│ │ ├── compat/
│ │ │ ├── fabricapi/
│ │ │ │ └── MixinServerLoginNetworkAddon.java
│ │ │ ├── krypton/
│ │ │ │ └── MixinServerLoginNetworkHandler.java
│ │ │ ├── package-info.java
│ │ │ └── qsl/
│ │ │ └── MixinServerLoginNetworkAddon.java
│ │ ├── package-info.java
│ │ └── server/
│ │ ├── MixinPlayerManager1_20_1.java
│ │ ├── MixinPlayerManager1_20_2.java
│ │ ├── MixinServerCommonNetworkHandler.java
│ │ ├── MixinServerLoginNetworkHandler.java
│ │ ├── MixinServerNetworkIo.java
│ │ ├── MixinServerNetworkIo1.java
│ │ └── MixinServerPlayNetworkHandler1_20_1.java
│ └── resources/
│ ├── fabric.mod.json
│ ├── raknetify-fabric.accesswidener
│ └── raknetify-fabric.mixins.json
├── genMappings.sh
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── modrinth_license.txt
├── settings.gradle
└── velocity/
├── HEADER.txt
├── LICENSE
├── build.gradle
└── src/
└── main/
├── java/
│ └── com/
│ └── ishland/
│ └── raknetify/
│ └── velocity/
│ ├── RaknetifyVelocityLaunchWrapper.java
│ ├── RaknetifyVelocityPlugin.java
│ ├── connection/
│ │ ├── RakNetVelocityChannelEventListener.java
│ │ ├── RakNetVelocityConnectionUtil.java
│ │ ├── RakNetVelocityPingUpdater.java
│ │ └── RakNetVelocityServerChannelEventListener.java
│ └── init/
│ ├── VelocityPacketRegistryInjector.java
│ └── VelocityRaknetifyServer.java
└── resources/
└── velocity-plugin.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/build.yml
================================================
# Automatically build the project and run any configured tests for every push
# and submitted pull request. This can help catch issues that only occur on
# certain platforms or Java versions, and provides a first line of defence
# against bad commits.
name: build
on: [pull_request, push]
jobs:
build:
strategy:
matrix:
# Use these Java versions
java: [
21, # Current Java LTS & minimum supported by Minecraft
]
# and run on both Linux and Windows
os: [ubuntu-24.04]
runs-on: ${{ matrix.os }}
steps:
- name: checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: validate gradle wrapper
uses: gradle/actions/wrapper-validation@v4
- name: setup jdk ${{ matrix.java }}
uses: actions/setup-java@v2
with:
distribution: 'zulu'
java-version: ${{ matrix.java }}
java-package: jdk
- uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
./.gradle/loom-cache
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: build
run: ./gradlew build
- name: upload to modrinth and curseforge
run: ./gradlew modrinth publishMainPublicationToCurseForge
if: github.ref == 'refs/heads/master'
env:
MODRINTH_TOKEN: ${{ secrets.MODRINTH_UPLOAD_TOKEN }}
CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_API_TOKEN }}
GITHUB_EVENT_RAW_PATH: ${{ github.event_path }}
continue-on-error: true
- name: capture build artifacts
if: ${{ runner.os == 'Linux' && matrix.java == '21' }} # Only upload artifacts built from latest java on one OS
uses: actions/upload-artifact@v4
with:
name: Artifacts
path: ./**/build/libs/*-all.jar
================================================
FILE: .github/workflows/checkMappings.yml
================================================
name: check mappings
on: [pull_request, push]
jobs:
checkMappings:
strategy:
matrix:
# Use these Java versions
java: [
21, # Current Java LTS & minimum supported by Minecraft
]
# and run on both Linux and Windows
os: [ubuntu-24.04]
runs-on: ${{ matrix.os }}
steps:
- name: checkout repository
uses: actions/checkout@v2
with:
fetch-depth: 0
submodules: true
- name: validate gradle wrapper
uses: gradle/actions/wrapper-validation@v4
- name: setup jdk ${{ matrix.java }}
uses: actions/setup-java@v2
with:
distribution: 'zulu'
java-version: ${{ matrix.java }}
java-package: jdk
- uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
./.gradle/loom-cache
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: "cache mappingsGen"
uses: actions/cache@v4
with:
path: |
./run-mappingsGen
key: ${{ runner.os }}-mappingsGen-${{ hashFiles('./genMappings.sh') }}
restore-keys: |
${{ runner.os }}-mappingsGen-
- name: generate mappings
env:
MAPPINGS_GEN_FRESH: true
run: ./genMappings.sh
- name: fail if mappings changed
run: |
git update-index --refresh
if ! git diff-index --quiet HEAD --; then
echo "Mappings changed, please commit them"
git diff
git diff --staged
exit 1
fi
================================================
FILE: .gitignore
================================================
# gradle
.gradle/
build/
out/
classes/
# eclipse
*.launch
# idea
.idea/
*.iml
*.ipr
*.iws
# vscode
.settings/
.vscode/
bin/
.classpath
.project
# macos
*.DS_Store
# fabric
run*/
================================================
FILE: .gitmodules
================================================
[submodule "netty-raknet"]
path = netty-raknet
url = https://github.com/RelativityMC/netty-raknet.git
================================================
FILE: .run/BungeeCord Server.run.xml
================================================
================================================
FILE: .run/Velocity Server.run.xml
================================================
================================================
FILE: HEADER.txt
================================================
This file is a part of the Raknetify project, licensed under MIT.
Copyright (c) 2022-2025 ishland
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: Jenkinsfile
================================================
pipeline {
agent { label 'slave' }
options { timestamps() }
stages {
stage('SCM-SKIP') {
steps {
scmSkip(skipPattern:'.*\\[ci skip\\].*')
}
}
stage('Build') {
tools {
jdk "OpenJDK 21"
}
steps {
withMaven(
maven: '3',
mavenLocalRepo: '.repository',
publisherStrategy: 'EXPLICIT'
) {
sh 'git fetch --tags'
sh 'git reset --hard'
sh './gradlew clean build'
}
}
post {
success {
archiveArtifacts artifacts: "**/build/libs/*-all.jar", fingerprint: true
}
failure {
cleanWs()
}
}
}
}
}
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2022-2025 ishland
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# Raknetify
A Fabric mod / Velocity plugin / BungeeCord plugin that uses RakNet to improve multiplayer experience significantly
under unreliable and rate-limited connections.
# Features
- Higher reliability and lower latency under unreliable and rate-limited client connections.
- Uses RakNet's multiple channels with priorities to achieve higher responsiveness.
- Supports ViaVersion client-side and ViaVersion server-side.
# How to use it?
## Prerequisites
- Raknetify is designed to work on Minecraft 1.17.1+
Note: On proxies such as Velocity and BungeeCord, **unsupported client version** will cause
multi-channelling failing to initialize, causing **reduced responsiveness**.
- You need to have a UDP port opened at the same port number of your normal server port.
## Installation and usage
- Download the latest release from
[GitHub](https://github.com/RelativityMC/raknetify/releases)
[Modrinth (Fabric)](https://modrinth.com/mod/raknetify/versions)
[CurseForge (Fabric)](https://www.curseforge.com/minecraft/mc-mods/raknetify/files)
[SpigotMC (BungeeCord)](https://www.spigotmc.org/resources/raknetify-bungeecord.102509/)
or development builds from [CodeMC](https://ci.codemc.io/job/RelativityMC/job/raknetify/)
- Install the mod on both client and server. (Installation on backend servers are not needed if using on proxies)
- Prefix your server address with `raknet;` (or `raknetl;` to use high mtu) and save or connect directly.
(e.g. `raknet;example.com`)
- Enjoy!
================================================
FILE: build.gradle
================================================
plugins {
id 'fabric-loom' version '1.13-SNAPSHOT' apply false
id 'com.gradleup.shadow' version '9.2.1' apply false
id 'dev.yumi.gradle.licenser' version '2.1.1' apply false
id 'com.modrinth.minotaur' version '2.+' apply false
id 'io.github.themrmilchmann.curseforge-publish' version '0.8.0' apply false
}
subprojects {
apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'maven-publish'
apply plugin: 'dev.yumi.gradle.licenser'
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
version = project.mod_version + "." + getVersionSuffix()
license {
rule(rootProject.file('HEADER.txt'))
}
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
maven { url 'https://repo.codemc.org/repository/maven-public' }
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
}
}
tasks.withType(AbstractArchiveTask) {
preserveFileTimestamps = false
reproducibleFileOrder = true
}
afterEvaluate {
if (it.plugins.hasPlugin("com.modrinth.minotaur")) {
modrinth {
token = System.getenv("MODRINTH_TOKEN") // This is the default. Remember to have the MODRINTH_TOKEN environment variable set or else this will fail, or set it to whatever you want - just make sure it stays private!
projectId = "raknetify" // This can be the project ID or the slug. Either will work!
// versionNumber = project.version + "+" + project.minecraft_version // You don't need to set this manually. Will fail if Modrinth has this version already
// versionName = project.version + " devbuild for " + project.minecraft_version
versionType = "alpha" // This is the default -- can also be `beta` or `alpha`
// uploadFile = remapShadowJar // With Loom, this MUST be set to `remapJar` instead of `jar`!
gameVersions = ["1.18", "1.18.1", "1.18.2", "1.19", "1.19.1", "1.19.2", "1.19.3", "1.19.4", "1.20", "1.20.1", "1.20.2", "1.20.3", "1.20.4", "1.20.5", "1.20.6", "1.21", "1.21.1", "1.21.2", "1.21.3", "1.21.4", "1.21.5", "1.21.6", "1.21.7", "1.21.8", "1.21.9", "1.21.10", "1.21.11"]
// loaders = ["fabric"]
changelog = com.ishland.buildscript.ParseGItHubActionChangelog.getChangelog()
}
}
}
}
afterEvaluate {
logger.lifecycle("Version String: ${project.mod_version + '.' + getVersionSuffix()}")
logger.lifecycle(com.ishland.buildscript.ParseGItHubActionChangelog.getChangelog())
}
String getVersionSuffix() {
def stdout = providers.exec {
commandLine 'git', 'describe', '--tags', '--dirty', '--broken'
}.standardOutput.asText.get()
stdout = stdout.toString().strip()
def suffix = ""
if (stdout.endsWith("-dirty")) {
stdout = stdout.substring(0, stdout.length() - "-dirty".length())
suffix = "-dirty"
}
if (stdout.indexOf('-') < 0) {
return "0" + suffix;
}
def split = stdout.split('-')
return split[split.length - 2] + suffix
}
================================================
FILE: buildSrc/build.gradle
================================================
plugins {
id 'java'
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
repositories {
mavenCentral()
}
dependencies {
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation 'com.google.code.gson:gson:+'
}
================================================
FILE: buildSrc/src/main/java/com/ishland/buildscript/ParseGItHubActionChangelog.java
================================================
package com.ishland.buildscript;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.nio.file.Files;
import java.nio.file.Path;
public class ParseGItHubActionChangelog {
public static String getChangelog() throws Throwable {
final String path = System.getenv("GITHUB_EVENT_RAW_PATH");
if (path == null || path.isBlank()) return "No changelog was specified. ";
final JsonObject jsonObject = new Gson().fromJson(Files.readString(Path.of(path)), JsonObject.class);
StringBuilder builder = new StringBuilder();
builder.append("This version is uploaded automatically by GitHub Actions. \n\n")
.append("Changelog: \n");
final JsonArray commits = jsonObject.getAsJsonArray("commits");
if (commits.isEmpty()) {
builder.append("No changes detected. \n");
} else {
for (JsonElement commit : commits) {
JsonObject object = commit.getAsJsonObject();
builder.append("- ");
builder.append('[').append(object.get("id").getAsString(), 0, 8).append(']')
.append('(').append(object.get("url").getAsString()).append(')');
builder.append(' ');
builder.append(object.get("message").getAsString().split("\n")[0]);
builder.append(" - ");
builder.append(object.get("author").getAsJsonObject().get("name").getAsString());
builder.append(" ").append('\n');
}
}
return builder.toString();
}
}
================================================
FILE: bungee/build.gradle
================================================
import java.nio.file.Files
import java.nio.file.StandardCopyOption
evaluationDependsOn(":")
apply plugin: 'com.gradleup.shadow'
apply plugin: 'com.modrinth.minotaur'
base {
archivesName = project.archives_base_name + "-bungee"
}
group = project.maven_group + ".bungee"
repositories {
ivy {
url 'https://ci.md-5.net/job/'
patternLayout {
// artifact "[organization]/versions/[module]/builds/[revision]/downloads/[organization]-[module]-[revision](.[ext])"
// https://ci.md-5.net/job/BungeeCord/1636/artifact/bootstrap/target/BungeeCord.jar
artifact "[module]/[revision]/artifact/bootstrap/target/BungeeCord(.[ext])"
}
metadataSources {
it.artifact()
}
}
}
configurations {
shadowInclude
}
dependencies {
implementation 'bungee:BungeeCord:2000'
// implementation "net.md-5:bungeecord-proxy:1.+"
// compileOnly 'org.projectlombok:lombok:1.18.24' // for bungeecord sources
shadowInclude implementation(project(":common"))
}
processResources {
inputs.property "version", project.version
filesMatching("bungee.yml") {
expand "version": project.version
}
}
jar {
exclude "META-INF/LICENSE.txt"
exclude "META-INF/NOTICE.txt"
from "LICENSE"
}
shadowJar {
// dependencies {
// exclude(dependency('it.unimi.dsi:fastutil'))
// }
exclude "META-INF/LICENSE.txt"
exclude "META-INF/NOTICE.txt"
minimize()
archiveClassifier = "all"
configurations = [ project.configurations.shadowInclude ]
from "LICENSE"
}
assemble.dependsOn(shadowJar)
tasks.withType(AbstractArchiveTask) {
preserveFileTimestamps = false
reproducibleFileOrder = true
}
modrinth {
versionNumber = project.version + "+bungeecord"
versionName = project.version + " devbuild for BungeeCord"
uploadFile = shadowJar
loaders = ["bungeecord", "waterfall"]
}
task("prepareRunBungee", dependsOn: shadowJar) {
doFirst {
Files.createDirectories(rootProject.projectDir.toPath().resolve("run-bungee").resolve("plugins"))
Files.copy(shadowJar.archiveFile.getAsFile().get().toPath(), rootProject.projectDir.toPath().resolve("run-bungee").resolve("plugins").resolve("raknetify-bungee-devlaunch.jar"), StandardCopyOption.REPLACE_EXISTING)
}
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/RaknetifyBungeePlugin.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee;
import com.ishland.raknetify.bungee.connection.RakNetBungeeConnectionUtil;
import com.ishland.raknetify.bungee.init.BungeeRaknetifyServer;
import com.ishland.raknetify.common.data.ProtocolMultiChannelMappings;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import java.util.logging.Logger;
public class RaknetifyBungeePlugin extends Plugin implements Listener {
public static Logger LOGGER;
public static RaknetifyBungeePlugin INSTANCE;
@Override
public void onEnable() {
super.onEnable();
INSTANCE = this;
LOGGER = this.getLogger();
ProtocolMultiChannelMappings.init();
BungeeRaknetifyServer.inject();
this.getProxy().getPluginManager().registerListener(this, this);
}
@Override
public void onDisable() {
super.onDisable();
BungeeRaknetifyServer.disable();
}
@EventHandler
public void onPostLogin(PostLoginEvent evt) {
RakNetBungeeConnectionUtil.onPlayerLogin(evt);
}
@EventHandler
public void handleServerSwitch(ServerConnectedEvent evt) {
RakNetBungeeConnectionUtil.handleServerSwitch(evt);
}
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/connection/RakNetBungeeClientChannelEventListener.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee.connection;
import com.google.common.base.Preconditions;
import com.ishland.raknetify.bungee.RaknetifyBungeePlugin;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.MultiChannellingEncryption;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.common.connection.SynchronizationLayer;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import net.md_5.bungee.EncryptionUtil;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.Protocol;
import net.md_5.bungee.protocol.packet.Commands;
import net.md_5.bungee.protocol.packet.EncryptionResponse;
import net.md_5.bungee.protocol.packet.FinishConfiguration;
import net.md_5.bungee.protocol.packet.Login;
import net.md_5.bungee.protocol.packet.Respawn;
import net.md_5.bungee.protocol.packet.SetCompression;
import net.md_5.bungee.protocol.packet.StartConfiguration;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.Field;
import java.security.GeneralSecurityException;
import java.util.logging.Level;
public class RakNetBungeeClientChannelEventListener extends ChannelDuplexHandler {
public static final String NAME = "raknetify-bungee-event-listener";
private SecretKey encryptionKey = null;
private boolean needResetCompression = false;
private Protocol protocol = null;
private int protocolVersion = -1;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (this.needResetCompression) {
RaknetifyBungeePlugin.LOGGER.info("Preventing vanilla compression as streaming compression is enabled");
// // note: this may corrupt bungeecords compression state, find a better way to do this
// ctx.channel().pipeline().replace("compress", "compress", new ChannelDuplexHandler()); // no-op
// ctx.channel().pipeline().replace("decompress", "decompress", new ChannelDuplexHandler()); // no-op
final HandlerBoss handlerBoss = ctx.channel().pipeline().get(HandlerBoss.class);
final Field channelField = HandlerBoss.class.getDeclaredField("channel");
channelField.setAccessible(true);
final ChannelWrapper channelWrapper = (ChannelWrapper) channelField.get(handlerBoss);
Preconditions.checkState(channelWrapper != null, "channelWrapper is null");
channelWrapper.setCompressionThreshold(-1);
this.needResetCompression = false;
}
if (this.encryptionKey != null) {
ctx.channel().pipeline().replace(PipelineUtils.DECRYPT_HANDLER, PipelineUtils.DECRYPT_HANDLER, new ChannelDuplexHandler());
ctx.channel().pipeline().replace(PipelineUtils.ENCRYPT_HANDLER, PipelineUtils.ENCRYPT_HANDLER, new ChannelDuplexHandler());
ctx.channel().pipeline().addBefore(MultiChannelingStreamingCompression.NAME, MultiChannellingEncryption.NAME, new MultiChannellingEncryption(encryptionKey));
this.encryptionKey = null;
}
if (msg instanceof SetCompression) {
final MultiChannelingStreamingCompression compression = ctx.channel().pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
RaknetifyBungeePlugin.LOGGER.info("Preventing vanilla compression as streaming compression is enabled");
promise.setSuccess(); // swallow SetCompression packet
needResetCompression = true;
return;
}
} else if (msg instanceof Respawn || msg instanceof Login || msg instanceof StartConfiguration || msg instanceof FinishConfiguration) {
ctx.write(SynchronizationLayer.SYNC_REQUEST_OBJECT); // sync
super.write(ctx, msg, promise);
return;
} else if (msg instanceof Commands) {
ctx.write(RakNetSimpleMultiChannelCodec.SIGNAL_START_MULTICHANNEL);
super.write(ctx, msg, promise);
return;
}
super.write(ctx, msg, promise);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof PacketWrapper wrapper) {
if (wrapper.packet instanceof EncryptionResponse packet) {
try {
this.encryptionKey = getSecretUnchecked(packet);
} catch (Throwable t) {
RaknetifyBungeePlugin.LOGGER.log(Level.WARNING, "Failed to decrypt captured encryption secret, the raknetify connection is broken", t);
}
}
}
super.channelRead(ctx, msg);
}
private static SecretKey getSecretUnchecked(EncryptionResponse resp) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, EncryptionUtil.keys.getPrivate());
return new SecretKeySpec(cipher.doFinal(resp.getSharedSecret()), "AES");
}
public void setProtocol(Protocol protocol, int protocolVersion) {
this.protocol = protocol;
this.protocolVersion = protocolVersion;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
cause.printStackTrace();
}
// @Override
// public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// super.userEventTriggered(ctx, evt);
// if (evt == VelocityConnectionEvent.COMPRESSION_ENABLED) {
// final MultiChannelingStreamingCompression compression = ctx.channel().pipeline().get(MultiChannelingStreamingCompression.class);
// if (compression != null && compression.isActive()) {
// RaknetifyVelocityPlugin.LOGGER.info("Preventing vanilla compression as streaming compression is enabled");
// ctx.channel().pipeline().replace(Connections.COMPRESSION_ENCODER, Connections.COMPRESSION_ENCODER, new ChannelDuplexHandler()); // no-op
// ctx.channel().pipeline().replace(Connections.COMPRESSION_DECODER, Connections.COMPRESSION_DECODER, new ChannelDuplexHandler()); // no-op
// }
// } else if (evt == VelocityConnectionEvent.COMPRESSION_DISABLED) {
// ctx.channel().pipeline().replace(Connections.FRAME_DECODER, Connections.FRAME_DECODER, new ChannelDuplexHandler()); // no-op
// ctx.channel().pipeline().replace(Connections.FRAME_ENCODER, Connections.FRAME_ENCODER, new ChannelDuplexHandler()); // no-op
// } else if (evt == VelocityConnectionEvent.ENCRYPTION_ENABLED) {
// Preconditions.checkState(this.encryptionKey != null, "EncryptionResponse not received yet or already consumed");
// ctx.channel().pipeline().replace(Connections.CIPHER_ENCODER, Connections.CIPHER_ENCODER, new ChannelDuplexHandler());
// ctx.channel().pipeline().replace(Connections.CIPHER_DECODER, Connections.CIPHER_DECODER, new ChannelDuplexHandler());
// ctx.channel().pipeline().addAfter(MultiChannelingStreamingCompression.NAME, MultiChannellingEncryption.NAME, new MultiChannellingEncryption(encryptionKey));
// }
// }
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/connection/RakNetBungeeConnectionUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee.connection;
import com.ishland.raknetify.bungee.RaknetifyBungeePlugin;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.RakNetConnectionUtil;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.common.connection.SynchronizationLayer;
import com.ishland.raknetify.common.connection.multichannel.CustomPayloadChannel;
import com.ishland.raknetify.common.data.ProtocolMultiChannelMappings;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import net.md_5.bungee.ServerConnection;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.protocol.MinecraftEncoder;
import net.md_5.bungee.protocol.Protocol;
import net.md_5.bungee.protocol.packet.PluginMessage;
import network.ycc.raknet.RakNet;
import java.lang.reflect.Field;
import static com.ishland.raknetify.common.util.ReflectionUtil.accessible;
public class RakNetBungeeConnectionUtil {
private static final Field USER_CONNECTION_CH;
private static final Field SERVER_CONNECTION_CH;
private static final Field ENCODER_PROTOCOL_VERSION;
static {
try {
USER_CONNECTION_CH = accessible(UserConnection.class.getDeclaredField("ch"));
SERVER_CONNECTION_CH = accessible(ServerConnection.class.getDeclaredField("ch"));
ENCODER_PROTOCOL_VERSION = accessible(MinecraftEncoder.class.getDeclaredField("protocolVersion"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private RakNetBungeeConnectionUtil() {
}
public static void initChannel(Channel channel) {
if (channel.config() instanceof RakNet.Config) {
RakNetConnectionUtil.initChannel(channel);
// channel.pipeline().addAfter(MultiChannelingStreamingCompression.NAME, MultiChannellingDataCodec.NAME, new MultiChannellingDataCodec(Constants.RAKNET_GAME_PACKET_ID));
channel.pipeline().addAfter(MultiChannelingStreamingCompression.NAME, RakNetSimpleMultiChannelCodec.NAME, new RakNetSimpleMultiChannelCodec(Constants.RAKNET_GAME_PACKET_ID));
}
}
public static void postInitChannel(Channel channel, boolean isClientSide) {
if (channel.config() instanceof RakNet.Config) {
channel.pipeline().replace(PipelineUtils.TIMEOUT_HANDLER, PipelineUtils.TIMEOUT_HANDLER, new ChannelDuplexHandler()); // no-op
channel.pipeline().replace(PipelineUtils.FRAME_DECODER, PipelineUtils.FRAME_DECODER, new ChannelDuplexHandler()); // no-op
channel.pipeline().addBefore(PipelineUtils.FRAME_PREPENDER_AND_COMPRESS, StripFrameHandler.NAME, StripFrameHandler.INSTANCE); // no-op
if (channel.pipeline().get(HAProxyMessageDecoder.class) != null)
channel.pipeline().remove(HAProxyMessageDecoder.class);
// channel.pipeline().replace(PipelineUtils.WRITE_TIMEOUT_HANDLER, PipelineUtils.WRITE_TIMEOUT_HANDLER, new DebugWriteTimeoutHandler(30));
channel.pipeline().addBefore(PipelineUtils.BOSS_HANDLER, RakNetBungeeClientChannelEventListener.NAME, new RakNetBungeeClientChannelEventListener());
// System.out.println(channel.pipeline().names());
// final MultiChannellingPacketCapture handler = new MultiChannellingPacketCapture();
// channel.pipeline().addLast("raknetify-multi-channel-packet-cature", handler);
// channel.pipeline().get(MultiChannellingDataCodec.class).setCapture(handler);
}
}
public static void onPlayerLogin(PostLoginEvent evt) {
try {
final UserConnection player = (UserConnection) evt.getPlayer();
final ChannelWrapper channelWrapper = (ChannelWrapper) USER_CONNECTION_CH.get(player);
final Channel channel = channelWrapper.getHandle();
if (channel != null && channel.config() instanceof RakNet.Config config) {
// multi-channel setup
final RakNetSimpleMultiChannelCodec multiChannelCodec = channel.pipeline().get(RakNetSimpleMultiChannelCodec.class);
if (multiChannelCodec != null) {
final int protocolVersion = (int) ENCODER_PROTOCOL_VERSION.get(channel.pipeline().get(MinecraftEncoder.class));
final ProtocolMultiChannelMappings.VersionMapping versionMapping = ProtocolMultiChannelMappings.INSTANCE.mappings.get(protocolVersion);
if (versionMapping != null) {
// handle custom payload separately
final Object directionDataToClient = accessible(Protocol.class.getDeclaredField("TO_CLIENT")).get(Protocol.GAME);
final int pluginMessageId = (int) accessible(Class.forName("net.md_5.bungee.protocol.Protocol$DirectionData").getDeclaredMethod("getId", Class.class, int.class))
.invoke(directionDataToClient, PluginMessage.class, protocolVersion);
if (Constants.DEBUG) RaknetifyBungeePlugin.LOGGER.info("PluginMessage packetId=%d at version=%d".formatted(pluginMessageId, protocolVersion));
multiChannelCodec.addHandler(new CustomPayloadChannel.OverrideHandler(value -> value == pluginMessageId));
// packet id -> channel id
multiChannelCodec.addHandler(new RakNetSimpleMultiChannelCodec.PacketIdBasedOverrideHandler(
versionMapping.s2c,
"protocol version %d".formatted(protocolVersion)
));
} else {
RaknetifyBungeePlugin.LOGGER.warning("No multi-channel mapping found for protocol version %d, reduced responsiveness is expected"
.formatted(protocolVersion));
}
}
// ping update setup
channel.pipeline().addBefore(PipelineUtils.BOSS_HANDLER, RakNetBungeePingUpdater.NAME, new RakNetBungeePingUpdater(player));
RaknetifyBungeePlugin.LOGGER.info(String.format("Raknetify: %s logged in via RakNet, mtu %d", player.getName(), config.getMTU()));
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public static void handleServerSwitch(ServerConnectedEvent evt) {
try {
final UserConnection player = (UserConnection) evt.getPlayer();
final Channel playerChannel = ((ChannelWrapper) USER_CONNECTION_CH.get(player)).getHandle();
if (playerChannel != null && playerChannel.config() instanceof RakNet.Config config) {
// this exists because bungeecord sends several packets to reset state before Respawn packet during server switch
playerChannel.write(SynchronizationLayer.SYNC_REQUEST_OBJECT);
// and inject into the server channel
final ServerConnection server = (ServerConnection) evt.getServer();
final Channel serverChannel = ((ChannelWrapper) SERVER_CONNECTION_CH.get(server)).getHandle();
serverChannel.pipeline().addBefore(PipelineUtils.BOSS_HANDLER, RakNetBungeeServerChannelEventListener.NAME, new RakNetBungeeServerChannelEventListener(playerChannel));
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/connection/RakNetBungeePingUpdater.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee.connection;
import com.google.common.base.Preconditions;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import network.ycc.raknet.RakNet;
import network.ycc.raknet.packet.Ping;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class RakNetBungeePingUpdater extends ChannelDuplexHandler {
public static final String NAME = "raknetify-bungee-ping-updater";
private final UserConnection player;
ScheduledFuture> updateTask = null;
public RakNetBungeePingUpdater(UserConnection player) {
this.player = Objects.requireNonNull(player);
}
public void handlerAdded(ChannelHandlerContext ctx) {
if (ctx.channel().config() instanceof RakNet.Config config) {
updateTask = ctx.channel().eventLoop().scheduleAtFixedRate(
() -> player.setPing((int) ((config.getRTTNanos() + config.getRTTStdDevNanos()) / 1_000_000)),
0, 1000, TimeUnit.MILLISECONDS
);
}
}
public void handlerRemoved(ChannelHandlerContext ctx) {
if (updateTask != null) {
updateTask.cancel(false);
updateTask = null;
}
}
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/connection/RakNetBungeeServerChannelEventListener.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee.connection;
import com.google.common.base.Preconditions;
import com.ishland.raknetify.bungee.RaknetifyBungeePlugin;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.SynchronizationLayer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.protocol.DefinedPacket;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.packet.KeepAlive;
import net.md_5.bungee.protocol.packet.Respawn;
import network.ycc.raknet.RakNet;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class RakNetBungeeServerChannelEventListener extends ChannelDuplexHandler {
public static final String NAME = "raknetify-bungee-downstream-event-listener";
private final Channel clientChannel;
public RakNetBungeeServerChannelEventListener(Channel clientChannel) {
Preconditions.checkArgument(clientChannel.config() instanceof RakNet.Config);
this.clientChannel = clientChannel;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof PacketWrapper wrapper) {
final DefinedPacket packet = wrapper.packet;
if (packet instanceof Respawn) {
clientChannel.write(SynchronizationLayer.SYNC_REQUEST_OBJECT);
} else if (packet instanceof KeepAlive) {
if (Constants.DEBUG) RaknetifyBungeePlugin.LOGGER.info("Received downstream keepalive, swallowing it");
final long rttNanos = RakNet.config(clientChannel).getRTTNanos();
// ProxyServer.getInstance().getScheduler()
// .schedule(RaknetifyBungeePlugin.INSTANCE, () -> ctx.write(packet), Math.max(rttNanos - 4_000_000, 0), TimeUnit.NANOSECONDS); // reduce delay to aid scheduling overhead
ctx.channel().eventLoop().schedule(() -> ctx.writeAndFlush(packet), Math.max(rttNanos - 4_000_000, 0), TimeUnit.NANOSECONDS); // reduce delay to aid scheduling overhead
return; // prevent keepalive from being sent to clients
}
}
super.channelRead(ctx, msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
cause.printStackTrace();
for (Map.Entry entry : ctx.channel().pipeline().toMap().entrySet()) {
System.out.println("%s: %s".formatted(entry.getKey(), entry.getValue().getClass().getName()));
}
}
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/connection/StripFrameHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee.connection;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import net.md_5.bungee.protocol.DefinedPacket;
@ChannelHandler.Sharable
public class StripFrameHandler extends ChannelOutboundHandlerAdapter {
public static final String NAME = "raknetify-bungee-strip-frame";
public static final StripFrameHandler INSTANCE = new StripFrameHandler();
private StripFrameHandler() {
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof ByteBuf buf) {
DefinedPacket.readVarInt(buf);
ctx.write(buf.slice(), promise);
return;
}
super.write(ctx, msg, promise);
}
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/init/BungeeRaknetifyServer.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee.init;
import com.ishland.raknetify.bungee.RaknetifyBungeePlugin;
import com.ishland.raknetify.bungee.connection.RakNetBungeeConnectionUtil;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.RakNetConnectionUtil;
import com.ishland.raknetify.common.util.NetworkInterfaceListener;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.ReflectiveChannelFactory;
import io.netty.channel.socket.DatagramChannel;
import io.netty.util.AttributeKey;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ListenerInfo;
import net.md_5.bungee.netty.PipelineUtils;
import net.md_5.bungee.query.QueryHandler;
import network.ycc.raknet.server.channel.RakNetServerChannel;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.stream.Stream;
import static com.ishland.raknetify.common.util.ReflectionUtil.accessible;
public class BungeeRaknetifyServer {
private static final int portOverride = Integer.getInteger("raknetify.bungee.portOverride", -1);
private static final Method INIT_CHANNEL;
private static final Field BUNGEE_LISTENERS_FIELD;
private static final Class> ACCEPTOR_CLASS;
static {
try {
INIT_CHANNEL = accessible(ChannelInitializer.class.getDeclaredMethod("initChannel", Channel.class));
BUNGEE_LISTENERS_FIELD = accessible(BungeeCord.class.getDeclaredField("listeners"));
ACCEPTOR_CLASS = Class.forName("io.netty.bootstrap.ServerBootstrap$ServerBootstrapAcceptor");
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private static final Reference2ReferenceOpenHashMap> channels = new Reference2ReferenceOpenHashMap<>();
private static final ReferenceOpenHashSet nonWildcardChannels = new ReferenceOpenHashSet<>();
private static volatile boolean active = false;
private static volatile int activeIndex = 0;
private static boolean injected = false;
private static volatile Consumer listener = null;
public static void inject() {
if (active) return;
try {
active = true;
final BungeeCord instance = (BungeeCord) ProxyServer.getInstance();
// stopAllQueryPorts();
final Set listeners = (Set) BUNGEE_LISTENERS_FIELD.get(instance);
if (!injected) {
BUNGEE_LISTENERS_FIELD.set(instance, new InjectedSet(listeners));
injected = true;
}
List errors = new ArrayList<>();
for (Channel listener : listeners) {
try {
injectChannel(instance, listener, true);
} catch (Throwable t) {
errors.add(t);
}
}
int currentActiveIndex = ++activeIndex;
listener = event -> {
if (!active) {
NetworkInterfaceListener.removeListener(listener);
}
if (currentActiveIndex != activeIndex) return; // we can't remove ourselves now, is plugin reloaded?
if (event.added()) {
for (Channel channel : channels.keySet()) {
injectChannel(instance, channel, false);
}
} else {
for (ReferenceOpenHashSet futures : channels.values()) {
for (ObjectIterator iterator = futures.iterator(); iterator.hasNext(); ) {
ChannelFuture future = iterator.next();
if (((InetSocketAddress) future.channel().localAddress()).getAddress().equals(event.address())) {
RaknetifyBungeePlugin.LOGGER.info("Closing Raknetify server %s".formatted(future.channel().localAddress()));
future.channel().close();
iterator.remove();
}
}
}
}
};
NetworkInterfaceListener.addListener(event ->
instance.getScheduler().schedule(RaknetifyBungeePlugin.INSTANCE, () -> listener.accept(event), 100, TimeUnit.MILLISECONDS));
if (!errors.isEmpty()) {
final RuntimeException exception = new RuntimeException("Failed to start Raknetify server");
errors.forEach(exception::addSuppressed);
throw exception;
}
} catch (Throwable t) {
throw new RuntimeException("Failed to start Raknetify server", t);
}
}
public static void injectChannel(BungeeCord instance, Channel listener, boolean throwErrors) {
try {
if (!active) return;
final boolean hasPortOverride = portOverride > 0 && portOverride < 65535;
if (hasPortOverride && !channels.isEmpty()) return; // avoid duplicate listeners
if (!(listener.localAddress() instanceof InetSocketAddress)) return;
ChannelInitializer initializer = null;
ListenerInfo info = null;
for (String name : listener.pipeline().names()) {
final ChannelHandler handler = listener.pipeline().get(name);
if (handler instanceof QueryHandler) {
return;
}
if (handler != null && ACCEPTOR_CLASS.isAssignableFrom(handler.getClass())) {
try {
initializer = (ChannelInitializer) accessible(ACCEPTOR_CLASS.getDeclaredField("childHandler")).get(handler);
final Map.Entry, ?>[] attrs = (Map.Entry, ?>[])
accessible(ACCEPTOR_CLASS.getDeclaredField("childAttrs")).get(handler);
for (var attr : attrs) {
if (attr.getKey() == PipelineUtils.LISTENER) {
info = (ListenerInfo) attr.getValue();
}
}
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
}
if (initializer == null) {
RaknetifyBungeePlugin.LOGGER.severe("Unable to find channel initializer for listener %s".formatted(listener));
return;
}
if (info == null) {
RaknetifyBungeePlugin.LOGGER.severe("Unable to find listener info for listener %s".formatted(listener));
return;
}
if (listener.getClass().getName().startsWith("org.geysermc.geyser.network")) { // filter out geyser
return;
}
if (((InetSocketAddress) info.getSocketAddress()).getAddress().isAnyLocalAddress()) {
for (NetworkInterface networkInterface : NetworkInterface.networkInterfaces().toList()) {
final Iterator iterator = networkInterface.getInetAddresses().asIterator();
while (iterator.hasNext()) {
final InetAddress address = iterator.next();
try {
startServer(instance, listener, initializer, info, address);
} catch (Throwable t) {
RaknetifyBungeePlugin.LOGGER.log(Level.SEVERE, "Failed to start Raknetify server", t);
}
}
}
} else {
startServer(instance, listener, initializer, info, null);
}
} catch (Throwable t) {
if (throwErrors) throw new RuntimeException("Failed to start Raknetify server", t);
else RaknetifyBungeePlugin.LOGGER.log(Level.SEVERE, "Failed to start Raknetify server", t);
}
}
private static void startServer(BungeeCord instance, Channel listener, ChannelInitializer initializer, ListenerInfo info, InetAddress address) throws NoSuchFieldException, IllegalAccessException {
if (address != null) {
final ReferenceOpenHashSet futures = channels.get(listener);
if (futures != null) {
for (ChannelFuture future : futures) {
if (((InetSocketAddress) future.channel().localAddress()).getAddress().equals(address))
return; // avoid duplicate
}
}
}
final boolean hasPortOverride = portOverride > 0 && portOverride < 65535;
final ReflectiveChannelFactory extends DatagramChannel> factory = new ReflectiveChannelFactory<>(PipelineUtils.getDatagramChannel());
final InetAddress actualAddress = address == null ? ((InetSocketAddress) info.getSocketAddress()).getAddress() : address;
final ChannelFuture future = new ServerBootstrap()
.channelFactory(() -> new RakNetServerChannel(() -> {
final DatagramChannel channel = factory.newChannel();
channel.config().setOption(ChannelOption.IP_TOS, RakNetConnectionUtil.DEFAULT_IP_TOS);
channel.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(Constants.LARGE_MTU + 512).maxMessagesPerRead(128));
return channel;
}))
.option(ChannelOption.SO_REUSEADDR, true)
.childAttr(PipelineUtils.LISTENER, info)
.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(Channel channel) throws Exception {
RakNetBungeeConnectionUtil.initChannel(channel);
INIT_CHANNEL.invoke(initializer, channel);
RakNetBungeeConnectionUtil.postInitChannel(channel, false);
}
})
.group(getBossEventLoopGroup(instance), getWorkerEventLoopGroup(instance))
.localAddress(hasPortOverride ? new InetSocketAddress(actualAddress, portOverride) : new InetSocketAddress(actualAddress, ((InetSocketAddress) info.getSocketAddress()).getPort()))
.bind()
.syncUninterruptibly();
if (address == null) {
nonWildcardChannels.add(future);
} else {
channels.computeIfAbsent(listener, unused -> new ReferenceOpenHashSet<>()).add(future);
}
RaknetifyBungeePlugin.LOGGER.info("Raknetify server started on %s".formatted(future.channel().localAddress()));
}
public static void stopAll() {
if (!active) return;
for (ChannelFuture future : Stream.concat(channels.values().stream().flatMap(Collection::stream), nonWildcardChannels.stream()).toList()) {
RaknetifyBungeePlugin.LOGGER.info("Closing Raknetify server %s".formatted(future.channel().localAddress()));
try {
future.channel().close().sync();
} catch (InterruptedException e) {
RaknetifyBungeePlugin.LOGGER.severe("Interrupted whilst closing raknetify server");
}
}
channels.clear();
nonWildcardChannels.clear();
}
public static void disable() {
if (!active) return;
stopAll();
active = false;
}
private static EventLoopGroup getBossEventLoopGroup(BungeeCord instance) throws NoSuchFieldException, IllegalAccessException {
try {
return (EventLoopGroup) accessible(BungeeCord.class.getDeclaredField("eventLoops")).get(instance);
} catch (NoSuchFieldException e) { // waterfall: use split boss and worker group
//noinspection JavaReflectionMemberAccess
return (EventLoopGroup) accessible(BungeeCord.class.getDeclaredField("bossEventLoopGroup")).get(instance);
}
}
private static EventLoopGroup getWorkerEventLoopGroup(BungeeCord instance) throws NoSuchFieldException, IllegalAccessException {
try {
return (EventLoopGroup) accessible(BungeeCord.class.getDeclaredField("eventLoops")).get(instance);
} catch (NoSuchFieldException e) { // waterfall: use split boss and worker group
//noinspection JavaReflectionMemberAccess
return (EventLoopGroup) accessible(BungeeCord.class.getDeclaredField("workerEventLoopGroup")).get(instance);
}
}
}
================================================
FILE: bungee/src/main/java/com/ishland/raknetify/bungee/init/InjectedSet.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.bungee.init;
import com.google.common.collect.ForwardingSet;
import com.ishland.raknetify.bungee.RaknetifyBungeePlugin;
import io.netty.channel.Channel;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.ProxyServer;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class InjectedSet extends ForwardingSet {
private final Set delegate;
public InjectedSet(Set delegate) {
this.delegate = delegate;
}
@Override
public boolean add(Channel element) {
ProxyServer.getInstance().getScheduler().schedule(
RaknetifyBungeePlugin.INSTANCE,
() -> BungeeRaknetifyServer.injectChannel((BungeeCord) ProxyServer.getInstance(), element, false),
100, TimeUnit.MILLISECONDS);
return super.add(element);
}
@Override
public void clear() {
BungeeRaknetifyServer.stopAll();
super.clear();
}
@Override
protected Set delegate() {
return this.delegate;
}
}
================================================
FILE: bungee/src/main/resources/bungee.yml
================================================
#
# This file is a part of the Raknetify project, licensed under MIT.
#
# Copyright (c) 2022-2025 ishland
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
name: raknetify
main: com.ishland.raknetify.bungee.RaknetifyBungeePlugin
version: ${version}
author: ishland
softDepends:
- ViaVersion
================================================
FILE: common/build.gradle
================================================
dependencies {
api("com.github.RelativityMC.netty-raknet:netty-raknet-common") {
transitive = false
}
api("com.github.RelativityMC.netty-raknet:netty-raknet-client")
api("com.github.RelativityMC.netty-raknet:netty-raknet-server")
api("org.apache.commons:commons-math3:3.6.1")
//noinspection GradlePackageUpdate
compileOnly("io.netty:netty-all:4.1.25.Final")
compileOnly("com.google.code.gson:gson:2.9.0")
compileOnly("com.google.guava:guava:31.1-jre")
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/Constants.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common;
public class Constants {
public static final boolean DEBUG = Boolean.getBoolean("raknetify.debug");
public static final String RAKNET_PREFIX = "raknet;";
public static final String RAKNET_LARGE_MTU_PREFIX = "raknetl;";
public static final int RAKNET_PING_PACKET_ID = 0xFA;
public static final int RAKNET_GAME_PACKET_ID = 0xFD;
public static final int RAKNET_STREAMING_COMPRESSION_PACKET_ID = 0xED;
public static final int RAKNET_STREAMING_COMPRESSION_HANDSHAKE_PACKET_ID = 0xEC;
public static final int RAKNET_SYNC_PACKET_ID = 0xFC;
public static final int RAKNET_METRICS_SYNC_PACKET_ID = 0xFB;
public static final int MAX_QUEUED_SIZE = 256 * 1024 * 1024;
public static final int DEFAULT_MTU = 1400;
public static final int LARGE_MTU = 8192;
public static final int MAX_PENDING_FRAME_SETS = 512;
public static final int DEFAULT_PENDING_FRAME_SETS = 4;
public static final int[] SYNC_IGNORE_CHANNELS = new int[] {1};
private Constants() {
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/ByteBufCopyDecoder.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ByteBufCopyDecoder extends ChannelInboundHandlerAdapter {
public static final String NAME = "raknetify-byte-buf-copy-decoder";
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf buf && !buf.hasMemoryAddress()) {
ctx.fireChannelRead(ctx.alloc().directBuffer(buf.readableBytes()).writeBytes(buf));
buf.release();
return;
}
super.channelRead(ctx, msg);
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/FrameDataBlocker.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import network.ycc.raknet.frame.FrameData;
public class FrameDataBlocker extends ChannelInboundHandlerAdapter {
private static final boolean printBlockedFrames = Boolean.getBoolean("raknetify.printBlockedFrames");
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FrameData data) {
if (printBlockedFrames) System.out.println("Blocked %s".formatted(msg));
data.release();
return;
}
ctx.fireChannelRead(msg);
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/MetricsSynchronizationHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import com.ishland.raknetify.common.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;
import network.ycc.raknet.RakNet;
import network.ycc.raknet.frame.FrameData;
import network.ycc.raknet.packet.FramedPacket;
import java.util.concurrent.TimeUnit;
public class MetricsSynchronizationHandler extends ChannelDuplexHandler {
// Packet format:
// byte: version (currently 0x00)
// long: packet sent time (used to filter out old packets)
// int: buffer size in bytes
// int: burst size
// double: error rate
// int: tx
// int: rx
private static final byte VERSION = 0x00;
private ScheduledFuture> future;
private ChannelHandlerContext ctx;
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
this.ctx = ctx;
this.future = ctx.channel().eventLoop().scheduleAtFixedRate(this::sendSyncPacket, 200, 200, TimeUnit.MILLISECONDS);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
if (future != null) future.cancel(false);
}
private void sendSyncPacket() {
if (this.ctx.channel().config() instanceof RakNet.Config config && config.getMetrics() instanceof SimpleMetricsLogger logger){
ByteBuf buffer = null;
try {
buffer = this.ctx.alloc().buffer(1 + 8 + 4 + 4 + 8 + 4 + 4);
buffer.writeByte(VERSION);
buffer.writeLong(System.currentTimeMillis());
buffer.writeInt(logger.getCurrentQueuedBytes());
buffer.writeInt((int) (logger.getMeasureBurstTokens() + config.getDefaultPendingFrameSets()));
buffer.writeDouble(logger.getMeasureErrorRate());
buffer.writeInt(logger.getMeasureTX());
buffer.writeInt(logger.getMeasureRX());
final FrameData frameData = FrameData.create(this.ctx.alloc(), Constants.RAKNET_METRICS_SYNC_PACKET_ID, buffer);
frameData.setReliability(FramedPacket.Reliability.UNRELIABLE);
this.ctx.write(frameData);
} finally {
if (buffer != null) buffer.release();
}
}
}
private boolean isRemoteSupported = false;
private long lastRecv = 0L;
private int queuedBytes;
private int burst;
private double errorRate;
private int tx;
private int rx;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FrameData frameData && frameData.getDataSize() > 0 && frameData.getPacketId() == Constants.RAKNET_METRICS_SYNC_PACKET_ID) {
ByteBuf byteBuf = null;
try {
byteBuf = frameData.createData().skipBytes(1);
final byte version = byteBuf.readByte();
if (version != VERSION) return;
final long time = byteBuf.readLong();
if (time < this.lastRecv) return;
this.lastRecv = time;
this.isRemoteSupported = true;
this.queuedBytes = byteBuf.readInt();
this.burst = byteBuf.readInt();
this.errorRate = byteBuf.readDouble();
this.tx = byteBuf.readInt();
this.rx = byteBuf.readInt();
} finally {
if (byteBuf != null) byteBuf.release();
frameData.release();
}
return;
}
super.channelRead(ctx, msg);
}
public boolean isRemoteSupported() {
return this.isRemoteSupported;
}
public int getQueuedBytes() {
return queuedBytes;
}
public int getBurst() {
return burst;
}
public double getErrorRate() {
return errorRate;
}
public int getTX() {
return tx;
}
public int getRX() {
return rx;
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/MultiChannelingStreamingCompression.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import com.ishland.raknetify.common.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import network.ycc.raknet.frame.FrameData;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class MultiChannelingStreamingCompression extends ChannelDuplexHandler {
public static final String NAME = "raknetify-multichannel-streaming-compression";
public static final long SERVER_HANDSHAKE = 0x40000010;
public static final long CHANNEL_START = 0x40000012;
private final Inflater[] inflaters = new Inflater[8];
private final Deflater[] deflaters = new Deflater[8];
private final IntOpenHashSet channelsToIgnoreWhenReinit = new IntOpenHashSet();
private final byte[] inflateBuffer = new byte[256 * 1024];
private final byte[] deflateBuffer = new byte[256 * 1024];
private final int rawPacketId;
private final int compressedPacketId;
private volatile long outBytesRaw = 0L;
private volatile long outBytesCompressed = 0L;
private volatile long inBytesCompressed = 0L;
private volatile long inBytesRaw = 0L;
private boolean active = false;
public MultiChannelingStreamingCompression(int rawPacketId, int compressedPacketId) {
this.rawPacketId = rawPacketId;
this.compressedPacketId = compressedPacketId;
}
private void doServerHandshake(ChannelHandlerContext ctx) {
final ByteBuf buf = ctx.alloc().buffer().writeLong(SERVER_HANDSHAKE);
try {
final FrameData data = FrameData.create(ctx.alloc(), Constants.RAKNET_STREAMING_COMPRESSION_HANDSHAKE_PACKET_ID,
buf);
ctx.write(data);
} finally {
buf.release();
}
}
private void doChannelStart(ChannelHandlerContext ctx) {
if (!active) return;
ByteBuf buf = ctx.alloc().buffer().writeLong(CHANNEL_START);
try {
for (int i = 0; i < 8; i++) {
final FrameData data = FrameData.create(ctx.alloc(), Constants.RAKNET_STREAMING_COMPRESSION_HANDSHAKE_PACKET_ID,
buf);
data.setOrderChannel(i);
ctx.write(data);
initDeflater(i);
}
} finally {
buf.release();
}
}
private void initDeflater(int channel) {
if (!active) return;
if (deflaters[channel] != null) deflaters[channel].end();
deflaters[channel] = new Deflater();
if (Constants.DEBUG) System.out.println("Raknetify: Streaming compression deflater for ch%d is ready".formatted(channel));
}
private void initInflater(int channel) {
if (!active) return;
if (inflaters[channel] != null) inflaters[channel].end();
inflaters[channel] = new Inflater();
if (Constants.DEBUG) System.out.println("Raknetify: Streaming compression inflater for ch%d is ready".formatted(channel));
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
doServerHandshake(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FrameData compressedFrameData) {
compressedFrameData.touch();
if (compressedFrameData.getPacketId() == Constants.RAKNET_STREAMING_COMPRESSION_HANDSHAKE_PACKET_ID) {
final int orderChannel = compressedFrameData.getOrderChannel();
ByteBuf payload = null;
try {
payload = compressedFrameData.createData().skipBytes(1);
if (payload.readableBytes() == 8) {
final long l = payload.readLong();
if (l == CHANNEL_START) {
initInflater(orderChannel);
return;
} else if (l == SERVER_HANDSHAKE) {
active = true;
doChannelStart(ctx);
return;
}
}
} finally {
compressedFrameData.release();
if (payload != null) payload.release();
}
} else if (compressedFrameData.getPacketId() == compressedPacketId && compressedFrameData.getReliability().isReliable && compressedFrameData.getReliability().isOrdered && !compressedFrameData.getReliability().isSequenced && inflaters[compressedFrameData.getOrderChannel()] != null) {
final int orderChannel = compressedFrameData.getOrderChannel();
final Inflater inflater = inflaters[orderChannel];
final ByteBuf data = compressedFrameData.createData().skipBytes(1);
ByteBuf out = null;
FrameData rawFrameData = null;
try {
inflater.setInput(data.nioBuffer());
inBytesCompressed += data.readableBytes();
out = ctx.alloc().buffer();
{
int inflatedBytes;
while ((inflatedBytes = inflater.inflate(inflateBuffer)) != 0) {
out.writeBytes(inflateBuffer, 0, inflatedBytes);
}
}
inBytesRaw += out.writerIndex();
rawFrameData = FrameData.create(ctx.alloc(), rawPacketId, out);
rawFrameData.setReliability(compressedFrameData.getReliability());
rawFrameData.setOrderChannel(orderChannel);
ctx.fireChannelRead(rawFrameData);
rawFrameData = null;
return;
} finally {
data.release();
compressedFrameData.release();
if (out != null) out.release();
if (rawFrameData != null) rawFrameData.release();
}
}
}
super.channelRead(ctx, msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg == SynchronizationLayer.SYNC_REQUEST_OBJECT) {
super.write(ctx, msg, promise);
doChannelStart(ctx);
return;
} else if (msg instanceof FrameData rawFrameData) {
rawFrameData.touch();
if (rawFrameData.getPacketId() == rawPacketId && rawFrameData.getReliability().isReliable && rawFrameData.getReliability().isOrdered && !rawFrameData.getReliability().isSequenced && deflaters[rawFrameData.getOrderChannel()] != null) {
if (rawFrameData.getDataSize() < 16 + 1) {
outBytesRaw += rawFrameData.getDataSize() - 1;
outBytesCompressed += rawFrameData.getDataSize() - 1;
ctx.write(rawFrameData, promise);
return;
}
final int orderChannel = rawFrameData.getOrderChannel();
final Deflater deflater = deflaters[orderChannel];
final ByteBuf data = rawFrameData.createData().skipBytes(1);
ByteBuf out = null;
FrameData compressedFrameData = null;
try {
deflater.setInput(data.nioBuffer());
outBytesRaw += data.readableBytes();
out = ctx.alloc().buffer();
{
int deflatedBytes;
while ((deflatedBytes = deflater.deflate(deflateBuffer, 0, deflateBuffer.length, Deflater.SYNC_FLUSH)) != 0) {
out.writeBytes(deflateBuffer, 0, deflatedBytes);
}
}
outBytesCompressed += out.writerIndex();
compressedFrameData = FrameData.create(ctx.alloc(), compressedPacketId, out);
compressedFrameData.setReliability(rawFrameData.getReliability());
compressedFrameData.setOrderChannel(orderChannel);
ctx.write(compressedFrameData, promise);
compressedFrameData = null;
return;
} finally {
data.release();
rawFrameData.release();
if (out != null) out.release();
if (compressedFrameData != null) compressedFrameData.release();
}
}
}
super.write(ctx, msg, promise);
}
public long getInBytesCompressed() {
return inBytesCompressed;
}
public long getInBytesRaw() {
return inBytesRaw;
}
public long getOutBytesCompressed() {
return outBytesCompressed;
}
public long getOutBytesRaw() {
return outBytesRaw;
}
public boolean isActive() {
return active;
}
private ScheduledFuture> future;
public void handlerAdded(ChannelHandlerContext ctx) {
this.future = ctx.channel().eventLoop().scheduleAtFixedRate(this::tickMetrics, 1000, 1000, TimeUnit.MILLISECONDS);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
if (future != null) future.cancel(false);
for (int i = 0; i < 8; i++) {
if (inflaters[i] != null) inflaters[i].end();
if (deflaters[i] != null) deflaters[i].end();
}
}
private long lastInBytesCompressed;
private long lastInBytesRaw;
private long lastOutBytesRaw;
private long lastOutBytesCompressed;
private final DescriptiveStatistics inCompressionRatioStats = new DescriptiveStatistics(16);
private final DescriptiveStatistics outCompressionRatioStats = new DescriptiveStatistics(16);
private volatile double inCompressionRatio;
private volatile double outCompressionRatio;
private void tickMetrics() {
long deltaInBytesCompressed = this.inBytesCompressed - this.lastInBytesCompressed;
long deltaInBytesRaw = this.inBytesRaw - this.lastInBytesRaw;
long deltaOutBytesCompressed = this.outBytesCompressed - this.lastOutBytesCompressed;
long deltaOutBytesRaw = this.outBytesRaw - this.lastOutBytesRaw;
if (deltaInBytesRaw != 0) {
double currentInCompressionRatio = deltaInBytesCompressed / (double) deltaInBytesRaw;
inCompressionRatioStats.addValue(currentInCompressionRatio);
}
if (deltaOutBytesRaw != 0) {
double currentOutCompressionRatio = deltaOutBytesCompressed / (double) deltaOutBytesRaw;
outCompressionRatioStats.addValue(currentOutCompressionRatio);
}
this.inCompressionRatio = inCompressionRatioStats.getMean();
this.outCompressionRatio = outCompressionRatioStats.getMean();
this.lastInBytesCompressed = this.inBytesCompressed;
this.lastInBytesRaw = this.inBytesRaw;
this.lastOutBytesCompressed = this.outBytesCompressed;
this.lastOutBytesRaw = this.outBytesRaw;
}
public double getInCompressionRatio() {
return inCompressionRatio;
}
public double getOutCompressionRatio() {
return outCompressionRatio;
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/MultiChannellingEncryption.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import network.ycc.raknet.frame.FrameData;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.GeneralSecurityException;
import java.util.Objects;
public class MultiChannellingEncryption extends ChannelDuplexHandler {
public static final String NAME = "raknetify-multichannel-encryption";
private final PacketEncryptionManager decryption;
private final PacketEncryptionManager encryption;
public MultiChannellingEncryption(SecretKey key) throws GeneralSecurityException {
Cipher decryption = Cipher.getInstance("AES/CFB8/NoPadding");
decryption.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(key.getEncoded()));
this.decryption = new PacketEncryptionManager(decryption);
Cipher encryption = Cipher.getInstance("AES/CFB8/NoPadding");
encryption.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(key.getEncoded()));
this.encryption = new PacketEncryptionManager(encryption);
}
public MultiChannellingEncryption(Cipher decryption, Cipher encryption) {
this.decryption = new PacketEncryptionManager(Objects.requireNonNull(decryption));
this.encryption = new PacketEncryptionManager(Objects.requireNonNull(encryption));
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof FrameData data) {
data.touch();
final ByteBuf buf = data.createData().skipBytes(1);
ByteBuf res = null;
FrameData resFrame = null;
try {
res = ctx.alloc().buffer(data.getDataSize());
encryption.doWork(buf, res);
resFrame = FrameData.create(ctx.alloc(), data.getPacketId(), res);
// res = null;
resFrame.setOrderChannel(data.getOrderChannel());
resFrame.setReliability(data.getReliability());
ctx.write(resFrame, promise);
resFrame = null;
return;
} finally {
buf.release();
data.release();
if (res != null) res.release();
if (resFrame != null) resFrame.release();
}
}
super.write(ctx, msg, promise);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FrameData data) {
data.touch();
final ByteBuf buf = data.createData().skipBytes(1);
ByteBuf res = null;
FrameData resFrame = null;
try {
res = ctx.alloc().buffer(data.getDataSize());
decryption.doWork(buf, res);
resFrame = FrameData.create(ctx.alloc(), data.getPacketId(), res);
resFrame.setOrderChannel(data.getOrderChannel());
resFrame.setReliability(data.getReliability());
ctx.fireChannelRead(resFrame);
resFrame = null;
return;
} finally {
buf.release();
data.release();
if (res != null) res.release();
if (resFrame != null) resFrame.release();
}
}
super.channelRead(ctx, msg);
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/NoFlush.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
public class NoFlush extends ChannelDuplexHandler {
@Override
public void flush(ChannelHandlerContext ctx) {
// no-op
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/PacketEncryptionManager.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import io.netty.buffer.ByteBuf;
import javax.crypto.Cipher;
import java.security.GeneralSecurityException;
// TODO [VanillaCopy] from fabric
public class PacketEncryptionManager {
private final Cipher cipher;
private byte[] conversionBuffer = new byte[0];
private byte[] encryptionBuffer = new byte[0];
protected PacketEncryptionManager(Cipher cipher) {
this.cipher = cipher;
}
private byte[] toByteArray(ByteBuf buf) {
int i = buf.readableBytes();
if (this.conversionBuffer.length < i) {
this.conversionBuffer = new byte[i];
}
buf.readBytes(this.conversionBuffer, 0, i);
return this.conversionBuffer;
}
public void doWork(ByteBuf buf, ByteBuf result) throws GeneralSecurityException {
int i = buf.readableBytes();
byte[] bs = this.toByteArray(buf);
int outputSize = this.cipher.getOutputSize(i);
if (this.encryptionBuffer.length < outputSize) {
this.encryptionBuffer = new byte[outputSize];
}
result.writeBytes(this.encryptionBuffer, 0, this.cipher.doFinal(bs, 0, i, this.encryptionBuffer));
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/RakNetConnectionUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import com.ishland.raknetify.common.Constants;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.ReadTimeoutHandler;
import network.ycc.raknet.RakNet;
import network.ycc.raknet.client.channel.RakNetClientThreadedChannel;
import network.ycc.raknet.frame.Frame;
import network.ycc.raknet.pipeline.ReliabilityHandler;
import network.ycc.raknet.server.channel.RakNetApplicationChannel;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import static com.ishland.raknetify.common.util.ReflectionUtil.accessible;
public class RakNetConnectionUtil {
public static final int IP_TOS_LOWDELAY = 0b00010000;
public static final int IP_TOS_THROUGHPUT = 0b00001000;
public static final int IP_TOS_RELIABILITY = 0b00000100;
public static final int DEFAULT_IP_TOS = IP_TOS_LOWDELAY | IP_TOS_THROUGHPUT;
private RakNetConnectionUtil() {
}
private static final Comparator cmp =
Comparator
.comparingInt((Frame frame) -> frame.getReliability().isReliable ? 1 : 0) // unreliable then reliable
.thenComparingInt(frame -> frame.getReliability().isOrdered ? 1 : 0) // unordered then ordered
.thenComparingInt(Frame::getOrderChannel) // lower channel first
.thenComparingInt(Frame::getOrderIndex); // lower index first
public static void initChannel(Channel channel) {
if (channel.config() instanceof RakNet.Config config) {
config.setMaxQueuedBytes(Constants.MAX_QUEUED_SIZE);
config.setMaxPendingFrameSets(Constants.MAX_PENDING_FRAME_SETS);
config.setRetryDelayNanos(TimeUnit.NANOSECONDS.convert(50, TimeUnit.MILLISECONDS));
config.setDefaultPendingFrameSets(Constants.DEFAULT_PENDING_FRAME_SETS);
config.setNACKEnabled(false);
config.setNoDelayEnabled(false);
// config.setIgnoreResendGauge(true);
initRaknetChannel(channel);
// channel.pipeline().addLast("raknetify-flush-enforcer", new FlushEnforcer());
// channel.pipeline().addLast("raknetify-flush-consolidation", new FlushConsolidationHandler(Integer.MAX_VALUE, true));
channel.pipeline().addLast("raknetify-no-flush", new NoFlush());
channel.pipeline().addLast(MultiChannelingStreamingCompression.NAME, new MultiChannelingStreamingCompression(Constants.RAKNET_GAME_PACKET_ID, Constants.RAKNET_STREAMING_COMPRESSION_PACKET_ID));
// channel.pipeline().addLast(MultiChannellingDataCodec.NAME, new MultiChannellingDataCodec(Constants.RAKNET_GAME_PACKET_ID));
channel.pipeline().addLast("raknetify-frame-data-blocker", new FrameDataBlocker());
}
}
private static void initRaknetChannel(Channel appChannel) {
final Channel channel;
final String threadedReadHandlerName;
if (appChannel instanceof RakNetApplicationChannel) {
channel = appChannel.parent();
threadedReadHandlerName = RakNetApplicationChannel.NAME_SERVER_PARENT_THREADED_READ_HANDLER;
} else if (appChannel instanceof RakNetClientThreadedChannel) {
channel = appChannel.parent();
threadedReadHandlerName = RakNetClientThreadedChannel.NAME_CLIENT_PARENT_THREADED_READ_HANDLER;
} else {
channel = appChannel;
threadedReadHandlerName = null;
}
channel.pipeline().addLast(new ChannelInitializer<>() {
@Override
protected void initChannel(Channel ch) {
final RakNet.Config config = (RakNet.Config) ch.config();
final SimpleMetricsLogger simpleMetricsLogger = new SimpleMetricsLogger();
config.setMetrics(simpleMetricsLogger);
final MetricsSynchronizationHandler metricsSynchronizationHandler = new MetricsSynchronizationHandler();
simpleMetricsLogger.setMetricsSynchronizationHandler(metricsSynchronizationHandler);
final SynchronizationLayer synchronizationLayer = new SynchronizationLayer(Constants.SYNC_IGNORE_CHANNELS);
reInitChannelForOrdering(channel);
if (threadedReadHandlerName != null) {
ch.pipeline().addBefore(threadedReadHandlerName, "raknetify-metrics-sync", metricsSynchronizationHandler);
ch.pipeline().addBefore(threadedReadHandlerName, "raknetify-synchronization-layer", synchronizationLayer);
} else {
ch.pipeline().addLast("raknetify-metrics-sync", metricsSynchronizationHandler);
ch.pipeline().addLast("raknetify-synchronization-layer", synchronizationLayer);
}
ch.pipeline().addFirst("raknetify-timeout", new ReadTimeoutHandler(15));
}
});
}
// public static void postInitChannel(Channel channel, boolean isClientSide) {
// if (channel.config() instanceof RakNet.Config) {
// ViaFabricCompatInjector.inject(channel, isClientSide);
// channel.pipeline().replace("timeout", "timeout", new ChannelDuplexHandler()); // no-op
// channel.pipeline().replace("splitter", "splitter", new ChannelDuplexHandler()); // no-op
// channel.pipeline().replace("prepender", "prepender", new ChannelDuplexHandler()); // no-op
// final MultiChannellingPacketCapture handler = new MultiChannellingPacketCapture();
// channel.pipeline().addLast("raknetify-multi-channel-packet-cature", handler);
// channel.pipeline().get(MultiChannellingDataCodec.class).setCapture(handler);
// }
// }
@SuppressWarnings("unchecked")
private static void reInitChannelForOrdering(Channel channel) {
if (channel.config() instanceof RakNet.Config config) {
try {
final ReliabilityHandler reliabilityHandler = channel.pipeline().get(ReliabilityHandler.class);
final Field frameQueueField = accessible(ReliabilityHandler.class.getDeclaredField("frameQueue"));
PriorityQueue reliabilityHandlerFrameQueue = (PriorityQueue ) frameQueueField.get(reliabilityHandler);
final PriorityQueue newSet = new PriorityQueue<>(cmp);
newSet.addAll(reliabilityHandlerFrameQueue);
frameQueueField.set(reliabilityHandler, newSet);
} catch (Throwable t) {
System.err.println("Raknetify: Error occurred while reinitializing channel ordering");
t.printStackTrace();
}
}
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/RakNetSimpleMultiChannelCodec.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.util.MathUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import network.ycc.raknet.frame.FrameData;
import network.ycc.raknet.packet.FramedPacket;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class RakNetSimpleMultiChannelCodec extends ChannelDuplexHandler {
public static final String NAME = "raknetify-simple-multi-channel-data-codec";
public static final Object SIGNAL_START_MULTICHANNEL = new Object();
private final int packetId;
public RakNetSimpleMultiChannelCodec(int packetId) {
this.packetId = packetId;
}
private final ObjectArrayList handlers = new ObjectArrayList<>();
public RakNetSimpleMultiChannelCodec addHandler(OverrideHandler handler) {
synchronized (handlers) {
handlers.add(handler);
}
return this;
}
public void removeHandler(OverrideHandler handler) {
synchronized (handlers) {
handlers.remove(handler);
}
}
public T getHandler(Class clazz) {
synchronized (handlers) {
for (OverrideHandler handler : handlers) {
if (clazz.isInstance(handler)) return clazz.cast(handler);
}
}
return null;
}
private boolean isMultichannelEnabled;
private boolean queuePendingWrites = false;
private final Queue pendingWrites = new LinkedList<>();
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
super.handlerRemoved(ctx);
for (PendingWrite pendingWrite : pendingWrites) {
pendingWrite.promise.setFailure(new IllegalStateException("Channel closed"));
pendingWrite.frameData.release();
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (this.queuePendingWrites && msg instanceof ByteBuf buf) {
final FrameData data = encode0(ctx, buf);
if (data != null) {
pendingWrites.add(new PendingWrite(data, promise));
} else {
promise.setSuccess();
}
buf.release();
return;
}
if (msg == SIGNAL_START_MULTICHANNEL) {
promise.trySuccess();
if (this.isMultichannelEnabled) return;
if (!this.isMultichannelAvailable()) {
System.out.println("Raknetify: [MultiChannellingDataCodec] Failed to start multichannel: not available");
return;
}
final ByteBuf buf = ctx.alloc().buffer(1).writeByte(0);
try {
final FrameData frameData = FrameData.create(ctx.alloc(), Constants.RAKNET_PING_PACKET_ID, buf);
frameData.setOrderChannel(7);
this.queuePendingWrites = true;
ctx.write(frameData).addListener(future -> {
isMultichannelEnabled = true;
if (Constants.DEBUG) System.out.println("Raknetify: [MultiChannellingDataCodec] Started multichannel");
flushPendingWrites(ctx);
});
} finally {
buf.release();
}
return;
}
if (msg == SynchronizationLayer.SYNC_REQUEST_OBJECT) {
if (this.isMultichannelEnabled) {
if (Constants.DEBUG) System.out.println("Raknetify: [MultiChannellingDataCodec] Stopped multichannel");
this.isMultichannelEnabled = false;
super.write(ctx, msg, promise);
}
promise.setSuccess();
return; // discard sync request when multichannel is not active
}
if (msg instanceof ByteBuf buf && buf.isReadable()) {
try {
final FrameData frameData = encode0(ctx, buf);
if (frameData != null) {
ctx.write(frameData, promise);
} else {
promise.setSuccess();
}
} finally {
buf.release();
}
return;
}
super.write(ctx, msg, promise);
}
private FrameData encode0(ChannelHandlerContext ctx, ByteBuf buf) {
if (buf.isReadable()) {
final int packetChannelOverride = getChannelOverride(buf, !isMultichannelEnabled);
if (packetChannelOverride == Integer.MIN_VALUE) {
return null; // the void
}
final FrameData frameData = FrameData.create(ctx.alloc(), packetId, buf);
if (isMultichannelEnabled) {
if (packetChannelOverride >= 0)
frameData.setOrderChannel(packetChannelOverride);
else if (packetChannelOverride == -1)
frameData.setReliability(FramedPacket.Reliability.RELIABLE);
else if (packetChannelOverride == -2)
frameData.setReliability(FramedPacket.Reliability.UNRELIABLE);
}
return frameData;
}
return null;
}
private void flushPendingWrites(ChannelHandlerContext ctx) {
this.queuePendingWrites = false;
PendingWrite pendingWrite;
while ((pendingWrite = this.pendingWrites.poll()) != null) {
try {
super.write(ctx, pendingWrite.frameData, pendingWrite.promise);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
}
}
protected boolean isMultichannelAvailable() {
synchronized (handlers) {
return !handlers.isEmpty();
}
}
protected int getChannelOverride(ByteBuf buf, boolean suppressWarning) {
synchronized (handlers) {
for (OverrideHandler handler : handlers) {
final int override = handler.getChannelOverride(buf, suppressWarning);
if (override != 0) return override;
}
}
return 0;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FrameData packet && !packet.isFragment() && packet.getDataSize() > 0) {
try {
if (packetId == packet.getPacketId()) {
ctx.fireChannelRead(packet.createData().skipBytes(1));
} else if (packet.getPacketId() == Constants.RAKNET_PING_PACKET_ID) {
return;
} else {
ctx.fireChannelRead(packet.retain());
}
} finally {
packet.release();
}
return;
}
super.channelRead(ctx, msg);
}
protected void decode(ChannelHandlerContext ctx, FrameData packet, List out) {
assert !packet.isFragment();
if (packet.getDataSize() > 0) {
if (packetId == packet.getPacketId()) {
out.add(packet.createData().skipBytes(1));
} else if (packet.getPacketId() == Constants.RAKNET_PING_PACKET_ID) {
return;
} else {
out.add(packet.retain());
}
}
}
public interface OverrideHandler {
int getChannelOverride(ByteBuf buf, boolean suppressWarning);
}
public static class PacketIdBasedOverrideHandler implements OverrideHandler {
private final IntOpenHashSet unknownPacketIds = new IntOpenHashSet();
private final Int2IntOpenHashMap channelMapping;
private final String descriptiveProtocolStatus;
public PacketIdBasedOverrideHandler(Int2IntMap channelMapping, String descriptiveProtocolStatus) {
this.channelMapping = new Int2IntOpenHashMap(channelMapping);
this.descriptiveProtocolStatus = descriptiveProtocolStatus;
}
@Override
public int getChannelOverride(ByteBuf buf, boolean suppressWarning) {
final ByteBuf slice = buf.slice();
final int packetId = MathUtil.readVarInt(slice);
final int override = this.channelMapping.get(packetId);
if (override == Integer.MAX_VALUE) {
if (!suppressWarning) {
if (this.unknownPacketIds.add(packetId)) {
System.err.println("Raknetify: Unknown packet id %d for %s".formatted(packetId, descriptiveProtocolStatus));
}
}
return 7;
}
return override;
}
}
private record PendingWrite(FrameData frameData, ChannelPromise promise) {
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/RaknetifyEventLoops.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import com.google.common.base.Suppliers;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.FastThreadLocalThread;
import java.util.function.Supplier;
public class RaknetifyEventLoops {
public static final Supplier NIO_EVENT_LOOP_GROUP =
Suppliers.memoize(() -> new NioEventLoopGroup(
0,
new ThreadFactoryBuilder()
.setThreadFactory(FastThreadLocalThread::new)
.setNameFormat("Netty Server NIO Raknetify #%d")
.setDaemon(true)
.build()
)
);
public static final Supplier NIO_CLIENT_EVENT_LOOP_GROUP =
Suppliers.memoize(() -> new NioEventLoopGroup(
0,
new ThreadFactoryBuilder()
.setThreadFactory(FastThreadLocalThread::new)
.setNameFormat("Netty Client NIO Raknetify #%d")
.setDaemon(true)
.build()
)
);
public static final Supplier EPOLL_EVENT_LOOP_GROUP =
Suppliers.memoize(() -> new EpollEventLoopGroup(
0,
new ThreadFactoryBuilder()
.setThreadFactory(FastThreadLocalThread::new)
.setNameFormat("Netty Server Epoll Raknetify #%d")
.setDaemon(true)
.build()
)
);
public static final Supplier EPOLL_CLIENT_EVENT_LOOP_GROUP =
Suppliers.memoize(() -> new EpollEventLoopGroup(
0,
new ThreadFactoryBuilder()
.setThreadFactory(FastThreadLocalThread::new)
.setNameFormat("Netty Client Epoll Raknetify #%d")
.setDaemon(true)
.build()
)
);
public static final Supplier DEFAULT_EVENT_LOOP_GROUP =
Suppliers.memoize(() -> new DefaultEventLoopGroup(
0,
new ThreadFactoryBuilder()
.setThreadFactory(FastThreadLocalThread::new)
.setNameFormat("Netty Server App Raknetify #%d")
.setDaemon(true)
.build()
)
);
public static final Supplier DEFAULT_CLIENT_EVENT_LOOP_GROUP =
Suppliers.memoize(() -> new DefaultEventLoopGroup(
0,
new ThreadFactoryBuilder()
.setThreadFactory(FastThreadLocalThread::new)
.setNameFormat("Netty Client App Raknetify #%d")
.setDaemon(true)
.build()
)
);
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/SimpleMetricsLogger.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import com.ishland.raknetify.common.util.MathUtil;
import network.ycc.raknet.RakNet;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
/**
* This implementation is only designed to be modified single-threaded
*/
@SuppressWarnings("NonAtomicOperationOnVolatileField")
public class SimpleMetricsLogger implements RakNet.MetricsLogger {
// ========== Loggers ==========
private volatile long packetsIn = 0L;
private volatile long framesIn = 0L;
private volatile long framesError = 0L;
private volatile long bytesIn = 0L;
private volatile long packetsOut = 0L;
private volatile long framesOut = 0L;
private volatile long bytesOut = 0L;
private volatile long bytesRecalled = 0L;
private volatile long bytesACKd = 0L;
private volatile long bytesNACKd = 0L;
private volatile long acksSent = 0L;
private volatile long nacksSent = 0L;
private volatile long measureRTTns = 0L;
private volatile long measureRTTnsStdDev = 0L;
private volatile long measureBurstTokens = 0L;
private volatile int currentQueuedBytes = 0;
@Override
public void packetsIn(int delta) {
packetsIn += delta;
}
@Override
public void framesIn(int delta) {
framesIn += delta;
}
@Override
public void frameError(int delta) {
framesError += delta;
}
@Override
public void bytesIn(int delta) {
bytesIn += delta;
}
@Override
public void packetsOut(int delta) {
packetsOut += delta;
}
@Override
public void framesOut(int delta) {
framesOut += delta;
}
@Override
public void bytesOut(int delta) {
bytesOut += delta;
tick();
}
@Override
public void bytesRecalled(int delta) {
bytesRecalled += delta;
}
@Override
public void bytesACKd(int delta) {
bytesACKd += delta;
}
@Override
public void bytesNACKd(int delta) {
bytesNACKd += delta;
}
@Override
public void acksSent(int delta) {
acksSent += delta;
}
@Override
public void nacksSent(int delta) {
nacksSent += delta;
}
@Override
public void measureRTTns(long n) {
measureRTTns = n;
}
@Override
public void measureRTTnsStdDev(long n) {
measureRTTnsStdDev = n;
tick();
}
@Override
public void measureBurstTokens(int n) {
measureBurstTokens = n;
}
@Override
public void currentQueuedBytes(int bytes) {
currentQueuedBytes = bytes;
}
// ========== Calculations ==========
private long lastMeasureMillis = System.currentTimeMillis();
private synchronized void tick() {
final long measureMillis = System.currentTimeMillis();
final long deltaTime = measureMillis - lastMeasureMillis;
if (deltaTime < 990) return; // throttle
this.lastMeasureMillis = measureMillis;
tickErrorRate();
tickRXTX(deltaTime);
}
private final DescriptiveStatistics errorStats = new DescriptiveStatistics(16);
private long lastBytesTotal = 0L;
private long lastBytesRecalled = 0L;
private volatile double measureErrorRate = 0.0D;
private void tickErrorRate() {
final long bytesTotal = this.bytesIn + this.bytesOut;
final long bytesRecalled = this.bytesRecalled;
final long bytesTotalDelta = bytesTotal - lastBytesTotal;
final long bytesRecalledDelta = bytesRecalled - this.lastBytesRecalled;
if (bytesTotalDelta != 0) {
this.errorStats.addValue(bytesRecalledDelta / (double) bytesTotalDelta);
this.measureErrorRate = this.errorStats.getMean();
}
this.lastBytesTotal = bytesTotal;
this.lastBytesRecalled = bytesRecalled;
}
private final DescriptiveStatistics rxStats = new DescriptiveStatistics(8);
private final DescriptiveStatistics txStats = new DescriptiveStatistics(8);
private long lastPacketsIn = 0L;
private long lastPacketsOut = 0L;
private long lastBytesIn = 0L;
private long lastBytesOut = 0L;
private volatile int measureRX = 0;
private volatile int measureTX = 0;
private volatile long measureBytesInRate = 0;
private volatile long measureBytesOutRate = 0;
private volatile String measureTrafficInFormatted = "...";
private volatile String measureTrafficOutFormatted = "...";
private void tickRXTX(long deltaTime) {
final long packetsIn = this.packetsIn;
final long packetsOut = this.packetsOut;
final long bytesIn = this.bytesIn;
final long bytesOut = this.bytesOut;
final double timeDeltaS = deltaTime / 1000.0;
this.rxStats.addValue((packetsIn - this.lastPacketsIn) / timeDeltaS);
this.txStats.addValue((packetsOut - this.lastPacketsOut) / timeDeltaS);
this.measureRX = (int) this.rxStats.getMean();
this.measureTX = (int) this.txStats.getMean();
this.measureBytesInRate = (long) ((bytesIn - this.lastBytesIn) / timeDeltaS);
this.measureBytesOutRate = (long) ((bytesOut - this.lastBytesOut) / timeDeltaS);
this.measureTrafficInFormatted = MathUtil.humanReadableByteCountBin(this.measureBytesInRate) + "/s";
this.measureTrafficOutFormatted = MathUtil.humanReadableByteCountBin(this.measureBytesOutRate) + "/s";
this.lastPacketsIn = packetsIn;
this.lastPacketsOut = packetsOut;
this.lastBytesIn = bytesIn;
this.lastBytesOut = bytesOut;
}
// ========== Getters ==========
public long getMeasureRTTns() {
return measureRTTns;
}
public long getMeasureRTTnsStdDev() {
return measureRTTnsStdDev;
}
public double getMeasureErrorRate() {
return measureErrorRate;
}
public int getMeasureRX() {
return measureRX;
}
public int getMeasureTX() {
return measureTX;
}
public int getCurrentQueuedBytes() {
return currentQueuedBytes;
}
public long getMeasureBurstTokens() {
return measureBurstTokens;
}
public long getMeasureBytesInRate() {
return measureBytesInRate;
}
public long getMeasureBytesOutRate() {
return measureBytesOutRate;
}
public String getMeasureTrafficInFormatted() {
return measureTrafficInFormatted;
}
public String getMeasureTrafficOutFormatted() {
return measureTrafficOutFormatted;
}
public long getBytesIn() {
return bytesIn;
}
// ========== Misc ==========
private MetricsSynchronizationHandler metricsSynchronizationHandler;
public MetricsSynchronizationHandler getMetricsSynchronizationHandler() {
return this.metricsSynchronizationHandler;
}
public void setMetricsSynchronizationHandler(MetricsSynchronizationHandler metricsSynchronizationHandler) {
this.metricsSynchronizationHandler = metricsSynchronizationHandler;
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/SynchronizationLayer.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection;
import com.ishland.raknetify.common.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet;
import network.ycc.raknet.frame.Frame;
import network.ycc.raknet.frame.FrameData;
import network.ycc.raknet.packet.FrameSet;
import network.ycc.raknet.packet.FramedPacket;
import network.ycc.raknet.pipeline.FrameJoiner;
import network.ycc.raknet.pipeline.FrameOrderIn;
import network.ycc.raknet.pipeline.FrameOrderOut;
import network.ycc.raknet.pipeline.ReliabilityHandler;
import org.apache.commons.math3.util.Pair;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.PriorityQueue;
import static com.ishland.raknetify.common.util.ReflectionUtil.accessible;
public class SynchronizationLayer extends ChannelDuplexHandler {
// Request structure:
// byte: total channel count `n`
// next `n` groups: {
// byte: channel index
// integer: current orderIndex (or lastOrderIndex, (nextOrderIndex - 1))
// }
// integer: current seqId (or lastReceivedSeqId, (nextSendSeqId - 1))
//
// Response callback is handled using reliable transport
public static final Object SYNC_REQUEST_OBJECT = new Object();
static final Class> CLASS_QUEUE;
static final Class> CLASS_FRAME_JOINER_BUILDER;
static final Field FIELD_QUEUE_LAST_ORDER_INDEX;
static final Method METHOD_QUEUE_BUILDER_RELEASE;
static final Method METHOD_QUEUE_CLEAR;
static final Field FIELD_RELIABILITY_NEXT_SEND_SEQ_ID;
static final Field FIELD_RELIABILITY_LAST_RECEIVED_SEQ_ID;
static final Field FIELD_RELIABILITY_QUEUED_BYTES;
static final Field FIELD_FRAME_JOINER_BUILDER_SAMPLE_PACKET;
static {
try {
CLASS_QUEUE = Class.forName("network.ycc.raknet.pipeline.FrameOrderIn$OrderedChannelPacketQueue");
CLASS_FRAME_JOINER_BUILDER = Class.forName("network.ycc.raknet.pipeline.FrameJoiner$Builder");
FIELD_QUEUE_LAST_ORDER_INDEX = accessible(CLASS_QUEUE.getDeclaredField("lastOrderIndex"));
FIELD_RELIABILITY_NEXT_SEND_SEQ_ID = accessible(ReliabilityHandler.class.getDeclaredField("nextSendSeqId"));
FIELD_RELIABILITY_LAST_RECEIVED_SEQ_ID = accessible(ReliabilityHandler.class.getDeclaredField("lastReceivedSeqId"));
FIELD_RELIABILITY_QUEUED_BYTES = accessible(ReliabilityHandler.class.getDeclaredField("queuedBytes"));
FIELD_FRAME_JOINER_BUILDER_SAMPLE_PACKET = accessible(CLASS_FRAME_JOINER_BUILDER.getDeclaredField("samplePacket"));
METHOD_QUEUE_BUILDER_RELEASE = accessible(CLASS_FRAME_JOINER_BUILDER.getDeclaredMethod("release"));
METHOD_QUEUE_CLEAR = accessible(CLASS_QUEUE.getDeclaredMethod("clear"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private final IntSet channelToIgnore = new IntOpenHashSet();
private FrameOrderIn frameOrderIn;
private Object[] frameOrderInQueues;
private FrameOrderOut frameOrderOut;
private int[] frameOrderOutNextOrderIndex;
private ReliabilityHandler reliabilityHandler;
private PriorityQueue reliabilityHandlerFrameQueue;
private Int2ObjectMap reliabilityHandlerPendingFrameSets;
private FrameJoiner frameJoiner;
private Int2ObjectOpenHashMap> frameJoinerPendingPackets;
private int channelsLength;
private boolean initialized = false;
public SynchronizationLayer(int... channelsToIgnore) {
for (int ch : channelsToIgnore) {
channelToIgnore.add(ch);
}
}
@SuppressWarnings("unchecked")
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
initializeIfNecessary(ctx);
}
private void initializeIfNecessary(ChannelHandlerContext ctx) {
if (initialized) return;
try {
this.frameOrderIn = ctx.pipeline().get(FrameOrderIn.class);
Object frameOrderInQueueArray = accessible(FrameOrderIn.class.getDeclaredField("channels")).get(this.frameOrderIn);
this.frameOrderInQueues = new Object[Array.getLength(frameOrderInQueueArray)];
for (int i = 0; i < this.frameOrderInQueues.length; i++) {
this.frameOrderInQueues[i] = Array.get(frameOrderInQueueArray, i);
}
this.frameOrderOut = ctx.pipeline().get(FrameOrderOut.class);
this.frameOrderOutNextOrderIndex = (int[]) accessible(FrameOrderOut.class.getDeclaredField("nextOrderIndex")).get(this.frameOrderOut);
this.reliabilityHandler = ctx.pipeline().get(ReliabilityHandler.class);
this.reliabilityHandlerFrameQueue = (PriorityQueue ) accessible(ReliabilityHandler.class.getDeclaredField("frameQueue")).get(this.reliabilityHandler);
this.reliabilityHandlerPendingFrameSets = (Int2ObjectMap) accessible(ReliabilityHandler.class.getDeclaredField("pendingFrameSets")).get(this.reliabilityHandler);
int originalChannelsLength = this.frameOrderOutNextOrderIndex.length;
//noinspection deprecation
this.channelsLength = (int) (originalChannelsLength - this.channelToIgnore.stream().filter(value -> value < originalChannelsLength).count());
this.frameJoiner = ctx.pipeline().get(FrameJoiner.class);
this.frameJoinerPendingPackets = (Int2ObjectOpenHashMap>) accessible(FrameJoiner.class.getDeclaredField("pendingPackets")).get(this.frameJoiner);
initialized = true;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
initializeIfNecessary(ctx);
if (msg instanceof FrameData packet && packet.getPacketId() == Constants.RAKNET_SYNC_PACKET_ID) {
// read
{
if (Constants.DEBUG) System.out.println("Raknetify: Received sync packet");
ctx.fireUserEventTriggered(SYNC_REQUEST_OBJECT);
final ByteBuf byteBuf = packet.createData().skipBytes(1);
try {
final byte count = byteBuf.readByte();
for (int i = 0; i < count; i++) {
final byte channel = byteBuf.readByte();
final int orderIndex = byteBuf.readInt();
if (Constants.DEBUG)
System.out.println("Raknetify: Channel %d: %d -> %d"
.formatted(channel,
(int) FIELD_QUEUE_LAST_ORDER_INDEX.get(frameOrderInQueues[channel]),
orderIndex
));
FIELD_QUEUE_LAST_ORDER_INDEX.set(frameOrderInQueues[channel], orderIndex);
final ObjectIterator> iterator = this.frameJoinerPendingPackets.values().iterator();
while (iterator.hasNext()) {
final Object next = iterator.next();
try {
final Frame frame = (Frame) FIELD_FRAME_JOINER_BUILDER_SAMPLE_PACKET.get(next);
if (frame.getReliability().isOrdered && frame.getOrderChannel() == channel) {
METHOD_QUEUE_BUILDER_RELEASE.invoke(next);
iterator.remove();
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
final int seqId = byteBuf.readInt();
if (Constants.DEBUG)
System.out.println("Raknetify: ReliabilityHandler: %d -> %d".formatted(
(int) FIELD_RELIABILITY_LAST_RECEIVED_SEQ_ID.get(this.reliabilityHandler),
seqId
));
FIELD_RELIABILITY_LAST_RECEIVED_SEQ_ID.set(this.reliabilityHandler, seqId);
} finally {
byteBuf.release();
}
}
return;
}
ctx.fireChannelRead(msg);
}
private final ReferenceLinkedOpenHashSet> queue = new ReferenceLinkedOpenHashSet<>();
private final ObjectArrayList queuedFrames = new ObjectArrayList<>();
private boolean isWaitingForResponse = false;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
initializeIfNecessary(ctx);
if (msg == SYNC_REQUEST_OBJECT) {
if (isWaitingForResponse) {
promise.setSuccess();
return;
}
dropSenderPackets();
final ByteBuf byteBuf = ctx.alloc().buffer(1 + channelsLength * 5 + 4);
byteBuf.writeByte(channelsLength);
for (int channel = 0, frameOrderOutNextOrderIndexLength = frameOrderOutNextOrderIndex.length; channel < frameOrderOutNextOrderIndexLength; channel++) {
if (channelToIgnore.contains(channel)) continue;
int orderOutNextOrderIndex = frameOrderOutNextOrderIndex[channel];
if (Constants.DEBUG)
System.out.println("Raknetify: Writing sync packet: Channel %d: %d".formatted(channel, orderOutNextOrderIndex - 1));
byteBuf.writeByte(channel);
byteBuf.writeInt(orderOutNextOrderIndex - 1);
}
int seqId = (int) FIELD_RELIABILITY_NEXT_SEND_SEQ_ID.get(this.reliabilityHandler); // TODO implementation details (probable lib bug): nextSendSeqId == lastReceivedSeqId
if (Constants.DEBUG)
System.out.println("Raknetify: Writing sync packet: ReliabilityHandler: %d".formatted(seqId));
byteBuf.writeInt(seqId);
final FrameData frameData = FrameData.create(ctx.alloc(), Constants.RAKNET_SYNC_PACKET_ID, byteBuf);
frameData.setReliability(FramedPacket.Reliability.RELIABLE);
this.isWaitingForResponse = true;
ctx.write(frameData).addListener(future -> this.flushQueue(ctx));
byteBuf.release();
promise.setSuccess();
return;
}
if (isWaitingForResponse) {
this.queue.add(Pair.create(promise, msg));
return;
}
super.write(ctx, msg, promise);
}
private void dropSenderPackets() {
int droppedFrames = 0;
ArrayList retainedFrameList = new ArrayList<>();
//noinspection CollectionAddAllCanBeReplacedWithConstructor
retainedFrameList.addAll(this.reliabilityHandlerFrameQueue);
this.reliabilityHandlerFrameQueue.clear();
for (FrameSet frameSet : this.reliabilityHandlerPendingFrameSets.values()) {
frameSet.createFrames(retainedFrameList::add);
frameSet.release();
}
this.reliabilityHandlerPendingFrameSets.clear();
int byteSize = 0;
for (Iterator iterator = retainedFrameList.iterator(); iterator.hasNext(); ) {
Frame frame = iterator.next();
if (frame.getReliability().isOrdered && !channelToIgnore.contains(frame.getOrderChannel())) {
final ChannelPromise promise1 = frame.getPromise();
if (promise1 != null) promise1.trySuccess();
iterator.remove();
frame.release();
droppedFrames++;
} else {
byteSize += frame.getRoughPacketSize();
}
}
this.queuedFrames.addAll(retainedFrameList);
if (Constants.DEBUG) System.out.println("Raknetify: Dropping %d frames".formatted(droppedFrames));
try {
FIELD_RELIABILITY_QUEUED_BYTES.set(this.reliabilityHandler, byteSize);
} catch (Throwable t) {
throw new RuntimeException(t);
}
this.reliabilityHandlerPendingFrameSets.clear();
}
private void flushQueue(ChannelHandlerContext ctx) {
if (!isWaitingForResponse) {
if (Constants.DEBUG) System.out.println("Raknetify: Ignoring duplicate call to flushQueue()");
return;
}
if (!ctx.channel().eventLoop().inEventLoop()) {
ctx.channel().eventLoop().execute(() -> flushQueue(ctx));
return;
}
this.isWaitingForResponse = false;
if (Constants.DEBUG) System.out.println("Raknetify: Picking up %d queued frames".formatted(this.queuedFrames.size()));
this.reliabilityHandlerFrameQueue.addAll(this.queuedFrames);
this.queuedFrames.clear();
if (Constants.DEBUG) System.out.println("Raknetify: Flushing %d queued packets as synchronization finished".formatted(this.queue.size()));
while (!this.queue.isEmpty()) {
Pair pair = this.queue.removeFirst();
final ChannelPromise promise = pair.getFirst();
final Object msg = pair.getSecond();
ctx.write(msg, promise);
}
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/connection/multichannel/CustomPayloadChannel.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.connection.multichannel;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.common.util.MathUtil;
import io.netty.buffer.ByteBuf;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.Objects;
import java.util.function.IntPredicate;
public class CustomPayloadChannel {
public static final Object2IntOpenHashMap identifier2channel;
static {
// See .fabric.common.connection.RakNetMultiChannel
identifier2channel = new Object2IntOpenHashMap<>();
identifier2channel.defaultReturnValue(0);
identifier2channel.put("porting_lib:extra_data_entity_spawn", 2);
identifier2channel.put("porting_lib:extra_entity_spawn_data", 2); // https://github.com/Fabricators-of-Create/Porting-Lib/commit/4b0cd845731f89eafd9fb39e13e1a7d87f5e14a4
}
public static class OverrideHandler implements RakNetSimpleMultiChannelCodec.OverrideHandler {
private final IntPredicate isCustomPayload;
public OverrideHandler(IntPredicate isCustomPayload) {
this.isCustomPayload = Objects.requireNonNull(isCustomPayload);
}
@Override
public int getChannelOverride(ByteBuf origBuf, boolean suppressWarning) {
ByteBuf buf = origBuf.slice();
final int packetId = MathUtil.readVarInt(buf);
if (isCustomPayload.test(packetId)) {
final String identifier = MathUtil.readString(buf); // we assume modern custom payloads
if (Constants.DEBUG) System.out.println("Raknetify: Handling custom payload: " + identifier);
return identifier2channel.getInt(identifier);
} else {
return 0;
}
}
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/data/ProtocolMultiChannelMappings.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.data;
import com.google.gson.Gson;
import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ProtocolMultiChannelMappings {
public static final ProtocolMultiChannelMappings INSTANCE;
static {
final InputStream resource = ProtocolMultiChannelMappings.class.getClassLoader().getResourceAsStream("raknetify-channel-mappings.json");
if (resource == null) {
System.err.println("Raknetify: Failed to load raknetify channel mappings");
INSTANCE = new ProtocolMultiChannelMappings();
} else {
ProtocolMultiChannelMappings read = new ProtocolMultiChannelMappings();
try (var in = resource;
var reader = new InputStreamReader(resource)) {
final Gson gson = new Gson();
read = gson.fromJson(reader, ProtocolMultiChannelMappings.class);
} catch (IOException e) {
System.err.println("Raknetify: Failed to load raknetify channel mappings");
e.printStackTrace();
}
INSTANCE = read;
}
}
public static void init() {
}
public Int2ObjectArrayMap mappings = new Int2ObjectArrayMap<>();
public static class VersionMapping {
public Int2IntArrayMap s2c = new Int2IntArrayMap();
public Int2IntArrayMap c2s = new Int2IntArrayMap();
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/package-info.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common;
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/util/DebugUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.util;
import com.ishland.raknetify.common.connection.MetricsSynchronizationHandler;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.SimpleMetricsLogger;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import network.ycc.raknet.RakNet;
public class DebugUtil {
public static String printChannelDetails(Channel channel) {
final StringBuilder b = new StringBuilder();
b.append("Channel details for ").append(channel.toString()).append(' ').append('(').append(channel.getClass().getName()).append(')').append('\n');
b.append("Connection: ").append(channel.localAddress()).append(" <--> ").append(channel.remoteAddress()).append('\n');
b.append("Open: ").append(channel.isOpen()).append('\n');
b.append("Active: ").append(channel.isActive()).append('\n');
b.append("Auto Read: ").append(channel.config().isAutoRead()).append('\n');
if (channel.config() instanceof RakNet.Config config) {
b.append("MTU: ").append(config.getMTU()).append('\n');
b.append("RTT: %.2f/%.2fms"
.formatted(
config.getRTTNanos() / 1_000_000.0,
config.getRTTStdDevNanos() / 1_000_000.0
)).append('\n');
if (config.getMetrics() instanceof SimpleMetricsLogger logger) {
final MetricsSynchronizationHandler sync = logger.getMetricsSynchronizationHandler();
if (sync != null && sync.isRemoteSupported()) {
b.append("Local Buffer: %.2fMB; Remote buffer: %.2fMB"
.formatted(
logger.getCurrentQueuedBytes() / 1024.0 / 1024.0,
sync.getQueuedBytes() / 1024.0 / 1024.0
)).append('\n');
} else {
b.append("Local buffer: %.2fMB"
.formatted(
logger.getCurrentQueuedBytes() / 1024.0 / 1024.0
)).append('\n');
}
b.append("Local traffic: I: %s, O: %s"
.formatted(
logger.getMeasureTrafficInFormatted(),
logger.getMeasureTrafficOutFormatted()
)).append('\n');
b.append("Local Statistics: ERR: %.4f%%, %d tx, %d rx, Burst: %d"
.formatted(
logger.getMeasureErrorRate() * 100.0,
logger.getMeasureTX(), logger.getMeasureRX(),
logger.getMeasureBurstTokens() + config.getDefaultPendingFrameSets()
)).append('\n');
if (sync != null && sync.isRemoteSupported()) {
b.append("Remote Statistics: ERR: %.4f%%, %d tx, %d rx, Burst: %d"
.formatted(
sync.getErrorRate() * 100.0,
sync.getTX(), sync.getRX(),
sync.getBurst()
)).append('\n');
}
final MultiChannelingStreamingCompression compression = channel.pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
b.append("Local Streaming Compression Ratio: I: %.2f%%, O: %.2f%%"
.formatted(compression.getInCompressionRatio() * 100, compression.getOutCompressionRatio() * 100)).append('\n');
}
}
}
b.append('\n');
b.append("Pipeline: ").append('\n');
for (String name : channel.pipeline().names()) {
final ChannelHandler channelHandler = channel.pipeline().get(name);
if (channelHandler == null) {
b.append("\t").append(name).append(": \t").append("null").append('\n');
} else {
b.append("\t").append(name).append(": \t").append(channelHandler.toString()).append("(").append(channelHandler.getClass().getName()).append(")").append('\n');
}
}
if (channel.parent() != null) {
b.append('\n');
b.append("Parent: ").append('\n');
b.append(printChannelDetails(channel.parent()).replace("\n", "\n\t"));
}
return b.toString();
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/util/MathUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.util;
import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class MathUtil {
public static String humanReadableByteCountBin(long bytes) {
long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
if (absB < 1024) {
return bytes + " B";
}
long value = absB;
CharacterIterator ci = new StringCharacterIterator("KMGTPE");
for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) {
value >>= 10;
ci.next();
}
value *= Long.signum(bytes);
return String.format("%.2f %ciB", value / 1024.0, ci.current());
}
public static int readVarInt(ByteBuf buf) {
// TODO [VanillaCopy]
int i = 0;
int j = 0;
byte b;
do {
b = buf.readByte();
i |= (b & 127) << j++ * 7;
if (j > 5) {
throw new RuntimeException("VarInt too big");
}
} while ((b & 128) == 128);
return i;
}
public static String readString(ByteBuf buf) {
return readString(buf, Short.MAX_VALUE);
}
public static String readString(ByteBuf buf, int maxLen) {
// Copied from BungeeCord
int len = readVarInt(buf);
if (len > maxLen * 3) {
throw new IllegalArgumentException("Cannot receive string longer than " + maxLen * 3 + " (got " + len + " bytes)");
}
String s = buf.toString(buf.readerIndex(), len, Charsets.UTF_8);
buf.readerIndex(buf.readerIndex() + len);
if (s.length() > maxLen) {
throw new IllegalArgumentException("Cannot receive string longer than " + maxLen + " (got " + s.length() + " characters)");
}
return s;
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/util/NetworkInterfaceListener.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.util;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import it.unimi.dsi.fastutil.objects.ReferenceSet;
import it.unimi.dsi.fastutil.objects.ReferenceSets;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class NetworkInterfaceListener {
private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
r -> {
final Thread thread = new Thread(r, "Raknetify IFListener");
thread.setDaemon(true);
thread.setPriority(Thread.NORM_PRIORITY - 1);
return thread;
}
);
static {
scheduler.scheduleAtFixedRate(() -> {
try {
pollChanges();
} catch (Throwable t) {
t.printStackTrace();
}
}, 0, 10, TimeUnit.SECONDS);
}
public static void init() {
}
private static final ObjectOpenHashSet knownAddresses = new ObjectOpenHashSet<>();
private static final ReferenceSet> listeners = ReferenceSets.synchronize(new ReferenceOpenHashSet<>());
private static void pollChanges() {
try {
final List networkInterfaces = NetworkInterface.networkInterfaces().toList();
ObjectOpenHashSet currentAddresses = new ObjectOpenHashSet<>();
for (NetworkInterface networkInterface : networkInterfaces) {
if (networkInterface.isUp()) {
for (InetAddress address : networkInterface.inetAddresses().toList()) {
currentAddresses.add(address);
if (knownAddresses.add(address)) {
listeners.forEach(consumer -> consumer.accept(new InterfaceAddressChangeEvent(true, address)));
}
}
}
}
final ObjectIterator iterator = knownAddresses.iterator();
while (iterator.hasNext()) {
final InetAddress address = iterator.next();
if (!currentAddresses.contains(address)) {
iterator.remove();
listeners.forEach(consumer -> consumer.accept(new InterfaceAddressChangeEvent(false, address)));
}
}
} catch (Throwable t) {
t.printStackTrace();
}
}
public static void addListener(Consumer consumer) {
listeners.add(consumer);
}
public static void removeListener(Consumer consumer) {
listeners.remove(consumer);
}
public record InterfaceAddressChangeEvent(boolean added, InetAddress address) {
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/util/PrefixUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.util;
import com.ishland.raknetify.common.Constants;
public class PrefixUtil {
public static Info getInfo(String address) {
if (address.startsWith(Constants.RAKNET_PREFIX)) {
return new Info(true, address.substring(Constants.RAKNET_PREFIX.length()), false);
} else if (address.startsWith(Constants.RAKNET_LARGE_MTU_PREFIX)) {
return new Info(true, address.substring(Constants.RAKNET_LARGE_MTU_PREFIX.length()), true);
} else {
return new Info(false, address, false);
}
}
public record Info(boolean useRakNet, String stripped, boolean largeMTU) {
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/util/ReflectionUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionUtil {
public static Field accessible(Field field) {
field.setAccessible(true);
return field;
}
public static Method accessible(Method method) {
method.setAccessible(true);
return method;
}
}
================================================
FILE: common/src/main/java/com/ishland/raknetify/common/util/ThreadLocalUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.common.util;
public class ThreadLocalUtil {
private ThreadLocalUtil() {
}
private static final ThreadLocal initializingRaknet = ThreadLocal.withInitial(() -> false);
private static final ThreadLocal initializingRaknetLargeMTU = ThreadLocal.withInitial(() -> false);
public static void setInitializingRaknet(boolean value) {
initializingRaknet.set(value);
}
public static void setInitializingRaknetLargeMTU(boolean value) {
initializingRaknetLargeMTU.set(value);
}
public static boolean isInitializingRaknet() {
return initializingRaknet.get();
}
public static boolean isInitializingRaknetLargeMTU() {
return initializingRaknetLargeMTU.get();
}
}
================================================
FILE: common/src/main/resources/raknetify-channel-mappings.json
================================================
{
"mappings": {
"755": {
"s2c": {
"0": 2,
"1": 2,
"2": 2,
"3": 2,
"4": 1,
"5": 4,
"6": 2,
"7": -1,
"8": 7,
"9": 7,
"10": 7,
"11": 7,
"12": 7,
"13": 1,
"14": 1,
"15": 1,
"16": 1,
"17": 1,
"18": 1,
"19": 3,
"20": 3,
"21": 3,
"22": 3,
"23": 1,
"24": 3,
"25": 4,
"26": -1,
"27": 2,
"28": 2,
"29": 7,
"30": 2,
"31": 3,
"32": 3,
"33": -1,
"34": 7,
"35": 7,
"36": 4,
"37": 7,
"38": 2,
"39": 4,
"40": 3,
"41": 2,
"42": 2,
"43": 2,
"44": 2,
"45": 3,
"46": 3,
"47": 7,
"48": -1,
"49": 3,
"50": 2,
"51": 2,
"52": 2,
"53": 1,
"54": 1,
"55": 1,
"56": 1,
"57": 3,
"58": 2,
"59": 2,
"60": -1,
"61": 3,
"62": 2,
"63": 7,
"64": -1,
"65": 1,
"66": 3,
"67": 3,
"68": 3,
"69": 3,
"70": 3,
"71": 2,
"72": 3,
"73": 7,
"74": 7,
"75": 2,
"76": 1,
"77": 2,
"78": 2,
"79": 2,
"80": 2,
"81": 1,
"82": 1,
"83": 1,
"84": 2,
"85": 1,
"86": 1,
"87": 1,
"88": 1,
"89": 1,
"90": 1,
"91": 4,
"92": 4,
"93": 4,
"94": 1,
"95": 3,
"96": 2,
"97": 2,
"98": 1,
"99": 2,
"100": 2,
"101": 1,
"102": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 3,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 3,
"10": 3,
"11": 3,
"12": 3,
"13": 2,
"14": 7,
"15": -1,
"16": 1,
"17": 2,
"18": 2,
"19": 2,
"20": 2,
"21": 2,
"22": 2,
"23": 3,
"24": 3,
"25": 3,
"26": 1,
"27": 1,
"28": 1,
"29": -1,
"30": 3,
"31": 3,
"32": 3,
"33": -1,
"34": -1,
"35": 3,
"36": 3,
"37": 3,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 7,
"44": 2,
"45": 3,
"46": 2,
"47": 2
}
},
"756": {
"s2c": {
"0": 2,
"1": 2,
"2": 2,
"3": 2,
"4": 1,
"5": 4,
"6": 2,
"7": -1,
"8": 7,
"9": 7,
"10": 7,
"11": 7,
"12": 7,
"13": 1,
"14": 1,
"15": 1,
"16": 1,
"17": 1,
"18": 1,
"19": 3,
"20": 3,
"21": 3,
"22": 3,
"23": 1,
"24": 3,
"25": 4,
"26": -1,
"27": 2,
"28": 2,
"29": 7,
"30": 2,
"31": 3,
"32": 3,
"33": -1,
"34": 7,
"35": 7,
"36": 4,
"37": 7,
"38": 2,
"39": 4,
"40": 3,
"41": 2,
"42": 2,
"43": 2,
"44": 2,
"45": 3,
"46": 3,
"47": 7,
"48": -1,
"49": 3,
"50": 2,
"51": 2,
"52": 2,
"53": 1,
"54": 1,
"55": 1,
"56": 1,
"57": 3,
"58": 2,
"59": 2,
"60": -1,
"61": 3,
"62": 2,
"63": 7,
"64": -1,
"65": 1,
"66": 3,
"67": 3,
"68": 3,
"69": 3,
"70": 3,
"71": 2,
"72": 3,
"73": 7,
"74": 7,
"75": 2,
"76": 1,
"77": 2,
"78": 2,
"79": 2,
"80": 2,
"81": 1,
"82": 1,
"83": 1,
"84": 2,
"85": 1,
"86": 1,
"87": 1,
"88": 1,
"89": 1,
"90": 1,
"91": 4,
"92": 4,
"93": 4,
"94": 1,
"95": 3,
"96": 2,
"97": 2,
"98": 1,
"99": 2,
"100": 2,
"101": 1,
"102": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 3,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 3,
"10": 3,
"11": 3,
"12": 3,
"13": 2,
"14": 7,
"15": -1,
"16": 1,
"17": 2,
"18": 2,
"19": 2,
"20": 2,
"21": 2,
"22": 2,
"23": 3,
"24": 3,
"25": 3,
"26": 1,
"27": 1,
"28": 1,
"29": -1,
"30": 3,
"31": 3,
"32": 3,
"33": -1,
"34": -1,
"35": 3,
"36": 3,
"37": 3,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 7,
"44": 2,
"45": 3,
"46": 2,
"47": 2
}
},
"757": {
"s2c": {
"0": 2,
"1": 2,
"2": 2,
"3": 2,
"4": 1,
"5": 4,
"6": 2,
"7": -1,
"8": 7,
"9": 7,
"10": 7,
"11": 7,
"12": 7,
"13": 1,
"14": 1,
"15": 1,
"16": 1,
"17": 1,
"18": 1,
"19": 3,
"20": 3,
"21": 3,
"22": 3,
"23": 1,
"24": 3,
"25": 4,
"26": -1,
"27": 2,
"28": 2,
"29": 7,
"30": 2,
"31": 3,
"32": 3,
"33": -1,
"34": 7,
"35": 7,
"36": 4,
"37": 7,
"38": 2,
"39": 4,
"40": 3,
"41": 2,
"42": 2,
"43": 2,
"44": 2,
"45": 3,
"46": 3,
"47": 7,
"48": -1,
"49": 3,
"50": 2,
"51": 2,
"52": 2,
"53": 1,
"54": 1,
"55": 1,
"56": 1,
"57": 3,
"58": 2,
"59": 2,
"60": -1,
"61": 3,
"62": 2,
"63": 7,
"64": -1,
"65": 1,
"66": 3,
"67": 3,
"68": 3,
"69": 3,
"70": 3,
"71": 2,
"72": 3,
"73": 7,
"74": 7,
"75": 2,
"76": 1,
"77": 2,
"78": 2,
"79": 2,
"80": 2,
"81": 1,
"82": 1,
"83": 1,
"84": 2,
"85": 1,
"86": 1,
"87": 7,
"88": 1,
"89": 1,
"90": 1,
"91": 1,
"92": 4,
"93": 4,
"94": 4,
"95": 1,
"96": 3,
"97": 2,
"98": 2,
"99": 1,
"100": 2,
"101": 2,
"102": 1,
"103": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 3,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 3,
"10": 3,
"11": 3,
"12": 3,
"13": 2,
"14": 7,
"15": -1,
"16": 1,
"17": 2,
"18": 2,
"19": 2,
"20": 2,
"21": 2,
"22": 2,
"23": 3,
"24": 3,
"25": 3,
"26": 1,
"27": 1,
"28": 1,
"29": -1,
"30": 3,
"31": 3,
"32": 3,
"33": -1,
"34": -1,
"35": 3,
"36": 3,
"37": 3,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 7,
"44": 2,
"45": 3,
"46": 2,
"47": 2
}
},
"758": {
"s2c": {
"0": 2,
"1": 2,
"2": 2,
"3": 2,
"4": 1,
"5": 4,
"6": 2,
"7": -1,
"8": 7,
"9": 7,
"10": 7,
"11": 7,
"12": 7,
"13": 1,
"14": 1,
"15": 1,
"16": 1,
"17": 1,
"18": 1,
"19": 3,
"20": 3,
"21": 3,
"22": 3,
"23": 1,
"24": 3,
"25": 4,
"26": -1,
"27": 2,
"28": 2,
"29": 7,
"30": 2,
"31": 3,
"32": 3,
"33": -1,
"34": 7,
"35": 7,
"36": 4,
"37": 7,
"38": 2,
"39": 4,
"40": 3,
"41": 2,
"42": 2,
"43": 2,
"44": 2,
"45": 3,
"46": 3,
"47": 7,
"48": -1,
"49": 3,
"50": 2,
"51": 2,
"52": 2,
"53": 1,
"54": 1,
"55": 1,
"56": 1,
"57": 3,
"58": 2,
"59": 2,
"60": -1,
"61": 3,
"62": 2,
"63": 7,
"64": -1,
"65": 1,
"66": 3,
"67": 3,
"68": 3,
"69": 3,
"70": 3,
"71": 2,
"72": 3,
"73": 7,
"74": 7,
"75": 2,
"76": 1,
"77": 2,
"78": 2,
"79": 2,
"80": 2,
"81": 1,
"82": 1,
"83": 1,
"84": 2,
"85": 1,
"86": 1,
"87": 7,
"88": 1,
"89": 1,
"90": 1,
"91": 1,
"92": 4,
"93": 4,
"94": 4,
"95": 1,
"96": 3,
"97": 2,
"98": 2,
"99": 1,
"100": 2,
"101": 2,
"102": 1,
"103": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 3,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 3,
"10": 3,
"11": 3,
"12": 3,
"13": 2,
"14": 7,
"15": -1,
"16": 1,
"17": 2,
"18": 2,
"19": 2,
"20": 2,
"21": 2,
"22": 2,
"23": 3,
"24": 3,
"25": 3,
"26": 1,
"27": 1,
"28": 1,
"29": -1,
"30": 3,
"31": 3,
"32": 3,
"33": -1,
"34": -1,
"35": 3,
"36": 3,
"37": 3,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 7,
"44": 2,
"45": 3,
"46": 2,
"47": 2
}
},
"759": {
"s2c": {
"0": 2,
"1": 2,
"2": 1,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 1,
"13": 1,
"14": 1,
"15": 1,
"16": 3,
"17": 3,
"18": 3,
"19": 3,
"20": 1,
"21": 3,
"22": 4,
"23": -1,
"24": 2,
"25": 2,
"26": 7,
"27": 2,
"28": 3,
"29": 3,
"30": -1,
"31": 7,
"32": 7,
"33": 4,
"34": 7,
"35": 2,
"36": 4,
"37": 3,
"38": 2,
"39": 2,
"40": 2,
"41": 2,
"42": 3,
"43": 3,
"44": 7,
"45": -1,
"46": 3,
"47": 2,
"48": 1,
"49": 2,
"50": 2,
"51": 1,
"52": 1,
"53": 1,
"54": 1,
"55": 3,
"56": 2,
"57": 2,
"58": -1,
"59": 3,
"60": 2,
"61": 7,
"62": -1,
"63": 1,
"64": 1,
"65": 3,
"66": 3,
"67": 3,
"68": 3,
"69": 3,
"70": 2,
"71": 3,
"72": 7,
"73": 7,
"74": 2,
"75": 1,
"76": 1,
"77": 2,
"78": 2,
"79": 2,
"80": 2,
"81": 1,
"82": 1,
"83": 1,
"84": 2,
"85": 1,
"86": 1,
"87": 7,
"88": 1,
"89": 1,
"90": 1,
"91": 1,
"92": 4,
"93": 4,
"94": 4,
"95": 1,
"96": 1,
"97": 3,
"98": 2,
"99": 2,
"100": 1,
"101": 2,
"102": 2,
"103": 1,
"104": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 3,
"7": 1,
"8": 1,
"9": 1,
"10": 1,
"11": 3,
"12": 3,
"13": 3,
"14": 3,
"15": 2,
"16": 7,
"17": -1,
"18": 1,
"19": 2,
"20": 2,
"21": 2,
"22": 2,
"23": 2,
"24": 2,
"25": 3,
"26": 3,
"27": 3,
"28": 1,
"29": 1,
"30": 1,
"31": -1,
"32": 3,
"33": 3,
"34": 3,
"35": -1,
"36": -1,
"37": 3,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 3,
"44": 3,
"45": 7,
"46": 2,
"47": 3,
"48": 2,
"49": 2
}
},
"760": {
"s2c": {
"0": 2,
"1": 2,
"2": 1,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 1,
"13": 1,
"14": 1,
"15": 1,
"16": 3,
"17": 3,
"18": 3,
"19": 3,
"20": 1,
"21": 1,
"22": 3,
"23": 4,
"24": 1,
"25": -1,
"26": 2,
"27": 2,
"28": 7,
"29": 2,
"30": 3,
"31": 3,
"32": -1,
"33": 7,
"34": 7,
"35": 4,
"36": 7,
"37": 2,
"38": 4,
"39": 3,
"40": 2,
"41": 2,
"42": 2,
"43": 2,
"44": 3,
"45": 3,
"46": 7,
"47": -1,
"48": 3,
"49": 2,
"50": 1,
"51": 1,
"52": 2,
"53": 2,
"54": 1,
"55": 1,
"56": 1,
"57": 1,
"58": 3,
"59": 2,
"60": 2,
"61": -1,
"62": 3,
"63": 2,
"64": 7,
"65": -1,
"66": 1,
"67": 1,
"68": 3,
"69": 3,
"70": 3,
"71": 3,
"72": 3,
"73": 2,
"74": 3,
"75": 7,
"76": 7,
"77": 2,
"78": 1,
"79": 1,
"80": 2,
"81": 2,
"82": 2,
"83": 2,
"84": 1,
"85": 1,
"86": 1,
"87": 2,
"88": 1,
"89": 1,
"90": 7,
"91": 1,
"92": 1,
"93": 1,
"94": 1,
"95": 4,
"96": 4,
"97": 4,
"98": 1,
"99": 1,
"100": 3,
"101": 2,
"102": 2,
"103": 1,
"104": 2,
"105": 2,
"106": 1,
"107": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 3,
"8": 1,
"9": 1,
"10": 1,
"11": 1,
"12": 3,
"13": 3,
"14": 3,
"15": 3,
"16": 2,
"17": 7,
"18": -1,
"19": 1,
"20": 2,
"21": 2,
"22": 2,
"23": 2,
"24": 2,
"25": 2,
"26": 3,
"27": 3,
"28": 3,
"29": 1,
"30": 1,
"31": 1,
"32": -1,
"33": 3,
"34": 3,
"35": 3,
"36": -1,
"37": -1,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 3,
"44": 3,
"45": 3,
"46": 7,
"47": 2,
"48": 3,
"49": 2,
"50": 2
}
},
"761": {
"s2c": {
"0": 2,
"1": 2,
"2": 1,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 1,
"13": 1,
"14": 1,
"15": 3,
"16": 3,
"17": 3,
"18": 3,
"19": 1,
"20": 1,
"21": 3,
"22": 1,
"23": -1,
"24": 1,
"25": 2,
"26": 2,
"27": 7,
"28": 2,
"29": 3,
"30": 3,
"31": -1,
"32": 7,
"33": 7,
"34": 4,
"35": 7,
"36": 2,
"37": 4,
"38": 3,
"39": 2,
"40": 2,
"41": 2,
"42": 2,
"43": 3,
"44": 3,
"45": 7,
"46": -1,
"47": 3,
"48": 2,
"49": 1,
"50": 2,
"51": 2,
"52": 1,
"53": 1,
"54": 1,
"55": 1,
"56": 1,
"57": 3,
"58": 2,
"59": 2,
"60": -1,
"61": 3,
"62": 2,
"63": 7,
"64": -1,
"65": 1,
"66": 1,
"67": 3,
"68": 3,
"69": 3,
"70": 3,
"71": 3,
"72": 2,
"73": 3,
"74": 7,
"75": 7,
"76": 2,
"77": 1,
"78": 2,
"79": 2,
"80": 2,
"81": 2,
"82": 1,
"83": 1,
"84": 1,
"85": 2,
"86": 1,
"87": 1,
"88": 7,
"89": 1,
"90": 1,
"91": 1,
"92": 1,
"93": 4,
"94": 4,
"95": 4,
"96": 1,
"97": 1,
"98": 3,
"99": 2,
"100": 2,
"101": 1,
"102": 2,
"103": 2,
"104": 2,
"105": 1,
"106": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 3,
"7": 1,
"8": 1,
"9": 1,
"10": 1,
"11": 3,
"12": 3,
"13": 3,
"14": 3,
"15": 2,
"16": 7,
"17": -1,
"18": 1,
"19": 2,
"20": 2,
"21": 2,
"22": 2,
"23": 2,
"24": 2,
"25": 3,
"26": 3,
"27": 3,
"28": 1,
"29": 1,
"30": 1,
"31": -1,
"32": 1,
"33": 3,
"34": 3,
"35": 3,
"36": -1,
"37": -1,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 3,
"44": 3,
"45": 3,
"46": 7,
"47": 2,
"48": 3,
"49": 2,
"50": 2
}
},
"762": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 1,
"4": 2,
"5": -1,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 7,
"11": 1,
"12": 1,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 3,
"24": 2,
"25": 1,
"26": -1,
"27": 1,
"28": 2,
"29": 2,
"30": 7,
"31": 2,
"32": 3,
"33": 2,
"34": 3,
"35": -1,
"36": 7,
"37": 7,
"38": 4,
"39": 7,
"40": 2,
"41": 4,
"42": 3,
"43": 2,
"44": 2,
"45": 2,
"46": 2,
"47": 3,
"48": 3,
"49": 7,
"50": -1,
"51": 3,
"52": 2,
"53": 1,
"54": 2,
"55": 2,
"56": 1,
"57": 1,
"58": 1,
"59": 1,
"60": 1,
"61": 3,
"62": 2,
"63": 2,
"64": -1,
"65": 3,
"66": 2,
"67": 7,
"68": -1,
"69": 1,
"70": 1,
"71": 3,
"72": 3,
"73": 3,
"74": 3,
"75": 3,
"76": 2,
"77": 3,
"78": 7,
"79": 7,
"80": 2,
"81": 1,
"82": 2,
"83": 2,
"84": 2,
"85": 2,
"86": 1,
"87": 1,
"88": 1,
"89": 2,
"90": 1,
"91": 1,
"92": 7,
"93": 1,
"94": 1,
"95": 1,
"96": 1,
"97": 4,
"98": 4,
"99": 4,
"100": 1,
"101": 1,
"102": 3,
"103": 2,
"104": 2,
"105": 1,
"106": 2,
"107": 2,
"108": 2,
"109": 1,
"110": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 3,
"8": 1,
"9": 1,
"10": 1,
"11": 1,
"12": 3,
"13": 3,
"14": 3,
"15": 3,
"16": 2,
"17": 7,
"18": -1,
"19": 1,
"20": 2,
"21": 2,
"22": 2,
"23": 2,
"24": 2,
"25": 2,
"26": 3,
"27": 3,
"28": 3,
"29": 1,
"30": 1,
"31": 1,
"32": -1,
"33": 3,
"34": 3,
"35": 3,
"36": -1,
"37": -1,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 3,
"44": 3,
"45": 3,
"46": 7,
"47": 2,
"48": 3,
"49": 2,
"50": 2
}
},
"763": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 1,
"4": 2,
"5": -1,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 7,
"11": 1,
"12": 1,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 3,
"24": 2,
"25": 1,
"26": -1,
"27": 1,
"28": 2,
"29": 2,
"30": 7,
"31": 2,
"32": 3,
"33": 2,
"34": 3,
"35": -1,
"36": 7,
"37": 7,
"38": 4,
"39": 7,
"40": 2,
"41": 4,
"42": 3,
"43": 2,
"44": 2,
"45": 2,
"46": 2,
"47": 3,
"48": 3,
"49": 7,
"50": -1,
"51": 3,
"52": 2,
"53": 1,
"54": 2,
"55": 2,
"56": 1,
"57": 1,
"58": 1,
"59": 1,
"60": 1,
"61": 3,
"62": 2,
"63": 2,
"64": -1,
"65": 3,
"66": 2,
"67": 7,
"68": -1,
"69": 1,
"70": 1,
"71": 3,
"72": 3,
"73": 3,
"74": 3,
"75": 3,
"76": 2,
"77": 3,
"78": 7,
"79": 7,
"80": 2,
"81": 1,
"82": 2,
"83": 2,
"84": 2,
"85": 2,
"86": 1,
"87": 1,
"88": 1,
"89": 2,
"90": 1,
"91": 1,
"92": 7,
"93": 1,
"94": 1,
"95": 1,
"96": 1,
"97": 4,
"98": 4,
"99": 4,
"100": 1,
"101": 1,
"102": 3,
"103": 2,
"104": 2,
"105": 1,
"106": 2,
"107": 2,
"108": 2,
"109": 1,
"110": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 3,
"8": 1,
"9": 1,
"10": 1,
"11": 1,
"12": 3,
"13": 3,
"14": 3,
"15": 3,
"16": 2,
"17": 7,
"18": -1,
"19": 1,
"20": 2,
"21": 2,
"22": 2,
"23": 2,
"24": 2,
"25": 2,
"26": 3,
"27": 3,
"28": 3,
"29": 1,
"30": 1,
"31": 1,
"32": -1,
"33": 3,
"34": 3,
"35": 3,
"36": -1,
"37": -1,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 3,
"44": 3,
"45": 3,
"46": 7,
"47": 2,
"48": 3,
"49": 2,
"50": 2
}
},
"764": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 7,
"13": 7,
"14": 7,
"15": 1,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 3,
"21": 3,
"22": 1,
"23": 1,
"24": 3,
"25": 2,
"26": 1,
"27": -1,
"28": 1,
"29": 2,
"30": 2,
"31": 7,
"32": 2,
"33": 3,
"34": 2,
"35": 3,
"36": -1,
"37": 7,
"38": 7,
"39": 4,
"40": 7,
"41": 2,
"42": 4,
"43": 3,
"44": 2,
"45": 2,
"46": 2,
"47": 2,
"48": 3,
"49": 3,
"50": 7,
"51": -1,
"52": -1,
"53": 3,
"54": 2,
"55": 1,
"56": 2,
"57": 2,
"58": 1,
"59": 1,
"60": 1,
"61": 1,
"62": 1,
"63": 3,
"64": 2,
"65": 2,
"66": -1,
"67": 3,
"68": 2,
"69": 7,
"70": -1,
"71": 1,
"72": 1,
"73": 3,
"74": 3,
"75": 3,
"76": 3,
"77": 3,
"78": 2,
"79": 3,
"80": 7,
"81": 7,
"82": 2,
"83": 1,
"84": 2,
"85": 2,
"86": 2,
"87": 2,
"88": 1,
"89": 1,
"90": 1,
"91": 2,
"92": 1,
"93": 1,
"94": 7,
"95": 1,
"96": 1,
"97": 1,
"98": 1,
"99": 4,
"100": 4,
"101": 0,
"102": 4,
"103": 1,
"104": 1,
"105": 3,
"106": 2,
"107": 2,
"108": 1,
"109": 2,
"110": 2,
"111": 1,
"112": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 7,
"8": 3,
"9": 1,
"10": 1,
"11": 0,
"12": 1,
"13": 1,
"14": 3,
"15": 3,
"16": 3,
"17": 3,
"18": 2,
"19": 7,
"20": -1,
"21": 1,
"22": 2,
"23": 2,
"24": 2,
"25": 2,
"26": 2,
"27": 2,
"28": 3,
"29": -1,
"30": 3,
"31": 3,
"32": 1,
"33": 1,
"34": 1,
"35": -1,
"36": 3,
"37": 3,
"38": 3,
"39": -1,
"40": -1,
"41": 3,
"42": 3,
"43": 3,
"44": 3,
"45": 3,
"46": 3,
"47": 3,
"48": 3,
"49": 7,
"50": 2,
"51": 3,
"52": 2,
"53": 2
}
},
"765": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 7,
"13": 7,
"14": 7,
"15": 1,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 3,
"21": 3,
"22": 1,
"23": 1,
"24": 3,
"25": 2,
"26": 1,
"27": -1,
"28": 1,
"29": 2,
"30": 2,
"31": 7,
"32": 2,
"33": 3,
"34": 2,
"35": 3,
"36": -1,
"37": 7,
"38": 7,
"39": 4,
"40": 7,
"41": 2,
"42": 4,
"43": 3,
"44": 2,
"45": 2,
"46": 2,
"47": 2,
"48": 3,
"49": 3,
"50": 7,
"51": -1,
"52": -1,
"53": 3,
"54": 2,
"55": 1,
"56": 2,
"57": 2,
"58": 1,
"59": 1,
"60": 1,
"61": 1,
"62": 1,
"63": 3,
"64": 2,
"65": 2,
"66": 1,
"67": -1,
"68": -1,
"69": 3,
"70": 2,
"71": 7,
"72": -1,
"73": 1,
"74": 1,
"75": 3,
"76": 3,
"77": 3,
"78": 3,
"79": 3,
"80": 2,
"81": 3,
"82": 7,
"83": 7,
"84": 2,
"85": 1,
"86": 2,
"87": 2,
"88": 2,
"89": 2,
"90": 1,
"91": 1,
"92": 1,
"93": 2,
"94": 1,
"95": 1,
"96": 7,
"97": 1,
"98": 1,
"99": 1,
"100": 1,
"101": 4,
"102": 4,
"103": 0,
"104": 4,
"105": 1,
"106": 1,
"107": 3,
"108": 2,
"109": 2,
"110": 3,
"111": 3,
"112": 1,
"113": 2,
"114": 2,
"115": 1,
"116": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 7,
"8": 3,
"9": 1,
"10": 1,
"11": 0,
"12": 1,
"13": 1,
"14": 3,
"15": 3,
"16": 3,
"17": 3,
"18": 3,
"19": 2,
"20": 7,
"21": -1,
"22": 1,
"23": 2,
"24": 2,
"25": 2,
"26": 2,
"27": 2,
"28": 2,
"29": 3,
"30": -1,
"31": 3,
"32": 3,
"33": 1,
"34": 1,
"35": 1,
"36": -1,
"37": 3,
"38": 3,
"39": 3,
"40": -1,
"41": -1,
"42": 3,
"43": 3,
"44": 3,
"45": 3,
"46": 3,
"47": 3,
"48": 3,
"49": 3,
"50": 7,
"51": 2,
"52": 3,
"53": 2,
"54": 2
}
},
"766": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 7,
"13": 7,
"14": 7,
"15": 1,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 3,
"21": 3,
"22": 1,
"23": 1,
"24": 1,
"25": 3,
"26": 2,
"27": 1,
"28": 1,
"29": -1,
"30": 1,
"31": 2,
"32": 2,
"33": 7,
"34": 2,
"35": 3,
"36": 2,
"37": 3,
"38": -1,
"39": 7,
"40": 7,
"41": 4,
"42": 7,
"43": 2,
"44": 4,
"45": 3,
"46": 2,
"47": 2,
"48": 2,
"49": 2,
"50": 3,
"51": 3,
"52": 7,
"53": -1,
"54": -1,
"55": 3,
"56": 2,
"57": 1,
"58": 2,
"59": 2,
"60": 1,
"61": 1,
"62": 1,
"63": 1,
"64": 1,
"65": 3,
"66": 2,
"67": 2,
"68": 1,
"69": -1,
"70": -1,
"71": 3,
"72": 2,
"73": 7,
"74": -1,
"75": 1,
"76": 1,
"77": 3,
"78": 3,
"79": 3,
"80": 3,
"81": 3,
"82": 2,
"83": 3,
"84": 7,
"85": 7,
"86": 2,
"87": 1,
"88": 2,
"89": 2,
"90": 2,
"91": 2,
"92": 1,
"93": 1,
"94": 1,
"95": 2,
"96": 1,
"97": 1,
"98": 7,
"99": 1,
"100": 1,
"101": 1,
"102": 1,
"103": 4,
"104": 4,
"105": 0,
"106": 4,
"107": 1,
"108": 1,
"109": 1,
"110": 3,
"111": 2,
"112": 2,
"113": 3,
"114": 3,
"115": 0,
"116": 1,
"117": 2,
"118": 2,
"119": 1,
"120": 1,
"121": 2
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 1,
"8": 7,
"9": 3,
"10": 1,
"11": 1,
"12": 0,
"13": 1,
"14": 1,
"15": 3,
"16": 3,
"17": 1,
"18": 3,
"19": 1,
"20": 3,
"21": 3,
"22": 2,
"23": 7,
"24": -1,
"25": 1,
"26": 2,
"27": 2,
"28": 2,
"29": 2,
"30": 2,
"31": 2,
"32": 3,
"33": -1,
"34": 3,
"35": 3,
"36": 1,
"37": 1,
"38": 1,
"39": -1,
"40": 3,
"41": 3,
"42": 3,
"43": -1,
"44": -1,
"45": 3,
"46": 3,
"47": 3,
"48": 3,
"49": 3,
"50": 3,
"51": 3,
"52": 3,
"53": 7,
"54": 2,
"55": 3,
"56": 2,
"57": 2
}
},
"767": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 7,
"13": 7,
"14": 7,
"15": 1,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 3,
"21": 3,
"22": 1,
"23": 1,
"24": 1,
"25": 3,
"26": 2,
"27": 1,
"28": 1,
"29": -1,
"30": 1,
"31": 2,
"32": 2,
"33": 7,
"34": 2,
"35": 3,
"36": 2,
"37": 3,
"38": -1,
"39": 7,
"40": 7,
"41": 4,
"42": 7,
"43": 2,
"44": 4,
"45": 3,
"46": 2,
"47": 2,
"48": 2,
"49": 2,
"50": 3,
"51": 3,
"52": 7,
"53": -1,
"54": -1,
"55": 3,
"56": 2,
"57": 1,
"58": 2,
"59": 2,
"60": 1,
"61": 1,
"62": 1,
"63": 1,
"64": 1,
"65": 3,
"66": 2,
"67": 2,
"68": 1,
"69": -1,
"70": -1,
"71": 3,
"72": 2,
"73": 7,
"74": -1,
"75": 1,
"76": 1,
"77": 3,
"78": 3,
"79": 3,
"80": 3,
"81": 3,
"82": 2,
"83": 3,
"84": 7,
"85": 7,
"86": 2,
"87": 1,
"88": 2,
"89": 2,
"90": 2,
"91": 2,
"92": 1,
"93": 1,
"94": 1,
"95": 2,
"96": 1,
"97": 1,
"98": 7,
"99": 1,
"100": 1,
"101": 1,
"102": 1,
"103": 4,
"104": 4,
"105": 0,
"106": 4,
"107": 1,
"108": 1,
"109": 1,
"110": 3,
"111": 2,
"112": 2,
"113": 3,
"114": 3,
"115": 0,
"116": 1,
"117": 2,
"118": 2,
"119": 1,
"120": 1,
"121": 2,
"122": -1,
"123": -1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 1,
"8": 7,
"9": 3,
"10": 1,
"11": 1,
"12": 0,
"13": 1,
"14": 1,
"15": 3,
"16": 3,
"17": 1,
"18": 3,
"19": 1,
"20": 3,
"21": 3,
"22": 2,
"23": 7,
"24": -1,
"25": 1,
"26": 2,
"27": 2,
"28": 2,
"29": 2,
"30": 2,
"31": 2,
"32": 3,
"33": -1,
"34": 3,
"35": 3,
"36": 1,
"37": 1,
"38": 1,
"39": -1,
"40": 3,
"41": 3,
"42": 3,
"43": -1,
"44": -1,
"45": 3,
"46": 3,
"47": 3,
"48": 3,
"49": 3,
"50": 3,
"51": 3,
"52": 3,
"53": 7,
"54": 2,
"55": 3,
"56": 2,
"57": 2
}
},
"768": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 7,
"13": 7,
"14": 7,
"15": 1,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 3,
"21": 3,
"22": 1,
"23": 1,
"24": 1,
"25": 3,
"26": 2,
"27": 1,
"28": 1,
"29": -1,
"30": 1,
"31": 2,
"32": 2,
"33": 2,
"34": 7,
"35": 2,
"36": 3,
"37": 2,
"38": 3,
"39": -1,
"40": 7,
"41": 7,
"42": 4,
"43": 7,
"44": 2,
"45": 4,
"46": 3,
"47": 2,
"48": 2,
"49": 2,
"50": 2,
"51": 2,
"52": 3,
"53": 3,
"54": 7,
"55": -1,
"56": -1,
"57": 3,
"58": 2,
"59": 1,
"60": 2,
"61": 2,
"62": 1,
"63": 1,
"64": 1,
"65": 1,
"66": 1,
"67": 2,
"68": 3,
"69": 3,
"70": 3,
"71": 2,
"72": 2,
"73": 1,
"74": -1,
"75": -1,
"76": 3,
"77": 2,
"78": 7,
"79": -1,
"80": 1,
"81": 1,
"82": 3,
"83": 3,
"84": 3,
"85": 3,
"86": 3,
"87": 2,
"88": 7,
"89": 7,
"90": 3,
"91": 2,
"92": 1,
"93": 2,
"94": 2,
"95": 2,
"96": 2,
"97": 1,
"98": 1,
"99": 3,
"100": 1,
"101": 2,
"102": 3,
"103": 1,
"104": 1,
"105": 7,
"106": 1,
"107": 1,
"108": 1,
"109": 1,
"110": 4,
"111": 4,
"112": 0,
"113": 4,
"114": 1,
"115": 1,
"116": 1,
"117": 3,
"118": 2,
"119": 2,
"120": 3,
"121": 3,
"122": 0,
"123": 1,
"124": 2,
"125": 2,
"126": 1,
"127": 1,
"128": 2,
"129": -1,
"130": -1
},
"c2s": {
"0": 3,
"1": 3,
"2": 3,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 7,
"10": 3,
"11": 2,
"12": 1,
"13": 1,
"14": 0,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 1,
"20": 3,
"21": 1,
"22": 3,
"23": 3,
"24": 2,
"25": 7,
"26": -1,
"27": 1,
"28": 2,
"29": 2,
"30": 2,
"31": 2,
"32": 2,
"33": 2,
"34": 3,
"35": -1,
"36": 3,
"37": 3,
"38": 1,
"39": 1,
"40": 1,
"41": -1,
"42": 3,
"43": 3,
"44": 3,
"45": -1,
"46": -1,
"47": 3,
"48": 3,
"49": 3,
"50": 3,
"51": 3,
"52": 3,
"53": 3,
"54": 3,
"55": 7,
"56": 2,
"57": 3,
"58": 2,
"59": 2
}
},
"769": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 2,
"4": -1,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 1,
"11": 1,
"12": 7,
"13": 7,
"14": 7,
"15": 1,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 3,
"21": 3,
"22": 1,
"23": 1,
"24": 1,
"25": 3,
"26": 2,
"27": 1,
"28": 1,
"29": -1,
"30": 1,
"31": 2,
"32": 2,
"33": 2,
"34": 7,
"35": 2,
"36": 3,
"37": 2,
"38": 3,
"39": -1,
"40": 7,
"41": 7,
"42": 4,
"43": 7,
"44": 2,
"45": 4,
"46": 3,
"47": 2,
"48": 2,
"49": 2,
"50": 2,
"51": 2,
"52": 3,
"53": 3,
"54": 7,
"55": -1,
"56": -1,
"57": 3,
"58": 2,
"59": 1,
"60": 2,
"61": 2,
"62": 1,
"63": 1,
"64": 1,
"65": 1,
"66": 1,
"67": 2,
"68": 3,
"69": 3,
"70": 3,
"71": 2,
"72": 2,
"73": 1,
"74": -1,
"75": -1,
"76": 3,
"77": 2,
"78": 7,
"79": -1,
"80": 1,
"81": 1,
"82": 3,
"83": 3,
"84": 3,
"85": 3,
"86": 3,
"87": 2,
"88": 7,
"89": 7,
"90": 3,
"91": 2,
"92": 1,
"93": 2,
"94": 2,
"95": 2,
"96": 2,
"97": 1,
"98": 1,
"99": 3,
"100": 1,
"101": 2,
"102": 3,
"103": 1,
"104": 1,
"105": 7,
"106": 1,
"107": 1,
"108": 1,
"109": 1,
"110": 4,
"111": 4,
"112": 0,
"113": 4,
"114": 1,
"115": 1,
"116": 1,
"117": 3,
"118": 2,
"119": 2,
"120": 3,
"121": 3,
"122": 0,
"123": 1,
"124": 2,
"125": 2,
"126": 1,
"127": 1,
"128": 2,
"129": -1,
"130": -1
},
"c2s": {
"0": 3,
"1": 3,
"2": 3,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 7,
"10": 3,
"11": 2,
"12": 1,
"13": 1,
"14": 0,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 1,
"20": 3,
"21": 1,
"22": 3,
"23": 3,
"24": 2,
"25": 7,
"26": -1,
"27": 1,
"28": 2,
"29": 2,
"30": 2,
"31": 2,
"32": 2,
"33": 2,
"34": 1,
"35": 1,
"36": -1,
"37": 3,
"38": 3,
"39": 1,
"40": 1,
"41": 1,
"42": 7,
"43": -1,
"44": 3,
"45": 3,
"46": 3,
"47": -1,
"48": -1,
"49": 3,
"50": 3,
"51": 3,
"52": 3,
"53": 3,
"54": 3,
"55": 3,
"56": 3,
"57": 7,
"58": 2,
"59": 3,
"60": 2,
"61": 2
}
},
"770": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": -1,
"4": 7,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 1,
"10": 1,
"11": 7,
"12": 7,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 1,
"24": 3,
"25": 2,
"26": 1,
"27": 1,
"28": -1,
"29": 1,
"30": 2,
"31": 2,
"32": 2,
"33": 7,
"34": 2,
"35": 3,
"36": 2,
"37": 3,
"38": -1,
"39": 7,
"40": 7,
"41": 4,
"42": 7,
"43": 2,
"44": 4,
"45": 3,
"46": 2,
"47": 2,
"48": 2,
"49": 2,
"50": 2,
"51": 3,
"52": 3,
"53": 7,
"54": -1,
"55": -1,
"56": 3,
"57": 2,
"58": 1,
"59": 2,
"60": 2,
"61": 1,
"62": 1,
"63": 1,
"64": 1,
"65": 1,
"66": 2,
"67": 3,
"68": 3,
"69": 3,
"70": 2,
"71": 2,
"72": 1,
"73": -1,
"74": -1,
"75": 3,
"76": 2,
"77": 7,
"78": -1,
"79": 1,
"80": 1,
"81": 3,
"82": 3,
"83": 3,
"84": 3,
"85": 3,
"86": 2,
"87": 7,
"88": 7,
"89": 3,
"90": 2,
"91": 1,
"92": 2,
"93": 2,
"94": 2,
"95": 2,
"96": 1,
"97": 1,
"98": 3,
"99": 1,
"100": 2,
"101": 3,
"102": 1,
"103": 1,
"104": 7,
"105": 1,
"106": 1,
"107": 1,
"108": 1,
"109": 4,
"110": 4,
"111": 0,
"112": 4,
"113": 1,
"114": 1,
"115": 1,
"116": 3,
"117": 2,
"118": 2,
"119": 7,
"120": 3,
"121": 3,
"122": 0,
"123": 1,
"124": 2,
"125": 2,
"126": 1,
"127": 1,
"128": 2,
"129": -1,
"130": -1
},
"c2s": {
"0": 3,
"1": 3,
"2": 3,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 7,
"10": 3,
"11": 2,
"12": 1,
"13": 1,
"14": 0,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 1,
"20": 3,
"21": 1,
"22": 3,
"23": 3,
"24": 2,
"25": 7,
"26": -1,
"27": 1,
"28": 2,
"29": 2,
"30": 2,
"31": 2,
"32": 2,
"33": 2,
"34": 1,
"35": 1,
"36": -1,
"37": 3,
"38": 3,
"39": 1,
"40": 1,
"41": 1,
"42": 7,
"43": -1,
"44": 3,
"45": 3,
"46": 3,
"47": -1,
"48": -1,
"49": 3,
"50": 3,
"51": 3,
"52": 3,
"53": 3,
"54": 3,
"55": 3,
"56": 3,
"57": 3,
"58": 7,
"59": 2,
"60": 3,
"61": 3,
"62": 2,
"63": 2
}
},
"771": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": -1,
"4": 7,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 1,
"10": 1,
"11": 7,
"12": 7,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 1,
"24": 3,
"25": 2,
"26": 1,
"27": 1,
"28": -1,
"29": 1,
"30": 2,
"31": 2,
"32": 2,
"33": 7,
"34": 2,
"35": 3,
"36": 2,
"37": 3,
"38": -1,
"39": 7,
"40": 7,
"41": 4,
"42": 7,
"43": 2,
"44": 4,
"45": 3,
"46": 2,
"47": 2,
"48": 2,
"49": 2,
"50": 2,
"51": 3,
"52": 3,
"53": 7,
"54": -1,
"55": -1,
"56": 3,
"57": 2,
"58": 1,
"59": 2,
"60": 2,
"61": 1,
"62": 1,
"63": 1,
"64": 1,
"65": 1,
"66": 2,
"67": 3,
"68": 3,
"69": 3,
"70": 2,
"71": 2,
"72": 1,
"73": -1,
"74": -1,
"75": 3,
"76": 2,
"77": 7,
"78": -1,
"79": 1,
"80": 1,
"81": 3,
"82": 3,
"83": 3,
"84": 3,
"85": 3,
"86": 2,
"87": 7,
"88": 7,
"89": 3,
"90": 2,
"91": 1,
"92": 2,
"93": 2,
"94": 2,
"95": 2,
"96": 1,
"97": 1,
"98": 3,
"99": 1,
"100": 2,
"101": 3,
"102": 1,
"103": 1,
"104": 7,
"105": 1,
"106": 1,
"107": 1,
"108": 1,
"109": 4,
"110": 4,
"111": 0,
"112": 4,
"113": 1,
"114": 1,
"115": 1,
"116": 3,
"117": 2,
"118": 2,
"119": 7,
"120": 3,
"121": 3,
"122": 0,
"123": 1,
"124": 2,
"125": 2,
"126": 1,
"127": 1,
"128": 2,
"129": -1,
"130": -1,
"131": 1,
"132": 1,
"133": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 3,
"3": 1,
"4": 2,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 1,
"10": 7,
"11": 3,
"12": 2,
"13": 1,
"14": 1,
"15": 0,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 1,
"21": 3,
"22": 1,
"23": 3,
"24": 3,
"25": 2,
"26": 7,
"27": -1,
"28": 1,
"29": 2,
"30": 2,
"31": 2,
"32": 2,
"33": 2,
"34": 2,
"35": 1,
"36": 1,
"37": -1,
"38": 3,
"39": 3,
"40": 1,
"41": 1,
"42": 1,
"43": 7,
"44": -1,
"45": 3,
"46": 3,
"47": 3,
"48": -1,
"49": -1,
"50": 3,
"51": 3,
"52": 3,
"53": 3,
"54": 3,
"55": 3,
"56": 3,
"57": 3,
"58": 3,
"59": 7,
"60": 2,
"61": 3,
"62": 3,
"63": 2,
"64": 2,
"65": 1
}
},
"772": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": -1,
"4": 7,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 1,
"10": 1,
"11": 7,
"12": 7,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 1,
"24": 3,
"25": 2,
"26": 1,
"27": 1,
"28": -1,
"29": 1,
"30": 2,
"31": 2,
"32": 2,
"33": 7,
"34": 2,
"35": 3,
"36": 2,
"37": 3,
"38": -1,
"39": 7,
"40": 7,
"41": 4,
"42": 7,
"43": 2,
"44": 4,
"45": 3,
"46": 2,
"47": 2,
"48": 2,
"49": 2,
"50": 2,
"51": 3,
"52": 3,
"53": 7,
"54": -1,
"55": -1,
"56": 3,
"57": 2,
"58": 1,
"59": 2,
"60": 2,
"61": 1,
"62": 1,
"63": 1,
"64": 1,
"65": 1,
"66": 2,
"67": 3,
"68": 3,
"69": 3,
"70": 2,
"71": 2,
"72": 1,
"73": -1,
"74": -1,
"75": 3,
"76": 2,
"77": 7,
"78": -1,
"79": 1,
"80": 1,
"81": 3,
"82": 3,
"83": 3,
"84": 3,
"85": 3,
"86": 2,
"87": 7,
"88": 7,
"89": 3,
"90": 2,
"91": 1,
"92": 2,
"93": 2,
"94": 2,
"95": 2,
"96": 1,
"97": 1,
"98": 3,
"99": 1,
"100": 2,
"101": 3,
"102": 1,
"103": 1,
"104": 7,
"105": 1,
"106": 1,
"107": 1,
"108": 1,
"109": 4,
"110": 4,
"111": 0,
"112": 4,
"113": 1,
"114": 1,
"115": 1,
"116": 3,
"117": 2,
"118": 2,
"119": 7,
"120": 3,
"121": 3,
"122": 0,
"123": 1,
"124": 2,
"125": 2,
"126": 1,
"127": 1,
"128": 2,
"129": -1,
"130": -1,
"131": 1,
"132": 1,
"133": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 3,
"3": 1,
"4": 2,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 1,
"10": 7,
"11": 3,
"12": 2,
"13": 1,
"14": 1,
"15": 0,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 1,
"21": 3,
"22": 1,
"23": 3,
"24": 3,
"25": 2,
"26": 7,
"27": -1,
"28": 1,
"29": 2,
"30": 2,
"31": 2,
"32": 2,
"33": 2,
"34": 2,
"35": 1,
"36": 1,
"37": -1,
"38": 3,
"39": 3,
"40": 1,
"41": 1,
"42": 1,
"43": 7,
"44": -1,
"45": 3,
"46": 3,
"47": 3,
"48": -1,
"49": -1,
"50": 3,
"51": 3,
"52": 3,
"53": 3,
"54": 3,
"55": 3,
"56": 3,
"57": 3,
"58": 3,
"59": 7,
"60": 2,
"61": 3,
"62": 3,
"63": 2,
"64": 2,
"65": 1
}
},
"773": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": -1,
"4": 7,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 1,
"10": 1,
"11": 7,
"12": 7,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 1,
"24": 3,
"25": 2,
"26": 7,
"27": 7,
"28": 2,
"29": 2,
"30": 1,
"31": 1,
"32": -1,
"33": 1,
"34": 2,
"35": 2,
"36": 2,
"37": 7,
"38": 2,
"39": 7,
"40": 3,
"41": 2,
"42": 3,
"43": -1,
"44": 7,
"45": 7,
"46": 4,
"47": 7,
"48": 2,
"49": 4,
"50": 3,
"51": 2,
"52": 2,
"53": 2,
"54": 2,
"55": 2,
"56": 3,
"57": 3,
"58": 7,
"59": -1,
"60": -1,
"61": 3,
"62": 2,
"63": 1,
"64": 2,
"65": 2,
"66": 1,
"67": 1,
"68": 1,
"69": 1,
"70": 1,
"71": 2,
"72": 3,
"73": 3,
"74": 3,
"75": 2,
"76": 2,
"77": 1,
"78": -1,
"79": -1,
"80": 3,
"81": 2,
"82": 7,
"83": -1,
"84": 1,
"85": 1,
"86": 3,
"87": 3,
"88": 3,
"89": 3,
"90": 3,
"91": 2,
"92": 7,
"93": 7,
"94": 3,
"95": 2,
"96": 1,
"97": 2,
"98": 2,
"99": 2,
"100": 2,
"101": 1,
"102": 1,
"103": 3,
"104": 1,
"105": 2,
"106": 3,
"107": 1,
"108": 1,
"109": 7,
"110": 1,
"111": 1,
"112": 1,
"113": 1,
"114": 4,
"115": 4,
"116": 0,
"117": 4,
"118": 1,
"119": 1,
"120": 1,
"121": 3,
"122": 2,
"123": 2,
"124": 7,
"125": 3,
"126": 3,
"127": 0,
"128": 1,
"129": 2,
"130": 2,
"131": 1,
"132": 1,
"133": 2,
"134": -1,
"135": -1,
"136": 1,
"137": 1,
"138": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 3,
"3": 1,
"4": 2,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 1,
"10": 7,
"11": 3,
"12": 2,
"13": 1,
"14": 1,
"15": 0,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 1,
"21": 3,
"22": 1,
"23": 3,
"24": 3,
"25": 2,
"26": 7,
"27": -1,
"28": 1,
"29": 2,
"30": 2,
"31": 2,
"32": 2,
"33": 2,
"34": 2,
"35": 1,
"36": 1,
"37": -1,
"38": 3,
"39": 3,
"40": 1,
"41": 1,
"42": 1,
"43": 7,
"44": -1,
"45": 3,
"46": 3,
"47": 3,
"48": -1,
"49": -1,
"50": 3,
"51": 3,
"52": 3,
"53": 3,
"54": 3,
"55": 3,
"56": 3,
"57": 3,
"58": 3,
"59": 7,
"60": 2,
"61": 3,
"62": 3,
"63": 2,
"64": 2,
"65": 1
}
},
"774": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": -1,
"4": 7,
"5": 7,
"6": 7,
"7": 7,
"8": 7,
"9": 1,
"10": 1,
"11": 7,
"12": 7,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 1,
"24": 3,
"25": 2,
"26": 7,
"27": 7,
"28": 2,
"29": 2,
"30": 1,
"31": 1,
"32": -1,
"33": 1,
"34": 2,
"35": 2,
"36": 2,
"37": 7,
"38": 2,
"39": 7,
"40": 3,
"41": 2,
"42": 3,
"43": -1,
"44": 7,
"45": 7,
"46": 4,
"47": 7,
"48": 2,
"49": 4,
"50": 3,
"51": 2,
"52": 2,
"53": 2,
"54": 2,
"55": 2,
"56": 3,
"57": 3,
"58": 7,
"59": -1,
"60": -1,
"61": 3,
"62": 2,
"63": 1,
"64": 2,
"65": 2,
"66": 1,
"67": 1,
"68": 1,
"69": 1,
"70": 1,
"71": 2,
"72": 3,
"73": 3,
"74": 3,
"75": 2,
"76": 2,
"77": 1,
"78": -1,
"79": -1,
"80": 3,
"81": 2,
"82": 7,
"83": -1,
"84": 1,
"85": 1,
"86": 3,
"87": 3,
"88": 3,
"89": 3,
"90": 3,
"91": 2,
"92": 7,
"93": 7,
"94": 3,
"95": 2,
"96": 1,
"97": 2,
"98": 2,
"99": 2,
"100": 2,
"101": 1,
"102": 1,
"103": 3,
"104": 1,
"105": 2,
"106": 3,
"107": 1,
"108": 1,
"109": 7,
"110": 1,
"111": 1,
"112": 1,
"113": 1,
"114": 4,
"115": 4,
"116": 0,
"117": 4,
"118": 1,
"119": 1,
"120": 1,
"121": 3,
"122": 2,
"123": 2,
"124": 7,
"125": 3,
"126": 3,
"127": 0,
"128": 1,
"129": 2,
"130": 2,
"131": 1,
"132": 1,
"133": 2,
"134": -1,
"135": -1,
"136": 1,
"137": 1,
"138": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 3,
"3": 1,
"4": 2,
"5": 1,
"6": 1,
"7": 1,
"8": 1,
"9": 1,
"10": 7,
"11": 3,
"12": 2,
"13": 1,
"14": 1,
"15": 0,
"16": 1,
"17": 1,
"18": 3,
"19": 3,
"20": 1,
"21": 3,
"22": 1,
"23": 3,
"24": 3,
"25": 2,
"26": 7,
"27": -1,
"28": 1,
"29": 2,
"30": 2,
"31": 2,
"32": 2,
"33": 2,
"34": 2,
"35": 1,
"36": 1,
"37": -1,
"38": 3,
"39": 3,
"40": 1,
"41": 1,
"42": 1,
"43": 7,
"44": -1,
"45": 3,
"46": 3,
"47": 3,
"48": -1,
"49": -1,
"50": 3,
"51": 3,
"52": 3,
"53": 3,
"54": 3,
"55": 3,
"56": 3,
"57": 3,
"58": 3,
"59": 7,
"60": 2,
"61": 3,
"62": 3,
"63": 2,
"64": 2,
"65": 1
}
},
"1073741953": {
"s2c": {
"0": -2147483648,
"1": 2,
"2": 2,
"3": 1,
"4": 2,
"5": -1,
"6": 7,
"7": 7,
"8": 7,
"9": 7,
"10": 7,
"11": 1,
"12": 1,
"13": 7,
"14": 1,
"15": 1,
"16": 1,
"17": 3,
"18": 3,
"19": 3,
"20": 3,
"21": 1,
"22": 1,
"23": 3,
"24": 2,
"25": 1,
"26": -1,
"27": 1,
"28": 2,
"29": 2,
"30": 7,
"31": 2,
"32": 3,
"33": 2,
"34": 3,
"35": -1,
"36": 7,
"37": 7,
"38": 4,
"39": 7,
"40": 2,
"41": 4,
"42": 3,
"43": 2,
"44": 2,
"45": 2,
"46": 2,
"47": 3,
"48": 3,
"49": 7,
"50": -1,
"51": 3,
"52": 2,
"53": 1,
"54": 2,
"55": 2,
"56": 1,
"57": 1,
"58": 1,
"59": 1,
"60": 1,
"61": 3,
"62": 2,
"63": 2,
"64": -1,
"65": 3,
"66": 2,
"67": 7,
"68": -1,
"69": 1,
"70": 1,
"71": 3,
"72": 3,
"73": 3,
"74": 3,
"75": 3,
"76": 2,
"77": 3,
"78": 7,
"79": 7,
"80": 2,
"81": 1,
"82": 2,
"83": 2,
"84": 2,
"85": 2,
"86": 1,
"87": 1,
"88": 1,
"89": 2,
"90": 1,
"91": 1,
"92": 7,
"93": 1,
"94": 1,
"95": 1,
"96": 1,
"97": 4,
"98": 4,
"99": 4,
"100": 1,
"101": 1,
"102": 3,
"103": 2,
"104": 2,
"105": 1,
"106": 2,
"107": 2,
"108": 2,
"109": 1,
"110": 1,
"111": 1,
"112": 1,
"113": 1,
"114": 1,
"115": 1,
"116": 1
},
"c2s": {
"0": 3,
"1": 3,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1,
"7": 3,
"8": 1,
"9": 1,
"10": 1,
"11": 1,
"12": 3,
"13": 3,
"14": 3,
"15": 3,
"16": 2,
"17": 7,
"18": -1,
"19": 1,
"20": 2,
"21": 2,
"22": 2,
"23": 2,
"24": 2,
"25": 2,
"26": 3,
"27": 3,
"28": 3,
"29": 1,
"30": 1,
"31": 1,
"32": -1,
"33": 3,
"34": 3,
"35": 3,
"36": -1,
"37": -1,
"38": 3,
"39": 3,
"40": 3,
"41": 3,
"42": 3,
"43": 3,
"44": 3,
"45": 3,
"46": 7,
"47": 2,
"48": 3,
"49": 2,
"50": 2,
"51": 1,
"52": 2
}
}
}
}
================================================
FILE: fabric/build.gradle
================================================
evaluationDependsOn(":")
apply plugin: 'fabric-loom'
apply plugin: 'com.gradleup.shadow'
apply plugin: 'com.modrinth.minotaur'
apply plugin: 'io.github.themrmilchmann.curseforge-publish'
base {
archivesName = project.archives_base_name + "-fabric"
}
group = project.maven_group + ".fabric"
configurations {
shadowInclude
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
shadowInclude implementation(project(":common"))
// Fabric API. This is technically optional, but you probably want it anyway.
// modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
}
processResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
tasks.withType(JavaCompile).configureEach {
// Minecraft 1.18 (1.18-pre2) upwards uses Java 17.
it.options.release = 17
}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
loom {
accessWidenerPath = file("src/main/resources/raknetify-fabric.accesswidener")
runs {
server {
vmArgs "-Draknetify.debug=true", "-Dio.netty.leakDetection.level=advanced"
ideConfigGenerated(true)
}
client {
vmArgs "-Draknetify.debug=true", "-Dio.netty.leakDetection.level=advanced"
ideConfigGenerated(true)
}
}
mixin {
useLegacyMixinAp = true
}
}
jar {
exclude "META-INF/LICENSE.txt"
exclude "META-INF/NOTICE.txt"
from "../LICENSE"
}
shadowJar {
dependencies {
exclude(dependency('it.unimi.dsi:fastutil'))
}
exclude "META-INF/LICENSE.txt"
exclude "META-INF/NOTICE.txt"
minimize()
archiveClassifier = "all-dev"
configurations = [ project.configurations.shadowInclude ]
from "../LICENSE"
}
//noinspection UnnecessaryQualifiedReference
task("remapShadowJar", type: net.fabricmc.loom.task.RemapJarTask, dependsOn: shadowJar) {
input = shadowJar.archiveFile
archiveFileName = shadowJar.archiveFileName.get().replaceAll("-dev\\.jar\$", ".jar")
addNestedDependencies = true
}
assemble.dependsOn(remapShadowJar)
afterEvaluate {
migrateMappings.configure {
outputDir = project.file("build/remappedSrc")
doLast {
copy {
from project.file("build/remappedSrc")
into project.file("src/main/java")
}
}
}
}
tasks.withType(AbstractArchiveTask) {
preserveFileTimestamps = false
reproducibleFileOrder = true
}
modrinth {
versionNumber = project.version
versionName = project.version + " devbuild"
uploadFile = remapShadowJar
loaders = ["fabric", "quilt"]
}
curseforge {
apiToken = System.getenv("CURSEFORGE_TOKEN")
publications {
register("main") {
projectId = "631457"
gameVersion("minecraft-1-18", "1-18")
gameVersion("minecraft-1-18", "1-18-1")
gameVersion("minecraft-1-18", "1-18-2")
gameVersion("minecraft-1-19", "1-19")
gameVersion("minecraft-1-19", "1-19-1")
gameVersion("minecraft-1-19", "1-19-2")
gameVersion("minecraft-1-19", "1-19-3")
gameVersion("minecraft-1-19", "1-19-4")
gameVersion("minecraft-1-20", "1-20")
gameVersion("minecraft-1-20", "1-20-1")
gameVersion("minecraft-1-20", "1-20-2")
gameVersion("minecraft-1-20", "1-20-3")
gameVersion("minecraft-1-20", "1-20-4")
gameVersion("minecraft-1-20", "1-20-5")
gameVersion("minecraft-1-20", "1-20-6")
gameVersion("minecraft-1-21", "1-21")
gameVersion("minecraft-1-21", "1-21-1")
gameVersion("minecraft-1-21", "1-21-2")
gameVersion("minecraft-1-21", "1-21-3")
gameVersion("minecraft-1-21", "1-21-4")
gameVersion("minecraft-1-21", "1-21-5")
gameVersion("minecraft-1-21", "1-21-6")
gameVersion("minecraft-1-21", "1-21-7")
gameVersion("minecraft-1-21", "1-21-8")
gameVersion("minecraft-1-21", "1-21-9")
gameVersion("minecraft-1-21", "1-21-10")
gameVersion("minecraft-1-21", "1-21-11")
gameVersion("modloader", "fabric")
gameVersion("java", "java-22")
gameVersion("java", "java-21")
gameVersion("java", "java-20")
gameVersion("java", "java-19")
gameVersion("java", "java-18")
gameVersion("java", "java-17")
gameVersion("environment", "server")
gameVersion("environment", "client")
artifacts.register("main") {
from(remapShadowJar)
displayName = project.version + " devbuild"
releaseType = io.github.themrmilchmann.gradle.publish.curseforge.ReleaseType.ALPHA
changelog {
format = io.github.themrmilchmann.gradle.publish.curseforge.ChangelogFormat.MARKDOWN
from(com.ishland.buildscript.ParseGItHubActionChangelog.getChangelog())
}
}
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/RaknetifyFabric.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ishland.raknetify.common.data.ProtocolMultiChannelMappings;
import com.ishland.raknetify.fabric.common.client.DebugHudUtil1_21_9;
import com.ishland.raknetify.fabric.common.connection.RakNetMultiChannel;
import com.ishland.raknetify.common.util.NetworkInterfaceListener;
import com.ishland.raknetify.fabric.common.util.FieldSignatureParser;
import com.ishland.raknetify.fabric.common.util.MultiVersionUtil;
import com.ishland.raknetify.fabric.mixin.RaknetifyFabricMixinPlugin;
import com.ishland.raknetify.fabric.mixin.access.INetworkState1_20_4;
import com.ishland.raknetify.fabric.mixin.access.INetworkStateInternalPacketHandler;
import com.ishland.raknetify.fabric.mixin.access.IPacketCodecDispatcher;
import io.netty.buffer.ByteBuf;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.internal.SystemPropertyUtil;
import it.unimi.dsi.fastutil.ints.AbstractInt2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
import net.minecraft.SharedConstants;
import net.minecraft.network.NetworkPhase;
import net.minecraft.network.NetworkSide;
import net.minecraft.network.RegistryByteBuf;
import net.minecraft.network.listener.ClientPlayPacketListener;
import net.minecraft.network.listener.ServerPlayPacketListener;
import net.minecraft.network.packet.CommonPackets;
import net.minecraft.network.packet.CookiePackets;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.PacketType;
import net.minecraft.network.packet.PingPackets;
import net.minecraft.network.packet.PlayPackets;
import net.minecraft.network.state.NetworkState;
import net.minecraft.network.state.PlayStateFactories;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.FieldNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.service.MixinService;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RaknetifyFabric implements ModInitializer, PreLaunchEntrypoint {
private static final boolean SAVE_CHANNEL_MAPPINGS = Boolean.getBoolean("raknetify.saveChannelMappings");
private static final boolean EXIT_AFTER_SAVE_CHANNEL_MAPPINGS = Boolean.getBoolean("raknetify.saveChannelMappings.exit");
@Override
public void onPreLaunch() {
}
@Override
public void onInitialize() {
MultiVersionUtil.init();
if (FabricLoader.getInstance().isDevelopmentEnvironment())
auditMixins();
handleMappings();
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT && RaknetifyFabricMixinPlugin.AFTER_1_21_8) {
DebugHudUtil1_21_9.init();
}
// If new property name is present, use it
String levelStr = SystemPropertyUtil.get("io.netty.leakDetection.level", ResourceLeakDetector.Level.SIMPLE.name());
ResourceLeakDetector.Level level = ResourceLeakDetector.Level.SIMPLE;
try {
level = ResourceLeakDetector.Level.valueOf(levelStr.trim().toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException ignored) {
}
System.out.println("Raknetify: Using leak detector level %s".formatted(level));
ResourceLeakDetector.setLevel(level);
}
private static void handleMappings() {
RakNetMultiChannel.init();
// RakNetMultiChannel.iterateKnownPackets();
NetworkInterfaceListener.init();
Int2IntArrayMap s2c = new Int2IntArrayMap();
Int2IntArrayMap c2s = new Int2IntArrayMap();
if (!RaknetifyFabricMixinPlugin.AFTER_1_20_4) {
for (Map.Entry entry : ((INetworkState1_20_4) (Object) NetworkPhase.PLAY).getPacketHandlers().entrySet()) {
final Object value = entry.getValue();
final Object2IntMap>> packetIds = getPacketIdsFromPacketHandler(value);
for (Object2IntMap.Entry>> type : packetIds.object2IntEntrySet()) {
if (entry.getKey() == NetworkSide.CLIENTBOUND)
s2c.put(type.getIntValue(), RakNetMultiChannel.getPacketChannelOverride(type.getKey(), false));
else if (entry.getKey() == NetworkSide.SERVERBOUND)
c2s.put(type.getIntValue(), RakNetMultiChannel.getPacketChannelOverride(type.getKey(), false));
}
}
} else {
final List>> c2sPacketTypes;
final List>> s2cPacketTypes;
if (!RaknetifyFabricMixinPlugin.AFTER_1_21_4) {
try {
c2sPacketTypes = ((IPacketCodecDispatcher, PacketType>>)
((NetworkState) MultiVersionUtil.NetworkState$Factory$bind1_20_5.invoke(MultiVersionUtil.PlayStateFactories$C2S1_20_5.get(), RegistryByteBuf.makeFactory(null))).codec()).getPacketTypes()
.stream().map(byteBufPacketPacketTypePacketType -> byteBufPacketPacketTypePacketType.id()).toList();
} catch (Throwable e) {
throw new RuntimeException(e);
}
try {
s2cPacketTypes = ((IPacketCodecDispatcher, PacketType>>)
((NetworkState) MultiVersionUtil.NetworkState$Factory$bind1_20_5.invoke(MultiVersionUtil.PlayStateFactories$S2C1_20_5.get(), RegistryByteBuf.makeFactory(null))).codec()).getPacketTypes()
.stream().map(byteBufPacketPacketTypePacketType -> byteBufPacketPacketTypePacketType.id()).toList();
} catch (Throwable e) {
throw new RuntimeException(e);
}
} else {
c2sPacketTypes = ((IPacketCodecDispatcher, PacketType>>)
PlayStateFactories.C2S.bind(RegistryByteBuf.makeFactory(null), null).codec()).getPacketTypes()
.stream().map(byteBufPacketPacketTypePacketType -> byteBufPacketPacketTypePacketType.id()).toList();
s2cPacketTypes = ((IPacketCodecDispatcher, PacketType>>)
PlayStateFactories.S2C.bind(RegistryByteBuf.makeFactory(null)).codec()).getPacketTypes()
.stream().map(byteBufPacketPacketTypePacketType -> byteBufPacketPacketTypePacketType.id()).toList();
}
record FieldNodeClazzPair(FieldNode fieldNode, Class> clazz) {
}
Map, Class>> vanillaPacketTypes = new Object2ObjectOpenHashMap<>();
for (FieldNodeClazzPair fieldNodeClazzPair : Stream.of(PlayPackets.class, CommonPackets.class, CookiePackets.class, PingPackets.class)
.flatMap(clazz -> {
try {
return MixinService.getService().getBytecodeProvider().getClassNode(Type.getInternalName(clazz)).fields.stream()
.map(fieldNode -> new FieldNodeClazzPair(fieldNode, clazz));
} catch (ClassNotFoundException | IOException e) {
throw new RuntimeException(e);
}
})
.toList()) {
final FieldNode field = fieldNodeClazzPair.fieldNode();
final List parameterGenerics = FieldSignatureParser.parse(field.signature);
for (Type type : parameterGenerics) {
try {
final Class> clazz = Class.forName(type.getClassName());
if (Packet.class.isAssignableFrom(clazz)) {
final PacketType> actualType;
try {
actualType = (PacketType>) fieldNodeClazzPair.clazz().getField(field.name).get(null);
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
vanillaPacketTypes.put(actualType, clazz);
}
} catch (ClassNotFoundException ignored) {
}
}
}
for (int i = 0, s2cPacketTypesSize = s2cPacketTypes.size(); i < s2cPacketTypesSize; i++) {
PacketType> s2cPacketType = s2cPacketTypes.get(i);
final Class> clazz = vanillaPacketTypes.get(s2cPacketType);
if (clazz == null) {
System.out.println("Skipping unmapped packet type: " + s2cPacketType);
continue;
}
s2c.put(i, RakNetMultiChannel.getPacketChannelOverride(clazz, false));
// System.out.println("Mapped packet type: " + s2cPacketType + " to channel " + RakNetMultiChannel.getPacketChannelOverride(clazz));
}
for (int i = 0, c2sPacketTypesSize = c2sPacketTypes.size(); i < c2sPacketTypesSize; i++) {
PacketType> c2sPacketType = c2sPacketTypes.get(i);
final Class> clazz = vanillaPacketTypes.get(c2sPacketType);
if (clazz == null) {
System.out.println("Skipping unmapped packet type: " + c2sPacketType);
continue;
}
c2s.put(i, RakNetMultiChannel.getPacketChannelOverride(clazz, false));
// System.out.println("Mapped packet type: " + c2sPacketType + " to channel " + RakNetMultiChannel.getPacketChannelOverride(clazz));
}
}
if (SAVE_CHANNEL_MAPPINGS) {
auditMixins();
final Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
ProtocolMultiChannelMappings mappings = new ProtocolMultiChannelMappings();
Path path = Path.of("channelMappings.json");
try {
mappings = gson.fromJson(Files.readString(path), ProtocolMultiChannelMappings.class);
} catch (IOException e) {
System.out.println("Error reading previously generated mappings: " + e.toString());
}
final ProtocolMultiChannelMappings.VersionMapping versionMapping = new ProtocolMultiChannelMappings.VersionMapping();
versionMapping.c2s = c2s;
versionMapping.s2c = s2c;
mappings.mappings.put(SharedConstants.getProtocolVersion(), versionMapping);
// reproducible mappings
mappings.mappings = mappings.mappings.int2ObjectEntrySet()
.stream()
.map(entry -> {
final ProtocolMultiChannelMappings.VersionMapping value = entry.getValue();
value.s2c = value.s2c.int2IntEntrySet().stream()
.sorted(Comparator.comparingInt(Int2IntMap.Entry::getIntKey))
.collect(Collectors.toMap(Int2IntMap.Entry::getIntKey, Int2IntMap.Entry::getIntValue, (o, o2) -> {
throw new RuntimeException("Unresolvable conflicts");
}, Int2IntArrayMap::new));
value.c2s = value.c2s.int2IntEntrySet().stream()
.sorted(Comparator.comparingInt(Int2IntMap.Entry::getIntKey))
.collect(Collectors.toMap(Int2IntMap.Entry::getIntKey, Int2IntMap.Entry::getIntValue, (o, o2) -> {
throw new RuntimeException("Unresolvable conflicts");
}, Int2IntArrayMap::new));
return new AbstractInt2ObjectMap.BasicEntry<>(
entry.getIntKey(),
value
);
})
.sorted(Comparator.comparingInt(Int2ObjectMap.Entry::getIntKey))
.collect(Collectors.toMap(Int2ObjectMap.Entry::getIntKey, Int2ObjectMap.Entry::getValue, (o, o2) -> {
throw new RuntimeException("Unresolvable conflicts");
}, Int2ObjectArrayMap::new));
try {
Files.writeString(path, gson.toJson(mappings), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
System.out.println("Error writing generated mappings: " + e.toString());
}
if (EXIT_AFTER_SAVE_CHANNEL_MAPPINGS) System.exit(0);
}
}
public static Object2IntMap>> getPacketIdsFromPacketHandler(Object value) {
Object2IntMap>> packetIds;
if (value instanceof INetworkStateInternalPacketHandler) {
packetIds = ((INetworkStateInternalPacketHandler) value).getPacketIds();
} else if (MultiVersionUtil.clazzNetworkStatePacketHandler.isInstance(value)) {
packetIds = ((INetworkStateInternalPacketHandler) MultiVersionUtil.NetworkStatePacketHandler$backingHandler1_20_2.get(value)).getPacketIds();
} else {
throw new IllegalStateException("Unknown packet handler type: " + value.getClass());
}
return packetIds;
}
private static void auditMixins() {
Logger auditLogger = LoggerFactory.getLogger("Raknetify Mixin Audit");
try {
final Class> transformerClazz = Class.forName("org.spongepowered.asm.mixin.transformer.MixinTransformer");
if (transformerClazz.isInstance(MixinEnvironment.getCurrentEnvironment().getActiveTransformer())) {
final Field processorField = transformerClazz.getDeclaredField("processor");
processorField.setAccessible(true);
final Object processor = processorField.get(MixinEnvironment.getCurrentEnvironment().getActiveTransformer());
final Class> processorClazz = Class.forName("org.spongepowered.asm.mixin.transformer.MixinProcessor");
final Field configsField = processorClazz.getDeclaredField("configs");
configsField.setAccessible(true);
final List> configs = (List>) configsField.get(processor);
final Class> configClazz = Class.forName("org.spongepowered.asm.mixin.transformer.MixinConfig");
final Method getUnhandledTargetsMethod = configClazz.getDeclaredMethod("getUnhandledTargets");
getUnhandledTargetsMethod.setAccessible(true);
Set unhandled = new HashSet<>();
for (Object config : configs) {
final Set unhandledTargets = (Set) getUnhandledTargetsMethod.invoke(config);
unhandled.addAll(unhandledTargets);
}
for (String s : unhandled) {
auditLogger.info("Loading class {}", s);
MixinService.getService().getClassProvider().findClass(s, false);
}
for (Object config : configs) {
for (String unhandledTarget : (Set) getUnhandledTargetsMethod.invoke(config)) {
auditLogger.error("{} is already classloaded", unhandledTarget);
}
}
}
} catch (Throwable t) {
throw new RuntimeException("Failed to audit mixins", t);
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/client/DebugHudUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.client;
import com.ishland.raknetify.common.connection.MetricsSynchronizationHandler;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.SimpleMetricsLogger;
import com.ishland.raknetify.fabric.common.util.MultiVersionUtil;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import io.netty.channel.Channel;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.ClientConnection;
import network.ycc.raknet.RakNet;
import java.util.function.Consumer;
public class DebugHudUtil {
public static void getDebugString(Consumer consumer) {
final ClientPlayNetworkHandler networkHandler = MinecraftClient.getInstance().getNetworkHandler();
if (networkHandler != null) {
final ClientConnection connection = (ClientConnection) MultiVersionUtil.ClientPlayNetworkHandler$connection.get(networkHandler);
final Channel channel = ((IClientConnection) connection).getChannel();
if (channel != null) {
if (channel.config() instanceof RakNet.Config config) {
if (config.getMetrics() instanceof SimpleMetricsLogger logger) {
consumer.accept(
"[Raknetify] A: true, MTU: %d, RTT: %.2f/%.2fms"
.formatted(config.getMTU(),
logger.getMeasureRTTns() / 1_000_000.0,
logger.getMeasureRTTnsStdDev() / 1_000_000.0
));
final MetricsSynchronizationHandler serverSync = logger.getMetricsSynchronizationHandler();
if (serverSync != null && serverSync.isRemoteSupported()) {
consumer.accept(
"[Raknetify] C: BUF: %.2fMB; S: BUF: %.2fMB"
.formatted(
logger.getCurrentQueuedBytes() / 1024.0 / 1024.0,
serverSync.getQueuedBytes() / 1024.0 / 1024.0
));
} else {
consumer.accept(
"[Raknetify] C: BUF: %.2fMB"
.formatted(
logger.getCurrentQueuedBytes() / 1024.0 / 1024.0
));
}
consumer.accept(
"[Raknetify] C: I: %s, O: %s"
.formatted(
logger.getMeasureTrafficInFormatted(),
logger.getMeasureTrafficOutFormatted()
));
consumer.accept(
"[Raknetify] C: ERR: %.4f%%, %d tx, %d rx, BST: %d"
.formatted(
logger.getMeasureErrorRate() * 100.0,
logger.getMeasureTX(), logger.getMeasureRX(),
logger.getMeasureBurstTokens() + config.getDefaultPendingFrameSets()
));
if (serverSync != null && serverSync.isRemoteSupported()) {
consumer.accept(
"[Raknetify] S: ERR: %.4f%%, %d tx, %d rx, BST: %d"
.formatted(
serverSync.getErrorRate() * 100.0,
serverSync.getTX(), serverSync.getRX(),
serverSync.getBurst()
));
}
} else {
consumer.accept(
"[Raknetify] A: true, MTU: %d"
.formatted(config.getMTU())
);
}
final MultiChannelingStreamingCompression compression = channel.pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
consumer.accept(
"[Raknetify] CRatio: I: %.2f%%, O: %.2f%%"
.formatted(compression.getInCompressionRatio() * 100, compression.getOutCompressionRatio() * 100)
);
}
return;
}
}
}
consumer.accept("[Raknetify] A: false");
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/client/DebugHudUtil1_21_9.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.client;
import com.ishland.raknetify.fabric.mixin.access.IDebugHudEntries;
import net.minecraft.client.gui.hud.debug.DebugHudEntry;
import net.minecraft.client.gui.hud.debug.DebugHudLines;
import net.minecraft.util.Identifier;
import net.minecraft.world.World;
import net.minecraft.world.chunk.WorldChunk;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.atomic.AtomicBoolean;
public class DebugHudUtil1_21_9 {
private static final AtomicBoolean initialized = new AtomicBoolean(false);
public static void init() {
if (!initialized.compareAndSet(false, true)) return;
Identifier identifier = Identifier.of("raknetify", "raknetify_debug_info");
IDebugHudEntries.invokeRegister(identifier, new DebugHudEntry() {
@Override
public void render(DebugHudLines lines, @Nullable World world, @Nullable WorldChunk clientChunk, @Nullable WorldChunk chunk) {
DebugHudUtil.getDebugString(s -> lines.addLineToSection(identifier, s));
}
@Override
public boolean canShow(boolean reducedDebugInfo) {
return true;
}
});
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/compat/package-info.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.compat;
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/compat/viafabric/ViaFabricCompatInjector.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.compat.viafabric;
import com.google.common.base.Preconditions;
import com.ishland.raknetify.fabric.mixin.RaknetifyFabricMixinPlugin;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import net.fabricmc.loader.api.FabricLoader;
import java.lang.reflect.Constructor;
public class ViaFabricCompatInjector {
public static void inject(Channel channel, boolean isClientSide) {
Preconditions.checkNotNull(channel);
if (FabricLoader.getInstance().isModLoaded("viafabric")) {
try {
final Class> userConnectionImplClass = Class.forName("com.viaversion.viaversion.connection.UserConnectionImpl");
final Constructor> userConnectionImplConstructor = userConnectionImplClass.getConstructor(Channel.class, boolean.class);
final Object user = userConnectionImplConstructor.newInstance(channel, isClientSide);
final Class> userConnectionClass = Class.forName("com.viaversion.viaversion.api.connection.UserConnection");
final Class> protocolPipelineImplClass = Class.forName("com.viaversion.viaversion.protocol.ProtocolPipelineImpl");
Object protocolPipeline = protocolPipelineImplClass.getConstructor(userConnectionClass).newInstance(user);
if (RaknetifyFabricMixinPlugin.AFTER_1_20_2) {
Class> protocolPipelineClass = Class.forName("com.viaversion.viaversion.api.protocol.ProtocolPipeline");
Class> protocolClass = Class.forName("com.viaversion.viaversion.api.protocol.Protocol");
if ((boolean) userConnectionClass.getMethod("isClientSide").invoke(user)) {
Class> hostnameParserProtocolClass = Class.forName("com.viaversion.fabric.common.protocol.HostnameParserProtocol");
Object hostnameParserProtocolInstance = hostnameParserProtocolClass.getField("INSTANCE").get(null);
protocolPipelineClass.getMethod("add", protocolClass).invoke(protocolPipeline, hostnameParserProtocolInstance);
}
}
final Class> commonTransformerClass = Class.forName("com.viaversion.fabric.common.handler.CommonTransformer");
final String handlerEncoderName = (String) commonTransformerClass.getField("HANDLER_ENCODER_NAME").get(null);
final String handlerDecoderName = (String) commonTransformerClass.getField("HANDLER_DECODER_NAME").get(null);
@SuppressWarnings("unchecked") final Class extends MessageToMessageEncoder> fabricEncodeHandlerClass = (Class extends MessageToMessageEncoder>) Class.forName("com.viaversion.fabric.common.handler.FabricEncodeHandler");
final MessageToMessageEncoder fabricEncodeHandler = fabricEncodeHandlerClass.getConstructor(userConnectionClass).newInstance(user);
@SuppressWarnings("unchecked") final Class extends MessageToMessageDecoder> fabricDecodeHandlerClass = (Class extends MessageToMessageDecoder>) Class.forName("com.viaversion.fabric.common.handler.FabricDecodeHandler");
final MessageToMessageDecoder fabricDecodeHandler = fabricDecodeHandlerClass.getConstructor(userConnectionClass).newInstance(user);
channel.pipeline().addBefore(determineEncoderName(channel.pipeline()), handlerEncoderName, fabricEncodeHandler);
channel.pipeline().addBefore(determineDecoderName(channel.pipeline()), handlerDecoderName, fabricDecodeHandler);
} catch (Throwable t) {
//noinspection RedundantStringFormatCall
System.err.println(String.format("Raknetify: Could not inject ViaVersion compatibility into RakNet channel %s: %s", channel, t));
t.printStackTrace();
}
}
}
private static String determineEncoderName(ChannelPipeline pipeline) {
if (pipeline.get("encoder") != null) return "encoder";
if (pipeline.get("outbound_config") != null) return "outbound_config";
throw new UnsupportedOperationException();
}
private static String determineDecoderName(ChannelPipeline pipeline) {
if (pipeline.get("decoder") != null) return "decoder";
if (pipeline.get("inbound_config") != null) return "inbound_config";
throw new UnsupportedOperationException();
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/MultiChannellingPacketCapture.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.common.connection.multichannel.CustomPayloadChannel;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import net.minecraft.network.packet.c2s.common.CustomPayloadC2SPacket;
import net.minecraft.network.packet.s2c.common.CustomPayloadS2CPacket;
@ChannelHandler.Sharable
public class MultiChannellingPacketCapture extends ChannelOutboundHandlerAdapter {
private Class> packetClass = null;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
this.packetClass = msg.getClass();
try {
ctx.write(msg, promise);
} finally {
this.packetClass = null;
}
}
public Class> getPacketClass() {
return this.packetClass;
}
public void setPacketClass(Class> packetClass) {
this.packetClass = packetClass;
}
public RakNetSimpleMultiChannelCodec.OverrideHandler getCaptureBasedHandler() {
return new CaptureBasedHandler();
}
public RakNetSimpleMultiChannelCodec.OverrideHandler getCustomPayloadHandler() {
return new CustomPayloadChannel.OverrideHandler(value -> packetClass == CustomPayloadS2CPacket.class || packetClass == CustomPayloadC2SPacket.class);
}
private class CaptureBasedHandler implements RakNetSimpleMultiChannelCodec.OverrideHandler {
@Override
public int getChannelOverride(ByteBuf buf, boolean suppressWarning) {
return RakNetMultiChannel.getPacketChannelOverride(packetClass, suppressWarning);
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/RakNetClientConnectionUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection;
import com.ishland.raknetify.common.util.ThreadLocalUtil;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import io.netty.channel.ChannelFuture;
import net.minecraft.network.ClientConnection;
import java.net.InetSocketAddress;
public class RakNetClientConnectionUtil {
private RakNetClientConnectionUtil() {
}
public static ClientConnection connect(InetSocketAddress address, boolean useEpoll, boolean largeMTU, Operation original, boolean hasPerformanceLog) {
System.out.println("aaa");
try {
ThreadLocalUtil.setInitializingRaknet(true);
ThreadLocalUtil.setInitializingRaknetLargeMTU(largeMTU);
if (hasPerformanceLog) {
return original.call(address, useEpoll, null);
} else {
return original.call(address, useEpoll);
}
} finally {
ThreadLocalUtil.setInitializingRaknet(false);
ThreadLocalUtil.setInitializingRaknetLargeMTU(false);
}
}
public static ClientConnection connect(InetSocketAddress address, Object backend, boolean largeMTU, Operation original) {
System.out.println("aaa");
try {
ThreadLocalUtil.setInitializingRaknet(true);
ThreadLocalUtil.setInitializingRaknetLargeMTU(largeMTU);
return original.call(address, backend, null);
} finally {
ThreadLocalUtil.setInitializingRaknet(false);
ThreadLocalUtil.setInitializingRaknetLargeMTU(false);
}
}
public static ChannelFuture connect(InetSocketAddress address, boolean useEpoll, boolean largeMTU, Operation original, ClientConnection connection) {
System.out.println("aaaa");
try {
ThreadLocalUtil.setInitializingRaknet(true);
ThreadLocalUtil.setInitializingRaknetLargeMTU(largeMTU);
return original.call(address, useEpoll, connection);
} finally {
ThreadLocalUtil.setInitializingRaknet(false);
ThreadLocalUtil.setInitializingRaknetLargeMTU(false);
}
}
public static ChannelFuture connect(InetSocketAddress address, Object backend, boolean largeMTU, Operation original, ClientConnection connection) {
System.out.println("aaaa");
try {
ThreadLocalUtil.setInitializingRaknet(true);
ThreadLocalUtil.setInitializingRaknetLargeMTU(largeMTU);
return original.call(address, backend, connection);
} finally {
ThreadLocalUtil.setInitializingRaknet(false);
ThreadLocalUtil.setInitializingRaknetLargeMTU(false);
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/RakNetCompressionCompatibilityHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import net.minecraft.network.packet.s2c.login.LoginCompressionS2CPacket;
public class RakNetCompressionCompatibilityHandler extends ChannelDuplexHandler {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof LoginCompressionS2CPacket) {
promise.trySuccess();
ctx.write(msg);
ctx.pipeline().remove(this);
return;
}
super.write(ctx, msg, promise);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/RakNetFabricChannelEventListener.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.common.connection.SynchronizationLayer;
import com.ishland.raknetify.fabric.mixin.RaknetifyFabricMixinPlugin;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import net.minecraft.network.handler.NetworkStateTransitions;
import net.minecraft.network.packet.c2s.play.AcknowledgeReconfigurationC2SPacket;
import net.minecraft.network.packet.s2c.play.CommandTreeS2CPacket;
import net.minecraft.network.packet.s2c.play.EnterReconfigurationS2CPacket;
import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket;
import net.minecraft.network.packet.s2c.play.PlayerRespawnS2CPacket;
public class RakNetFabricChannelEventListener extends ChannelDuplexHandler {
public static final String NAME = "raknetify-fabric-event-listener";
private static final boolean isReconfigurationSupported;
static {
boolean isReconfigurationSupported0;
try {
EnterReconfigurationS2CPacket.class.getName();
isReconfigurationSupported0 = true;
} catch (NoClassDefFoundError e) {
isReconfigurationSupported0 = false;
}
isReconfigurationSupported = isReconfigurationSupported0;
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof PlayerRespawnS2CPacket || msg instanceof GameJoinS2CPacket) {
ctx.write(SynchronizationLayer.SYNC_REQUEST_OBJECT);
}
if (isReconfigurationSupported) {
if (msg instanceof EnterReconfigurationS2CPacket || msg instanceof AcknowledgeReconfigurationC2SPacket) {
ctx.write(SynchronizationLayer.SYNC_REQUEST_OBJECT);
}
}
if (msg instanceof CommandTreeS2CPacket) {
ctx.write(RakNetSimpleMultiChannelCodec.SIGNAL_START_MULTICHANNEL);
}
if (RaknetifyFabricMixinPlugin.AFTER_1_20_5) {
if (msg instanceof NetworkStateTransitions.DecoderTransitioner || msg instanceof NetworkStateTransitions.EncoderTransitioner) {
ctx.write(RakNetNetworkTransitionUtil.handleTransition(msg), promise);
return;
}
}
super.write(ctx, msg, promise);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/RakNetFabricConnectionUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.RakNetConnectionUtil;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.fabric.common.compat.viafabric.ViaFabricCompatInjector;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.kqueue.KQueueDatagramChannel;
import io.netty.channel.kqueue.KQueueSocketChannel;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import network.ycc.raknet.RakNet;
public class RakNetFabricConnectionUtil {
public static final String NAME_RAKNETIFY_MULTI_CHANNEL_PACKET_CATURE = "raknetify-multi-channel-packet-cature";
private RakNetFabricConnectionUtil() {
}
public static void initChannel(Channel channel) {
if (channel.config() instanceof RakNet.Config) {
RakNetConnectionUtil.initChannel(channel);
channel.pipeline().addAfter(MultiChannelingStreamingCompression.NAME, RakNetSimpleMultiChannelCodec.NAME, new RakNetSimpleMultiChannelCodec(Constants.RAKNET_GAME_PACKET_ID));
}
}
public static void postInitChannel(Channel channel, boolean isClientSide) {
if (channel.config() instanceof RakNet.Config) {
ViaFabricCompatInjector.inject(channel, isClientSide);
channel.pipeline().replace("timeout", "timeout", new ChannelDuplexHandler()); // no-op
channel.pipeline().replace("splitter", "splitter", new ChannelDuplexHandler()); // no-op
channel.pipeline().replace("prepender", "prepender", new ChannelDuplexHandler()); // no-op
final MultiChannellingPacketCapture handler = new MultiChannellingPacketCapture();
channel.pipeline().addLast(NAME_RAKNETIFY_MULTI_CHANNEL_PACKET_CATURE, handler);
onPipelineReorder(channel.pipeline());
channel.pipeline().get(RakNetSimpleMultiChannelCodec.class)
.addHandler(handler.getCustomPayloadHandler())
.addHandler(handler.getCaptureBasedHandler());
channel.pipeline().addLast("raknetify-handle-compression-compatibility", new RakNetCompressionCompatibilityHandler());
channel.pipeline().addBefore("packet_handler", RakNetFabricChannelEventListener.NAME, new RakNetFabricChannelEventListener());
}
}
static void onPipelineReorder(ChannelPipeline pipeline) {
if (pipeline.get("encoder") == null) {
// System.out.println("Reordering failed: no encoder");
return;
}
// System.out.println("Reordering");
ChannelHandler handler = pipeline.remove(RakNetFabricConnectionUtil.NAME_RAKNETIFY_MULTI_CHANNEL_PACKET_CATURE);
if (handler != null) {
pipeline.addAfter("encoder", RakNetFabricConnectionUtil.NAME_RAKNETIFY_MULTI_CHANNEL_PACKET_CATURE, handler);
}
}
public static DatagramChannel fromSocketChannel(Class extends SocketChannel> clazz) {
if (clazz == NioSocketChannel.class) {
return new NioDatagramChannel();
} else if (clazz == EpollSocketChannel.class) {
return new EpollDatagramChannel();
} else if (clazz == KQueueSocketChannel.class) {
return new KQueueDatagramChannel();
} else {
throw new UnsupportedOperationException(clazz.getName());
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/RakNetMultiChannel.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection;
import com.google.common.collect.Sets;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.MappingResolver;
import java.util.HashSet;
import java.util.Set;
public class RakNetMultiChannel {
private RakNetMultiChannel() {
}
private static Set> createClassSet(String[] classNames) {
final MappingResolver mappingResolver = FabricLoader.getInstance().getMappingResolver();
final boolean isIntermediaryNamespace = mappingResolver.getCurrentRuntimeNamespace().equals("intermediary");
final HashSet> classHashSet = new HashSet<>();
for (String className : classNames) {
final String intermediary = mappingResolver.mapClassName("intermediary", className.replace('/', '.'));
if (!isIntermediaryNamespace && intermediary.equals(className))
//noinspection RedundantStringFormatCall
System.err.println("Raknetify: Warning: Failed to remap %s for raknet multi-channel".formatted(intermediary));
try {
classHashSet.add(Class.forName(intermediary, false, RakNetMultiChannel.class.getClassLoader()));
} catch (ClassNotFoundException e) {
if (Boolean.getBoolean("raknetify.printNotFoundClasses")) {
//noinspection RedundantStringFormatCall
System.out.println("Raknetify: Warning: %s not found for raknet multi-channel".formatted(intermediary));
}
}
}
return classHashSet; // no read-only wrapper for performance
}
private static final Set> unordered = createClassSet(new String[]{
"net/minecraft/class_2670", // KeepAliveS2C
"net/minecraft/class_2827", // KeepAliveC2S
"net/minecraft/class_2661", // DisconnectS2C
"net/minecraft/class_6373", // PlayPingS2C
"net/minecraft/class_6374", // PlayPongC2S
"net/minecraft/class_2720", // ResourcePackSendS2C
"net/minecraft/class_2856", // ResourcePackStatusC2S
"net/minecraft/class_9053", // ResourcePackRemoveS2CPacket
"net/minecraft/class_2617", // StatisticsS2C
"net/minecraft/class_2859", // AdvancementTabC2S
"net/minecraft/class_2729", // SelectAdvancementTabS2C
"net/minecraft/class_2935", // QueryPingC2SPacket
"net/minecraft/class_2923", // PingResultS2CPacket
"net/minecraft/class_9814", // CustomReportDetailsS2CPacket
"net/minecraft/class_9815", // ServerLinksS2CPacket
});
private static final Set> channel0 = createClassSet(new String[]{
"net/minecraft/class_8588", // EnterReconfigurationS2CPacket
"net/minecraft/class_8591", // AcknowledgeReconfigurationC2SPacket
"net/minecraft/class_9151", // ServerTransferS2CPacket
});
// Primarily used for interactions independent to world
private static final Set> channel1 = createClassSet(new String[]{
"net/minecraft/class_2629", // BossBarS2C
"net/minecraft/class_5888", // ClearTitleS2C
"net/minecraft/class_5903", // SubtitleS2C
"net/minecraft/class_5904", // TitleS2C
"net/minecraft/class_5905", // TitleFadeS2C
"net/minecraft/class_5892", // DeathMessageS2C
"net/minecraft/class_2635", // GameMessageS2CPacket
"net/minecraft/class_7439", // GameMessageS2CPacket
"net/minecraft/class_7827", // ProfilelessChatMessageS2CPacket
"net/minecraft/class_7519", // ChatPreviewStateChangeS2CPacket
"net/minecraft/class_7438", // ChatMessageS2CPacket
"net/minecraft/class_7494", // ChatPreviewS2CPacket
"net/minecraft/class_7618", // MOJMAP: ClientboundPlayerChatHeaderPacket
"net/minecraft/class_7597", // ChatSuggestionsS2CPacket
"net/minecraft/class_7617", // MOJMAP: ClientboundDeleteChatPacket
"net/minecraft/class_7861", // MOJMAP: ServerboundChatSessionUpdatePacket
"net/minecraft/class_7640", // UMMAPPED: chat related anyways
"net/minecraft/class_7495", // ServerMetadataS2CPacket
"net/minecraft/class_5894", // OverlayMessageS2C
"net/minecraft/class_2748", // ExperienceBarUpdateS2C
"net/minecraft/class_2749", // HealthUpdateS2C
"net/minecraft/class_2656", // CooldownUpdateS2CPacket
"net/minecraft/class_2736", // ScoreboardDisplayS2C
"net/minecraft/class_2751", // ScoreboardDisplayObjectiveUpdateS2C
"net/minecraft/class_2757", // ScoreboardPlayerUpdateS2C
"net/minecraft/class_9006", // ScoreboardScoreResetS2CPacket
"net/minecraft/class_2779", // AdvancementUpdateS2CPacket
"net/minecraft/class_2641", // CommandTreeS2C
"net/minecraft/class_2639", // CommandSuggestionsS2C
"net/minecraft/class_2805", // RequestCommandCompletionsC2S
"net/minecraft/class_7472", // CommandExecutionC2SPacket
"net/minecraft/class_9449", // ChatCommandSignedC2SPacket
"net/minecraft/class_7496", // RequestChatPreviewC2SPacket
"net/minecraft/class_2811", // ButtonClickC2S
"net/minecraft/class_2797", // ChatMessageC2S
"net/minecraft/class_2813", // ClickSlotC2S
"net/minecraft/class_2848", // ClientCommandC2S
"net/minecraft/class_2803", // ClientSettingsC2S
"net/minecraft/class_2803", // ClientStatusC2S
"net/minecraft/class_4210", // UpdateDifficultyC2S
"net/minecraft/class_4211", // UpdateDifficultyLockC2S
"net/minecraft/class_2708", // PlayerPositionLookS2C
"net/minecraft/class_2846", // PlayerActionC2S
"net/minecraft/class_2851", // PlayerInputC2S
// hard to categorize
"net/minecraft/class_10370", // PickItemFromBlockC2SPacket
"net/minecraft/class_10371", // PickItemFromEntityC2SPacket
"net/minecraft/class_2707", // LookAtS2C
"net/minecraft/class_2761", // WorldTimeUpdateS2C
"net/minecraft/class_2632", // DifficultyS2C
"net/minecraft/class_5900", // TeamS2C
"net/minecraft/class_2788", // SynchronizeRecipesS2C
"net/minecraft/class_2790", // SynchronizeTagsS2C
"net/minecraft/class_2703", // PlayerListS2C
"net/minecraft/class_2772", // PlayerListHeaderS2C
"net/minecraft/class_7828", // PlayerRemoveS2CPacket (actually only remove from list)
"net/minecraft/class_2613", // PlayerSpawnS2C
// 1.16.5
"net/minecraft/class_2755", // TeamS2CPacket
"net/minecraft/class_2762", // TitleS2CPacket
// 23w13a_or_b
"net/minecraft/class_8258", // ServerboundVoteCastPacket
"net/minecraft/class_8483", // ClientboundVoteStartPacket
"net/minecraft/class_8478", // ClientboundBulkVoteInfoPacket
"net/minecraft/class_8482", // ClientboundVoteProgressInfoPacket
"net/minecraft/class_8481", // ClientboundVoteFinishPacket
"net/minecraft/class_8479", // ClientboundRuleUpdatePacket
"net/minecraft/class_8480", // ClientboundVoteCastResultPacket
"net/minecraft/class_9088", // CookieRequestS2CPacket
"net/minecraft/class_9150", // StoreCookieS2CPacket
"net/minecraft/class_9091", // CookieResponseC2SPacket
"net/minecraft/class_9178", // DebugSampleS2CPacket
"net/minecraft/class_9179", // DebugSampleSubscriptionC2SPacket
"net/minecraft/class_11173", // WaypointS2CPacket
"net/minecraft/class_11406", // ClearDialogS2CPacket
"net/minecraft/class_11407", // ShowDialogS2CPacket
"net/minecraft/class_11411", // CustomClickActionC2SPacket
});
// Entities related stuff
private static final Set> channel2 = createClassSet(new String[]{
"net/minecraft/class_5890", // EndCombatS2C
"net/minecraft/class_5891", // EnterCombatS2C
"net/minecraft/class_2716", // EntitiesDestroyS2C
"net/minecraft/class_2604", // EntitySpawnS2C
"net/minecraft/class_2616", // EntityAnimationS2C
"net/minecraft/class_2663", // EntityStatusS2C
"net/minecraft/class_2684$class_2685", // EntityPacketS2C$MoveRelative
"net/minecraft/class_2684$class_2687", // EntityPacketS2C$Rotate
"net/minecraft/class_2684$class_2686", // EntityPacketS2C$RotateAndMoveRelative
"net/minecraft/class_2726", // EntitySetHeadYawS2C
"net/minecraft/class_2739", // EntityTrackerUpdateS2C
"net/minecraft/class_2740", // EntityAttachS2C
"net/minecraft/class_2743", // EntityVelocityUpdateS2C
"net/minecraft/class_2744", // EntityEquipmentUpdateS2C
"net/minecraft/class_2752", // EntityPassengerSetS2C
"net/minecraft/class_2777", // EntityPositionS2C
"net/minecraft/class_10264", // EntityPositionSyncS2CPacket
"net/minecraft/class_2781", // EntityAttributesS2C
"net/minecraft/class_2783", // EntityStatusEffectS2C
"net/minecraft/class_2718", // RemoveEntityStatusEffectS2C
"net/minecraft/class_2610", // MobSpawnS2C
"net/minecraft/class_2612", // PaintingSpawnS2C
"net/minecraft/class_2606", // ExperienceOrbSpawnS2CPacket
"net/minecraft/class_8043", // HurtAnimation (mojmap)
"net/minecraft/class_8143", // EntityDamageS2C
"net/minecraft/class_9833", // MoveMinecartAlongTrackS2CPacket
"net/minecraft/class_2885", // PlayerInteractBlockC2S
"net/minecraft/class_2886", // PlayerInteractItemC2S
"net/minecraft/class_2824", // PlayerInteractEntityC2S
"net/minecraft/class_2828", // PlayerMoveC2S
"net/minecraft/class_2828$class_5911", // PlayerMoveC2SPacket$OnGroundOnly
"net/minecraft/class_2828$class_2829", // PlayerMoveC2SPacket$PositionAndOnGround
"net/minecraft/class_2828$class_2830", // PlayerMoveC2SPacket$Full
"net/minecraft/class_2828$class_2831", // PlayerMoveC2SPacket$LookAndOnGround
"net/minecraft/class_9836", // ClientTickEndC2SPacket: used to track movement on vanilla server
"net/minecraft/class_11410", // ChangeGameModeC2SPacket
"net/minecraft/class_2664", // ExplosionS2C
"net/minecraft/class_2678", // GameJoinS2C
"net/minecraft/class_7832", // FeaturesS2CPacket
"net/minecraft/class_2668", // GameStateChangeS2C
"net/minecraft/class_2759", // PlayerSpawnPositionS2CPacket
"net/minecraft/class_2775", // ItemPickupAnimationS2C
"net/minecraft/class_2696", // PlayerAbilitiesS2C
"net/minecraft/class_2734", // SetCameraEntityS2C
"net/minecraft/class_2692", // VehicleMoveS2C
"net/minecraft/class_2836", // BoatPaddleStateC2S
"net/minecraft/class_2833", // VehicleMoveC2S
"net/minecraft/class_2879", // HandSwingC2S
"net/minecraft/class_10265", // PlayerRotationS2CPaket
// 1.16.5
"net/minecraft/class_2684", // EntityS2CPacket
"net/minecraft/class_2698", // CombatEventS2CPacket
// 23w13a_or_b
"net/minecraft/class_8484", // ServerboundCrashVehiclePacket
// 1.20.5
"net/minecraft/class_9632", // ProjectilePowerS2CPacket
"net/minecraft/class_11984", // EntityValueDebugS2CPacket
"net/minecraft/class_11985", // EventDebugS2CPacket
});
// Primarily used for interactions dependent to world
private static final Set> channel3 = createClassSet(new String[]{
"net/minecraft/class_2884", // SpectatorTeleportC2S
"net/minecraft/class_2793", // TeleportConfirmC2S
"net/minecraft/class_2795", // QueryBlockNbtC2S
"net/minecraft/class_2822", // QueryEntityNbtC2S
"net/minecraft/class_2774", // NbtQueryResponseS2C
"net/minecraft/class_2645", // CloseScreenS2C
"net/minecraft/class_2648", // OpenHorseScreenS2C
"net/minecraft/class_3944", // OpenScreenS2C
"net/minecraft/class_2651", // ScreenHandlerPropertyUpdateS2C
"net/minecraft/class_2653", // ScreenHandlerSlotUpdateS2C
"net/minecraft/class_3895", // OpenWrittenBookS2C
"net/minecraft/class_2649", // InventoryS2C
"net/minecraft/class_2713", // UnlockRecipesS2C
"net/minecraft/class_2735", // UpdateSelectedSlotS2C
"net/minecraft/class_3943", // SetTradeOffersS2C
"net/minecraft/class_10266", // RecipeBookAddS2CPacket
"net/minecraft/class_10268", // RecipeBookRemoveS2CPacket
"net/minecraft/class_10269", // RecipeBookSettingsS2CPacket
"net/minecraft/class_2820", // BookUpdateC2S
"net/minecraft/class_2853", // RecipeBookDataC2S
"net/minecraft/class_5427", // RecipeCategoryOptionsC2S
"net/minecraft/class_2855", // RenameItemC2S
"net/minecraft/class_2815", // CloseHandledScreenC2S
"net/minecraft/class_2873", // CreativeInventoryActionC2S
"net/minecraft/class_2840", // CraftRequestC2S
"net/minecraft/class_2838", // PickFromInventoryC2S
"net/minecraft/class_2863", // SelectMerchantTradeC2S
"net/minecraft/class_2866", // UpdateBeaconC2S
"net/minecraft/class_2870", // UpdateCommandBlockC2S
"net/minecraft/class_2871", // UpdateCommandBlockMinecartC2S
"net/minecraft/class_10615", // SetTestBlockC2SPacket
"net/minecraft/class_10616", // TestInstanceBlockActionC2SPacket
"net/minecraft/class_3753", // UpdateJigsawC2S
"net/minecraft/class_2842", // UpdatePlayerAbilitiesC2S
"net/minecraft/class_2868", // UpdateSelectedSlotC2S
"net/minecraft/class_2875", // UpdateStructureBlockC2S
"net/minecraft/class_2695", // CraftFailedResponseS2CPacket
"net/minecraft/class_8875", // SlotChangedStateC2SPacket
"net/minecraft/class_9834", // SetCursorItemS2CPacket
"net/minecraft/class_9835", // SetPlayerInventoryS2CPacket
"net/minecraft/class_9837", // BundleItemSelectedC2SPacket
"net/minecraft/class_5889", // WorldBorderInitializeS2C
"net/minecraft/class_5895", // WorldBorderCenterChangedS2C
"net/minecraft/class_5896", // WorldBorderInterpolateSizeS2C
"net/minecraft/class_5897", // WorldBorderSizeChangedS2C
"net/minecraft/class_5898", // WorldBorderWarningTimeChangedS2C
"net/minecraft/class_5899", // WorldBorderWarningBlockChangedS2C
"net/minecraft/class_2799", // ClientStatusC2SPacket
"net/minecraft/class_2724", // PlayerRespawnS2CPacket
"net/minecraft/class_2817", // CustomPayloadC2SPacket
"net/minecraft/class_2658", // CustomPayloadS2CPacket
"net/minecraft/class_8914", // TickStepS2CPacket
"net/minecraft/class_8913", // UpdateTickRateS2CPacket
// 1.16.5
"net/minecraft/class_2809", // ConfirmScreenActionC2SPacket
"net/minecraft/class_2644", // ConfirmScreenActionS2CPacket
"net/minecraft/class_2730", // WorldBorderS2CPacket
});
// Primarily for packets not very critical to interactions
private static final Set> channel4 = createClassSet(new String[]{
"net/minecraft/class_2683", // MapUpdateS2C
"net/minecraft/class_2660", // PlaySoundIdS2C
"net/minecraft/class_2765", // PlaySoundFromEntityS2C
"net/minecraft/class_2767", // PlaySoundS2C
"net/minecraft/class_2770", // StopSoundS2C
"net/minecraft/class_2675", // ParticleS2C
"net/minecraft/class_5747", // VibrationS2C
});
// Used for worlds
private static final Set> channel7 = createClassSet(new String[]{
"net/minecraft/class_5194", // JigsawGeneratingC2S
"net/minecraft/class_2693", // SignEditorOpenS2C
"net/minecraft/class_2877", // UpdateSignC2S
"net/minecraft/class_2623", // BlockEventS2CPacket
"net/minecraft/class_4282", // ChunkRenderDistanceCenterS2CPacket
"net/minecraft/class_4273", // ChunkLoadDistanceS2CPacket
"net/minecraft/class_6682", // SimulationDistanceS2C
"net/minecraft/class_2666", // UnloadChunkS2CPacket
"net/minecraft/class_2626", // BlockUpdateS2CPacket
"net/minecraft/class_2637", // ChunkDeltaUpdateS2CPacket
"net/minecraft/class_2673", // WorldEventS2CPacket
"net/minecraft/class_2620", // BlockBreakingProgressS2CPacket
"net/minecraft/class_2672", // ChunkDataS2CPacket
"net/minecraft/class_2622", // BlockEntityUpdateS2CPacket
"net/minecraft/class_2676", // LightUpdateS2CPacket
"net/minecraft/class_8212", // BiomeUpdateS2CPacket
"net/minecraft/class_8738", // ChunkSentS2CPacket
"net/minecraft/class_8739", // StartChunkSendS2CPacket
"net/minecraft/class_8590", // AcknowledgeChunksC2SPacket
"net/minecraft/class_4463", // PlayerActionResponseS2C
"net/minecraft/class_10387", // PlayerLoadedC2SPacket
"net/minecraft/class_10614", // TestInstanceBlockStatusS2CPacket
"net/minecraft/class_11982", // BlockValueDebugS2CPacket
"net/minecraft/class_11983", // ChunkValueDebugS2CPacket
"net/minecraft/class_11986", // GameTestHighlightPosS2CPacket
});
private static final Set> unreliable = createClassSet(new String[]{
});
private static final Set> theVoid = createClassSet(new String[]{
"net/minecraft/class_8037", // BundleDelimiterPacket
"net/minecraft/class_9093", // BundleDelimiterS2CPacket
});
private static final Object2IntOpenHashMap> classToChannelIdOverride = new Object2IntOpenHashMap<>();
static {
classToChannelIdOverride.defaultReturnValue(Integer.MAX_VALUE);
unordered.forEach(clazz -> classToChannelIdOverride.put(clazz, -1));
channel0.forEach(clazz -> classToChannelIdOverride.put(clazz, 0));
channel1.forEach(clazz -> classToChannelIdOverride.put(clazz, 1));
channel2.forEach(clazz -> classToChannelIdOverride.put(clazz, 2));
channel3.forEach(clazz -> classToChannelIdOverride.put(clazz, 3));
channel4.forEach(clazz -> classToChannelIdOverride.put(clazz, 4));
channel7.forEach(clazz -> classToChannelIdOverride.put(clazz, 7));
unreliable.forEach(clazz -> classToChannelIdOverride.put(clazz, -2));
theVoid.forEach(clazz -> classToChannelIdOverride.put(clazz, Integer.MIN_VALUE));
}
// private static final ThreadLocal> currentPacketClass = new ThreadLocal<>();
//
// public static void setCurrentPacketClass(Class> clazz) {
// Preconditions.checkNotNull(clazz, "clazz");
// if (currentPacketClass.get() != null) throw new IllegalStateException("Already set");
// currentPacketClass.set(clazz);
// }
//
// public static void clearCurrentPacketClass(Class> clazz) {
// Preconditions.checkNotNull(clazz);
// final Class> threadLocalClazz = currentPacketClass.get();
// if (threadLocalClazz == null) throw new IllegalArgumentException("Not set");
// if (threadLocalClazz != clazz) throw new IllegalArgumentException("Mismatch");
// currentPacketClass.set(null);
// }
private static final Set> foundUnknownClasses = Sets.newConcurrentHashSet();
public static int getPacketChannelOverride(Class> clazz, boolean suppressWarning) {
if (clazz == null) {
System.err.println("Raknetify: Warning: Tried to send packet without setting packet class");
return 0;
}
int channelOverride = classToChannelIdOverride.getInt(clazz);
if (channelOverride == Integer.MAX_VALUE) {
if (!suppressWarning) {
if (foundUnknownClasses.add(clazz)) {
final MappingResolver mappingResolver = FabricLoader.getInstance().getMappingResolver();
final String intermediary = mappingResolver.unmapClassName("intermediary", clazz.getName());
System.err.println("Raknetify: Warning: unknown packet type %s (%s) for raknet multi-channel".formatted(intermediary.replace('.', '/'), clazz.getName()));
}
}
channelOverride = 7;
}
return channelOverride;
}
public static void init() {
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/RakNetNetworkTransitionUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection;
import net.minecraft.network.handler.NetworkStateTransitions;
public class RakNetNetworkTransitionUtil {
static Object handleTransition(Object msg) {
if (msg instanceof NetworkStateTransitions.DecoderTransitioner transitioner) {
return transitioner.andThen(context -> RakNetFabricConnectionUtil.onPipelineReorder(context.pipeline()));
} else if (msg instanceof NetworkStateTransitions.EncoderTransitioner transitioner) {
return transitioner.andThen(context -> RakNetFabricConnectionUtil.onPipelineReorder(context.pipeline()));
}
return msg;
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/connection/encryption/PacketEncryptionManagerInterface.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.connection.encryption;
import io.netty.channel.ChannelHandlerContext;
public interface PacketEncryptionManagerInterface {
void setContext(ChannelHandlerContext ctx);
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/package-info.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common;
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/quirks/ClientHungerManager.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.quirks;
import com.ishland.raknetify.fabric.common.util.MultiVersionUtil;
import com.ishland.raknetify.fabric.mixin.RaknetifyFabricMixinPlugin;
import net.minecraft.component.type.FoodComponent;
import net.minecraft.entity.player.HungerManager;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.storage.NbtReadView;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class ClientHungerManager extends HungerManager {
public static ClientHungerManager from(HungerManager hungerManager) {
ClientHungerManager clientHungerManager = new ClientHungerManager();
if (RaknetifyFabricMixinPlugin.AFTER_1_21_5) {
for (Field field : HungerManager.class.getFields()) {
if ((field.getModifiers() & Modifier.STATIC) == 0 && (field.getModifiers() & Modifier.FINAL) == 0) {
if (!field.trySetAccessible()) {
System.err.println("Failed to set field " + field.getName() + " accessible in HungerManager");
continue;
}
try {
Object value = field.get(hungerManager);
field.set(clientHungerManager, value);
} catch (Throwable e) {
System.err.println("Failed to copy field " + field.getName() + " from HungerManager to ClientHungerManager");
e.printStackTrace();
}
}
}
} else {
NbtCompound compound = new NbtCompound();
try {
MultiVersionUtil.HungerManager$writeNbt1_21_5.invoke(hungerManager, compound);
} catch (Throwable e) {
throw new RuntimeException(e);
}
try {
MultiVersionUtil.HungerManager$readNbt1_21_5.invoke(clientHungerManager, compound);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
return clientHungerManager;
}
public void add(int food, float saturationModifier) {
// nop
}
public void eat(FoodComponent foodComponent) {
// nop
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/util/FieldSignatureParser.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.util;
import org.objectweb.asm.Type;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureVisitor;
import org.spongepowered.asm.util.asm.ASM;
import java.util.ArrayList;
import java.util.List;
public class FieldSignatureParser extends SignatureVisitor {
private final List results = new ArrayList<>();
private FieldSignatureParser() {
super(ASM.API_VERSION);
}
public static List parse(String signature) {
if (signature == null || signature.isEmpty()) {
return List.of();
}
FieldSignatureParser parser = new FieldSignatureParser();
new SignatureReader(signature).acceptType(parser);
return parser.results;
}
@Override
public void visitClassType(String name) {
results.add(Type.getObjectType(name));
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/util/LegacySupportUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.util;
import com.ishland.raknetify.fabric.mixin.RaknetifyFabricMixinPlugin;
import net.minecraft.entity.Entity;
import net.minecraft.world.World;
public class LegacySupportUtil {
public static World getEntityWorld(Entity entity) {
if (RaknetifyFabricMixinPlugin.AFTER_1_21_8) {
return entity.getEntityWorld();
} else {
try {
return (World) MultiVersionUtil.Entity$getEntity1_21_8.invokeExact(entity);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/util/MultiVersionUtil.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.util;
import com.google.common.collect.ImmutableList;
import net.fabricmc.api.EnvType;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.MappingResolver;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.HungerManager;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.state.NetworkState;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class MultiVersionUtil {
private static final String INTERMEDIARY = "intermediary";
private static final String CLASSNAME_ServerPlayNetworkHandler = "net.minecraft.class_3244";
private static final String CLASSNAME_NetworkStatePacketHandler = "net.minecraft.class_2539$class_8698";
private static final String CLASSNAME_NetworkState$InternalPacketHandler = "net.minecraft.class_2539$class_4532";
private static final String CLASSNAME_NetworkState$Factory = "net.minecraft.class_9127$class_9128";
private static final String CLASSNAME_ContextAwareNetworkStateFactory = "net.minecraft.class_10947";
private static final String CLASSNAME_PlayStateFactories = "net.minecraft.class_9095";
private static final String CLASSNAME_HungerManager = "net.minecraft.class_1702";
private static final String CLASSNAME_Entity = "net.minecraft.class_1297";
public static final VarHandle ServerPlayNetworkHandler$connection;
public static final VarHandle ClientPlayNetworkHandler$connection;
public static final VarHandle ServerPlayerEntity$pingMillis1_20_1;
public static final Class> clazzNetworkStatePacketHandler;
public static final VarHandle NetworkStatePacketHandler$backingHandler1_20_2;
public static final MethodHandle NetworkState$Factory$bind1_20_5;
public static final Class> clazzPlayStateFactories;
public static final VarHandle PlayStateFactories$C2S1_20_5;
public static final VarHandle PlayStateFactories$S2C1_20_5;
public static final MethodHandle HungerManager$writeNbt1_21_5;
public static final MethodHandle HungerManager$readNbt1_21_5;
public static final MethodHandle Entity$getEntity1_21_8;
static {
try {
final MappingResolver resolver = FabricLoader.getInstance().getMappingResolver();
{
final List connFields = tryLocateFields(ServerPlayNetworkHandler.class, ClientConnection.class, false);
if (connFields.size() != 1) {
throw new IllegalStateException("Ambiguous fields for ClientConnection in ServerPlayNetworkHandler: found " + Arrays.toString(connFields.toArray()));
}
if (connFields.isEmpty()) {
throw new IllegalStateException("Cannot find field for ClientConnection in ServerPlayNetworkHandler");
}
final Field connField = connFields.get(0);
connField.setAccessible(true);
ServerPlayNetworkHandler$connection = MethodHandles
.privateLookupIn(ServerPlayNetworkHandler.class, MethodHandles.lookup())
.unreflectVarHandle(connField);
}
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
final List connFields = tryLocateFields(ClientPlayNetworkHandler.class, ClientConnection.class, false);
if (connFields.size() != 1) {
throw new IllegalStateException("Ambiguous fields for ClientConnection in ClientPlayNetworkHandler: found " + Arrays.toString(connFields.toArray()));
}
if (connFields.isEmpty()) {
throw new IllegalStateException("Cannot find field for ClientConnection in ClientPlayNetworkHandler");
}
final Field connField = connFields.get(0);
connField.setAccessible(true);
ClientPlayNetworkHandler$connection = MethodHandles
.privateLookupIn(ClientPlayNetworkHandler.class, MethodHandles.lookup())
.unreflectVarHandle(connField);
} else {
ClientPlayNetworkHandler$connection = null;
}
{
final Field pingMillis1_20_1 = getOrNull(() -> ServerPlayerEntity.class.getDeclaredField(resolver.mapFieldName(INTERMEDIARY, "net.minecraft.class_3222", "field_13967", "I")), NoSuchFieldException.class);
if (pingMillis1_20_1 != null) {
pingMillis1_20_1.setAccessible(true);
ServerPlayerEntity$pingMillis1_20_1 = MethodHandles
.privateLookupIn(ServerPlayerEntity.class, MethodHandles.lookup())
.unreflectVarHandle(pingMillis1_20_1);
} else {
ServerPlayerEntity$pingMillis1_20_1 = null;
}
}
{
clazzNetworkStatePacketHandler = getOrNull(() -> Class.forName(resolver.mapClassName(INTERMEDIARY, CLASSNAME_NetworkStatePacketHandler)), ClassNotFoundException.class);
if (clazzNetworkStatePacketHandler != null) {
final Field backingHandler1_20_2 = getOrNull(() -> clazzNetworkStatePacketHandler.getDeclaredField(resolver.mapFieldName(INTERMEDIARY, CLASSNAME_NetworkStatePacketHandler, "field_45674", "L" + resolver.mapClassName(INTERMEDIARY, CLASSNAME_NetworkState$InternalPacketHandler) + ";")), NoSuchFieldException.class);
if (backingHandler1_20_2 != null) {
backingHandler1_20_2.setAccessible(true);
NetworkStatePacketHandler$backingHandler1_20_2 = MethodHandles
.privateLookupIn(clazzNetworkStatePacketHandler, MethodHandles.lookup())
.unreflectVarHandle(backingHandler1_20_2);
} else {
NetworkStatePacketHandler$backingHandler1_20_2 = null;
}
} else {
NetworkStatePacketHandler$backingHandler1_20_2 = null;
}
}
{
Method factoryBind = getOrNull(() -> NetworkState.Unbound.class.getDeclaredMethod("bind" /* actually not obfuscated in 1.20.6 */, Function.class), NoSuchMethodException.class, NoClassDefFoundError.class);
if (factoryBind == null) {
factoryBind = getOrNull(() -> NetworkState.Unbound.class.getDeclaredMethod(resolver.mapMethodName(INTERMEDIARY, CLASSNAME_NetworkState$Factory, "method_61107", "(Ljava/util/function/Function;)Lnet/minecraft/class_9127;"), Function.class), NoSuchMethodException.class, NoClassDefFoundError.class);
}
if (factoryBind != null) {
factoryBind.setAccessible(true);
NetworkState$Factory$bind1_20_5 = MethodHandles
.privateLookupIn(NetworkState.Unbound.class, MethodHandles.lookup())
.unreflect(factoryBind);
} else {
NetworkState$Factory$bind1_20_5 = null;
}
}
clazzPlayStateFactories = getOrNull(() -> Class.forName(resolver.mapClassName(INTERMEDIARY, CLASSNAME_PlayStateFactories), false, MultiVersionUtil.class.getClassLoader()), ClassNotFoundException.class);
{
if (clazzPlayStateFactories != null) {
final Field playStateFactoriesC2S1_20_5 = getOrNull(() -> clazzPlayStateFactories.getDeclaredField(resolver.mapFieldName(INTERMEDIARY, CLASSNAME_PlayStateFactories, "field_48172", "L" + CLASSNAME_NetworkState$Factory.replace('.', '/') + ";")), NoSuchFieldException.class);
if (playStateFactoriesC2S1_20_5 != null) {
playStateFactoriesC2S1_20_5.setAccessible(true);
PlayStateFactories$C2S1_20_5 = MethodHandles
.privateLookupIn(clazzPlayStateFactories, MethodHandles.lookup())
.unreflectVarHandle(playStateFactoriesC2S1_20_5);
} else {
PlayStateFactories$C2S1_20_5 = null;
}
} else {
PlayStateFactories$C2S1_20_5 = null;
}
}
{
if (clazzPlayStateFactories != null) {
final Field playStateFactoriesS2C1_20_5 = getOrNull(() -> clazzPlayStateFactories.getDeclaredField(resolver.mapFieldName(INTERMEDIARY, CLASSNAME_PlayStateFactories, "field_48173", "L" + CLASSNAME_NetworkState$Factory.replace('.', '/') + ";")), NoSuchFieldException.class);
if (playStateFactoriesS2C1_20_5 != null) {
playStateFactoriesS2C1_20_5.setAccessible(true);
PlayStateFactories$S2C1_20_5 = MethodHandles
.privateLookupIn(clazzPlayStateFactories, MethodHandles.lookup())
.unreflectVarHandle(playStateFactoriesS2C1_20_5);
} else {
PlayStateFactories$S2C1_20_5 = null;
}
} else {
PlayStateFactories$S2C1_20_5 = null;
}
}
{
final Method writeNbt1_21_5 = getOrNull(() -> HungerManager.class.getDeclaredMethod(resolver.mapMethodName(INTERMEDIARY, CLASSNAME_HungerManager, "method_7582", "(Lnet/minecraft/class_2487;)V"), NbtCompound.class), NoSuchMethodException.class);
if (writeNbt1_21_5 != null) {
writeNbt1_21_5.setAccessible(true);
HungerManager$writeNbt1_21_5 = MethodHandles
.privateLookupIn(HungerManager.class, MethodHandles.lookup())
.unreflect(writeNbt1_21_5);
} else {
HungerManager$writeNbt1_21_5 = null;
}
}
{
final Method readNbt1_21_5 = getOrNull(() -> HungerManager.class.getDeclaredMethod(resolver.mapMethodName(INTERMEDIARY, CLASSNAME_HungerManager, "method_7584", "(Lnet/minecraft/class_2487;)V"), NbtCompound.class), NoSuchMethodException.class);
if (readNbt1_21_5 != null) {
readNbt1_21_5.setAccessible(true);
HungerManager$readNbt1_21_5 = MethodHandles
.privateLookupIn(HungerManager.class, MethodHandles.lookup())
.unreflect(readNbt1_21_5);
} else {
HungerManager$readNbt1_21_5 = null;
}
}
{
final Method getEntity1_21_8 = getOrNull(() -> Entity.class.getDeclaredMethod(resolver.mapFieldName(INTERMEDIARY, CLASSNAME_Entity, "method_37908", "()Lnet/minecraft/class_1937;")), NoSuchMethodException.class);
if (getEntity1_21_8 != null) {
getEntity1_21_8.setAccessible(true);
Entity$getEntity1_21_8 = MethodHandles
.privateLookupIn(Entity.class, MethodHandles.lookup())
.unreflect(getEntity1_21_8);
} else {
Entity$getEntity1_21_8 = null;
}
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private static List tryLocateFields(Class> clazz, Class> fieldType, boolean includeMixinMerged) {
final ImmutableList.Builder builder = ImmutableList.builder();
final Class> superclass = clazz.getSuperclass();
if (superclass != null) {
builder.addAll(tryLocateFields(superclass, fieldType, includeMixinMerged));
}
__outerloop:
for (Field field : clazz.getDeclaredFields()) {
if (!includeMixinMerged) {
for (Annotation annotation : field.getDeclaredAnnotations()) {
if (annotation.annotationType() == MixinMerged.class) {
continue __outerloop;
}
}
}
if (field.getType() == fieldType) {
builder.add(field);
}
}
return builder.build();
}
public static void init() {
}
public static Class> tryLocateClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
private static T getOrNull(SupplierThrowable supplier, Class extends Throwable>... catchExceptions) {
try {
return supplier.get();
} catch (Throwable t) {
for (Class extends Throwable> catchException : catchExceptions) {
if (catchException.isInstance(t)) {
return null;
}
}
throw new RuntimeException(t);
}
}
private interface SupplierThrowable {
T get() throws Throwable;
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/common/util/NetworkStates.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.common.util;
import net.minecraft.network.NetworkPhase;
public class NetworkStates {
public static String getName(NetworkPhase state) {
return switch (state) {
case HANDSHAKING -> "HANDSHAKING";
case PLAY -> "PLAY";
case STATUS -> "STATUS";
case LOGIN -> "LOGIN";
default -> state.toString();
};
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/RaknetifyFabricMixinPlugin.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin;
import com.llamalad7.mixinextras.MixinExtrasBootstrap;
import net.fabricmc.api.EnvType;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.VersionParsingException;
import net.fabricmc.loader.api.metadata.version.VersionPredicate;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import java.util.List;
import java.util.Set;
public class RaknetifyFabricMixinPlugin implements IMixinConfigPlugin {
public static final boolean AFTER_1_20_1;
public static final boolean AFTER_1_20_2;
public static final boolean AFTER_1_20_4;
public static final boolean AFTER_1_20_5;
public static final boolean AFTER_1_21_4;
public static final boolean AFTER_1_21_5;
public static final boolean AFTER_1_21_8;
public static final boolean AFTER_1_21_10;
static {
try {
AFTER_1_20_1 = VersionPredicate.parse(">1.20.1").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
AFTER_1_20_2 = VersionPredicate.parse(">1.20.2").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
AFTER_1_20_4 = VersionPredicate.parse(">1.20.4").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
AFTER_1_20_5 = VersionPredicate.parse(">1.20.5").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
AFTER_1_21_4 = VersionPredicate.parse(">1.21.4").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
AFTER_1_21_5 = VersionPredicate.parse(">1.21.5").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
AFTER_1_21_8 = VersionPredicate.parse(">1.21.8").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
AFTER_1_21_10 = VersionPredicate.parse(">1.21.10").test(FabricLoader.getInstance().getModContainer("minecraft").get().getMetadata().getVersion());
} catch (VersionParsingException e) {
throw new RuntimeException(e);
}
}
@Override
public void onLoad(String mixinPackage) {
System.setProperty("raknetserver.maxPacketLoss", String.valueOf(Integer.MAX_VALUE));
MixinExtrasBootstrap.init();
}
@Override
public String getRefMapperConfig() {
return null;
}
@Override
public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
if (mixinClassName.startsWith("com.ishland.raknetify.fabric.mixin.client.")) {
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.client.MixinMultiplayerServerListPinger1_20_2"))
return AFTER_1_20_1 && !AFTER_1_20_4;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.client.MixinMultiplayerServerListPinger1_20_5"))
return AFTER_1_20_4 && !AFTER_1_21_10;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.client.MixinMultiplayerServerListPinger1_21_11"))
return AFTER_1_21_10;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.client.hud.MixinDebugHud1_21_8"))
return !AFTER_1_21_8;
return true;
} else {
return false;
}
}
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.server.MixinServerPlayNetworkHandler1_20_1"))
return !AFTER_1_20_1;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.server.MixinServerCommonNetworkHandler"))
return AFTER_1_20_1;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.server.MixinPlayerManager1_20_2"))
return AFTER_1_20_1;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.common.MixinClientConnection1_20_2"))
return AFTER_1_20_1;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.server.MixinPlayerManager1_20_1"))
return !AFTER_1_20_1;
if (mixinClassName.equals("com.ishland.raknetify.fabric.mixin.access.INetworkState1_20_4"))
return !AFTER_1_20_4;
return true;
}
@Override
public void acceptTargets(Set myTargets, Set otherTargets) {
}
@Override
public List getMixins() {
return null;
}
@Override
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
@Override
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IClientConnection.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import io.netty.channel.Channel;
import net.minecraft.network.ClientConnection;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ClientConnection.class)
public interface IClientConnection {
@Accessor
Channel getChannel();
@Accessor
void setEncrypted(boolean encrypted);
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IClientPlayNetworkHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.ClientConnection;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ClientPlayNetworkHandler.class)
public interface IClientPlayNetworkHandler {
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IDebugHudEntries.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import net.minecraft.client.gui.hud.debug.DebugHudEntries;
import net.minecraft.client.gui.hud.debug.DebugHudEntry;
import net.minecraft.util.Identifier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(DebugHudEntries.class)
public interface IDebugHudEntries {
@Invoker
static Identifier invokeRegister(Identifier id, DebugHudEntry entry) {
throw new AbstractMethodError();
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/INetworkState1_20_4.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import net.minecraft.network.NetworkPhase;
import net.minecraft.network.NetworkSide;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Map;
@Pseudo
@Mixin(targets = "net/minecraft/class_2539")
public interface INetworkState1_20_4 {
@Dynamic
@Accessor(value = "field_20595", remap = false)
Map getPacketHandlers();
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/INetworkStateInternalPacketHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import net.minecraft.network.NetworkPhase;
import net.minecraft.network.packet.Packet;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(targets = "net/minecraft/class_2539$class_4532")
public interface INetworkStateInternalPacketHandler {
@Accessor(value = "field_20596")
Object2IntMap>> getPacketIds();
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IPacketCodecDispatcher.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import io.netty.buffer.ByteBuf;
import net.minecraft.network.handler.PacketCodecDispatcher;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.List;
@Mixin(PacketCodecDispatcher.class)
public interface IPacketCodecDispatcher {
@Accessor
List> getPacketTypes();
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IPacketCodecDispatcherPacketType.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import net.minecraft.network.handler.PacketCodecDispatcher;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(PacketCodecDispatcher.PacketType.class)
public interface IPacketCodecDispatcherPacketType {
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IPacketEncryptionManager.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.network.encryption.PacketEncryptionManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import javax.crypto.ShortBufferException;
@Mixin(PacketEncryptionManager.class)
public interface IPacketEncryptionManager {
@Invoker
ByteBuf invokeDecrypt(ChannelHandlerContext context, ByteBuf buf) throws ShortBufferException;
@Invoker
void invokeEncrypt(ByteBuf buf, ByteBuf result) throws ShortBufferException;
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IServerPlayNetworkHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(ServerPlayNetworkHandler.class)
public interface IServerPlayNetworkHandler {
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/access/IWorld.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.access;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(World.class)
public interface IWorld {
@Accessor("isClient")
boolean raknetify$isClient();
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/MixinClientPlayNetworkHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.fabric.common.util.MultiVersionUtil;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import io.netty.channel.Channel;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientPlayNetworkHandler.class)
public class MixinClientPlayNetworkHandler {
@Inject(method = "onGameJoin", at = @At("RETURN"))
private void postGameJoin(GameJoinS2CPacket packet, CallbackInfo ci) {
final Channel channel = ((IClientConnection) MultiVersionUtil.ClientPlayNetworkHandler$connection.get((ClientPlayNetworkHandler) (Object) this)).getChannel();
if (channel == null) {
//noinspection RedundantStringFormatCall
System.err.println("Raknetify: Warning: %s don't have valid channel when logged in, not sending sync packet".formatted(this));
return;
}
channel.eventLoop().execute(() -> channel.write(RakNetSimpleMultiChannelCodec.SIGNAL_START_MULTICHANNEL));
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/MixinConnectionScreen1.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client;
import com.ishland.raknetify.fabric.common.connection.RakNetClientConnectionUtil;
import com.ishland.raknetify.common.util.PrefixUtil;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import io.netty.channel.ChannelFuture;
import net.minecraft.client.network.ServerAddress;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.NetworkingBackend;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.net.InetSocketAddress;
@Mixin(targets = "net/minecraft/client/gui/screen/multiplayer/ConnectScreen$1")
public class MixinConnectionScreen1 extends Thread {
@Mutable
@Shadow
@Final
ServerAddress field_33737;
@Unique
private boolean isRaknet = false;
@Unique
private boolean raknetLargeMTU = false;
@Inject(method = "*", at = @At("RETURN"), remap = false)
private void onInit(CallbackInfo ci) {
final PrefixUtil.Info info = PrefixUtil.getInfo(this.field_33737.getAddress());
if (info.useRakNet()) {
this.isRaknet = true;
this.raknetLargeMTU = info.largeMTU();
this.field_33737 = new ServerAddress(info.stripped(), this.field_33737.getPort());
}
}
@Dynamic
@WrapOperation(method = "run()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;method_10753(Ljava/net/InetSocketAddress;Z)Lnet/minecraft/network/ClientConnection;"), require = 0)
private ClientConnection connectRaknet(InetSocketAddress address, boolean useEpoll, Operation original) {
return this.isRaknet ? RakNetClientConnectionUtil.connect(address, useEpoll, this.raknetLargeMTU, original, false) : original.call(address, useEpoll);
}
@Dynamic
@WrapOperation(method = "run()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;method_52271(Ljava/net/InetSocketAddress;ZLnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;"), require = 0)
private ChannelFuture connectRaknet(InetSocketAddress address, boolean useEpoll, ClientConnection connection, Operation original) {
return this.isRaknet ? RakNetClientConnectionUtil.connect(address, useEpoll, this.raknetLargeMTU, original, connection) : original.call(address, useEpoll, connection);
}
@WrapOperation(method = "run()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;connect(Ljava/net/InetSocketAddress;Lnet/minecraft/network/NetworkingBackend;Lnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;"), require = 0)
private ChannelFuture connectRaknet(InetSocketAddress address, @Coerce Object backend, ClientConnection connection, Operation original) {
return this.isRaknet ? RakNetClientConnectionUtil.connect(address, backend, this.raknetLargeMTU, original, connection) : original.call(address, backend, connection);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/MixinMultiplayerServerListPinger.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client;
import com.ishland.raknetify.fabric.common.connection.RakNetClientConnectionUtil;
import com.ishland.raknetify.common.util.PrefixUtil;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.minecraft.client.network.MultiplayerServerListPinger;
import net.minecraft.client.network.ServerAddress;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.network.ClientConnection;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import java.net.InetSocketAddress;
@Mixin(MultiplayerServerListPinger.class)
public abstract class MixinMultiplayerServerListPinger {
@Dynamic
@WrapOperation(method = {"add", "method_3003"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ServerAddress;parse(Ljava/lang/String;)Lnet/minecraft/client/network/ServerAddress;"))
private ServerAddress modifyRaknetAddress(String address, Operation original) {
final PrefixUtil.Info info = PrefixUtil.getInfo(address);
return original.call(info.stripped());
}
@Dynamic
@WrapOperation(method = {"add", "method_3003"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;method_10753(Ljava/net/InetSocketAddress;Z)Lnet/minecraft/network/ClientConnection;"), require = 0)
private ClientConnection redirectConnect(InetSocketAddress address, boolean useEpoll, Operation original, ServerInfo entry, Runnable runnable) {
final PrefixUtil.Info info = PrefixUtil.getInfo(entry.address);
return info.useRakNet() ? RakNetClientConnectionUtil.connect(address, useEpoll, info.largeMTU(), original, false) : original.call(address, useEpoll);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/MixinMultiplayerServerListPinger1.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import com.llamalad7.mixinextras.injector.v2.WrapWithCondition;
import io.netty.channel.Channel;
import net.minecraft.client.network.MultiplayerServerListPinger;
import net.minecraft.client.network.ServerAddress;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.NetworkingBackend;
import net.minecraft.network.listener.ClientQueryPacketListener;
import network.ycc.raknet.RakNet;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.net.InetSocketAddress;
@Mixin(targets = "net/minecraft/client/network/MultiplayerServerListPinger$1")
public abstract class MixinMultiplayerServerListPinger1 implements ClientQueryPacketListener {
@Shadow
@Final
ClientConnection field_3774; // synthetic
@Shadow
@Final
ServerInfo field_3776; // synthetic
@Inject(method = "onResponse(Lnet/minecraft/network/packet/s2c/query/QueryResponseS2CPacket;)V", at = @At("RETURN"))
private void setPingImmediately(CallbackInfo ci) {
final Channel channel = ((IClientConnection) field_3774).getChannel();
if (channel.config() instanceof RakNet.Config config) {
field_3776.ping = config.getRTTNanos() / 1_000_000;
}
}
@Dynamic
@WrapWithCondition(method = {"method_10839(Lnet/minecraft/class_2561;)V", "onDisconnected"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/MultiplayerServerListPinger;method_3001(Ljava/net/InetSocketAddress;Lnet/minecraft/client/network/ServerAddress;Lnet/minecraft/client/network/ServerInfo;)V"), require = 0)
private boolean noPingRaknet(MultiplayerServerListPinger instance, InetSocketAddress socketAddress, ServerAddress address, ServerInfo serverInfo) {
final Channel channel = ((IClientConnection) field_3774).getChannel();
return !(channel.config() instanceof RakNet.Config);
}
@WrapWithCondition(method = "onDisconnected", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/MultiplayerServerListPinger;ping(Ljava/net/InetSocketAddress;Lnet/minecraft/client/network/ServerAddress;Lnet/minecraft/client/network/ServerInfo;Lnet/minecraft/network/NetworkingBackend;)V"), require = 0)
private boolean noPingRaknet(MultiplayerServerListPinger instance, InetSocketAddress socketAddress, ServerAddress address, ServerInfo serverInfo, NetworkingBackend backend) {
final Channel channel = ((IClientConnection) field_3774).getChannel();
return !(channel.config() instanceof RakNet.Config);
}
@Dynamic
@WrapWithCondition(method = "method_10839(Lnet/minecraft/class_2561;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/MultiplayerServerListPinger;method_3001(Ljava/net/InetSocketAddress;Lnet/minecraft/client/network/ServerInfo;)V"), require = 0)
private boolean noPingRaknet(MultiplayerServerListPinger instance, InetSocketAddress address, ServerInfo info) {
final Channel channel = ((IClientConnection) field_3774).getChannel();
return !(channel.config() instanceof RakNet.Config);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/MixinMultiplayerServerListPinger1_20_2.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client;
import com.ishland.raknetify.common.util.PrefixUtil;
import com.ishland.raknetify.fabric.common.connection.RakNetClientConnectionUtil;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.minecraft.client.network.MultiplayerServerListPinger;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.network.ClientConnection;
import net.minecraft.util.profiler.log.DebugSampleLog;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.net.InetSocketAddress;
@Mixin(MultiplayerServerListPinger.class)
public class MixinMultiplayerServerListPinger1_20_2 {
@Dynamic
@WrapOperation(method = {"add", "method_3003"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;method_10753(Ljava/net/InetSocketAddress;ZLnet/minecraft/class_8743;)Lnet/minecraft/network/ClientConnection;"))
private ClientConnection redirectConnect(InetSocketAddress address, boolean useEpoll, DebugSampleLog log, Operation original, ServerInfo entry, Runnable runnable) {
final PrefixUtil.Info info = PrefixUtil.getInfo(entry.address);
return info.useRakNet() ? RakNetClientConnectionUtil.connect(address, useEpoll, info.largeMTU(), original, true) : original.call(address, useEpoll, null);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/MixinMultiplayerServerListPinger1_20_5.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client;
import com.ishland.raknetify.common.util.PrefixUtil;
import com.ishland.raknetify.fabric.common.connection.RakNetClientConnectionUtil;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.minecraft.client.network.MultiplayerServerListPinger;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.network.ClientConnection;
import net.minecraft.util.profiler.MultiValueDebugSampleLogImpl;
import net.minecraft.util.profiler.log.DebugSampleLog;
import net.minecraft.util.profiler.log.MultiValueDebugSampleLog;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.net.InetSocketAddress;
@Mixin(MultiplayerServerListPinger.class)
public class MixinMultiplayerServerListPinger1_20_5 {
@Dynamic
@WrapOperation(method = {"add", "method_3003"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;method_10753(Ljava/net/InetSocketAddress;ZLnet/minecraft/util/profiler/MultiValueDebugSampleLogImpl;)Lnet/minecraft/network/ClientConnection;"))
private ClientConnection redirectConnect(InetSocketAddress address, boolean useEpoll, MultiValueDebugSampleLogImpl log, Operation original, ServerInfo entry, Runnable runnable) {
final PrefixUtil.Info info = PrefixUtil.getInfo(entry.address);
return info.useRakNet() ? RakNetClientConnectionUtil.connect(address, useEpoll, info.largeMTU(), original, true) : original.call(address, useEpoll, null);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/MixinMultiplayerServerListPinger1_21_11.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client;
import com.ishland.raknetify.common.util.PrefixUtil;
import com.ishland.raknetify.fabric.common.connection.RakNetClientConnectionUtil;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import net.minecraft.client.network.MultiplayerServerListPinger;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.NetworkingBackend;
import net.minecraft.util.profiler.MultiValueDebugSampleLogImpl;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.net.InetSocketAddress;
@Mixin(MultiplayerServerListPinger.class)
public class MixinMultiplayerServerListPinger1_21_11 {
@WrapOperation(method = "add", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;connect(Ljava/net/InetSocketAddress;Lnet/minecraft/network/NetworkingBackend;Lnet/minecraft/util/profiler/MultiValueDebugSampleLogImpl;)Lnet/minecraft/network/ClientConnection;"))
private ClientConnection redirectConnect(InetSocketAddress address, NetworkingBackend backend, MultiValueDebugSampleLogImpl packetSizeLog, Operation original, ServerInfo entry) {
final PrefixUtil.Info info = PrefixUtil.getInfo(entry.address);
return info.useRakNet() ? RakNetClientConnectionUtil.connect(address, backend, info.largeMTU(), original) : original.call(address, backend, null);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/client/hud/MixinDebugHud1_21_8.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.client.hud;
import com.ishland.raknetify.fabric.common.client.DebugHudUtil;
import net.minecraft.client.gui.hud.DebugHud;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
@Mixin(DebugHud.class)
public class MixinDebugHud1_21_8 {
@Dynamic
@Inject(method = "method_1835", at = @At("RETURN"))
private void getLeftText(CallbackInfoReturnable> cir) {
DebugHudUtil.getDebugString(cir.getReturnValue()::add);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/MixinCCConnect.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.RakNetConnectionUtil;
import com.ishland.raknetify.common.connection.RaknetifyEventLoops;
import com.ishland.raknetify.common.util.ThreadLocalUtil;
import com.ishland.raknetify.fabric.common.connection.RakNetFabricConnectionUtil;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Share;
import com.llamalad7.mixinextras.sugar.ref.LocalRef;
import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.ReflectiveChannelFactory;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import net.minecraft.network.ClientConnection;
import network.ycc.raknet.RakNet;
import network.ycc.raknet.client.channel.RakNetClientThreadedChannel;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.net.InetSocketAddress;
@Mixin(ClientConnection.class)
public class MixinCCConnect {
@Dynamic("method_10753, method_52271 for compat")
@WrapOperation(method = {"connect(Ljava/net/InetSocketAddress;Lnet/minecraft/network/NetworkingBackend;Lnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;", "method_52271(Ljava/net/InetSocketAddress;ZLnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;", "method_10753(Ljava/net/InetSocketAddress;Z)Lnet/minecraft/network/ClientConnection;", "method_10753"}, at = @At(value = "INVOKE", target = "Lio/netty/bootstrap/Bootstrap;group(Lio/netty/channel/EventLoopGroup;)Lio/netty/bootstrap/AbstractBootstrap;", remap = false), require = 1)
private static AbstractBootstrap redirectGroup(Bootstrap instance, EventLoopGroup eventLoopGroup, Operation> original, InetSocketAddress address, @Share("raknetify$eventLoop") LocalRef raknetify$eventLoop) {
raknetify$eventLoop.set(eventLoopGroup);
return ThreadLocalUtil.isInitializingRaknet()
? original.call(instance, RaknetifyEventLoops.DEFAULT_CLIENT_EVENT_LOOP_GROUP.get())
: original.call(instance, eventLoopGroup);
}
@Dynamic("method_10753, method_52271 for compat")
@WrapOperation(method = {"connect(Ljava/net/InetSocketAddress;Lnet/minecraft/network/NetworkingBackend;Lnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;", "method_52271(Ljava/net/InetSocketAddress;ZLnet/minecraft/network/ClientConnection;)Lio/netty/channel/ChannelFuture;", "method_10753(Ljava/net/InetSocketAddress;Z)Lnet/minecraft/network/ClientConnection;", "method_10753"}, at = @At(value = "INVOKE", target = "Lio/netty/bootstrap/Bootstrap;channel(Ljava/lang/Class;)Lio/netty/bootstrap/AbstractBootstrap;", remap = false), require = 1)
private static AbstractBootstrap redirectChannel(Bootstrap instance, Class extends SocketChannel> aClass, Operation> original, InetSocketAddress address, @Share("raknetify$eventLoop") LocalRef raknetify$eventLoop) {
EventLoopGroup eventLoopGroup = raknetify$eventLoop.get();
return ThreadLocalUtil.isInitializingRaknet()
? instance.channelFactory(() -> {
final boolean initializingRaknetLargeMTU = ThreadLocalUtil.isInitializingRaknetLargeMTU();
final RakNetClientThreadedChannel channel = new RakNetClientThreadedChannel(() -> {
final DatagramChannel channel1 = RakNetFabricConnectionUtil.fromSocketChannel(aClass);
channel1.config().setOption(ChannelOption.IP_TOS, RakNetConnectionUtil.DEFAULT_IP_TOS);
if (initializingRaknetLargeMTU)
channel1.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(Constants.LARGE_MTU + 512).maxMessagesPerRead(128));
else
channel1.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(Constants.DEFAULT_MTU + 512).maxMessagesPerRead(128));
return channel1;
});
RakNet.config(channel).setMTU(initializingRaknetLargeMTU ? Constants.LARGE_MTU : Constants.DEFAULT_MTU);
channel.setProvidedParentEventLoop(eventLoopGroup.next());
return channel;
})
: original.call(instance, aClass);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/MixinClientConnection.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.util.DebugUtil;
import com.ishland.raknetify.fabric.common.util.NetworkStates;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.NetworkPhase;
import net.minecraft.network.NetworkSide;
import net.minecraft.network.listener.PacketListener;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
@Mixin(ClientConnection.class)
public abstract class MixinClientConnection {
@Shadow
private Channel channel;
@Shadow public abstract SocketAddress getAddress();
@Shadow private SocketAddress address;
@Shadow public abstract NetworkSide getSide();
@Shadow private volatile @Nullable PacketListener packetListener;
@Unique
private volatile boolean isClosing = false;
@Redirect(method = {"disconnect(Lnet/minecraft/text/Text;)V", "disconnect(Lnet/minecraft/network/DisconnectionInfo;)V"}, at = @At(value = "INVOKE", target = "Lio/netty/channel/ChannelFuture;awaitUninterruptibly()Lio/netty/channel/ChannelFuture;", remap = false), require = 1)
private ChannelFuture noDisconnectWait(ChannelFuture instance) {
isClosing = true;
// if (instance.channel().eventLoop().inEventLoop()) {
// return instance; // no-op
// } else {
// return instance.awaitUninterruptibly();
// }
return instance;
}
@Redirect(method = "*", at = @At(value = "INVOKE", target = "Lio/netty/channel/Channel;isOpen()Z", remap = false))
private boolean redirectIsOpen(Channel instance) {
return this.channel != null && (this.channel.isOpen() && !this.isClosing);
}
// @Inject(method = "channelActive", at = @At("HEAD"))
// private void onChannelActive(ChannelHandlerContext ctx, CallbackInfo ci) {
// final Channel channel = ctx.channel();
// if (channel.config() instanceof RakNet.Config config) {
// if (this.side == NetworkSide.SERVERBOUND) {
// System.out.println(String.format("RakNet connection from %s, mtu %d", channel.remoteAddress(), config.getMTU()));
// } else if (this.side == NetworkSide.CLIENTBOUND) {
// System.out.println(String.format("RakNet conncted to %s, mtu %d", channel.remoteAddress(), config.getMTU()));
// }
// }
// }
@Inject(method = "exceptionCaught", at = @At("HEAD"))
private void onExceptionCaught(ChannelHandlerContext context, Throwable ex, CallbackInfo ci) {
if (ex instanceof ClosedChannelException) return;
if (Constants.DEBUG) {
System.err.println("Exception caught for connection %s".formatted(this.channel));
for (String s : DebugUtil.printChannelDetails(this.channel).split("\n")) {
System.err.println(" " + s);
}
ex.printStackTrace();
} else {
final NetworkPhase state;
Object handler = this.channel.attr(AttributeKey.valueOf("protocol")).get(); // pre-1.20.2
if (handler != null) {
if (handler instanceof NetworkPhase state1) {
state = state1;
} else {
System.err.println("Unknown handler type: " + handler.getClass().getName());
state = null;
}
} else {
final PacketListener packetListener1 = this.packetListener;
state = packetListener1 != null ? packetListener1.getPhase() : null;
}
if (state != null && state != NetworkPhase.HANDSHAKING) {
System.err.println(String.format("%s %s %s", this.address, NetworkStates.getName(state), ex.toString()));
}
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/MixinClientConnection1.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common;
import com.ishland.raknetify.fabric.common.connection.RakNetFabricConnectionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(targets = "net/minecraft/network/ClientConnection$1")
public abstract class MixinClientConnection1 extends ChannelInitializer {
@Inject(method = "initChannel(Lio/netty/channel/Channel;)V", at = @At("HEAD"))
private void onChannelInit(Channel channel, CallbackInfo ci) {
RakNetFabricConnectionUtil.initChannel(channel);
}
@Inject(method = "initChannel(Lio/netty/channel/Channel;)V", at = @At("RETURN"))
private void postChannelInit(Channel channel, CallbackInfo ci) {
RakNetFabricConnectionUtil.postInitChannel(channel, true);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/MixinClientConnection1_20_2.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common;
import com.ishland.raknetify.common.connection.SimpleMetricsLogger;
import io.netty.channel.Channel;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.handler.PacketSizeLogger;
import network.ycc.raknet.RakNet;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientConnection.class)
public class MixinClientConnection1_20_2 {
@Shadow private Channel channel;
@Shadow private @Nullable PacketSizeLogger packetSizeLogger;
@Unique
private long raknetify$lastBytesIn = 0L;
@Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/handler/PacketSizeLogger;push()V"))
private void onPacketLoggerPush(CallbackInfo ci) {
PacketSizeLogger logger = this.packetSizeLogger;
if (logger != null && this.channel.config() instanceof RakNet.Config config && config.getMetrics() instanceof SimpleMetricsLogger simpleMetricsLogger) {
long bytesIn = simpleMetricsLogger.getBytesIn();
logger.increment((int) (bytesIn - this.raknetify$lastBytesIn));
this.raknetify$lastBytesIn = bytesIn;
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/MixinServerAddress.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.util.PrefixUtil;
import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import net.minecraft.client.network.ServerAddress;
import org.spongepowered.asm.mixin.Mixin;
@Mixin(ServerAddress.class)
public class MixinServerAddress {
@WrapMethod(method = "parse")
private static ServerAddress wrapParsing(String address, Operation original) {
PrefixUtil.Info info = PrefixUtil.getInfo(address);
if (info.useRakNet()) {
ServerAddress addr = original.call(info.stripped());
return new ServerAddress(
(info.largeMTU() ? Constants.RAKNET_LARGE_MTU_PREFIX : Constants.RAKNET_PREFIX) + addr.getAddress(),
addr.getPort()
);
} else {
return original.call(address);
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/encryption/MixinClientConnection.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common.encryption;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.MultiChannellingEncryption;
import io.netty.channel.Channel;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.encryption.PacketDecryptor;
import net.minecraft.network.encryption.PacketEncryptionManager;
import net.minecraft.network.encryption.PacketEncryptor;
import network.ycc.raknet.RakNet;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import javax.crypto.Cipher;
@Mixin(ClientConnection.class)
public class MixinClientConnection {
@Shadow
private boolean encrypted;
@Shadow
private Channel channel;
@Inject(method = "setupEncryption", at = @At("HEAD"), cancellable = true)
public void beforeSetupEncryption(Cipher decryptionCipher, Cipher encryptionCipher, CallbackInfo ci) {
if (this.channel.config() instanceof RakNet.Config) {
ci.cancel();
this.encrypted = true;
try {
this.channel.pipeline().remove("decrypt");
this.channel.pipeline().remove("encrypt");
} catch (Throwable ignored) {
}
try {
this.channel.pipeline().remove(MultiChannellingEncryption.NAME);
} catch (Throwable ignored) {
}
this.channel.pipeline().addBefore(MultiChannelingStreamingCompression.NAME, MultiChannellingEncryption.NAME,
new MultiChannellingEncryption(decryptionCipher, encryptionCipher));
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/encryption/MixinPacketDecryptor.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common.encryption;
import com.ishland.raknetify.fabric.common.connection.encryption.PacketEncryptionManagerInterface;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.network.encryption.PacketDecryptor;
import net.minecraft.network.encryption.PacketEncryptionManager;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.List;
@Mixin(PacketDecryptor.class)
public class MixinPacketDecryptor {
@Shadow @Final private PacketEncryptionManager manager;
@Inject(method = "decode(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Ljava/util/List;)V", at = @At("HEAD"))
private void preDecrypt(ChannelHandlerContext ctx, ByteBuf byteBuf, List list, CallbackInfo ci) {
((PacketEncryptionManagerInterface) this.manager).setContext(ctx);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/encryption/MixinPacketEncryptionManager.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common.encryption;
import com.ishland.raknetify.fabric.common.connection.encryption.PacketEncryptionManagerInterface;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.network.encryption.PacketEncryptionManager;
import network.ycc.raknet.RakNet;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;
@Mixin(PacketEncryptionManager.class)
public class MixinPacketEncryptionManager implements PacketEncryptionManagerInterface {
@Unique
private ChannelHandlerContext ctx;
@Override
public void setContext(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Redirect(method = "decrypt", at = @At(value = "INVOKE", target = "Ljavax/crypto/Cipher;update([BII[BI)I"))
private int redirectDecrypt(Cipher instance, byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
if (ctx.channel().config() instanceof RakNet.Config) {
return instance.doFinal(input, inputOffset, inputLen, output, outputOffset);
} else {
return instance.update(input, inputOffset, inputLen, output, outputOffset);
}
}
@Redirect(method = "encrypt", at = @At(value = "INVOKE", target = "Ljavax/crypto/Cipher;update([BII[B)I"))
private int redirectEncrypt(Cipher instance, byte[] input, int inputOffset, int inputLen, byte[] output) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
if (ctx.channel().config() instanceof RakNet.Config) {
return instance.doFinal(input, inputOffset, inputLen, output);
} else {
return instance.update(input, inputOffset, inputLen, output);
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/encryption/MixinPacketEncryptor.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common.encryption;
import com.ishland.raknetify.fabric.common.connection.encryption.PacketEncryptionManagerInterface;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.network.encryption.PacketEncryptionManager;
import net.minecraft.network.encryption.PacketEncryptor;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PacketEncryptor.class)
public class MixinPacketEncryptor {
@Shadow @Final private PacketEncryptionManager manager;
@Inject(method = "encode(Lio/netty/channel/ChannelHandlerContext;Lio/netty/buffer/ByteBuf;Lio/netty/buffer/ByteBuf;)V", at = @At("HEAD"))
private void preEncrypt(ChannelHandlerContext ctx, ByteBuf byteBuf, ByteBuf byteBuf2, CallbackInfo ci) {
((PacketEncryptionManagerInterface) this.manager).setContext(ctx);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/quirks/MixinPlayerEntity.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common.quirks;
import com.ishland.raknetify.fabric.common.quirks.ClientHungerManager;
import com.ishland.raknetify.fabric.common.util.LegacySupportUtil;
import com.ishland.raknetify.fabric.mixin.access.IWorld;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.HungerManager;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerEntity.class)
public abstract class MixinPlayerEntity extends LivingEntity {
@Shadow protected HungerManager hungerManager;
protected MixinPlayerEntity(EntityType extends LivingEntity> entityType, World world) {
super(entityType, world);
}
@Inject(method = "", at = @At("RETURN"), remap = false)
private void replaceHungerManager(CallbackInfo ci) {
if (((IWorld) LegacySupportUtil.getEntityWorld(this)).raknetify$isClient()) {
this.hungerManager = ClientHungerManager.from(this.hungerManager);
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/common/quirks/MixinSampleSubscriptionTracker.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.common.quirks;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Queue;
@Pseudo
@Mixin(targets = "net.minecraft.class_9188")
public class MixinSampleSubscriptionTracker {
@Shadow(aliases = "field_48812") @Final private Queue> pendingQueue;
@Dynamic
@Inject(method = "method_56654", at = @At("RETURN"))
private void cleanQueue(CallbackInfo ci) {
this.pendingQueue.clear();
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/compat/fabricapi/MixinServerLoginNetworkAddon.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.compat.fabricapi;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import net.minecraft.network.ClientConnection;
import net.minecraft.server.MinecraftServer;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.lang.reflect.Method;
@Pseudo
@Mixin(targets = "net.fabricmc.fabric.impl.networking.server.ServerLoginNetworkAddon")
public class MixinServerLoginNetworkAddon {
@Shadow
@Final
private ClientConnection connection;
@Dynamic("Pseudo")
@Redirect(method = "sendCompressionPacket()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getNetworkCompressionThreshold()I"))
private int stopCompressionIfStreamingCompressionExists(MinecraftServer server) {
final MultiChannelingStreamingCompression compression = ((IClientConnection) this.connection).getChannel().pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
System.out.println("Raknetify: Preventing vanilla compression as streaming compression is enabled");
return -1;
}
return server.getNetworkCompressionThreshold();
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/compat/krypton/MixinServerLoginNetworkHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.compat.krypton;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.encryption.NetworkEncryptionException;
import net.minecraft.network.encryption.NetworkEncryptionUtils;
import net.minecraft.network.packet.c2s.login.LoginKeyC2SPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerLoginNetworkHandler;
import network.ycc.raknet.RakNet;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.security.PrivateKey;
@Mixin(ServerLoginNetworkHandler.class)
public class MixinServerLoginNetworkHandler {
@Shadow
@Final
public ClientConnection connection;
@Shadow @Final private MinecraftServer server;
@Shadow @Final private byte[] nonce;
@Inject(method = "onKey", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/ClientConnection;setupEncryption(Ljavax/crypto/Cipher;Ljavax/crypto/Cipher;)V", shift = At.Shift.AFTER))
private void afterSetupEncryption(LoginKeyC2SPacket packet, CallbackInfo ci) throws NetworkEncryptionException {
final ChannelPipeline pipeline = ((IClientConnection) this.connection).getChannel().pipeline();
if (((IClientConnection) this.connection).getChannel().config() instanceof RakNet.Config) {
final ChannelHandler decrypt = pipeline.get("decrypt");
final ChannelHandler encrypt = pipeline.get("encrypt");
if (decrypt != null && (decrypt.getClass().getName().equals("me.steinborn.krypton.mod.shared.network.pipeline.MinecraftCipherDecoder")) &&
encrypt != null && (encrypt.getClass().getName().equals("me.steinborn.krypton.mod.shared.network.pipeline.MinecraftCipherEncoder"))) {
System.out.println("Raknetify: Krypton detected, applying compatibility");
pipeline.remove("decrypt");
pipeline.remove("encrypt");
// TODO [VanillaCopy]
PrivateKey privateKey = this.server.getKeyPair().getPrivate();
SecretKey secretKey = packet.decryptSecretKey(privateKey);
Cipher cipher = NetworkEncryptionUtils.cipherFromKey(2, secretKey);
Cipher cipher2 = NetworkEncryptionUtils.cipherFromKey(1, secretKey);
((IClientConnection) this.connection).setEncrypted(false);
this.connection.setupEncryption(cipher, cipher2);
}
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/compat/package-info.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.compat;
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/compat/qsl/MixinServerLoginNetworkAddon.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.compat.qsl;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import net.minecraft.network.ClientConnection;
import net.minecraft.server.MinecraftServer;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.lang.reflect.Method;
@Pseudo
@Mixin(targets = "org.quiltmc.qsl.networking.impl.server.ServerLoginNetworkAddon")
public class MixinServerLoginNetworkAddon {
@Shadow
@Final
private ClientConnection connection;
@Dynamic("Pseudo")
@Redirect(method = "sendCompressionPacket()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getNetworkCompressionThreshold()I"))
private int stopCompressionIfStreamingCompressionExists(MinecraftServer server) {
final MultiChannelingStreamingCompression compression = ((IClientConnection) this.connection).getChannel().pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
System.out.println("Raknetify: Preventing vanilla compression as streaming compression is enabled");
return -1;
}
return server.getNetworkCompressionThreshold();
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/package-info.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin;
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/server/MixinPlayerManager1_20_1.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.server;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import io.netty.channel.Channel;
import net.minecraft.network.ClientConnection;
import net.minecraft.server.PlayerManager;
import net.minecraft.server.network.ServerPlayerEntity;
import network.ycc.raknet.RakNet;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerManager.class)
public class MixinPlayerManager1_20_1 {
@Dynamic
@Inject(method = {"onPlayerConnect", "method_12975"}, at = @At("HEAD"), require = 0)
private void onJoin(ClientConnection connection, ServerPlayerEntity player, int latency, CallbackInfo ci) {
if (((IClientConnection) connection).getChannel().config() instanceof RakNet.Config config) {
System.out.println(String.format("Raknetify: %s logged in via RakNet, mtu %d", player.getName().getString(), config.getMTU()));
}
}
@Surrogate
private void onJoin(ClientConnection connection, ServerPlayerEntity player, CallbackInfo ci) {
if (((IClientConnection) connection).getChannel().config() instanceof RakNet.Config config) {
System.out.println(String.format("Raknetify: %s logged in via RakNet, mtu %d", player.getName().getString(), config.getMTU()));
}
}
@Dynamic
@Inject(method = {"onPlayerConnect", "method_12975"}, at = @At("RETURN"), require = 0)
private void postJoin(ClientConnection connection, ServerPlayerEntity player, int latency, CallbackInfo ci) {
final Channel channel = ((IClientConnection) connection).getChannel();
if (channel == null) {
//noinspection RedundantStringFormatCall
System.err.println("Raknetify: Warning: %s don't have valid channel when logged in, not sending sync packet".formatted(this));
return;
}
channel.write(RakNetSimpleMultiChannelCodec.SIGNAL_START_MULTICHANNEL);
}
@Surrogate
private void postJoin(ClientConnection connection, ServerPlayerEntity player, CallbackInfo ci) {
final Channel channel = ((IClientConnection) connection).getChannel();
if (channel == null) {
//noinspection RedundantStringFormatCall
System.err.println("Raknetify: Warning: %s don't have valid channel when logged in, not sending sync packet".formatted(this));
return;
}
channel.write(RakNetSimpleMultiChannelCodec.SIGNAL_START_MULTICHANNEL);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/server/MixinPlayerManager1_20_2.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.server;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import io.netty.channel.Channel;
import net.minecraft.network.ClientConnection;
import net.minecraft.server.PlayerManager;
import net.minecraft.server.network.ConnectedClientData;
import net.minecraft.server.network.ServerPlayerEntity;
import network.ycc.raknet.RakNet;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerManager.class)
public class MixinPlayerManager1_20_2 {
@Inject(method = "onPlayerConnect", at = @At("HEAD"))
private void onJoin(ClientConnection connection, ServerPlayerEntity player, ConnectedClientData clientData, CallbackInfo ci) {
if (((IClientConnection) connection).getChannel().config() instanceof RakNet.Config config) {
System.out.println(String.format("Raknetify: %s logged in via RakNet, mtu %d", player.getName().getString(), config.getMTU()));
}
}
@Inject(method = "onPlayerConnect", at = @At("RETURN"))
private void postJoin(ClientConnection connection, ServerPlayerEntity player, ConnectedClientData clientData, CallbackInfo ci) {
final Channel channel = ((IClientConnection) connection).getChannel();
if (channel == null) {
//noinspection RedundantStringFormatCall
System.err.println("Raknetify: Warning: %s don't have valid channel when logged in, not sending sync packet".formatted(this));
return;
}
channel.write(RakNetSimpleMultiChannelCodec.SIGNAL_START_MULTICHANNEL);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/server/MixinServerCommonNetworkHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.server;
import com.ishland.raknetify.fabric.common.util.MultiVersionUtil;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import com.llamalad7.mixinextras.injector.WrapWithCondition;
import io.netty.channel.Channel;
import net.minecraft.network.ClientConnection;
import net.minecraft.network.listener.ServerCommonPacketListener;
import net.minecraft.server.network.ServerCommonNetworkHandler;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.text.Text;
import net.minecraft.util.Util;
import network.ycc.raknet.RakNet;
import org.objectweb.asm.Opcodes;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerCommonNetworkHandler.class)
public abstract class MixinServerCommonNetworkHandler implements ServerCommonPacketListener {
@Shadow @Final protected ClientConnection connection;
@Shadow private int latency;
@ModifyExpressionValue(method = "baseTick", at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/ServerCommonNetworkHandler;lastKeepAliveTime:J", opcode = Opcodes.GETFIELD))
private long disableKeepAlive(long original) {
if (!(((IClientConnection) this.connection).getChannel().config() instanceof RakNet.Config)) {
return original;
}
return Util.getMeasuringTimeMs();
}
@WrapWithCondition(method = "onKeepAlive", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerCommonNetworkHandler;disconnect(Lnet/minecraft/text/Text;)V"))
private boolean stopTimeoutPlayersOnKeepAlive(ServerCommonNetworkHandler instance, Text reason) {
return !(((IClientConnection) MultiVersionUtil.ServerPlayNetworkHandler$connection.get((ServerCommonNetworkHandler) (Object) this)).getChannel().config() instanceof RakNet.Config);
}
@WrapWithCondition(method = "onKeepAlive", at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/ServerCommonNetworkHandler;latency:I", opcode = Opcodes.PUTFIELD))
private boolean redirectPingStoring(ServerCommonNetworkHandler instance, int value) {
return !(((IClientConnection) MultiVersionUtil.ServerPlayNetworkHandler$connection.get((ServerCommonNetworkHandler) (Object) this)).getChannel().config() instanceof RakNet.Config);
}
@Inject(method = "baseTick", at = @At("HEAD"))
private void onTick(CallbackInfo ci) {
final Channel channel = ((IClientConnection) MultiVersionUtil.ServerPlayNetworkHandler$connection.get((ServerCommonNetworkHandler) (Object) this)).getChannel();
if (channel != null && channel.config() instanceof RakNet.Config config) {
this.latency = (int) ((config.getRTTNanos() + config.getRTTStdDevNanos()) / 1_000_000);
}
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/server/MixinServerLoginNetworkHandler.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.server;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import net.minecraft.network.ClientConnection;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerLoginNetworkHandler;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.lang.reflect.Method;
@Mixin(value = ServerLoginNetworkHandler.class, priority = 900)
public class MixinServerLoginNetworkHandler {
@Shadow @Final public ClientConnection connection;
@Shadow @Final private MinecraftServer server;
@Dynamic
@Redirect(method = {"method_14384()V", "tickVerify"}, at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getNetworkCompressionThreshold()I"), require = 1)
private int stopCompressionIfStreamingCompressionExists(MinecraftServer server) {
final MultiChannelingStreamingCompression compression = ((IClientConnection) this.connection).getChannel().pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
System.out.println("Raknetify: Preventing vanilla compression as streaming compression is enabled");
return -1;
}
return server.getNetworkCompressionThreshold();
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/server/MixinServerNetworkIo.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.server;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.RakNetConnectionUtil;
import com.ishland.raknetify.common.connection.RaknetifyEventLoops;
import com.ishland.raknetify.common.util.ThreadLocalUtil;
import com.ishland.raknetify.common.util.NetworkInterfaceListener;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.ServerChannel;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ServerNetworkIo;
import network.ycc.raknet.server.channel.RakNetServerChannel;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
@Mixin(ServerNetworkIo.class)
public abstract class MixinServerNetworkIo {
@Unique
private static final int raknetify$portOverride = Integer.getInteger("raknetify.fabric.portOverride", -1);
@Shadow
@Final
private MinecraftServer server;
@Shadow
public abstract void bind(@Nullable InetAddress address, int port) throws IOException;
@Shadow
public volatile boolean active;
@Shadow
@Final
private List channels;
@Unique
private Consumer raknetify$eventListener = null;
@Inject(method = "bind", at = @At("HEAD"))
private void bindUdp(InetAddress address, int port, CallbackInfo ci) throws IOException {
if (!ThreadLocalUtil.isInitializingRaknet()) {
try {
ThreadLocalUtil.setInitializingRaknet(true);
final boolean hasPortOverride = raknetify$portOverride > 0 && raknetify$portOverride < 65535;
if (address == null) {
for (NetworkInterface networkInterface : NetworkInterface.networkInterfaces().toList()) {
final Iterator iterator = networkInterface.getInetAddresses().asIterator();
while (iterator.hasNext()) {
final InetAddress inetAddress = iterator.next();
System.out.println("Starting raknetify server on %s".formatted(inetAddress));
try {
bind(inetAddress, hasPortOverride ? raknetify$portOverride : port);
} catch (IOException t) {
System.out.println("**** FAILED TO BIND TO PORT! %s".formatted(t.getMessage()));
}
}
}
if (this.raknetify$eventListener == null) {
this.raknetify$eventListener = event -> {
if (!this.active) {
NetworkInterfaceListener.removeListener(this.raknetify$eventListener);
return;
}
try {
ThreadLocalUtil.setInitializingRaknet(true);
final InetAddress inetAddress = event.address();
if (event.added()) {
System.out.println("Starting raknetify server on %s".formatted(inetAddress));
try {
bind(inetAddress, hasPortOverride ? raknetify$portOverride : port);
} catch (IOException t) {
System.out.println("**** FAILED TO BIND TO PORT! %s".formatted(t.getMessage()));
} catch (Throwable t) {
t.printStackTrace();
}
} else {
synchronized (this.channels) {
for (Iterator iter = this.channels.iterator(); iter.hasNext(); ) {
ChannelFuture channel = iter.next();
final SocketAddress socketAddress = channel.channel().localAddress();
if (socketAddress instanceof InetSocketAddress channelAddress) {
if (inetAddress.equals(channelAddress.getAddress())) {
System.out.println("Stopping raknetify server on %s".formatted(inetAddress));
channel.channel().close();
iter.remove();
}
}
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
ThreadLocalUtil.setInitializingRaknet(false);
}
};
NetworkInterfaceListener.addListener(event -> this.server.submit(() -> raknetify$eventListener.accept(event)));
}
} else {
System.out.println("Starting raknetify server on %s".formatted(address));
bind(address, hasPortOverride ? raknetify$portOverride : port);
}
} finally {
ThreadLocalUtil.setInitializingRaknet(false);
}
}
}
@WrapOperation(method = "bind", at = @At(value = "INVOKE", target = "Lio/netty/bootstrap/ServerBootstrap;group(Lio/netty/channel/EventLoopGroup;)Lio/netty/bootstrap/ServerBootstrap;", remap = false))
private ServerBootstrap redirectGroup(ServerBootstrap instance, EventLoopGroup group, Operation original) {
final boolean useEpoll = Epoll.isAvailable() && this.server.isUsingNativeTransport();
return ThreadLocalUtil.isInitializingRaknet()
? original.call(instance, useEpoll ? RaknetifyEventLoops.EPOLL_EVENT_LOOP_GROUP.get() : RaknetifyEventLoops.NIO_EVENT_LOOP_GROUP.get())
: original.call(instance, group);
}
@WrapOperation(method = "bind", at = @At(value = "INVOKE", target = "Lio/netty/bootstrap/ServerBootstrap;channel(Ljava/lang/Class;)Lio/netty/bootstrap/AbstractBootstrap;", remap = false))
private AbstractBootstrap redirectChannel(ServerBootstrap instance, Class extends ServerSocketChannel> aClass, Operation> original) {
final boolean useEpoll = Epoll.isAvailable() && this.server.isUsingNativeTransport();
return ThreadLocalUtil.isInitializingRaknet()
? instance.channelFactory(() -> {
RakNetServerChannel channel = new RakNetServerChannel(() -> {
final DatagramChannel channel1 = useEpoll ? new EpollDatagramChannel() : new NioDatagramChannel();
channel1.config().setOption(ChannelOption.SO_REUSEADDR, true);
channel1.config().setOption(ChannelOption.IP_TOS, RakNetConnectionUtil.DEFAULT_IP_TOS);
channel1.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(Constants.LARGE_MTU + 512).maxMessagesPerRead(128));
return channel1;
});
channel.setProvidedApplicationEventLoop(RaknetifyEventLoops.DEFAULT_EVENT_LOOP_GROUP.get().next());
return channel;
})
: original.call(instance, aClass);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/server/MixinServerNetworkIo1.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.server;
import com.ishland.raknetify.fabric.common.connection.RakNetFabricConnectionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(targets = "net/minecraft/server/ServerNetworkIo$1")
public abstract class MixinServerNetworkIo1 extends ChannelInitializer {
@Inject(method = "initChannel(Lio/netty/channel/Channel;)V", at = @At("HEAD"))
private void onChannelInit(Channel channel, CallbackInfo ci) {
RakNetFabricConnectionUtil.initChannel(channel);
}
@Inject(method = "initChannel(Lio/netty/channel/Channel;)V", at = @At("RETURN"))
private void postChannelInit(Channel channel, CallbackInfo ci) {
RakNetFabricConnectionUtil.postInitChannel(channel, false);
}
}
================================================
FILE: fabric/src/main/java/com/ishland/raknetify/fabric/mixin/server/MixinServerPlayNetworkHandler1_20_1.java
================================================
/*
* This file is a part of the Raknetify project, licensed under MIT.
*
* Copyright (c) 2022-2025 ishland
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ishland.raknetify.fabric.mixin.server;
import com.ishland.raknetify.fabric.common.util.MultiVersionUtil;
import com.ishland.raknetify.fabric.mixin.access.IClientConnection;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import com.llamalad7.mixinextras.injector.WrapWithCondition;
import io.netty.channel.Channel;
import net.minecraft.server.network.ServerCommonNetworkHandler;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Util;
import network.ycc.raknet.RakNet;
import org.objectweb.asm.Opcodes;
import org.spongepowered.asm.mixin.Dynamic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerPlayNetworkHandler.class)
public class MixinServerPlayNetworkHandler1_20_1 {
@Shadow public ServerPlayerEntity player;
@Dynamic
@ModifyExpressionValue(method = "tick", at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/ServerPlayNetworkHandler;field_14136:J", opcode = Opcodes.GETFIELD))
private long disableKeepAlive(long original) {
if (!(((IClientConnection) MultiVersionUtil.ServerPlayNetworkHandler$connection.get((ServerPlayNetworkHandler) (Object) this)).getChannel().config() instanceof RakNet.Config)) {
return original;
}
return Util.getMeasuringTimeMs();
}
@Dynamic
@WrapWithCondition(method = "method_12082", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/network/ServerPlayNetworkHandler;method_14367(Lnet/minecraft/text/Text;)V"))
private boolean stopTimeoutPlayersOnKeepAlive(ServerPlayNetworkHandler instance, Text reason) {
return !(((IClientConnection) MultiVersionUtil.ServerPlayNetworkHandler$connection.get((ServerPlayNetworkHandler) (Object) this)).getChannel().config() instanceof RakNet.Config);
}
@Dynamic
@WrapWithCondition(method = "method_12082", at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/ServerPlayerEntity;field_13967:I", opcode = Opcodes.PUTFIELD))
private boolean redirectPingStoring(ServerPlayerEntity instance, int value) {
return !(((IClientConnection) MultiVersionUtil.ServerPlayNetworkHandler$connection.get((ServerPlayNetworkHandler) (Object) this)).getChannel().config() instanceof RakNet.Config);
}
@Inject(method = "tick", at = @At("HEAD"))
private void onTick(CallbackInfo ci) {
final Channel channel = ((IClientConnection) MultiVersionUtil.ServerPlayNetworkHandler$connection.get((ServerPlayNetworkHandler) (Object) this)).getChannel();
if (channel != null && channel.config() instanceof RakNet.Config config) {
assert MultiVersionUtil.ServerPlayerEntity$pingMillis1_20_1 != null;
MultiVersionUtil.ServerPlayerEntity$pingMillis1_20_1.set(this.player, (int) ((config.getRTTNanos() + config.getRTTStdDevNanos()) / 1_000_000));
}
}
}
================================================
FILE: fabric/src/main/resources/fabric.mod.json
================================================
{
"schemaVersion": 1,
"id": "raknetify",
"version": "${version}",
"name": "Raknetify (Fabric)",
"description": "A Fabric mod that allows using RakNet as Minecraft networking backend. ",
"authors": [
"ishland"
],
"contact": {
},
"license": "MIT",
"environment": "*",
"entrypoints": {
"main": [
"com.ishland.raknetify.fabric.RaknetifyFabric"
],
"preLaunch": [
"com.ishland.raknetify.fabric.RaknetifyFabric"
]
},
"accessWidener" : "raknetify-fabric.accesswidener",
"mixins": [
"raknetify-fabric.mixins.json"
],
"depends": {
"fabricloader": ">=0.15.2",
"java": ">=17"
},
"suggests": {
}
}
================================================
FILE: fabric/src/main/resources/raknetify-fabric.accesswidener
================================================
accessWidener v1 named
accessible class net/minecraft/network/handler/PacketCodecDispatcher$PacketType
accessible method net/minecraft/network/encryption/PacketEncryptionManager (Ljavax/crypto/Cipher;)V
accessible method net/minecraft/client/network/MultiplayerServerListPinger createPlayerCountText (II)Lnet/minecraft/text/Text;
================================================
FILE: fabric/src/main/resources/raknetify-fabric.mixins.json
================================================
{
"required": true,
"minVersion": "0.8",
"package": "com.ishland.raknetify.fabric.mixin",
"plugin": "com.ishland.raknetify.fabric.mixin.RaknetifyFabricMixinPlugin",
"compatibilityLevel": "JAVA_16",
"mixinPriority": 1010,
"mixins": [
"access.IClientConnection",
"access.INetworkState1_20_4",
"access.INetworkStateInternalPacketHandler",
"access.IPacketCodecDispatcher",
"access.IPacketCodecDispatcherPacketType",
"access.IPacketEncryptionManager",
"access.IServerPlayNetworkHandler",
"access.IWorld",
"client.MixinClientPlayNetworkHandler",
"client.MixinConnectionScreen1",
"client.MixinMultiplayerServerListPinger",
"client.MixinMultiplayerServerListPinger1",
"client.hud.MixinDebugHud1_21_8",
"common.MixinCCConnect",
"common.MixinClientConnection",
"common.MixinClientConnection1",
"common.MixinClientConnection1_20_2",
"common.encryption.MixinClientConnection",
"common.encryption.MixinPacketDecryptor",
"common.encryption.MixinPacketEncryptionManager",
"common.encryption.MixinPacketEncryptor",
"common.quirks.MixinPlayerEntity",
"common.quirks.MixinSampleSubscriptionTracker",
"compat.fabricapi.MixinServerLoginNetworkAddon",
"compat.krypton.MixinServerLoginNetworkHandler",
"compat.qsl.MixinServerLoginNetworkAddon",
"server.MixinPlayerManager1_20_1",
"server.MixinPlayerManager1_20_2",
"server.MixinServerCommonNetworkHandler",
"server.MixinServerLoginNetworkHandler",
"server.MixinServerNetworkIo",
"server.MixinServerNetworkIo1",
"server.MixinServerPlayNetworkHandler1_20_1"
],
"injectors": {
"defaultRequire": 1
},
"client": [
"access.IClientPlayNetworkHandler",
"access.IDebugHudEntries",
"client.MixinMultiplayerServerListPinger1_20_2",
"client.MixinMultiplayerServerListPinger1_20_5",
"client.MixinMultiplayerServerListPinger1_21_11",
"common.MixinServerAddress"
]
}
================================================
FILE: genMappings.sh
================================================
#!/bin/bash
loader_version=0.18.4
installer_version=1.1.1
#declare -a vers
if [[ -z "$@" ]]; then
vers="1.17 1.17.1 1.18.1 1.18.2 1.19 1.19.2 1.19.3 1.19.4 23w13a_or_b 1.20.1 1.20.2 1.20.4 1.20.6 1.21.1 1.21.3 1.21.4 1.21.5 1.21.6 1.21.8 1.21.10 1.21.11"
else
vers=$@
fi
echo $vers
./gradlew clean build || exit 1
mkdir run-mappingsGen || true
cd run-mappingsGen || exit 1
rm -r mods
mkdir mods
cp ../fabric/build/libs/raknetify-*-all.jar mods/
rm channelMappings.json || true
if [[ -z "${MAPPINGS_GEN_FRESH}" ]]; then
cp ../common/src/main/resources/raknetify-channel-mappings.json channelMappings.json
fi
for version in $vers
do
if [ -e fabric-server-mc"$version".jar ]; then
echo "Using existing fabric-server-mc$version.jar"
else
wget -O fabric-server-mc"$version".jar https://meta.fabricmc.net/v2/versions/loader/"$version"/$loader_version/$installer_version/server/jar || exit 1
fi
sleep 1
java -Draknetify.saveChannelMappings=true -Draknetify.saveChannelMappings.exit=true -jar fabric-server-mc"$version".jar || exit 1
done
cp channelMappings.json ../common/src/main/resources/raknetify-channel-mappings.json
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
================================================
FILE: gradle.properties
================================================
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx4G
org.gradle.parallel=true
gradle-curseforge-publish.interop.fabric-loom=false
gradle-curseforge-publish.interop.forge-gradle=false
gradle-curseforge-publish.interop.neoforged=false
gradle-curseforge-publish.interop.neogradle=false
# Fabric Properties
# check these on https://fabricmc.net/develop
#
# Also don't forget to gen mappings in genMappings.sh
minecraft_version=1.21.11
yarn_mappings=1.21.11+build.1
loader_version=0.17.2
# Mod Properties
mod_version = 0.1.0+alpha.5
maven_group = com.ishland.raknetify
archives_base_name = raknetify
# Dependencies
#fabric_version=0.44.0+1.18
#mixinextras_version=0.1.1
================================================
FILE: gradlew
================================================
#!/bin/sh
#
# Copyright 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions $var, ${var}, ${var:-default}, ${var+SET},
# ${var#prefix}, ${var%suffix}, and $( cmd );
# * compound commands having a testable exit status, especially case;
# * various built-in commands including command, set, and ulimit.
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: jitpack.yml
================================================
before_install:
- source "$HOME/.sdkman/bin/sdkman-init.sh"
- sdk update
- sdk install java 17.0.2-zulu
- sdk use java 17.0.2-zulu
================================================
FILE: modrinth_license.txt
================================================
Licensing
Raknetify for fabric and BungeeCord is licensed under the MIT license,
you can find the license in the LICENSE file
Raknetify for Velocity is licensed under the GNU General Public License v3.0,
you can find the license in the velocity/LICENSE file
================================================
FILE: settings.gradle
================================================
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = "raknetify"
includeBuild('netty-raknet') {
dependencySubstitution {
substitute module("com.github.RelativityMC.netty-raknet:netty-raknet-common") using project(":netty-raknet-common")
substitute module("com.github.RelativityMC.netty-raknet:netty-raknet-client") using project(":netty-raknet-client")
substitute module("com.github.RelativityMC.netty-raknet:netty-raknet-server") using project(":netty-raknet-server")
}
}
include "fabric"
include "velocity"
include "bungee"
include "common"
================================================
FILE: velocity/HEADER.txt
================================================
This file is a part of the Velocity implementation of the Raknetify
project, licensed under GPLv3.
Copyright (c) 2022-2025 ishland
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
================================================
FILE: velocity/LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: velocity/build.gradle
================================================
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
evaluationDependsOn(":")
apply plugin: 'com.gradleup.shadow'
apply plugin: 'com.modrinth.minotaur'
afterEvaluate {
license {
rule(project.file('HEADER.txt'))
}
}
base {
archivesName = project.archives_base_name + "-velocity"
}
group = project.maven_group + ".velocity"
repositories {
maven {
name 'papermc'
url 'https://repo.papermc.io/repository/maven-public/'
}
ivy {
url 'https://api.papermc.io/v2/projects/'
patternLayout {
artifact "[organization]/versions/[module]/builds/[revision]/downloads/[organization]-[module]-[revision](.[ext])"
}
metadataSources {
it.artifact()
}
}
}
configurations {
shadowInclude
}
dependencies {
// api 'com.velocitypowered:velocity-api:3.1.1'
// annotationProcessor 'com.velocitypowered:velocity-api:3.1.1'
implementation 'velocity:3.4.0-SNAPSHOT:540'
// annotationProcessor 'velocity:3.1.2-SNAPSHOT:139'
shadowInclude implementation(project(":common"))
// copied here to workaround incomplete fastutil in velocity
api("com.github.RelativityMC.netty-raknet:netty-raknet-common") {
transitive = false
}
api("com.github.RelativityMC.netty-raknet:netty-raknet-client")
api("com.github.RelativityMC.netty-raknet:netty-raknet-server")
}
processResources {
inputs.property "version", project.version
filesMatching("velocity-plugin.json") {
expand "version": project.version
}
}
jar {
exclude "META-INF/LICENSE.txt"
exclude "META-INF/NOTICE.txt"
from "LICENSE"
}
shadowJar {
dependencies {
// exclude(dependency('it.unimi.dsi:fastutil'))
}
exclude "META-INF/LICENSE.txt"
exclude "META-INF/NOTICE.txt"
minimize()
archiveClassifier = "all"
configurations = [ project.configurations.shadowInclude ]
from "LICENSE"
}
assemble.dependsOn(shadowJar)
tasks.withType(AbstractArchiveTask) {
preserveFileTimestamps = false
reproducibleFileOrder = true
}
modrinth {
versionNumber = project.version + "+velocity"
versionName = project.version + " devbuild for Velocity"
uploadFile = shadowJar
loaders = ["velocity"]
}
task("prepareRunVelocity", dependsOn: shadowJar) {
doFirst {
Files.createDirectories(rootProject.projectDir.toPath().resolve("run-velocity").resolve("plugins"))
Files.copy(shadowJar.archiveFile.getAsFile().get().toPath(), rootProject.projectDir.toPath().resolve("run-velocity").resolve("plugins").resolve("raknetify-velocity-devlaunch.jar"), StandardCopyOption.REPLACE_EXISTING)
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/RaknetifyVelocityLaunchWrapper.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity;
import com.ishland.raknetify.common.data.ProtocolMultiChannelMappings;
import com.ishland.raknetify.velocity.connection.RakNetVelocityConnectionUtil;
import com.ishland.raknetify.velocity.init.VelocityPacketRegistryInjector;
import com.ishland.raknetify.velocity.init.VelocityRaknetifyServer;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.connection.LoginEvent;
import com.velocitypowered.api.event.player.ServerPostConnectEvent;
import com.velocitypowered.api.event.proxy.ListenerBoundEvent;
import com.velocitypowered.api.event.proxy.ListenerCloseEvent;
import static com.ishland.raknetify.velocity.RaknetifyVelocityPlugin.INSTANCE;
import static com.ishland.raknetify.velocity.RaknetifyVelocityPlugin.LOGGER;
import static com.ishland.raknetify.velocity.RaknetifyVelocityPlugin.PROXY;
public class RaknetifyVelocityLaunchWrapper {
public static void launch() {
if (!isCompatible()) {
Runnable runnable = () -> {
LOGGER.error("This version of Raknetify is NOT compatible with your version of Velocity");
LOGGER.error("Please update your Velocity at https://papermc.io/downloads#Velocity");
};
runnable.run();
PROXY.getEventManager().register(INSTANCE, ListenerBoundEvent.class, PostOrder.LAST, ignored -> runnable.run());
return;
}
ProtocolMultiChannelMappings.init();
VelocityPacketRegistryInjector.inject();
PROXY.getEventManager().register(INSTANCE, LoginEvent.class, PostOrder.LAST, RakNetVelocityConnectionUtil::onPlayerLogin);
PROXY.getEventManager().register(INSTANCE, ListenerBoundEvent.class, PostOrder.LAST, VelocityRaknetifyServer::start);
PROXY.getEventManager().register(INSTANCE, ListenerCloseEvent.class, PostOrder.LAST, VelocityRaknetifyServer::stop);
PROXY.getEventManager().register(INSTANCE, ServerPostConnectEvent.class, PostOrder.LAST, RakNetVelocityConnectionUtil::onServerSwitch);
}
private static boolean isCompatible() {
try {
Class.forName("com.velocitypowered.proxy.crypto.EncryptionUtils");
Class.forName("com.velocitypowered.proxy.protocol.packet.PluginMessagePacket");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/RaknetifyVelocityPlugin.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.proxy.ProxyServer;
import org.slf4j.Logger;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.regex.Pattern;
@Plugin(
id = "raknetify"
)
public class RaknetifyVelocityPlugin {
private static final ArrayList excludeRegex = new ArrayList<>();
static {
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.*Int2ObjectLinked*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.*Int2ObjectSorted*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.*Int2ObjectAVL*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.*Int2ObjectRB*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.*Int2ObjectArray*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.IntList*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.AbstractIntList*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.IntSorted*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.AbstractIntSorted*"));
excludeRegex.add(Pattern.compile("it.unimi.dsi.fastutil.ints.IntRB*"));
}
private static boolean isExcluded(String name) {
for (Pattern regex : excludeRegex) {
if (regex.matcher(name).find()) return true;
}
return false;
}
public static ProxyServer PROXY;
public static Logger LOGGER;
public static RaknetifyVelocityPlugin INSTANCE;
public static URLClassLoader WRAPPER;
@Inject
private ProxyServer proxy;
@Inject
private Logger logger;
@Subscribe
public void onProxyInit(ProxyInitializeEvent e) {
INSTANCE = this;
PROXY = this.proxy;
LOGGER = this.logger;
final CodeSource codeSource = RaknetifyVelocityPlugin.class.getProtectionDomain().getCodeSource();
if (codeSource != null && !isDevLaunch()) {
try {
LOGGER.info("Bootstrapping raknetify in wrapped environment");
final URLClassLoader urlClassLoader = new RaknetifyURLClassLoader("raknetify wrapper", new URL[]{codeSource.getLocation()}, RaknetifyVelocityPlugin.class.getClassLoader());
final Class> launchWrapper = urlClassLoader.loadClass("com.ishland.raknetify.velocity.RaknetifyVelocityLaunchWrapper");
Preconditions.checkState(launchWrapper.getClassLoader() == urlClassLoader, "Not launched in wrapper");
WRAPPER = urlClassLoader;
launchWrapper.getMethod("launch").invoke(null);
return;
} catch (Throwable t) {
LOGGER.error("Error bootstrapping raknetify inside wrapped environment, running in normal environment instead", t);
}
}
try {
Class.forName("com.ishland.raknetify.velocity.RaknetifyVelocityLaunchWrapper").getMethod("launch").invoke(null);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException ex) {
throw new RuntimeException(ex);
}
}
private static boolean isDevLaunch() {
try {
ClassLoader.getSystemClassLoader().loadClass("com.ishland.raknetify.velocity.RaknetifyVelocityPlugin");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
private static class RaknetifyURLClassLoader extends URLClassLoader {
public RaknetifyURLClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
public RaknetifyURLClassLoader(URL[] urls) {
super(urls);
}
public RaknetifyURLClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(urls, parent, factory);
}
public RaknetifyURLClassLoader(String name, URL[] urls, ClassLoader parent) {
super(name, urls, parent);
}
public RaknetifyURLClassLoader(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(name, urls, parent, factory);
}
@Override
protected Class> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (!(name.startsWith("com.ishland.raknetify") && !name.equals("com.ishland.raknetify.velocity.RaknetifyVelocityPlugin"))
&& !name.startsWith("network.ycc.raknet")
&& !isExcluded(name)) {
try {
return Class.forName(name, true, this.getParent());
} catch (ClassNotFoundException | NoClassDefFoundError e) {
// ignored, try our own loader
}
}
synchronized (getClassLoadingLock(name)) {
try {
final Class> clazz = this.findClass(name);
if (resolve) this.resolveClass(clazz);
return clazz;
} catch (ClassNotFoundException e1) {
// then fail here, there's nothing more we can do
throw new ClassNotFoundException(name, e1);
}
}
}
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/connection/RakNetVelocityChannelEventListener.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity.connection;
import com.google.common.base.Preconditions;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.MultiChannellingEncryption;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.common.connection.SynchronizationLayer;
import com.ishland.raknetify.velocity.RaknetifyVelocityPlugin;
import com.velocitypowered.proxy.VelocityServer;
import com.velocitypowered.proxy.connection.MinecraftConnection;
import com.velocitypowered.proxy.crypto.EncryptionUtils;
import com.velocitypowered.proxy.network.Connections;
import com.velocitypowered.proxy.protocol.VelocityConnectionEvent;
import com.velocitypowered.proxy.protocol.packet.AvailableCommandsPacket;
import com.velocitypowered.proxy.protocol.packet.EncryptionResponsePacket;
import com.velocitypowered.proxy.protocol.packet.JoinGamePacket;
import com.velocitypowered.proxy.protocol.packet.RespawnPacket;
import com.velocitypowered.proxy.protocol.packet.SetCompressionPacket;
import com.velocitypowered.proxy.protocol.packet.config.FinishedUpdatePacket;
import com.velocitypowered.proxy.protocol.packet.config.StartUpdatePacket;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class RakNetVelocityChannelEventListener extends ChannelDuplexHandler {
public static final String NAME = "raknetify-velocity-event-listener";
private SecretKey encryptionKey = null;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof SetCompressionPacket) {
final MultiChannelingStreamingCompression compression = ctx.channel().pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
RaknetifyVelocityPlugin.LOGGER.info("Preventing vanilla compression as streaming compression is enabled");
promise.setSuccess(); // swallow SetCompression packet
return;
}
} else if (msg instanceof RespawnPacket || msg instanceof JoinGamePacket || msg instanceof StartUpdatePacket || msg instanceof FinishedUpdatePacket) {
ctx.write(SynchronizationLayer.SYNC_REQUEST_OBJECT); // sync
super.write(ctx, msg, promise);
return;
} else if (msg instanceof AvailableCommandsPacket) {
ctx.write(RakNetSimpleMultiChannelCodec.SIGNAL_START_MULTICHANNEL);
super.write(ctx, msg, promise);
return;
}
super.write(ctx, msg, promise);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof EncryptionResponsePacket packet) {
try {
byte[] secret = EncryptionUtils.decryptRsa(((VelocityServer) RaknetifyVelocityPlugin.PROXY).getServerKeyPair(), packet.getSharedSecret());
this.encryptionKey = new SecretKeySpec(secret, "AES");
} catch (Throwable t) {
RaknetifyVelocityPlugin.LOGGER.warn("Failed to decrypt captured encryption secret, the raknetify connection is broken", t);
}
}
super.channelRead(ctx, msg);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt == VelocityConnectionEvent.COMPRESSION_ENABLED) {
final MultiChannelingStreamingCompression compression = ctx.channel().pipeline().get(MultiChannelingStreamingCompression.class);
if (compression != null && compression.isActive()) {
RaknetifyVelocityPlugin.LOGGER.info("Preventing vanilla compression as streaming compression is enabled");
ctx.channel().pipeline().replace(Connections.COMPRESSION_ENCODER, Connections.COMPRESSION_ENCODER, new ChannelDuplexHandler()); // no-op
ctx.channel().pipeline().replace(Connections.COMPRESSION_DECODER, Connections.COMPRESSION_DECODER, new ChannelDuplexHandler()); // no-op
// sync velocity compression state
final MinecraftConnection minecraftConnection = ctx.channel().pipeline().get(MinecraftConnection.class);
if (minecraftConnection != null) {
minecraftConnection.setCompressionThreshold(-1);
} else {
RaknetifyVelocityPlugin.LOGGER.warn("Unable to sync compression state with velocity");
}
}
} else if (evt == VelocityConnectionEvent.COMPRESSION_DISABLED) {
ctx.channel().pipeline().replace(Connections.FRAME_DECODER, Connections.FRAME_DECODER, new ChannelDuplexHandler()); // no-op
ctx.channel().pipeline().replace(Connections.FRAME_ENCODER, Connections.FRAME_ENCODER, new ChannelDuplexHandler()); // no-op
} else if (evt == VelocityConnectionEvent.ENCRYPTION_ENABLED) {
Preconditions.checkState(this.encryptionKey != null, "EncryptionResponse not received yet or already consumed");
ctx.channel().pipeline().replace(Connections.CIPHER_ENCODER, Connections.CIPHER_ENCODER, new ChannelDuplexHandler());
ctx.channel().pipeline().replace(Connections.CIPHER_DECODER, Connections.CIPHER_DECODER, new ChannelDuplexHandler());
ctx.channel().pipeline().addBefore(MultiChannelingStreamingCompression.NAME, MultiChannellingEncryption.NAME, new MultiChannellingEncryption(encryptionKey));
}
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/connection/RakNetVelocityConnectionUtil.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity.connection;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.ByteBufCopyDecoder;
import com.ishland.raknetify.common.connection.MultiChannelingStreamingCompression;
import com.ishland.raknetify.common.connection.RakNetConnectionUtil;
import com.ishland.raknetify.common.connection.RakNetSimpleMultiChannelCodec;
import com.ishland.raknetify.common.connection.multichannel.CustomPayloadChannel;
import com.ishland.raknetify.common.data.ProtocolMultiChannelMappings;
import com.ishland.raknetify.velocity.RaknetifyVelocityPlugin;
import com.velocitypowered.api.event.connection.LoginEvent;
import com.velocitypowered.api.event.player.ServerPostConnectEvent;
import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.proxy.connection.MinecraftConnection;
import com.velocitypowered.proxy.connection.backend.VelocityServerConnection;
import com.velocitypowered.proxy.connection.client.ConnectedPlayer;
import com.velocitypowered.proxy.network.Connections;
import com.velocitypowered.proxy.protocol.ProtocolUtils;
import com.velocitypowered.proxy.protocol.StateRegistry;
import com.velocitypowered.proxy.protocol.packet.PluginMessagePacket;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import network.ycc.raknet.RakNet;
import java.util.Arrays;
import java.util.Collections;
public class RakNetVelocityConnectionUtil {
private RakNetVelocityConnectionUtil() {
}
public static void initChannel(Channel channel) {
if (channel.config() instanceof RakNet.Config) {
RakNetConnectionUtil.initChannel(channel);
// channel.pipeline().addAfter(MultiChannelingStreamingCompression.NAME, MultiChannellingDataCodec.NAME, new MultiChannellingDataCodec(Constants.RAKNET_GAME_PACKET_ID));
channel.pipeline().addAfter(MultiChannelingStreamingCompression.NAME, RakNetSimpleMultiChannelCodec.NAME, new RakNetSimpleMultiChannelCodec(Constants.RAKNET_GAME_PACKET_ID));
channel.pipeline().addAfter(RakNetSimpleMultiChannelCodec.NAME, ByteBufCopyDecoder.NAME, new ByteBufCopyDecoder());
}
}
public static void postInitChannel(Channel channel, boolean isClientSide) {
if (channel.config() instanceof RakNet.Config) {
channel.pipeline().replace(Connections.READ_TIMEOUT, Connections.READ_TIMEOUT, new ChannelDuplexHandler()); // no-op
channel.pipeline().replace(Connections.FRAME_DECODER, Connections.FRAME_DECODER, new ChannelDuplexHandler()); // no-op
channel.pipeline().replace(Connections.FRAME_ENCODER, Connections.FRAME_ENCODER, new ChannelDuplexHandler()); // no-op
if (channel.pipeline().get(HAProxyMessageDecoder.class) != null)
channel.pipeline().remove(HAProxyMessageDecoder.class);
channel.pipeline().addBefore(Connections.HANDLER, RakNetVelocityChannelEventListener.NAME, new RakNetVelocityChannelEventListener());
// System.out.println(channel.pipeline().names());
// final MultiChannellingPacketCapture handler = new MultiChannellingPacketCapture();
// channel.pipeline().addLast("raknetify-multi-channel-packet-cature", handler);
// channel.pipeline().get(MultiChannellingDataCodec.class).setCapture(handler);
}
}
public static void onPlayerLogin(LoginEvent evt) {
final ConnectedPlayer player = (ConnectedPlayer) evt.getPlayer();
final Channel channel = player.getConnection().getChannel();
if (channel != null && channel.config() instanceof RakNet.Config config) {
final RakNetSimpleMultiChannelCodec multiChannelCodec = channel.pipeline().get(RakNetSimpleMultiChannelCodec.class);
if (multiChannelCodec != null) {
final ProtocolVersion protocolVersion = player.getProtocolVersion();
final ProtocolMultiChannelMappings.VersionMapping versionMapping = ProtocolMultiChannelMappings.INSTANCE.mappings.get(protocolVersion.getProtocol());
if (versionMapping != null) {
// handle custom payload separately
final int pluginMessageId = StateRegistry.PLAY.getProtocolRegistry(ProtocolUtils.Direction.CLIENTBOUND, protocolVersion).getPacketId(new PluginMessagePacket());
if (Constants.DEBUG) RaknetifyVelocityPlugin.LOGGER.info("PluginMessage packetId=%d at version=%d".formatted(pluginMessageId, protocolVersion.getProtocol()));
multiChannelCodec.addHandler(new CustomPayloadChannel.OverrideHandler(value -> value == pluginMessageId));
// packet id -> channel id
multiChannelCodec.addHandler(new RakNetSimpleMultiChannelCodec.PacketIdBasedOverrideHandler(
versionMapping.s2c,
"%s (%d)".formatted(protocolVersion.getVersionIntroducedIn(), protocolVersion.getProtocol())
));
} else {
RaknetifyVelocityPlugin.LOGGER.warn("No multi-channel mappings for protocol version {} ({})", protocolVersion.getProtocol(), Arrays.toString(protocolVersion.getVersionsSupportedBy().toArray(String[]::new)));
}
}
channel.pipeline().addBefore(Connections.HANDLER, RakNetVelocityPingUpdater.NAME, new RakNetVelocityPingUpdater(player));
RaknetifyVelocityPlugin.LOGGER.info(String.format("Raknetify: %s logged in via RakNet, mtu %d", evt.getPlayer().getGameProfile().getName(), config.getMTU()));
}
}
public static void onServerSwitch(ServerPostConnectEvent evt) {
final ConnectedPlayer player = (ConnectedPlayer) evt.getPlayer();
final VelocityServerConnection connectedServer = player.getConnectedServer();
if (connectedServer == null) {
RaknetifyVelocityPlugin.LOGGER.warn("No connected server for player ({}) after server switch?", player);
return;
}
final MinecraftConnection serverConnection = connectedServer.getConnection();
if (serverConnection == null) {
RaknetifyVelocityPlugin.LOGGER.warn("Connected server ({}) have no underlying connection?", connectedServer);
return;
}
final Channel channel = player.getConnection().getChannel();
if (channel.config() instanceof RakNet.Config) {
serverConnection.getChannel().pipeline().addBefore(Connections.HANDLER, RakNetVelocityServerChannelEventListener.NAME, new RakNetVelocityServerChannelEventListener(channel));
}
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/connection/RakNetVelocityPingUpdater.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity.connection;
import com.ishland.raknetify.common.util.ReflectionUtil;
import com.velocitypowered.proxy.connection.client.ConnectedPlayer;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;
import network.ycc.raknet.RakNet;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class RakNetVelocityPingUpdater extends ChannelDuplexHandler {
public static final String NAME = "raknetify-velocity-ping-updater";
private static final Method PLAYER_SET_PING;
static {
try {
PLAYER_SET_PING = ReflectionUtil.accessible(ConnectedPlayer.class.getDeclaredMethod("setPing", long.class));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private final ConnectedPlayer player;
ScheduledFuture> updateTask = null;
public RakNetVelocityPingUpdater(ConnectedPlayer player) {
this.player = Objects.requireNonNull(player);
}
public void handlerAdded(ChannelHandlerContext ctx) {
if (ctx.channel().config() instanceof RakNet.Config config) {
updateTask = ctx.channel().eventLoop().scheduleAtFixedRate(
() -> {
try {
PLAYER_SET_PING.invoke(player, ((config.getRTTNanos() + config.getRTTStdDevNanos()) / 1_000_000));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
},
0, 1000, TimeUnit.MILLISECONDS
);
}
}
public void handlerRemoved(ChannelHandlerContext ctx) {
if (updateTask != null) {
updateTask.cancel(false);
updateTask = null;
}
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/connection/RakNetVelocityServerChannelEventListener.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity.connection;
import com.google.common.base.Preconditions;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.velocity.RaknetifyVelocityPlugin;
import com.velocitypowered.proxy.protocol.packet.KeepAlivePacket;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import network.ycc.raknet.RakNet;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class RakNetVelocityServerChannelEventListener extends ChannelDuplexHandler {
public static final String NAME = "raknetify-bungee-downstream-event-listener";
private final Channel clientChannel;
public RakNetVelocityServerChannelEventListener(Channel clientChannel) {
Preconditions.checkArgument(clientChannel.config() instanceof RakNet.Config);
this.clientChannel = clientChannel;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof KeepAlivePacket) {
if (Constants.DEBUG) RaknetifyVelocityPlugin.LOGGER.info("Received downstream keepalive, swallowing it");
final long rttNanos = RakNet.config(clientChannel).getRTTNanos();
// RaknetifyVelocityPlugin.PROXY.getScheduler().buildTask(RaknetifyVelocityPlugin.INSTANCE, () -> ctx.write(msg))
// .delay(Math.max(rttNanos - 4_000_000, 0), TimeUnit.NANOSECONDS) // reduce delay to aid scheduling overhead
// .clearRepeat()
// .schedule();
ctx.channel().eventLoop().schedule(() -> ctx.writeAndFlush(msg), Math.max(rttNanos - 4_000_000, 0), TimeUnit.NANOSECONDS); // reduce delay to aid scheduling overhead
return; // prevent keepalive from being sent to clients
}
super.channelRead(ctx, msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
cause.printStackTrace();
for (Map.Entry entry : ctx.channel().pipeline().toMap().entrySet()) {
System.out.println("%s: %s".formatted(entry.getKey(), entry.getValue().getClass().getName()));
}
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/init/VelocityPacketRegistryInjector.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity.init;
import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.proxy.protocol.MinecraftPacket;
import com.velocitypowered.proxy.protocol.StateRegistry;
import com.velocitypowered.proxy.protocol.packet.RespawnPacket;
import io.netty.util.collection.IntObjectMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import java.util.Map;
import java.util.function.Supplier;
import static com.ishland.raknetify.common.util.ReflectionUtil.accessible;
public class VelocityPacketRegistryInjector {
public static void inject() {
try {
final StateRegistry.PacketRegistry registry = (StateRegistry.PacketRegistry)
accessible(StateRegistry.class.getDeclaredField("clientbound")).get(StateRegistry.PLAY);
final var versions = (Map)
accessible(StateRegistry.PacketRegistry.class.getDeclaredField("versions")).get(registry);
for (StateRegistry.PacketRegistry.ProtocolRegistry value : versions.values()) {
final var packetClassToId = (Object2IntMap>)
accessible(StateRegistry.PacketRegistry.ProtocolRegistry.class.getDeclaredField("packetClassToId")).get(value);
final var packetIdToSupplier = (IntObjectMap>)
accessible(StateRegistry.PacketRegistry.ProtocolRegistry.class.getDeclaredField("packetIdToSupplier")).get(value);
if (packetClassToId.containsKey(RespawnPacket.class)) {
final int packetId = packetClassToId.getInt(RespawnPacket.class);
if (!packetIdToSupplier.containsKey(packetId)) {
packetIdToSupplier.put(packetId, RespawnPacket::new); // make respawn packet no longer encodeOnly
}
}
}
} catch (Throwable t) {
throw new RuntimeException("Failed to inject velocity packet registry", t);
}
}
}
================================================
FILE: velocity/src/main/java/com/ishland/raknetify/velocity/init/VelocityRaknetifyServer.java
================================================
/*
* This file is a part of the Velocity implementation of the Raknetify
* project, licensed under GPLv3.
*
* Copyright (c) 2022-2025 ishland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.ishland.raknetify.velocity.init;
import com.google.common.base.Preconditions;
import com.ishland.raknetify.common.Constants;
import com.ishland.raknetify.common.connection.RakNetConnectionUtil;
import com.ishland.raknetify.common.util.NetworkInterfaceListener;
import com.ishland.raknetify.velocity.RaknetifyVelocityPlugin;
import com.ishland.raknetify.velocity.connection.RakNetVelocityConnectionUtil;
import com.velocitypowered.api.event.proxy.ListenerBoundEvent;
import com.velocitypowered.api.event.proxy.ListenerCloseEvent;
import com.velocitypowered.api.network.ListenerType;
import com.velocitypowered.proxy.VelocityServer;
import com.velocitypowered.proxy.network.ConnectionManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFactory;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.socket.DatagramChannel;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import network.ycc.raknet.server.channel.RakNetServerChannel;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.util.concurrent.TimeUnit;
import static com.ishland.raknetify.common.util.ReflectionUtil.accessible;
public class VelocityRaknetifyServer {
private static final int portOverride = Integer.getInteger("raknetify.velocity.portOverride", -1);
private static final Method INIT_CHANNEL;
static {
try {
INIT_CHANNEL = accessible(ChannelInitializer.class.getDeclaredMethod("initChannel", Channel.class));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private static final ReferenceOpenHashSet channels = new ReferenceOpenHashSet<>();
private static volatile InetSocketAddress currentServerAddress = null;
private static volatile boolean active = false;
static {
NetworkInterfaceListener.addListener(event -> {
RaknetifyVelocityPlugin.PROXY.getScheduler()
.buildTask(RaknetifyVelocityPlugin.INSTANCE, () -> {
if (!active) return;
final InetSocketAddress address = currentServerAddress;
if (address != null && address.getAddress().isAnyLocalAddress()) {
if (event.added()) {
startServer(new InetSocketAddress(event.address(), address.getPort()));
} else {
synchronized (channels) {
final ObjectIterator iterator = channels.iterator();
while (iterator.hasNext()) {
final ChannelFuture future = iterator.next();
if (((InetSocketAddress) future.channel().localAddress()).getAddress().equals(event.address())) {
closeServer(future);
iterator.remove();
}
}
}
}
}
})
.delay(100, TimeUnit.MILLISECONDS)
.schedule();
});
}
public static void start(ListenerBoundEvent evt) {
if (evt.getListenerType() != ListenerType.MINECRAFT) return;
Preconditions.checkArgument(RaknetifyVelocityPlugin.PROXY instanceof VelocityServer);
Preconditions.checkState(channels.isEmpty(), "Raknetify Server is already running");
final InetSocketAddress address = evt.getAddress();
currentServerAddress = address;
active = true;
if (address.getAddress().isAnyLocalAddress()) {
try {
for (NetworkInterface networkInterface : NetworkInterface.networkInterfaces().toList()) {
for (InetAddress inetAddress : networkInterface.inetAddresses().toList()) {
try {
startServer(new InetSocketAddress(inetAddress, address.getPort()));
} catch (Throwable t) {
RaknetifyVelocityPlugin.LOGGER.error("Failed to start raknetify server", t);
}
}
}
} catch (Throwable t) {
throw new RuntimeException("Failed to start raknetify server", t);
}
} else {
startServer(address);
}
}
private static void startServer(InetSocketAddress address) {
try {
final ConnectionManager cm = (ConnectionManager) accessible(VelocityServer.class.getDeclaredField("cm")).get(RaknetifyVelocityPlugin.PROXY);
final Object transportType = accessible(ConnectionManager.class.getDeclaredField("transportType")).get(cm);
final ChannelFactory extends DatagramChannel> datagramChannelFactory =
(ChannelFactory extends DatagramChannel>) accessible(Class.forName("com.velocitypowered.proxy.network.TransportType").getDeclaredField("datagramChannelFactory")).get(transportType);
final EventLoopGroup bossGroup = (EventLoopGroup) accessible(ConnectionManager.class.getDeclaredField("bossGroup")).get(cm);
final EventLoopGroup workerGroup = (EventLoopGroup) accessible(ConnectionManager.class.getDeclaredField("workerGroup")).get(cm);
final boolean hasPortOverride = portOverride > 0 && portOverride < 65535;
InetSocketAddress actualAddress = hasPortOverride ? new InetSocketAddress(address.getAddress(), portOverride) : address;
synchronized (channels) {
for (ChannelFuture future : channels) {
if (future.channel().localAddress().equals(actualAddress)) return;
}
ChannelFuture future = new ServerBootstrap()
.channelFactory(() -> new RakNetServerChannel(() -> {
final DatagramChannel channel = datagramChannelFactory.newChannel();
channel.config().setOption(ChannelOption.IP_TOS, RakNetConnectionUtil.DEFAULT_IP_TOS);
channel.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(Constants.LARGE_MTU + 512).maxMessagesPerRead(128));
return channel;
}))
.group(bossGroup, workerGroup)
.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(Channel channel) throws Exception {
RakNetVelocityConnectionUtil.initChannel(channel);
INIT_CHANNEL.invoke(cm.serverChannelInitializer.get(), channel);
RakNetVelocityConnectionUtil.postInitChannel(channel, false);
}
})
.localAddress(actualAddress)
.bind()
.syncUninterruptibly();
RaknetifyVelocityPlugin.LOGGER.info("Raknetify server started on {}", future.channel().localAddress());
channels.add(future);
}
} catch (Throwable t) {
if (t instanceof IOException) {
RaknetifyVelocityPlugin.LOGGER.error("Raknetify server failed to start on {}: {}", address, t.getMessage());
return;
}
throw new RuntimeException("Failed to start Raknetify server", t);
}
}
public static void stop(ListenerCloseEvent evt) {
if (evt.getListenerType() != ListenerType.MINECRAFT) return;
Preconditions.checkArgument(RaknetifyVelocityPlugin.PROXY instanceof VelocityServer);
Preconditions.checkState(!channels.isEmpty(), "Raknetify Server is not running");
synchronized (channels) {
active = false;
for (ChannelFuture channel : channels) {
closeServer(channel);
}
channels.clear();
}
}
private static void closeServer(ChannelFuture channel) {
RaknetifyVelocityPlugin.LOGGER.info("Closing Raknetify server {}", channel.channel().localAddress());
try {
channel.channel().close().sync();
} catch (InterruptedException e) {
RaknetifyVelocityPlugin.LOGGER.error("Interrupted whilst closing raknetify server");
}
}
}
================================================
FILE: velocity/src/main/resources/velocity-plugin.json
================================================
{
"id": "raknetify",
"name": "Raknetify (Velocity)",
"version": "${version}",
"description": "A Velocity plugin that allows using RakNet as Minecraft networking backend. ",
"authors": ["ishland"],
"dependencies": [],
"main": "com.ishland.raknetify.velocity.RaknetifyVelocityPlugin"
}