diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..176a458 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/.gitignore b/.gitignore index c476faf..3baf9e7 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,6 @@ hs_err_*.log replay_*.log *.hprof *.jfr + +# bukkit +craftbukkit-0.0.1-SNAPSHOT.jar diff --git a/bukkit173/build.gradle b/bukkit173/build.gradle new file mode 100644 index 0000000..5a74073 --- /dev/null +++ b/bukkit173/build.gradle @@ -0,0 +1,38 @@ +apply plugin: 'java' + +repositories { + mavenCentral() +} + +dependencies { + implementation files('craftbukkit-0.0.1-SNAPSHOT.jar') +} + +tasks.withType(JavaCompile).configureEach { + it.options.encoding = "UTF-8" + it.options.release = 8 + it.options.compilerArgs += ['-Xlint:deprecation', '-Xlint:unchecked'] +} + +java { + withSourcesJar() + + sourceCompatibility = 1.8 + targetCompatibility = 1.8 +} + +sourceSets { + main { + java { + srcDirs = [ + '../src/shared', + '../src/rpc-simple', + '../src/bukkitb173', + ] + resources { + srcDirs = ['../src'] + include 'plugin.yml' + } + } + } +} diff --git a/bukkit173/gradle.properties b/bukkit173/gradle.properties new file mode 100644 index 0000000..9c0a032 --- /dev/null +++ b/bukkit173/gradle.properties @@ -0,0 +1,3 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +org.gradle.parallel=true diff --git a/bukkit173/gradle/wrapper/gradle-wrapper.jar b/bukkit173/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/bukkit173/gradle/wrapper/gradle-wrapper.jar differ diff --git a/bukkit173/gradle/wrapper/gradle-wrapper.properties b/bukkit173/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9f4197d --- /dev/null +++ b/bukkit173/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/bukkit173/gradlew b/bukkit173/gradlew new file mode 100644 index 0000000..fcb6fca --- /dev/null +++ b/bukkit173/gradlew @@ -0,0 +1,248 @@ +#!/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/HEAD/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + 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 + + +# 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"' + +# 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 \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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" "$@" diff --git a/bukkit173/gradlew.bat b/bukkit173/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/bukkit173/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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% equ 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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/fabric/build.gradle b/fabric/build.gradle index 44d9bae..8a055a3 100644 --- a/fabric/build.gradle +++ b/fabric/build.gradle @@ -49,7 +49,11 @@ jar { sourceSets { main { java { - srcDirs = ['../src/fabric'] + srcDirs = [ + '../src/shared', + '../src/rpc-gson', + '../src/fabric', + ] resources { srcDirs = ['../src'] include 'fabric.mod.json' diff --git a/fabric/gradle.properties b/fabric/gradle.properties index 65dcd5a..c7985aa 100644 --- a/fabric/gradle.properties +++ b/fabric/gradle.properties @@ -9,6 +9,6 @@ yarn_mappings=1.20.1+build.10 loader_version=0.14.22 # Mod Properties -mod_version=1.0.1 +mod_version=1.1.0 maven_group=net.flashii.mcexts archives_base_name=flashii-extensions diff --git a/src/bukkitb173/ConfigPath.java b/src/bukkitb173/ConfigPath.java new file mode 100644 index 0000000..f63a6b2 --- /dev/null +++ b/src/bukkitb173/ConfigPath.java @@ -0,0 +1,20 @@ +package net.flashii.mcexts; + +import java.io.File; +import java.nio.file.Path; + +public class ConfigPath { + private static Path configPath = null; + + public static Path getPath() { + return configPath; + } + + public static Path getPath(String name) { + return configPath.resolve(name); + } + + public static void setPath(File path) { + configPath = path.toPath().toAbsolutePath(); + } +} diff --git a/src/bukkitb173/JoinListener.java b/src/bukkitb173/JoinListener.java new file mode 100644 index 0000000..d28d30c --- /dev/null +++ b/src/bukkitb173/JoinListener.java @@ -0,0 +1,48 @@ +package net.flashii.mcexts; + +import org.bukkit.event.player.PlayerListener; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerLoginEvent.Result; + +public class JoinListener extends PlayerListener { + @Override + public void onPlayerLogin(PlayerLoginEvent ev) { + if(ev.getResult() != Result.ALLOWED) + return; + + String authText = null; + + try { + RPCPayload payload = RPC.postAuth(ev.getPlayer().getDisplayName(), ev.getKickMessage()); + + if(!payload.is("auth:ok")) { + if(payload.is("error")) { + authText = payload.getAttrStr(payload.hasAttr("text") ? "text" : "code"); + } else if(payload.is("auth:authorise")) { + String userName = payload.getAttrStr("user_name"); + String url = payload.getAttrStr("url"); + + if(userName.length() > 20) + userName = userName.substring(0, 20); + + authText = "Welcome back, " + userName + "! Go to " + url + " to verify yourself."; + } else if(payload.is("auth:link")) { + String code = payload.getAttrStr("code"); + String url = payload.getAttrStr("url"); + + authText = "Visit " + url + " to connect your Flashii ID. Link code: " + code; + } else { + authText = "Flashii server returned unknown response, yell at flashwave about this."; + } + } + } catch(Exception ex) { + authText = "There was a serious problem during authentication, yell at flashwave about this."; + ex.printStackTrace(); + } + + if(authText == null) + ev.allow(); + else + ev.disallow(Result.KICK_OTHER, authText); + } +} diff --git a/src/bukkitb173/PluginMain.java b/src/bukkitb173/PluginMain.java new file mode 100644 index 0000000..b35b601 --- /dev/null +++ b/src/bukkitb173/PluginMain.java @@ -0,0 +1,26 @@ +package net.flashii.mcexts; + +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.Event.Priority; +import org.bukkit.plugin.java.JavaPlugin; + +public class PluginMain extends JavaPlugin { + public final static Logger logger = Logger.getLogger("FIIEXTS"); + + private final JoinListener joinListener = new JoinListener(); + + @Override + public void onEnable() { + logger.info("Flashii extensions enabled!"); + + ConfigPath.setPath(getDataFolder()); + Bukkit.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_LOGIN, joinListener, Priority.Highest, this); + } + + @Override + public void onDisable() { + logger.info("Flashii extensions disabled!"); + } +} diff --git a/src/fabric/ConfigPath.java b/src/fabric/ConfigPath.java new file mode 100644 index 0000000..b589ba5 --- /dev/null +++ b/src/fabric/ConfigPath.java @@ -0,0 +1,18 @@ +package net.flashii.mcexts; + +import java.nio.file.Path; +import net.fabricmc.loader.api.FabricLoader; + +public class ConfigPath { + private static Path configPath = null; + + public static Path getPath() { + if(configPath == null) + configPath = FabricLoader.getInstance().getGameDir().resolve("config").resolve("fiiexts"); + return configPath; + } + + public static Path getPath(String name) { + return getPath().resolve(name); + } +} diff --git a/src/fabric/net/flashii/mcexts/mixin/EnvironmentMixin.java b/src/fabric/mixin/EnvironmentMixin.java similarity index 100% rename from src/fabric/net/flashii/mcexts/mixin/EnvironmentMixin.java rename to src/fabric/mixin/EnvironmentMixin.java diff --git a/src/fabric/net/flashii/mcexts/mixin/PlayerListHudMixin.java b/src/fabric/mixin/PlayerListHudMixin.java similarity index 100% rename from src/fabric/net/flashii/mcexts/mixin/PlayerListHudMixin.java rename to src/fabric/mixin/PlayerListHudMixin.java diff --git a/src/fabric/net/flashii/mcexts/mixin/PlayerManagerMixin.java b/src/fabric/mixin/PlayerManagerMixin.java similarity index 87% rename from src/fabric/net/flashii/mcexts/mixin/PlayerManagerMixin.java rename to src/fabric/mixin/PlayerManagerMixin.java index a734995..42e65f5 100644 --- a/src/fabric/net/flashii/mcexts/mixin/PlayerManagerMixin.java +++ b/src/fabric/mixin/PlayerManagerMixin.java @@ -1,8 +1,6 @@ package net.flashii.mcexts.mixin; -import java.io.IOException; import java.net.SocketAddress; -import java.security.GeneralSecurityException; import com.mojang.authlib.GameProfile; import net.flashii.mcexts.RPC; import net.flashii.mcexts.RPCPayload; @@ -54,11 +52,8 @@ public abstract class PlayerManagerMixin { authText = Text.literal("Flashii authentication server returned an unknown response, yell at flashwave about this.").formatted(Formatting.RED); } } - } catch(IOException ex) { - authText = Text.literal("Flashii authentication server failed to respond, yell at flashwave about this.").formatted(Formatting.RED); - ex.printStackTrace(); - } catch(GeneralSecurityException ex) { - authText = Text.literal("Problem with request verification, yell at flashwave about this.").formatted(Formatting.RED); + } catch(Exception ex) { + authText = Text.literal("There was a serious problem during authentication, yell at flashwave about this.").formatted(Formatting.RED); ex.printStackTrace(); } diff --git a/src/fabric/net/flashii/mcexts/mixin/ServerMetadataMixin.java b/src/fabric/mixin/ServerMetadataMixin.java similarity index 100% rename from src/fabric/net/flashii/mcexts/mixin/ServerMetadataMixin.java rename to src/fabric/mixin/ServerMetadataMixin.java diff --git a/src/fabric/net/flashii/mcexts/mixin/TextureUrlCheckerMixin.java b/src/fabric/mixin/TextureUrlCheckerMixin.java similarity index 100% rename from src/fabric/net/flashii/mcexts/mixin/TextureUrlCheckerMixin.java rename to src/fabric/mixin/TextureUrlCheckerMixin.java diff --git a/src/fabric/net/flashii/mcexts/mixin/YggdrasilMinecraftSessionServiceMixin.java b/src/fabric/mixin/YggdrasilMinecraftSessionServiceMixin.java similarity index 100% rename from src/fabric/net/flashii/mcexts/mixin/YggdrasilMinecraftSessionServiceMixin.java rename to src/fabric/mixin/YggdrasilMinecraftSessionServiceMixin.java diff --git a/src/plugin.yml b/src/plugin.yml new file mode 100644 index 0000000..e5ef302 --- /dev/null +++ b/src/plugin.yml @@ -0,0 +1,3 @@ +name: fiiexts +main: net.flashii.mcexts.PluginMain +version: 1.1.0 diff --git a/src/fabric/net/flashii/mcexts/RPCPayloadDeserialiser.java b/src/rpc-gson/RPCPayloadDeserialiser.java similarity index 100% rename from src/fabric/net/flashii/mcexts/RPCPayloadDeserialiser.java rename to src/rpc-gson/RPCPayloadDeserialiser.java diff --git a/src/rpc-gson/RPCPayloadParser.java b/src/rpc-gson/RPCPayloadParser.java new file mode 100644 index 0000000..5088753 --- /dev/null +++ b/src/rpc-gson/RPCPayloadParser.java @@ -0,0 +1,18 @@ +package net.flashii.mcexts; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class RPCPayloadParser { + private final Gson gson; + + public RPCPayloadParser() { + gson = new GsonBuilder() + .registerTypeAdapter(RPCPayload.class, new RPCPayloadDeserialiser()) + .create(); + } + + public RPCPayload parse(String body) { + return gson.fromJson(body, RPCPayload.class); + } +} diff --git a/src/rpc-simple/RPCPayloadParser.java b/src/rpc-simple/RPCPayloadParser.java new file mode 100644 index 0000000..9d1a802 --- /dev/null +++ b/src/rpc-simple/RPCPayloadParser.java @@ -0,0 +1,31 @@ +package net.flashii.mcexts; + +import java.util.HashMap; +import java.util.Iterator; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.ParseException; +import org.json.simple.parser.JSONParser; + +public class RPCPayloadParser { + private final JSONParser parser = new JSONParser(); + + public RPCPayload parse(String body) + throws ParseException { + JSONObject root = (JSONObject)parser.parse(body); + String name = (String)root.get("name"); + HashMap attrs = new HashMap<>(); + + @SuppressWarnings("unchecked") + Iterator attrsIterator = ((JSONArray)root.get("attrs")).iterator(); + while(attrsIterator.hasNext()) { + JSONObject attrInfo = attrsIterator.next(); + attrs.put( + (String)attrInfo.get("name"), + attrInfo.get("value") + ); + } + + return new RPCPayload(name, attrs); + } +} diff --git a/src/fabric/net/flashii/mcexts/Config.java b/src/shared/Config.java similarity index 71% rename from src/fabric/net/flashii/mcexts/Config.java rename to src/shared/Config.java index 6a13893..22a49d2 100644 --- a/src/fabric/net/flashii/mcexts/Config.java +++ b/src/shared/Config.java @@ -3,9 +3,7 @@ package net.flashii.mcexts; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; -import net.fabricmc.loader.api.FabricLoader; public class Config { static class ConfigCache { @@ -24,25 +22,14 @@ public class Config { } } - private static Path configPath = null; private static HashMap cache = new HashMap<>(); - private static Path getConfigPath() { - if(configPath == null) - configPath = FabricLoader.getInstance().getGameDir().resolve("config").resolve("fiiexts"); - return configPath; - } - - private static Path getConfigPath(String name) { - return getConfigPath().resolve(name); - } - public static String getValue(String name) { return getValue(name, null); } public static String getValue(String name, String fallback) { - return getFileContentsCached(getConfigPath(name), fallback); + return getFileContentsCached(ConfigPath.getPath(name), fallback); } private static String getFileContentsCached(Path path, String fallback) { @@ -57,7 +44,7 @@ public class Config { if(output == null) { try { - output = Files.exists(path) ? Files.readString(path).trim() : fallback; + output = Files.exists(path) ? new String(Files.readAllBytes(path)).trim() : fallback; } catch(IOException ex) { ex.printStackTrace(); output = fallback; diff --git a/src/fabric/net/flashii/mcexts/HMAC.java b/src/shared/HMAC.java similarity index 100% rename from src/fabric/net/flashii/mcexts/HMAC.java rename to src/shared/HMAC.java diff --git a/src/fabric/net/flashii/mcexts/RNG.java b/src/shared/RNG.java similarity index 100% rename from src/fabric/net/flashii/mcexts/RNG.java rename to src/shared/RNG.java diff --git a/src/fabric/net/flashii/mcexts/RPC.java b/src/shared/RPC.java similarity index 75% rename from src/fabric/net/flashii/mcexts/RPC.java rename to src/shared/RPC.java index 1ee64fa..6e1ac95 100644 --- a/src/fabric/net/flashii/mcexts/RPC.java +++ b/src/shared/RPC.java @@ -2,8 +2,8 @@ package net.flashii.mcexts; import java.io.BufferedReader; import java.io.InputStreamReader; -import java.io.IOException; import java.io.OutputStream; +import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -11,25 +11,20 @@ import java.net.SocketAddress; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; public class RPC { private static final String DEFAULT_SECRET = "meow"; - private static Gson gson = null; + private static RPCPayloadParser parser = null; - public static Gson getGson() { - if(gson == null) - gson = new GsonBuilder() - .registerTypeAdapter(RPCPayload.class, new RPCPayloadDeserialiser()) - .create(); - return gson; + public static RPCPayloadParser getParser() { + if(parser == null) + parser = new RPCPayloadParser(); + return parser; } public static String getSecretKey() { @@ -46,7 +41,9 @@ public class RPC { params.forEach((key, value) -> { sb.append(key); sb.append('='); - sb.append(URLEncoder.encode(value.toString(), StandardCharsets.UTF_8)); + try { + sb.append(URLEncoder.encode(value.toString(), "UTF-8")); + } catch(UnsupportedEncodingException ex) {} sb.append('&'); }); @@ -59,7 +56,7 @@ public class RPC { } public static String createRequestSignature(String time, String path, String params) - throws GeneralSecurityException { + throws Exception { return Base64.getEncoder().encodeToString(HMAC.calculate( HMAC.SHA256, getSecretKey(), String.format("%s#%s?%s", time, path, params) )); @@ -67,7 +64,7 @@ public class RPC { // sigStr and bodyStr because sigStr must also include the query params if those are present public static RPCPayload callRpc(String path, String sigStr, String bodyStr) - throws GeneralSecurityException, IOException { + throws Exception { boolean hasBody = bodyStr != null; String time = getRequestTimestamp(); String hash = createRequestSignature(time, URLs.getRpcPath(path), sigStr); @@ -94,31 +91,48 @@ public class RPC { sb.append(line); } - return getGson().fromJson(sb.toString(), RPCPayload.class); + return getParser().parse(sb.toString()); } public static RPCPayload callRpc(String path, String paramStr) - throws GeneralSecurityException, IOException { + throws Exception { return callRpc(path, paramStr, paramStr); } public static RPCPayload callRpc(String path, Map params) - throws GeneralSecurityException, IOException { + throws Exception { return callRpc(path, createParamString(params)); } - public static RPCPayload postAuth(UUID id, String name, InetAddress remoteAddr) - throws GeneralSecurityException, IOException { + public static UUID createOfflinePlayerUUID(String name) { + return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes()); + } + + public static RPCPayload postAuth(String name, String remoteAddr) + throws Exception { + return postAuth( + createOfflinePlayerUUID(name), + name, remoteAddr + ); + } + + public static RPCPayload postAuth(UUID id, String name, String remoteAddr) + throws Exception { HashMap params = new HashMap<>(); params.put("id", id); params.put("name", name); - params.put("ip", remoteAddr.getHostAddress()); + params.put("ip", remoteAddr); return callRpc("/auth", params); } + public static RPCPayload postAuth(UUID id, String name, InetAddress remoteAddr) + throws Exception { + return postAuth(id, name, remoteAddr.getHostAddress()); + } + public static RPCPayload postAuth(UUID id, String name, SocketAddress sockAddr) - throws GeneralSecurityException, IOException { + throws Exception { InetAddress remoteAddr = sockAddr instanceof InetSocketAddress ? ((InetSocketAddress)sockAddr).getAddress() : InetAddress.getLoopbackAddress(); diff --git a/src/fabric/net/flashii/mcexts/RPCPayload.java b/src/shared/RPCPayload.java similarity index 100% rename from src/fabric/net/flashii/mcexts/RPCPayload.java rename to src/shared/RPCPayload.java diff --git a/src/fabric/net/flashii/mcexts/URLs.java b/src/shared/URLs.java similarity index 100% rename from src/fabric/net/flashii/mcexts/URLs.java rename to src/shared/URLs.java