├── .github └── workflows │ └── gradle.yml ├── .gitignore ├── LICENSE ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main ├── java └── net │ └── kernelcraft │ └── websocketfabric │ ├── WebSocketClientConnection.java │ ├── WebSocketConstants.java │ ├── WebSocketFabric.java │ ├── codec │ ├── FrameToPacketDecoder.java │ └── PacketToFrameEncoder.java │ ├── handler │ ├── ClientConnectedEventHandler.java │ └── ConnectedEventHandler.java │ ├── http │ └── WebSocketPageHandler.java │ ├── initializer │ ├── ClientWebSocketInitializer.java │ ├── ServerWebSocketInitializer.java │ └── listener │ │ └── ConnectedListener.java │ └── mixin │ ├── ClientConnectionAccessor.java │ ├── MixinClientConnection.java │ ├── MixinServerNetworkIo.java │ └── ServerNetworkIoAccessor.java └── resources ├── fabric.mod.json ├── websocketfabric.accesswidener └── websocketfabric.mixins.json /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | name: Build Gradle project 2 | 3 | on: 4 | push: 5 | 6 | jobs: 7 | build-gradle-project: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | contents: write 11 | steps: 12 | - name: Checkout project sources 13 | uses: actions/checkout@v3 14 | - uses: dev-drprasad/delete-tag-and-release@v0.2.0 15 | with: 16 | delete_release: true 17 | tag_name: "Latest" 18 | env: 19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 20 | - name: Setup Java 17 JDK 21 | uses: actions/setup-java@v3 22 | with: 23 | distribution: 'temurin' 24 | java-version: '17' 25 | - name: Setup Gradle 26 | uses: gradle/gradle-build-action@v2 27 | - name: Modify Gradlew permissions 28 | run: chmod +x ./gradlew 29 | - name: Build Gradlew project 30 | run: ./gradlew remapJar 31 | - name: Artifact upload 32 | uses: actions/upload-artifact@v3 33 | with: 34 | name: JARs 35 | path: build/libs 36 | 37 | - uses: ncipollo/release-action@v1 38 | with: 39 | artifacts: "./build/libs/*.jar" 40 | tag: "Latest" 41 | token: ${{ secrets.GITHUB_TOKEN }} 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # User-specific stuff 2 | .idea/ 3 | 4 | *.iml 5 | *.ipr 6 | *.iws 7 | 8 | # IntelliJ 9 | out/ 10 | # mpeltonen/sbt-idea plugin 11 | .idea_modules/ 12 | 13 | # JIRA plugin 14 | atlassian-ide-plugin.xml 15 | 16 | # Compiled class file 17 | *.class 18 | 19 | # Log file 20 | *.log 21 | 22 | # BlueJ files 23 | *.ctxt 24 | 25 | # Package Files # 26 | *.jar 27 | *.war 28 | *.nar 29 | *.ear 30 | *.zip 31 | *.tar.gz 32 | *.rar 33 | 34 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 35 | hs_err_pid* 36 | 37 | *~ 38 | 39 | # temporary files which can be created if a process still has a handle open of a deleted file 40 | .fuse_hidden* 41 | 42 | # KDE directory preferences 43 | .directory 44 | 45 | # Linux trash folder which might appear on any partition or disk 46 | .Trash-* 47 | 48 | # .nfs files are created when an open file is removed but is still being accessed 49 | .nfs* 50 | 51 | # General 52 | .DS_Store 53 | .AppleDouble 54 | .LSOverride 55 | 56 | # Icon must end with two \r 57 | Icon 58 | 59 | # Thumbnails 60 | ._* 61 | 62 | # Files that might appear in the root of a volume 63 | .DocumentRevisions-V100 64 | .fseventsd 65 | .Spotlight-V100 66 | .TemporaryItems 67 | .Trashes 68 | .VolumeIcon.icns 69 | .com.apple.timemachine.donotpresent 70 | 71 | # Directories potentially created on remote AFP share 72 | .AppleDB 73 | .AppleDesktop 74 | Network Trash Folder 75 | Temporary Items 76 | .apdisk 77 | 78 | # Windows thumbnail cache files 79 | Thumbs.db 80 | Thumbs.db:encryptable 81 | ehthumbs.db 82 | ehthumbs_vista.db 83 | 84 | # Dump file 85 | *.stackdump 86 | 87 | # Folder config file 88 | [Dd]esktop.ini 89 | 90 | # Recycle Bin used on file shares 91 | $RECYCLE.BIN/ 92 | 93 | # Windows Installer files 94 | *.cab 95 | *.msi 96 | *.msix 97 | *.msm 98 | *.msp 99 | 100 | # Windows shortcuts 101 | *.lnk 102 | 103 | .gradle 104 | build/ 105 | 106 | # Ignore Gradle GUI config 107 | gradle-app.setting 108 | 109 | # Cache of project 110 | .gradletasknamecache 111 | 112 | **/build/ 113 | 114 | # Common working directory 115 | run/ 116 | 117 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 118 | !gradle-wrapper.jar 119 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 KernelFreeze 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'fabric-loom' version '0.12-SNAPSHOT' 3 | id 'maven-publish' 4 | } 5 | 6 | version = project.mod_version 7 | group = project.maven_group 8 | 9 | dependencies { 10 | minecraft "com.mojang:minecraft:${project.minecraft_version}" 11 | mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" 12 | 13 | modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" 14 | modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" 15 | 16 | modImplementation 'io.netty:netty-codec-http:4.1.79.Final' 17 | include 'io.netty:netty-codec-http:4.1.79.Final' 18 | } 19 | 20 | processResources { 21 | inputs.property "version", project.version 22 | filteringCharset "UTF-8" 23 | 24 | filesMatching("fabric.mod.json") { 25 | expand "version": project.version 26 | } 27 | } 28 | 29 | def targetJavaVersion = 17 30 | tasks.withType(JavaCompile).configureEach { 31 | // ensure that the encoding is set to UTF-8, no matter what the system default is 32 | // this fixes some edge cases with special characters not displaying correctly 33 | // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html 34 | // If Javadoc is generated, this must be specified in that task too. 35 | it.options.encoding = "UTF-8" 36 | if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { 37 | it.options.release = targetJavaVersion 38 | } 39 | } 40 | 41 | java { 42 | def javaVersion = JavaVersion.toVersion(targetJavaVersion) 43 | if (JavaVersion.current() < javaVersion) { 44 | toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) 45 | } 46 | archivesBaseName = project.archives_base_name 47 | // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task 48 | // if it is present. 49 | // If you remove this line, sources will not be generated. 50 | withSourcesJar() 51 | } 52 | 53 | jar { 54 | from("LICENSE") { 55 | rename { "${it}_${project.archivesBaseName}" } 56 | } 57 | } 58 | 59 | loom { 60 | accessWidenerPath = file("src/main/resources/websocketfabric.accesswidener") 61 | } 62 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Done to increase the memory available to gradle. 2 | org.gradle.jvmargs=-Xmx1G 3 | 4 | # Fabric Properties 5 | # check these on https://modmuss50.me/fabric.html 6 | minecraft_version=1.19 7 | yarn_mappings=1.19+build.4 8 | loader_version=0.14.8 9 | 10 | # Mod Properties 11 | mod_version=1.0-SNAPSHOT 12 | maven_group=net.kernelcraft 13 | archives_base_name=WebSocketFabric 14 | 15 | # Dependencies 16 | # check this on https://modmuss50.me/fabric.html 17 | fabric_version=0.57.0+1.19 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KernelFreeze/WebSocketFabric/7a49af89eb4fa73e1da0d2d52b0357e30c18ec96/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven { 4 | name = 'Fabric' 5 | url = 'https://maven.fabricmc.net/' 6 | } 7 | gradlePluginPortal() 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/WebSocketClientConnection.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric; 2 | 3 | import java.util.List; 4 | 5 | import com.google.common.collect.Lists; 6 | import com.mojang.logging.LogUtils; 7 | import io.netty.channel.Channel; 8 | import io.netty.channel.ChannelFutureListener; 9 | import io.netty.channel.ChannelHandlerContext; 10 | import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; 11 | import io.netty.util.concurrent.Future; 12 | import io.netty.util.concurrent.GenericFutureListener; 13 | import net.kernelcraft.websocketfabric.initializer.listener.ConnectedListener; 14 | import net.kernelcraft.websocketfabric.mixin.ClientConnectionAccessor; 15 | import net.minecraft.network.ClientConnection; 16 | import net.minecraft.network.NetworkSide; 17 | import net.minecraft.network.NetworkState; 18 | import net.minecraft.network.Packet; 19 | import net.minecraft.text.Text; 20 | import org.jetbrains.annotations.Nullable; 21 | import org.slf4j.Logger; 22 | 23 | public class WebSocketClientConnection extends ClientConnection { 24 | private boolean connected = false; 25 | private static final Logger LOGGER = LogUtils.getLogger(); 26 | private final List connectionListeners = Lists.newArrayList(); 27 | 28 | public WebSocketClientConnection(NetworkSide side) { 29 | super(side); 30 | } 31 | 32 | public void addConnectedListener(ConnectedListener listener) { 33 | this.connectionListeners.add(listener); 34 | } 35 | 36 | public void onConnected() { 37 | this.connected = true; 38 | 39 | for (var listener : this.connectionListeners) { 40 | try { 41 | listener.onConnected(); 42 | } catch (Exception e) { 43 | LOGGER.error("Error while calling onConnected()", e); 44 | } 45 | } 46 | } 47 | 48 | @Override 49 | public void disconnect(Text disconnectReason) { 50 | var accessor = (ClientConnectionAccessor) this; 51 | var channel = getChannel(); 52 | 53 | if (channel.isOpen()) { 54 | channel 55 | .writeAndFlush(new CloseWebSocketFrame()) 56 | .addListener(ChannelFutureListener.CLOSE); 57 | accessor.setDisconnectReason(disconnectReason); 58 | } 59 | } 60 | 61 | @Override 62 | public void channelActive(ChannelHandlerContext ctx) { 63 | ctx.fireChannelActive(); 64 | 65 | var accessor = (ClientConnectionAccessor) this; 66 | 67 | accessor.setChannel(ctx.channel()); 68 | accessor.setAddress(ctx.channel().remoteAddress()); 69 | } 70 | 71 | @Override 72 | public void send(Packet packet, @Nullable GenericFutureListener> callback) { 73 | this.packetQueue.add(new QueuedPacket(packet, callback)); 74 | this.sendQueuedPackets(); 75 | } 76 | 77 | private NetworkState getState() { 78 | return getChannel().attr(PROTOCOL_ATTRIBUTE_KEY).get(); 79 | } 80 | 81 | private Channel getChannel() { 82 | var accessor = (ClientConnectionAccessor) this; 83 | return accessor.getChannel(); 84 | } 85 | 86 | @Override 87 | protected void sendImmediately(Packet packet, 88 | @Nullable GenericFutureListener> callback) { 89 | var packetState = NetworkState.getPacketHandlerState(packet); 90 | var protocolState = this.getState(); 91 | 92 | var newState = packetState != protocolState; 93 | 94 | if (getChannel().eventLoop().inEventLoop()) { 95 | if (newState) { 96 | this.setState(packetState); 97 | } 98 | doSendPacket(packet, callback); 99 | } else { 100 | // Note: In newer versions of Netty, we could use AbstractEventExecutor.LazyRunnable to avoid a wakeup. 101 | // This has the advantage of requiring slightly less code. 102 | // However, in practice, (almost) every write will use a WriteTask which doesn't wake up the event loop. 103 | // The only exceptions are transitioning states (very rare) and when a listener is provided (but this is 104 | // only upon disconnect of a client). So we can sit back and enjoy the GC savings. 105 | if (!newState && callback == null) { 106 | var voidPromise = getChannel().voidPromise(); 107 | 108 | getChannel().writeAndFlush(packet, voidPromise); 109 | } else { 110 | // Fallback. 111 | if (newState) { 112 | getChannel().config().setAutoRead(false); 113 | } 114 | 115 | getChannel().eventLoop().execute(() -> { 116 | if (newState) { 117 | this.setState(packetState); 118 | } 119 | doSendPacket(packet, callback); 120 | }); 121 | } 122 | } 123 | } 124 | 125 | private void doSendPacket(Packet packet, 126 | @Nullable GenericFutureListener> callback) { 127 | if (callback == null) { 128 | getChannel().write(packet, getChannel().voidPromise()); 129 | } else { 130 | var channelFuture = getChannel().write(packet); 131 | channelFuture.addListener(callback); 132 | channelFuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); 133 | } 134 | 135 | getChannel().flush(); 136 | } 137 | 138 | @Override 139 | protected void sendQueuedPackets() { 140 | if (!this.connected) { 141 | return; 142 | } 143 | super.sendQueuedPackets(); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/WebSocketConstants.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric; 2 | 3 | public class WebSocketConstants { 4 | public static final String WEBSOCKET_PATH = "/websocket"; 5 | public static final int MAX_SIZE = 0x900000; 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/WebSocketFabric.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric; 2 | 3 | import net.fabricmc.api.ModInitializer; 4 | 5 | public class WebSocketFabric implements ModInitializer { 6 | @Override 7 | public void onInitialize() { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/codec/FrameToPacketDecoder.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.codec; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | 6 | import com.mojang.logging.LogUtils; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.handler.codec.MessageToMessageDecoder; 9 | import io.netty.handler.codec.http.websocketx.WebSocketFrame; 10 | import net.minecraft.network.ClientConnection; 11 | import net.minecraft.network.NetworkSide; 12 | import net.minecraft.network.PacketByteBuf; 13 | import net.minecraft.util.profiling.jfr.FlightProfiler; 14 | import org.slf4j.Logger; 15 | 16 | public class FrameToPacketDecoder extends MessageToMessageDecoder { 17 | private static final Logger LOGGER = LogUtils.getLogger(); 18 | private final NetworkSide side; 19 | 20 | public FrameToPacketDecoder(NetworkSide side) { 21 | this.side = side; 22 | } 23 | 24 | @Override 25 | protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List out) throws IOException { 26 | var packetByteBuf = new PacketByteBuf(msg.content().retain()); 27 | var availableBytes = packetByteBuf.readableBytes(); 28 | if (availableBytes == 0) { 29 | return; 30 | } 31 | 32 | var packetId = packetByteBuf.readVarInt(); 33 | var packet = ctx.channel().attr(ClientConnection.PROTOCOL_ATTRIBUTE_KEY).get() 34 | .getPacketHandler(this.side, packetId, packetByteBuf); 35 | if (packet == null) { 36 | throw new IOException("Bad packet id " + packetId); 37 | } 38 | var protocolId = ctx.channel().attr(ClientConnection.PROTOCOL_ATTRIBUTE_KEY).get().getId(); 39 | FlightProfiler.INSTANCE.onPacketReceived(protocolId, packetId, ctx.channel().remoteAddress(), availableBytes); 40 | 41 | if (packetByteBuf.readableBytes() > 0) { 42 | throw new IOException( 43 | "Packet %d/%d (%s) was larger than I expected, found %d bytes extra whilst reading packet %d".formatted( 44 | ctx.channel().attr(ClientConnection.PROTOCOL_ATTRIBUTE_KEY).get() 45 | .getId(), packetId, packet.getClass() 46 | .getSimpleName(), packetByteBuf.readableBytes(), packetId)); 47 | } 48 | out.add(packet); 49 | } 50 | } -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/codec/PacketToFrameEncoder.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.codec; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | 6 | import com.mojang.logging.LogUtils; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.handler.codec.MessageToMessageEncoder; 9 | import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; 10 | import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; 11 | import net.kernelcraft.websocketfabric.WebSocketConstants; 12 | import net.minecraft.network.ClientConnection; 13 | import net.minecraft.network.NetworkSide; 14 | import net.minecraft.network.Packet; 15 | import net.minecraft.network.PacketEncoderException; 16 | import net.minecraft.util.profiling.jfr.FlightProfiler; 17 | import org.slf4j.Logger; 18 | 19 | public class PacketToFrameEncoder extends MessageToMessageEncoder> { 20 | private static final Logger LOGGER = LogUtils.getLogger(); 21 | 22 | private final NetworkSide side; 23 | 24 | public PacketToFrameEncoder(NetworkSide side) { 25 | this.side = side; 26 | } 27 | 28 | @Override 29 | protected void encode(ChannelHandlerContext ctx, Packet packet, List out) throws Exception { 30 | var networkState = ctx.channel().attr(ClientConnection.PROTOCOL_ATTRIBUTE_KEY).get(); 31 | if (networkState == null) { 32 | throw new RuntimeException("ConnectionProtocol unknown: " + packet); 33 | } 34 | 35 | var packetId = networkState.getPacketId(this.side, packet); 36 | if (packetId == null) { 37 | throw new IOException("Can't serialize unregistered packet"); 38 | } 39 | 40 | var packetByteBuf = PacketByteBufs.create(); 41 | packetByteBuf.writeVarInt(packetId); 42 | 43 | try { 44 | var writerIndex = packetByteBuf.writerIndex(); 45 | packet.write(packetByteBuf); 46 | 47 | var packetSize = packetByteBuf.writerIndex() - writerIndex; 48 | if (packetSize > WebSocketConstants.MAX_SIZE) { 49 | throw new IllegalArgumentException( 50 | "Packet too big (is %d, should be less than %d): %s".formatted(packetSize, 51 | WebSocketConstants.MAX_SIZE, packet)); 52 | } 53 | 54 | var protocolId = ctx.channel().attr(ClientConnection.PROTOCOL_ATTRIBUTE_KEY).get().getId(); 55 | FlightProfiler.INSTANCE.onPacketSent(protocolId, packetId, ctx.channel().remoteAddress(), packetSize); 56 | } catch (Throwable throwable) { 57 | LOGGER.error("Error encoding packet {}", packetId, throwable); 58 | if (packet.isWritingErrorSkippable()) { 59 | throw new PacketEncoderException(throwable); 60 | } 61 | throw throwable; 62 | } 63 | 64 | out.add(new BinaryWebSocketFrame(packetByteBuf)); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/handler/ClientConnectedEventHandler.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.handler; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.SimpleUserEventChannelHandler; 5 | import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler; 6 | import net.kernelcraft.websocketfabric.WebSocketClientConnection; 7 | 8 | public class ClientConnectedEventHandler extends 9 | SimpleUserEventChannelHandler { 10 | private final WebSocketClientConnection clientConnection; 11 | 12 | public ClientConnectedEventHandler(WebSocketClientConnection clientConnection) { 13 | this.clientConnection = clientConnection; 14 | } 15 | 16 | @Override 17 | protected void eventReceived(ChannelHandlerContext ctx, 18 | WebSocketClientProtocolHandler.ClientHandshakeStateEvent event) { 19 | if (event == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) { 20 | clientConnection.onConnected(); 21 | } else { 22 | ctx.fireUserEventTriggered(event); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/handler/ConnectedEventHandler.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.handler; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.SimpleUserEventChannelHandler; 5 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 6 | import net.kernelcraft.websocketfabric.WebSocketClientConnection; 7 | 8 | public class ConnectedEventHandler extends 9 | SimpleUserEventChannelHandler { 10 | private final WebSocketClientConnection clientConnection; 11 | 12 | public ConnectedEventHandler(WebSocketClientConnection clientConnection) { 13 | this.clientConnection = clientConnection; 14 | } 15 | 16 | @Override 17 | protected void eventReceived(ChannelHandlerContext ctx, 18 | WebSocketServerProtocolHandler.HandshakeComplete event) { 19 | clientConnection.onConnected(); 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/http/WebSocketPageHandler.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.http; 2 | 3 | import io.netty.buffer.Unpooled; 4 | import io.netty.channel.ChannelFutureListener; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.SimpleChannelInboundHandler; 7 | import io.netty.handler.codec.http.DefaultFullHttpResponse; 8 | import io.netty.handler.codec.http.FullHttpRequest; 9 | import io.netty.handler.codec.http.FullHttpResponse; 10 | import io.netty.handler.codec.http.HttpResponseStatus; 11 | import io.netty.handler.codec.http.HttpUtil; 12 | import io.netty.handler.codec.http.HttpVersion; 13 | import io.netty.util.CharsetUtil; 14 | 15 | public class WebSocketPageHandler extends SimpleChannelInboundHandler { 16 | @Override 17 | protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { 18 | sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST)); 19 | } 20 | 21 | private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { 22 | var buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); 23 | res.content().writeBytes(buf); 24 | buf.release(); 25 | HttpUtil.setContentLength(res, res.content().readableBytes()); 26 | 27 | // Send the response and close the connection if necessary. 28 | var f = ctx.channel().writeAndFlush(res); 29 | if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { 30 | f.addListener(ChannelFutureListener.CLOSE); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/initializer/ClientWebSocketInitializer.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.initializer; 2 | 3 | import java.net.URI; 4 | 5 | import io.netty.channel.Channel; 6 | import io.netty.channel.ChannelDuplexHandler; 7 | import io.netty.channel.ChannelException; 8 | import io.netty.channel.ChannelInitializer; 9 | import io.netty.channel.ChannelOption; 10 | import io.netty.handler.codec.http.DefaultHttpHeaders; 11 | import io.netty.handler.codec.http.HttpClientCodec; 12 | import io.netty.handler.codec.http.HttpHeaderNames; 13 | import io.netty.handler.codec.http.HttpObjectAggregator; 14 | import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; 15 | import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler; 16 | import io.netty.handler.codec.http.websocketx.WebSocketVersion; 17 | import io.netty.handler.timeout.ReadTimeoutHandler; 18 | import net.kernelcraft.websocketfabric.WebSocketClientConnection; 19 | import net.kernelcraft.websocketfabric.WebSocketConstants; 20 | import net.kernelcraft.websocketfabric.codec.FrameToPacketDecoder; 21 | import net.kernelcraft.websocketfabric.codec.PacketToFrameEncoder; 22 | import net.kernelcraft.websocketfabric.handler.ClientConnectedEventHandler; 23 | import net.minecraft.network.NetworkSide; 24 | import net.minecraft.network.NetworkState; 25 | import org.jetbrains.annotations.NotNull; 26 | 27 | public class ClientWebSocketInitializer extends ChannelInitializer { 28 | private final WebSocketClientConnection clientConnection; 29 | private final URI uri; 30 | 31 | public ClientWebSocketInitializer(WebSocketClientConnection clientConnection, URI uri) { 32 | this.clientConnection = clientConnection; 33 | this.uri = uri; 34 | } 35 | 36 | @Override 37 | protected void initChannel(@NotNull Channel channel) { 38 | setTCPNoDelay(channel); 39 | 40 | var handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, "minecraft", false, 41 | new DefaultHttpHeaders().add(HttpHeaderNames.USER_AGENT, "MinecraftClient/1.0"), 1280000); 42 | 43 | channel.pipeline() 44 | .addLast(new HttpClientCodec()) 45 | .addLast(new HttpObjectAggregator(WebSocketConstants.MAX_SIZE)) 46 | .addLast(new WebSocketClientProtocolHandler(handshaker)) 47 | .addLast(new ClientConnectedEventHandler(clientConnection)) 48 | .addLast("timeout", new ReadTimeoutHandler(30)) 49 | .addLast("splitter", new ChannelDuplexHandler()) // no-op 50 | .addLast("decoder", new FrameToPacketDecoder(NetworkSide.CLIENTBOUND)) 51 | .addLast("prepender", new ChannelDuplexHandler()) // no-op 52 | .addLast("encoder", new PacketToFrameEncoder(NetworkSide.SERVERBOUND)) 53 | .addLast("packet_handler", clientConnection); 54 | 55 | clientConnection.addConnectedListener(() -> clientConnection.setState(NetworkState.HANDSHAKING)); 56 | } 57 | 58 | private static void setTCPNoDelay(Channel channel) { 59 | try { 60 | channel.config().setOption(ChannelOption.TCP_NODELAY, true); 61 | } catch (ChannelException channelException) { 62 | // empty catch block 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/initializer/ServerWebSocketInitializer.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.initializer; 2 | 3 | import com.mojang.logging.LogUtils; 4 | import io.netty.channel.Channel; 5 | import io.netty.channel.ChannelDuplexHandler; 6 | import io.netty.channel.ChannelException; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelOption; 9 | import io.netty.handler.codec.http.HttpObjectAggregator; 10 | import io.netty.handler.codec.http.HttpServerCodec; 11 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 12 | import io.netty.handler.timeout.ReadTimeoutHandler; 13 | import net.kernelcraft.websocketfabric.WebSocketClientConnection; 14 | import net.kernelcraft.websocketfabric.WebSocketConstants; 15 | import net.kernelcraft.websocketfabric.codec.FrameToPacketDecoder; 16 | import net.kernelcraft.websocketfabric.codec.PacketToFrameEncoder; 17 | import net.kernelcraft.websocketfabric.handler.ClientConnectedEventHandler; 18 | import net.kernelcraft.websocketfabric.handler.ConnectedEventHandler; 19 | import net.kernelcraft.websocketfabric.http.WebSocketPageHandler; 20 | import net.kernelcraft.websocketfabric.mixin.ServerNetworkIoAccessor; 21 | import net.minecraft.network.NetworkSide; 22 | import net.minecraft.network.NetworkState; 23 | import net.minecraft.server.MinecraftServer; 24 | import net.minecraft.server.network.ServerHandshakeNetworkHandler; 25 | import org.jetbrains.annotations.NotNull; 26 | import org.slf4j.Logger; 27 | 28 | public class ServerWebSocketInitializer extends ChannelInitializer { 29 | private static final Logger LOGGER = LogUtils.getLogger(); 30 | 31 | private final MinecraftServer server; 32 | private final ServerNetworkIoAccessor networkIo; 33 | 34 | public ServerWebSocketInitializer(MinecraftServer server) { 35 | this.server = server; 36 | this.networkIo = (ServerNetworkIoAccessor) server.getNetworkIo(); 37 | } 38 | 39 | @Override 40 | public void initChannel(@NotNull Channel channel) { 41 | setTCPNoDelay(channel); 42 | var clientConnection = new WebSocketClientConnection(NetworkSide.SERVERBOUND); 43 | 44 | networkIo.getConnections().add(clientConnection); 45 | clientConnection.setPacketListener(new ServerHandshakeNetworkHandler(server, clientConnection)); 46 | 47 | channel.pipeline() 48 | .addLast(new HttpServerCodec()) 49 | .addLast(new HttpObjectAggregator(WebSocketConstants.MAX_SIZE)) 50 | .addLast(new WebSocketServerProtocolHandler(WebSocketConstants.WEBSOCKET_PATH, "minecraft", true)) 51 | .addLast(new WebSocketPageHandler()) 52 | .addLast(new ConnectedEventHandler(clientConnection)) 53 | .addLast("timeout", new ReadTimeoutHandler(120)) 54 | .addLast("splitter", new ChannelDuplexHandler()) // no-op 55 | .addLast("decoder", new FrameToPacketDecoder(NetworkSide.SERVERBOUND)) 56 | .addLast("prepender", new ChannelDuplexHandler()) 57 | .addLast("encoder", new PacketToFrameEncoder(NetworkSide.CLIENTBOUND)) 58 | .addLast("packet_handler", clientConnection); 59 | 60 | clientConnection.addConnectedListener(() -> { 61 | LOGGER.info("Client '{}' connected", clientConnection.getAddress()); 62 | clientConnection.setState(NetworkState.HANDSHAKING); 63 | }); 64 | } 65 | 66 | private void setTCPNoDelay(@NotNull Channel ch) { 67 | try { 68 | ch.config().setOption(ChannelOption.TCP_NODELAY, true); 69 | } catch (ChannelException ignored) { 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/initializer/listener/ConnectedListener.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.initializer.listener; 2 | 3 | public interface ConnectedListener { 4 | void onConnected(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/mixin/ClientConnectionAccessor.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.mixin; 2 | 3 | import java.net.SocketAddress; 4 | 5 | import io.netty.channel.Channel; 6 | import net.minecraft.network.ClientConnection; 7 | import net.minecraft.text.Text; 8 | import org.jetbrains.annotations.Nullable; 9 | import org.spongepowered.asm.mixin.Mixin; 10 | import org.spongepowered.asm.mixin.gen.Accessor; 11 | 12 | @Mixin(ClientConnection.class) 13 | public interface ClientConnectionAccessor { 14 | @Accessor 15 | void setChannel(Channel channel); 16 | 17 | @Accessor 18 | void setAddress(SocketAddress address); 19 | 20 | @Accessor 21 | Channel getChannel(); 22 | 23 | @Accessor 24 | SocketAddress getAddress(); 25 | 26 | @Accessor 27 | void setDisconnectReason(@Nullable Text disconnectReason); 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/mixin/MixinClientConnection.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.mixin; 2 | 3 | import java.net.InetSocketAddress; 4 | import java.net.URI; 5 | import java.net.URISyntaxException; 6 | 7 | import io.netty.bootstrap.Bootstrap; 8 | import io.netty.channel.EventLoopGroup; 9 | import io.netty.channel.epoll.Epoll; 10 | import io.netty.channel.epoll.EpollEventLoopGroup; 11 | import io.netty.channel.epoll.EpollSocketChannel; 12 | import io.netty.channel.nio.NioEventLoopGroup; 13 | import io.netty.channel.socket.SocketChannel; 14 | import io.netty.channel.socket.nio.NioSocketChannel; 15 | import net.kernelcraft.websocketfabric.WebSocketClientConnection; 16 | import net.kernelcraft.websocketfabric.initializer.ClientWebSocketInitializer; 17 | import net.kernelcraft.websocketfabric.WebSocketConstants; 18 | import net.minecraft.network.ClientConnection; 19 | import net.minecraft.network.NetworkSide; 20 | import net.minecraft.util.Lazy; 21 | import org.spongepowered.asm.mixin.Final; 22 | import org.spongepowered.asm.mixin.Mixin; 23 | import org.spongepowered.asm.mixin.Overwrite; 24 | import org.spongepowered.asm.mixin.Shadow; 25 | 26 | @SuppressWarnings("deprecation") 27 | @Mixin(ClientConnection.class) 28 | public class MixinClientConnection { 29 | @Shadow 30 | @Final 31 | public static Lazy EPOLL_CLIENT_IO_GROUP; 32 | 33 | @Shadow 34 | @Final 35 | public static Lazy CLIENT_IO_GROUP; 36 | 37 | /** 38 | * @author KernelFreeze 39 | * @reason Overwritten to use WebSocketInitializer 40 | */ 41 | @Overwrite 42 | public static ClientConnection connect(InetSocketAddress address, boolean useEpoll) throws URISyntaxException { 43 | Lazy lazy; 44 | Class socketChannel; 45 | 46 | var clientConnection = new WebSocketClientConnection(NetworkSide.CLIENTBOUND); 47 | if (Epoll.isAvailable() && useEpoll) { 48 | socketChannel = EpollSocketChannel.class; 49 | lazy = EPOLL_CLIENT_IO_GROUP; 50 | } else { 51 | socketChannel = NioSocketChannel.class; 52 | lazy = CLIENT_IO_GROUP; 53 | } 54 | 55 | var uri = new URI("ws://" + address.getHostString() + ":" + address.getPort() + WebSocketConstants.WEBSOCKET_PATH); 56 | new Bootstrap() 57 | .group(lazy.get()) 58 | .handler(new ClientWebSocketInitializer(clientConnection, uri)) 59 | .channel(socketChannel) 60 | .connect(address.getAddress(), address.getPort()) 61 | .syncUninterruptibly(); 62 | return clientConnection; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/mixin/MixinServerNetworkIo.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.mixin; 2 | 3 | import java.io.IOException; 4 | import java.net.InetAddress; 5 | import java.util.List; 6 | 7 | import io.netty.bootstrap.ServerBootstrap; 8 | import io.netty.channel.ChannelFuture; 9 | import io.netty.channel.EventLoopGroup; 10 | import io.netty.channel.epoll.Epoll; 11 | import io.netty.channel.epoll.EpollEventLoopGroup; 12 | import io.netty.channel.epoll.EpollServerSocketChannel; 13 | import io.netty.channel.nio.NioEventLoopGroup; 14 | import io.netty.channel.socket.ServerSocketChannel; 15 | import io.netty.channel.socket.nio.NioServerSocketChannel; 16 | import net.kernelcraft.websocketfabric.initializer.ServerWebSocketInitializer; 17 | import net.minecraft.server.MinecraftServer; 18 | import net.minecraft.server.ServerNetworkIo; 19 | import net.minecraft.util.Lazy; 20 | import org.jetbrains.annotations.Nullable; 21 | import org.slf4j.Logger; 22 | import org.spongepowered.asm.mixin.Final; 23 | import org.spongepowered.asm.mixin.Mixin; 24 | import org.spongepowered.asm.mixin.Overwrite; 25 | import org.spongepowered.asm.mixin.Shadow; 26 | 27 | @SuppressWarnings("deprecation") 28 | @Mixin(ServerNetworkIo.class) 29 | public abstract class MixinServerNetworkIo { 30 | @Shadow 31 | @Final 32 | MinecraftServer server; 33 | 34 | @Shadow 35 | @Final 36 | private List channels; 37 | 38 | @Shadow 39 | @Final 40 | public static Lazy EPOLL_CHANNEL; 41 | 42 | @Shadow 43 | @Final 44 | public static Lazy DEFAULT_CHANNEL; 45 | 46 | @Shadow 47 | @Final 48 | private static Logger LOGGER; 49 | 50 | /** 51 | * @author KernelFreeze 52 | * @reason Overwritten to use WebSocketInitializer 53 | */ 54 | @SuppressWarnings("SynchronizeOnNonFinalField") 55 | @Overwrite 56 | public void bind(@Nullable InetAddress address, int port) throws IOException { 57 | synchronized (this.channels) { 58 | Lazy lazy; 59 | Class socketChannel; 60 | 61 | if (Epoll.isAvailable() && this.server.isUsingNativeTransport()) { 62 | socketChannel = EpollServerSocketChannel.class; 63 | lazy = EPOLL_CHANNEL; 64 | LOGGER.info("Using epoll channel type"); 65 | } else { 66 | socketChannel = NioServerSocketChannel.class; 67 | lazy = DEFAULT_CHANNEL; 68 | LOGGER.info("Using default channel type"); 69 | } 70 | 71 | this.channels.add(new ServerBootstrap() 72 | .channel(socketChannel) 73 | .childHandler(new ServerWebSocketInitializer(server)) 74 | .group(lazy.get()) 75 | .localAddress(address, port) 76 | .bind() 77 | .syncUninterruptibly()); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/net/kernelcraft/websocketfabric/mixin/ServerNetworkIoAccessor.java: -------------------------------------------------------------------------------- 1 | package net.kernelcraft.websocketfabric.mixin; 2 | 3 | import java.util.List; 4 | 5 | import net.minecraft.network.ClientConnection; 6 | import net.minecraft.server.ServerNetworkIo; 7 | import org.checkerframework.checker.nullness.qual.NonNull; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.gen.Accessor; 10 | 11 | @Mixin(ServerNetworkIo.class) 12 | public interface ServerNetworkIoAccessor { 13 | @Accessor 14 | @NonNull 15 | List getConnections(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "websocketfabric", 4 | "version": "${version}", 5 | "name": "WebSocketFabric", 6 | "description": "WebSocketFabric is a Minecraft mod that adds a WebSocket server and client to the game.", 7 | "authors": [ 8 | "KernelFreeze" 9 | ], 10 | "contact": {}, 11 | "license": "All-Rights-Reserved", 12 | "environment": "*", 13 | "entrypoints": { 14 | "main": [ 15 | "net.kernelcraft.websocketfabric.WebSocketFabric" 16 | ] 17 | }, 18 | "mixins": [ 19 | "websocketfabric.mixins.json" 20 | ], 21 | "depends": { 22 | "fabricloader": ">=0.14.8", 23 | "fabric": "*", 24 | "minecraft": "1.19" 25 | }, 26 | "accessWidener": "websocketfabric.accesswidener" 27 | } 28 | -------------------------------------------------------------------------------- /src/main/resources/websocketfabric.accesswidener: -------------------------------------------------------------------------------- 1 | accessWidener v1 named 2 | 3 | extendable method net/minecraft/network/ClientConnection sendQueuedPackets ()V 4 | accessible field net/minecraft/network/ClientConnection packetQueue Ljava/util/Queue; 5 | accessible class net/minecraft/network/ClientConnection$QueuedPacket 6 | extendable method net/minecraft/network/ClientConnection sendImmediately (Lnet/minecraft/network/Packet;Lio/netty/util/concurrent/GenericFutureListener;)V -------------------------------------------------------------------------------- /src/main/resources/websocketfabric.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "minVersion": "0.8", 4 | "package": "net.kernelcraft.websocketfabric.mixin", 5 | "compatibilityLevel": "JAVA_17", 6 | "mixins": [ 7 | "ClientConnectionAccessor", 8 | "MixinClientConnection", 9 | "MixinServerNetworkIo", 10 | "ServerNetworkIoAccessor" 11 | ], 12 | "injectors": { 13 | "defaultRequire": 1 14 | } 15 | } 16 | --------------------------------------------------------------------------------